diff --git a/DEPS b/DEPS index 5d28798..c8aac75 100644 --- a/DEPS +++ b/DEPS
@@ -144,7 +144,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '8a5759d9902178a4a5e7225a3cd240b581987ef6', + 'skia_revision': '5207f35f33b1ccc173cff02bd0a38223554ba6f2', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. @@ -156,7 +156,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '02407743bd7261c37abae0f7e4962ea324662122', + 'angle_revision': 'cd369bb8a2518eaca7fbdb0936095d3b5d44b4ee', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -207,7 +207,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': '1855bc3168eed83649a33dc11f8042097da52d36', + 'catapult_revision': '249e608964291a3db12869d6158b6df5679c7a22', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -263,7 +263,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '76b75c40a1e27939957e6a598292e9f32b4e98d4', + 'spv_tools_revision': '3855447d93eb9a79723e0711b895b57ae444ce3f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -279,7 +279,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': '07b5be3bc5df96b6488bb129eb39248dea078a20', + 'dawn_revision': '4e3b218e9695b1f7011ff80319e75e14a35cf466', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -808,7 +808,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'e1edd548c20ffa519e97c18aeac4ab07dbc645b8', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'ec869c11c79de47fe0b31a17ad597337fb653117', 'condition': 'checkout_linux', }, @@ -902,7 +902,7 @@ }, 'src/third_party/glslang/src': - Var('chromium_git') + '/external/github.com/KhronosGroup/glslang.git' + '@' + '2bb2da919352bed58e73f39f62f24570dfefb60b', + Var('chromium_git') + '/external/github.com/KhronosGroup/glslang.git' + '@' + '302fe97e7b02e37856961ea74f76759098b99188', 'src/third_party/google_toolbox_for_mac/src': { 'url': Var('chromium_git') + '/external/github.com/google/google-toolbox-for-mac.git' + '@' + Var('google_toolbox_for_mac_revision'), @@ -1206,7 +1206,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'cde26f18fbf1a91dc06c99c68b3692c920dc826e', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '5f008e96a17fc8dfde695e50429222d857414b93', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1374,7 +1374,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'abaae129d9a0c6e1e092067e0b105475df43352e', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '8fcf354fa1c852c4ec1390f7ac00229a9b535fb3', + Var('webrtc_git') + '/src.git' + '@' + '61689ab0630a4489549a67024d6bd4fb2c153295', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1415,7 +1415,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@1f680135e59287c6f128ae3814dca5f05977107f', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@0ecadc16190aacfd177863dc7c64c9d39e2a7502', 'condition': 'checkout_src_internal', },
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index 1aa4a28..9736ebf 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -288,7 +288,6 @@ '^chromeos/geolocation/', '^chromeos/login/', '^chromeos/network/', - '^chromeos/printing/', '^chromeos/process_proxy/', '^chromeos/services/', '^chromeos/settings/',
diff --git a/android_webview/browser/aw_autofill_client.cc b/android_webview/browser/aw_autofill_client.cc index 489c517..451a9f5 100644 --- a/android_webview/browser/aw_autofill_client.cc +++ b/android_webview/browser/aw_autofill_client.cc
@@ -66,7 +66,7 @@ return nullptr; } -identity::IdentityManager* AwAutofillClient::GetIdentityManager() { +signin::IdentityManager* AwAutofillClient::GetIdentityManager() { return nullptr; }
diff --git a/android_webview/browser/aw_autofill_client.h b/android_webview/browser/aw_autofill_client.h index cbfd12c..b93d687b 100644 --- a/android_webview/browser/aw_autofill_client.h +++ b/android_webview/browser/aw_autofill_client.h
@@ -65,7 +65,7 @@ override; PrefService* GetPrefs() override; syncer::SyncService* GetSyncService() override; - identity::IdentityManager* GetIdentityManager() override; + signin::IdentityManager* GetIdentityManager() override; autofill::FormDataImporter* GetFormDataImporter() override; autofill::payments::PaymentsClient* GetPaymentsClient() override; autofill::StrikeDatabase* GetStrikeDatabase() override;
diff --git a/base/BUILD.gn b/base/BUILD.gn index 9f9f4ed..289cff1 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1125,6 +1125,7 @@ "win/windows_version.cc", "win/windows_version.h", "win/windowsx_shim.h", + "win/winrt_foundation_helpers.h", "win/winrt_storage_util.cc", "win/winrt_storage_util.h", "win/wmi.cc",
diff --git a/base/allocator/partition_allocator/memory_reclaimer.cc b/base/allocator/partition_allocator/memory_reclaimer.cc index e3a16f1..1a135c7 100644 --- a/base/allocator/partition_allocator/memory_reclaimer.cc +++ b/base/allocator/partition_allocator/memory_reclaimer.cc
@@ -17,8 +17,9 @@ const Feature kNoPartitionAllocDecommit{"NoPartitionAllocDecommit", FEATURE_DISABLED_BY_DEFAULT}; +// TODO(crbug.com/942512): Remove the feature after the M77 branch. const Feature kPartitionAllocPeriodicDecommit{"PartitionAllocPeriodicDecommit", - FEATURE_DISABLED_BY_DEFAULT}; + FEATURE_ENABLED_BY_DEFAULT}; } // namespace internal @@ -43,7 +44,6 @@ internal::PartitionRootBase* partition) { AutoLock lock(lock_); DCHECK(partition); - DCHECK(!timer_); auto it_and_whether_inserted = partitions_.insert(partition); DCHECK(it_and_whether_inserted.second); }
diff --git a/base/allocator/partition_allocator/memory_reclaimer_unittest.cc b/base/allocator/partition_allocator/memory_reclaimer_unittest.cc index 95c6039..a897ed6 100644 --- a/base/allocator/partition_allocator/memory_reclaimer_unittest.cc +++ b/base/allocator/partition_allocator/memory_reclaimer_unittest.cc
@@ -73,15 +73,20 @@ EXPECT_TRUE(task_environment_.NextTaskIsDelayed()); } -TEST_F(PartitionAllocMemoryReclaimerTest, IsDisabledByDefault) { +TEST_F(PartitionAllocMemoryReclaimerTest, IsEnabledByDefault) { + StartReclaimer(); + EXPECT_EQ(2u, task_environment_.GetPendingMainThreadTaskCount()); +} + +TEST_F(PartitionAllocMemoryReclaimerTest, CanBeDisabled) { + test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndDisableFeature( + internal::kPartitionAllocPeriodicDecommit); StartReclaimer(); EXPECT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount()); } TEST_F(PartitionAllocMemoryReclaimerTest, FreesMemory) { - test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndEnableFeature( - internal::kPartitionAllocPeriodicDecommit); PartitionRootGeneric* root = allocator_->root(); size_t committed_initially = root->total_size_of_committed_pages; @@ -99,9 +104,6 @@ } TEST_F(PartitionAllocMemoryReclaimerTest, Reclaim) { - StartReclaimer(); - EXPECT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount()); - PartitionRootGeneric* root = allocator_->root(); size_t committed_initially = root->total_size_of_committed_pages; @@ -116,67 +118,33 @@ EXPECT_LT(committed_after, committed_before); EXPECT_LE(committed_initially, committed_after); } - - // |Reclaim()| is always enabled. - { - test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndEnableFeature( - internal::kPartitionAllocPeriodicDecommit); - - AllocateAndFree(); - - size_t committed_before = root->total_size_of_committed_pages; - EXPECT_GT(committed_before, committed_initially); - PartitionAllocMemoryReclaimer::Instance()->Reclaim(); - size_t committed_after = root->total_size_of_committed_pages; - - EXPECT_LT(committed_after, committed_before); - EXPECT_LE(committed_initially, committed_after); - } } TEST_F(PartitionAllocMemoryReclaimerTest, DeprecatedReclaim) { - StartReclaimer(); - EXPECT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount()); PartitionRootGeneric* root = allocator_->root(); + // Deprecated reclaim is disabled by default. { - // Deprecated reclaim enabled by default. + AllocateAndFree(); + size_t committed_before = root->total_size_of_committed_pages; + PartitionAllocMemoryReclaimer::Instance()->DeprecatedReclaim(); + size_t committed_after = root->total_size_of_committed_pages; + EXPECT_EQ(committed_after, committed_before); + + PartitionAllocMemoryReclaimer::Instance()->Reclaim(); + } + + // Deprecated reclaim works when periodic reclaim is disabled. + { + test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndDisableFeature( + internal::kPartitionAllocPeriodicDecommit); AllocateAndFree(); size_t committed_before = root->total_size_of_committed_pages; PartitionAllocMemoryReclaimer::Instance()->DeprecatedReclaim(); size_t committed_after = root->total_size_of_committed_pages; EXPECT_LT(committed_after, committed_before); } - - // Either of the features disables deprecated reclaim. - { - test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndEnableFeature( - internal::kPartitionAllocPeriodicDecommit); - - AllocateAndFree(); - size_t committed_before = root->total_size_of_committed_pages; - PartitionAllocMemoryReclaimer::Instance()->DeprecatedReclaim(); - size_t committed_after = root->total_size_of_committed_pages; - EXPECT_EQ(committed_after, committed_before); - - PartitionAllocMemoryReclaimer::Instance()->Reclaim(); - } - - { - test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndEnableFeature( - internal::kNoPartitionAllocDecommit); - - AllocateAndFree(); - size_t committed_before = root->total_size_of_committed_pages; - PartitionAllocMemoryReclaimer::Instance()->DeprecatedReclaim(); - size_t committed_after = root->total_size_of_committed_pages; - EXPECT_EQ(committed_after, committed_before); - - PartitionAllocMemoryReclaimer::Instance()->Reclaim(); - } } TEST_F(PartitionAllocMemoryReclaimerTest, StatsRecording) { @@ -185,9 +153,6 @@ return; HistogramTester histogram_tester; - test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndEnableFeature( - internal::kPartitionAllocPeriodicDecommit); StartReclaimer(); EXPECT_EQ(GetExpectedTasksCount(), task_environment_.GetPendingMainThreadTaskCount());
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java index 43b670c9..dd22909f 100644 --- a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java +++ b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
@@ -4,8 +4,6 @@ package org.chromium.base.library_loader; -import static org.chromium.base.metrics.CachedMetrics.EnumeratedHistogramSample; - import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.ApplicationInfo; @@ -27,9 +25,11 @@ import org.chromium.base.StrictModeContext; import org.chromium.base.TraceEvent; import org.chromium.base.VisibleForTesting; +import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.MainDex; import org.chromium.base.compat.ApiHelperForM; +import org.chromium.base.metrics.CachedMetrics; import org.chromium.base.metrics.RecordHistogram; import java.io.File; @@ -83,9 +83,6 @@ // Shared preferences key for the reached code profiler. private static final String REACHED_CODE_PROFILER_ENABLED_KEY = "reached_code_profiler_enabled"; - private static final EnumeratedHistogramSample sRelinkerCountHistogram = - new EnumeratedHistogramSample("ChromiumAndroidLinker.RelinkerFallbackCount", 2); - // The singleton instance of LibraryLoader. Never null (not final for tests). private static LibraryLoader sInstance = new LibraryLoader(); @@ -303,14 +300,6 @@ } } - static void incrementRelinkerCountHitHistogram() { - sRelinkerCountHistogram.record(1); - } - - static void incrementRelinkerCountNotHitHistogram() { - sRelinkerCountHistogram.record(0); - } - // Experience shows that on some devices, the system sometimes fails to extract native libraries // at installation or update time from the APK. This function will extract the library and // return the extracted file path. @@ -341,6 +330,9 @@ String apkFilePath = isInZipFile() ? appInfo.sourceDir : null; linker.prepareLibraryLoad(apkFilePath); + // See base/android/linker/config.gni, the chromium linker is only enabled + // when we have a sinble library. + assert NativeLibraries.LIBRARIES.length == 1; for (String library : NativeLibraries.LIBRARIES) { // Don't self-load the linker. This is because the build system is // not clever enough to understand that all the libraries packaged @@ -361,13 +353,11 @@ try { // Load the library using this Linker. May throw UnsatisfiedLinkError. loadLibraryWithCustomLinkerAlreadyLocked(linker, libFilePath); - incrementRelinkerCountNotHitHistogram(); } catch (UnsatisfiedLinkError e) { if (!isInZipFile() && PLATFORM_REQUIRES_NATIVE_FALLBACK_EXTRACTION) { loadLibraryWithCustomLinkerAlreadyLocked( linker, getExtractedLibraryPath(appInfo, library)); - incrementRelinkerCountHitHistogram(); } else { Log.e(TAG, "Unable to load library: " + library); throw(e); @@ -622,6 +612,11 @@ } } + @CalledByNative + public static void onUmaRecordingReadyInRenderer() { + CachedMetrics.commitCachedMetrics(); + } + // Android system sometimes fails to extract libraries from APK (https://crbug.com/806998). // This function manually extract libraries as a fallback. @SuppressLint({"SetWorldReadable"})
diff --git a/base/android/java/src/org/chromium/base/library_loader/Linker.java b/base/android/java/src/org/chromium/base/library_loader/Linker.java index 27ee53f..09d56e6 100644 --- a/base/android/java/src/org/chromium/base/library_loader/Linker.java +++ b/base/android/java/src/org/chromium/base/library_loader/Linker.java
@@ -556,13 +556,11 @@ } try { System.loadLibrary(LINKER_JNI_LIBRARY); - LibraryLoader.incrementRelinkerCountNotHitHistogram(); } catch (UnsatisfiedLinkError e) { if (LibraryLoader.PLATFORM_REQUIRES_NATIVE_FALLBACK_EXTRACTION) { System.load(LibraryLoader.getExtractedLibraryPath( ContextUtils.getApplicationContext().getApplicationInfo(), LINKER_JNI_LIBRARY)); - LibraryLoader.incrementRelinkerCountHitHistogram(); } else { // Cannot continue if we cannot load the linker. Technically we could try to // load the library with the system linker on Android M+, but this should never
diff --git a/base/android/java/src/org/chromium/base/metrics/CachedMetrics.java b/base/android/java/src/org/chromium/base/metrics/CachedMetrics.java index 068b7df..0c0c12c 100644 --- a/base/android/java/src/org/chromium/base/metrics/CachedMetrics.java +++ b/base/android/java/src/org/chromium/base/metrics/CachedMetrics.java
@@ -13,6 +13,8 @@ * Utility classes for recording UMA metrics before the native library * may have been loaded. Metrics are cached until the library is known * to be loaded, then committed to the MetricsService all at once. + * + * NOTE: Currently supports recording metrics only in Browser/Webview/Renderer processes. */ public class CachedMetrics { /** @@ -306,7 +308,7 @@ /** * Calls out to native code to commit any cached histograms and events. - * Should be called once the native library has been loaded. + * Should be called once the native library has been initialized. */ public static void commitCachedMetrics() { synchronized (CachedMetric.sMetrics) {
diff --git a/base/android/library_loader/library_loader_hooks.cc b/base/android/library_loader/library_loader_hooks.cc index 60c9930..7d49e13 100644 --- a/base/android/library_loader/library_loader_hooks.cc +++ b/base/android/library_loader/library_loader_hooks.cc
@@ -64,6 +64,9 @@ UMA_HISTOGRAM_TIMES( "ChromiumAndroidLinker.RendererLoadTime", base::TimeDelta::FromMilliseconds(g_renderer_library_load_time_ms)); + + Java_LibraryLoader_onUmaRecordingReadyInRenderer( + base::android::AttachCurrentThread()); } void SetLibraryLoadedHook(LibraryLoadedHook* func) {
diff --git a/base/win/async_operation.h b/base/win/async_operation.h index 97f7aab6..fbe82d23 100644 --- a/base/win/async_operation.h +++ b/base/win/async_operation.h
@@ -19,6 +19,7 @@ #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/threading/thread_checker.h" +#include "base/win/winrt_foundation_helpers.h" namespace base { namespace win { @@ -70,70 +71,20 @@ namespace internal { // Template tricks needed to dispatch to the correct implementation below. -// -// For all types which are neither InterfaceGroups nor RuntimeClasses, the -// following three typedefs are synonyms for a single C++ type. But for -// InterfaceGroups and RuntimeClasses, they are different types: -// LogicalT: The C++ Type for the InterfaceGroup or RuntimeClass, when -// used as a template parameter. Eg "RCFoo*" -// AbiT: The C++ type for the default interface used to represent the -// InterfaceGroup or RuntimeClass when passed as a method parameter. -// Eg "IFoo*" -// ComplexT: An instantiation of the Internal "AggregateType" template that -// combines LogicalT with AbiT. Eg "AggregateType<RCFoo*,IFoo*>" -// -// windows.foundation.collections.h defines the following template and -// semantics in Windows::Foundation::Internal: -// -// template <class LogicalType, class AbiType> -// struct AggregateType; -// -// LogicalType - the Windows Runtime type (eg, runtime class, inteface group, -// etc) being provided as an argument to an _impl template, when -// that type cannot be represented at the ABI. -// AbiType - the type used for marshalling, ie "at the ABI", for the -// logical type. +// See base/win/winrt_foundation_helpers.h for explanation. + template <typename T> -using ComplexT = +using Complex = typename ABI::Windows::Foundation::IAsyncOperation<T>::TResult_complex; template <typename T> -using AbiT = - typename ABI::Windows::Foundation::Internal::GetAbiType<ComplexT<T>>::type; +using Abi = AbiType<Complex<T>>; template <typename T> -using LogicalT = typename ABI::Windows::Foundation::Internal::GetLogicalType< - ComplexT<T>>::type; +using OptionalStorageT = OptionalStorageType<Complex<T>>; template <typename T> -using InterfaceT = std::remove_pointer_t<AbiT<T>>; - -// Compile time switch to decide what container to use for the async results for -// |T|. Depends on whether the underlying Abi type is a pointer to IUnknown or -// not. It queries the internals of Windows::Foundation to obtain this -// information. -template <typename T> -using ResultT = - std::conditional_t<std::is_convertible<AbiT<T>, IUnknown*>::value, - Microsoft::WRL::ComPtr<std::remove_pointer_t<AbiT<T>>>, - AbiT<T>>; - -template <typename T> -using StorageT = - std::conditional_t<std::is_convertible<AbiT<T>, IUnknown*>::value, - Microsoft::WRL::ComPtr<std::remove_pointer_t<AbiT<T>>>, - base::Optional<AbiT<T>>>; - -template <typename T> -HRESULT CopyStorage(const Microsoft::WRL::ComPtr<T>& storage, T** results) { - return storage.CopyTo(results); -} - -template <typename T> -HRESULT CopyStorage(const base::Optional<T>& storage, T* results) { - *results = *storage; - return S_OK; -} +using StorageT = StorageType<Complex<T>>; } // namespace internal @@ -144,10 +95,11 @@ Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>, ABI::Windows::Foundation::IAsyncOperation<T>> { public: + using AbiT = internal::Abi<T>; + using OptionalStorageT = internal::OptionalStorageT<T>; using StorageT = internal::StorageT<T>; - using ResultT = internal::ResultT<T>; using Handler = ABI::Windows::Foundation::IAsyncOperationCompletedHandler<T>; - using ResultCallback = base::OnceCallback<void(ResultT)>; + using ResultCallback = base::OnceCallback<void(StorageT)>; AsyncOperation() : weak_factory_(this) { // Note: This can't be done in the constructor initializer list. This is @@ -169,9 +121,9 @@ DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return handler_.CopyTo(handler); } - IFACEMETHODIMP GetResults(internal::AbiT<T>* results) override { + IFACEMETHODIMP GetResults(AbiT* results) override { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - return storage_ ? internal::CopyStorage(storage_, results) : E_PENDING; + return results_ ? internal::CopyTo(results_, results) : E_PENDING; } ResultCallback callback() { @@ -185,16 +137,16 @@ handler_->Invoke(this, ABI::Windows::Foundation::AsyncStatus::Completed); } - void OnResult(ResultT result) { + void OnResult(StorageT result) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(!storage_); - storage_ = std::move(result); + DCHECK(!results_); + results_ = std::move(result); InvokeCompletedHandler(); } ResultCallback callback_; Microsoft::WRL::ComPtr<Handler> handler_; - StorageT storage_; + OptionalStorageT results_; THREAD_CHECKER(thread_checker_); base::WeakPtrFactory<AsyncOperation> weak_factory_;
diff --git a/base/win/vector.h b/base/win/vector.h index 41c0c81..ba94ecf 100644 --- a/base/win/vector.h +++ b/base/win/vector.h
@@ -17,6 +17,7 @@ #include "base/base_export.h" #include "base/containers/flat_map.h" #include "base/logging.h" +#include "base/win/winrt_foundation_helpers.h" namespace base { namespace win { @@ -26,17 +27,21 @@ namespace internal { +// Template tricks needed to dispatch to the correct implementation. +// See base/win/winrt_foundation_helpers.h for explanation. + template <typename T> using Complex = typename ABI::Windows::Foundation::Collections::IVector<T>::T_complex; template <typename T> -using Logical = typename ABI::Windows::Foundation::Internal::GetLogicalType< - Complex<T>>::type; +using Logical = LogicalType<Complex<T>>; template <typename T> -using Abi = - typename ABI::Windows::Foundation::Internal::GetAbiType<Complex<T>>::type; +using Abi = AbiType<Complex<T>>; + +template <typename T> +using Storage = StorageType<Complex<T>>; template <typename T> class VectorIterator @@ -177,45 +182,6 @@ EventRegistrationToken vector_changed_token_; }; -template <typename T> -HRESULT CopyTo(const T& value, T* ptr) { - *ptr = value; - return S_OK; -} - -template <typename T> -HRESULT CopyTo(const Microsoft::WRL::ComPtr<T>& com_ptr, T** ptr) { - return com_ptr.CopyTo(ptr); -} - -template <typename T> -HRESULT CopyN(typename std::vector<T>::const_iterator first, - unsigned count, - T* result) { - std::copy_n(first, count, result); - return S_OK; -} - -template <typename T> -HRESULT CopyN( - typename std::vector<Microsoft::WRL::ComPtr<T>>::const_iterator first, - unsigned count, - T** result) { - for (unsigned i = 0; i < count; ++i) - CopyTo(*first++, result++); - return S_OK; -} - -template <typename T> -bool IsEqual(const T& lhs, const T& rhs) { - return lhs == rhs; -} - -template <typename T> -bool IsEqual(const Microsoft::WRL::ComPtr<T>& com_ptr, const T* ptr) { - return com_ptr.Get() == ptr; -} - } // namespace internal // This file provides an implementation of Windows::Foundation::IVector. It @@ -238,24 +204,9 @@ ABI::Windows::Foundation::Collections::IIterable< internal::Logical<T>>> { public: - // windows.foundation.collections.h defines the following template and - // semantics in Windows::Foundation::Internal: - // - // template <class LogicalType, class AbiType> - // struct AggregateType; - // - // LogicalType - the Windows Runtime type (eg, runtime class, interface - // group, etc) being provided as an argument to an _impl - // template, when that type cannot be represented at the ABI. - // AbiType - the type used for marshalling, ie "at the ABI", for the - // logical type. using LogicalT = internal::Logical<T>; using AbiT = internal::Abi<T>; - - using StorageT = - std::conditional_t<std::is_convertible<AbiT, IUnknown*>::value, - Microsoft::WRL::ComPtr<std::remove_pointer_t<AbiT>>, - AbiT>; + using StorageT = internal::Storage<T>; Vector() = default; explicit Vector(const std::vector<StorageT>& vector) : vector_(vector) {}
diff --git a/base/win/winrt_foundation_helpers.h b/base/win/winrt_foundation_helpers.h new file mode 100644 index 0000000..819ae1b --- /dev/null +++ b/base/win/winrt_foundation_helpers.h
@@ -0,0 +1,151 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_WIN_WINRT_FOUNDATION_HELPERS_H_ +#define BASE_WIN_WINRT_FOUNDATION_HELPERS_H_ + +#include <windows.foundation.h> +#include <wrl/client.h> + +#include <vector> + +#include "base/optional.h" +#include "base/win/hstring_compare.h" + +// This file provides helpers for WinRT types. + +namespace base { +namespace win { +namespace internal { + +// Template tricks needed to dispatch to the correct implementation. +// +// For all types which are neither InterfaceGroups nor RuntimeClasses, the +// following three typedefs are synonyms for a single C++ type. But for +// InterfaceGroups and RuntimeClasses, they are different types: +// LogicalT: The C++ Type for the InterfaceGroup or RuntimeClass, when +// used as a template parameter. Eg "RCFoo*" +// AbiT: The C++ type for the default interface used to represent the +// InterfaceGroup or RuntimeClass when passed as a method parameter. +// Eg "IFoo*" +// ComplexT: An instantiation of the Internal "AggregateType" template that +// combines LogicalT with AbiT. Eg "AggregateType<RCFoo*,IFoo*>". +// ComplexT is tightly coupled to the interface being implemented, +// hence defined in headers which include this file. +// For instance base/win/async_operation.h or +// base/win/collection_helpers.h +// +// windows.foundation.collections.h defines the following template and +// semantics in Windows::Foundation::Internal: +// +// template <class LogicalType, class AbiType> +// struct AggregateType; +// +// LogicalType - the Windows Runtime type (eg, runtime class, interface group, +// etc) being provided as an argument to an _impl template, when +// that type cannot be represented at the ABI. +// AbiType - the type used for marshalling, ie "at the ABI", for the +// logical type. +template <typename TComplex> +using AbiType = + typename ABI::Windows::Foundation::Internal::GetAbiType<TComplex>::type; + +template <typename TComplex> +using LogicalType = + typename ABI::Windows::Foundation::Internal::GetLogicalType<TComplex>::type; + +// Compile time switch to decide what container to use for |TComplex|. +// Depends on whether the underlying Abi type is a pointer to IUnknown or not. +// It queries the internals of Windows::Foundation to obtain this information. +template <typename TComplex> +using StorageType = std::conditional_t< + std::is_convertible<AbiType<TComplex>, IUnknown*>::value, + Microsoft::WRL::ComPtr<std::remove_pointer_t<AbiType<TComplex>>>, + AbiType<TComplex>>; + +// Similar to StorageType, but returns a base::Optional in case underlying Abi +// type is not a pointer to IUnknown. +template <typename TComplex> +using OptionalStorageType = std::conditional_t< + std::is_convertible<AbiType<TComplex>, IUnknown*>::value, + Microsoft::WRL::ComPtr<std::remove_pointer_t<AbiType<TComplex>>>, + base::Optional<AbiType<TComplex>>>; + +template <typename T> +HRESULT CopyTo(const T& value, T* ptr) { + *ptr = value; + return S_OK; +} + +template <typename T> +HRESULT CopyTo(const Microsoft::WRL::ComPtr<T>& value, T** ptr) { + return value.CopyTo(ptr); +} + +template <typename T> +HRESULT CopyTo(const base::Optional<T>& value, T* ptr) { + *ptr = *value; + return S_OK; +} + +template <typename T> +HRESULT CopyN(typename std::vector<T>::const_iterator first, + unsigned count, + T* result) { + std::copy_n(first, count, result); + return S_OK; +} + +template <typename T> +HRESULT CopyN( + typename std::vector<Microsoft::WRL::ComPtr<T>>::const_iterator first, + unsigned count, + T** result) { + for (unsigned i = 0; i < count; ++i) + CopyTo(*first++, result++); + return S_OK; +} + +inline bool IsEqual(const HSTRING& lhs, const HSTRING& rhs) { + INT32 result; + HRESULT hr = HStringCompare(lhs, rhs, &result); + DCHECK(SUCCEEDED(hr)); + return result == 0; +} + +template <typename T> +bool IsEqual(const T& lhs, const T& rhs) { + return lhs == rhs; +} + +template <typename T> +bool IsEqual(const Microsoft::WRL::ComPtr<T>& com_ptr, const T* ptr) { + return com_ptr.Get() == ptr; +} + +struct Less { + bool operator()(const HSTRING& lhs, const HSTRING& rhs) const { + INT32 result; + HRESULT hr = HStringCompare(lhs, rhs, &result); + DCHECK(SUCCEEDED(hr)); + return result < 0; + } + + template <typename T> + bool operator()(const Microsoft::WRL::ComPtr<T>& com_ptr, + const T* ptr) const { + return com_ptr.Get() < ptr; + } + + template <typename T> + constexpr bool operator()(const T& lhs, const T& rhs) const { + return lhs < rhs; + } +}; + +} // namespace internal +} // namespace win +} // namespace base + +#endif // BASE_WIN_WINRT_FOUNDATION_HELPERS_H_
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 229830bee..a6da973 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8907184702725321600 \ No newline at end of file +8907154544763250576 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index ceb1964..21f99f0 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -8907184320698320384 \ No newline at end of file +8907153950120029888 \ No newline at end of file
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index 1f97571c..72a12460 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -136,7 +136,6 @@ "java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetProxy.java", "java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java", "java/src/org/chromium/chrome/browser/browserservices/BrowserServicesMetrics.java", - "java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentHandler.java", "java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java", "java/src/org/chromium/chrome/browser/browserservices/BrowserSessionDataProvider.java", "java/src/org/chromium/chrome/browser/browserservices/ClearDataDialogActivity.java", @@ -148,6 +147,8 @@ "java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java", "java/src/org/chromium/chrome/browser/browserservices/PostMessageHandler.java", "java/src/org/chromium/chrome/browser/browserservices/Relationship.java", + "java/src/org/chromium/chrome/browser/browserservices/SessionDataHolder.java", + "java/src/org/chromium/chrome/browser/browserservices/SessionHandler.java", "java/src/org/chromium/chrome/browser/browserservices/TrustedWebActivityClient.java", "java/src/org/chromium/chrome/browser/browserservices/TrustedWebActivityUmaRecorder.java", "java/src/org/chromium/chrome/browser/browserservices/UkmRecorder.java",
diff --git a/chrome/android/chrome_junit_test_java_sources.gni b/chrome/android/chrome_junit_test_java_sources.gni index 4b9a0386..bc270828 100644 --- a/chrome/android/chrome_junit_test_java_sources.gni +++ b/chrome/android/chrome_junit_test_java_sources.gni
@@ -24,6 +24,7 @@ "junit/src/org/chromium/chrome/browser/browserservices/ClientAppBroadcastReceiverTest.java", "junit/src/org/chromium/chrome/browser/browserservices/ClientAppDataRegisterTest.java", "junit/src/org/chromium/chrome/browser/browserservices/OriginTest.java", + "junit/src/org/chromium/chrome/browser/browserservices/SessionDataHolderTest.java", "junit/src/org/chromium/chrome/browser/browserservices/TrustedWebActivityClientTest.java", "junit/src/org/chromium/chrome/browser/browserservices/permissiondelegation/NotificationChannelPreserverTest.java", "junit/src/org/chromium/chrome/browser/browserservices/permissiondelegation/NotificationPermissionUpdaterTest.java",
diff --git a/chrome/android/features/autofill_assistant/BUILD.gn b/chrome/android/features/autofill_assistant/BUILD.gn index cc0b3f2..34e4710 100644 --- a/chrome/android/features/autofill_assistant/BUILD.gn +++ b/chrome/android/features/autofill_assistant/BUILD.gn
@@ -73,6 +73,7 @@ "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantClient.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryImpl.java", + "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionHandlerImpl.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantServiceInjector.java", "java/src/org/chromium/chrome/browser/autofill_assistant/BottomSheetUtils.java", "java/src/org/chromium/chrome/browser/autofill_assistant/EditDistance.java", @@ -180,6 +181,7 @@ "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionsCarouselUiTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantAutostartTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDetailsUiTest.java", + "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDirectActionHandlerTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantHeaderUiTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInfoBoxUiTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantOverlayUiTest.java", @@ -188,6 +190,7 @@ "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/AssistantOnboardingCoordinatorTest.java", + "javatests/src/org/chromium/chrome/browser/autofill_assistant/TestingAutofillAssistantModuleEntryProvider.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/EditDistanceTest.java", ] @@ -200,6 +203,7 @@ "//chrome/android:chrome_java", "//chrome/android:chrome_test_util_java", "//chrome/lib/image_fetcher/public/android:java", + "//chrome/test/android:chrome_java_test_support", "//components/autofill_assistant/browser:proto_java", "//content/public/android:content_java", "//content/public/test/android:content_java_test_support",
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionHandlerImpl.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionHandlerImpl.java new file mode 100644 index 0000000..c080869 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionHandlerImpl.java
@@ -0,0 +1,125 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill_assistant; + +import android.content.Context; +import android.os.Bundle; +import android.support.annotation.Nullable; + +import org.chromium.base.Callback; +import org.chromium.chrome.browser.autofill_assistant.overlay.AssistantOverlayCoordinator; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.widget.ScrimView; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * A handler that provides Autofill Assistant actions for a specific activity. + */ +class AutofillAssistantActionHandlerImpl implements AutofillAssistantActionHandler { + private final Context mContext; + private final BottomSheetController mBottomSheetController; + private final ScrimView mScrimView; + private final GetCurrentTab mGetCurrentTab; + + AutofillAssistantActionHandlerImpl(Context context, BottomSheetController bottomSheetController, + ScrimView scrimView, GetCurrentTab getCurrentTab) { + mContext = context; + mBottomSheetController = bottomSheetController; + mScrimView = scrimView; + mGetCurrentTab = getCurrentTab; + } + + @Override + public void listActions( + String experimentIds, Bundle arguments, Callback<Set<String>> callback) { + if (!AutofillAssistantPreferencesUtil.isAutofillOnboardingAccepted()) { + callback.onResult(Collections.emptySet()); + return; + } + AutofillAssistantClient client = getOrCreateClient(); + if (client == null) { + callback.onResult(Collections.emptySet()); + return; + } + + client.listDirectActions(experimentIds, toArgumentMap(arguments), callback); + } + + @Override + public void performOnboarding(String experimentIds, Callback<Boolean> callback) { + AssistantOnboardingCoordinator coordinator = new AssistantOnboardingCoordinator( + experimentIds, mContext, mBottomSheetController, mGetCurrentTab.get()); + coordinator.show(accepted -> { + coordinator.hide(); + callback.onResult(accepted); + }); + } + + @Override + public void performAction( + String name, String experimentIds, Bundle arguments, Callback<Boolean> callback) { + AutofillAssistantClient client = getOrCreateClient(); + if (client == null) { + callback.onResult(false); + return; + } + + Callback<AssistantOverlayCoordinator> afterOnboarding = (overlayController) -> { + Map<String, String> argumentMap = toArgumentMap(arguments); + if (name.isEmpty()) { + callback.onResult(client.start(/* initialUrl= */ "", argumentMap, experimentIds, + Bundle.EMPTY, overlayController)); + return; + } + callback.onResult(client.performDirectAction( + name, experimentIds, argumentMap, overlayController)); + }; + + if (!AutofillAssistantPreferencesUtil.isAutofillOnboardingAccepted()) { + AssistantOnboardingCoordinator coordinator = new AssistantOnboardingCoordinator( + experimentIds, mContext, mBottomSheetController, mGetCurrentTab.get()); + coordinator.show(accepted -> { + if (!accepted) { + coordinator.hide(); + callback.onResult(false); + return; + } + afterOnboarding.onResult(coordinator.transferControls()); + }); + return; + } + afterOnboarding.onResult(null); + } + + /** + * Returns a client for the current tab or {@code null} if there's no current tab or the current + * tab doesn't have an associated browser content. + */ + @Nullable + private AutofillAssistantClient getOrCreateClient() { + Tab tab = mGetCurrentTab.get(); + + if (tab == null || tab.getWebContents() == null) return null; + + return AutofillAssistantClient.fromWebContents(tab.getWebContents()); + } + + /** Extracts string arguments from a bundle. */ + private Map<String, String> toArgumentMap(Bundle bundle) { + Map<String, String> map = new HashMap<>(); + for (String key : bundle.keySet()) { + String value = bundle.getString(key); + if (value != null) { + map.put(key, value); + } + } + return map; + } +}
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantClient.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantClient.java index 849fd9b..a565c7c 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantClient.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantClient.java
@@ -10,6 +10,7 @@ import android.support.annotation.Nullable; import android.telephony.TelephonyManager; +import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; @@ -18,8 +19,11 @@ import org.chromium.components.signin.OAuth2TokenService; import org.chromium.content_public.browser.WebContents; +import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; /** * An Autofill Assistant client, associated with a specific WebContents. @@ -40,6 +44,11 @@ private long mNativeClientAndroid; /** + * Indicates whether account initialization was started. + */ + private boolean mAccountInitializationStarted; + + /** * Indicates whether {@link mAccount} has been initialized. */ private boolean mAccountInitialized; @@ -73,14 +82,34 @@ } } - void start(String initialUrl, Map<String, String> parameters, String experimentIds, + /** + * Start a flow on the current URL, autostarting scripts defined for that URL. + * + * <p>This immediately shows the UI, with a loading message, then fetches scripts + * from the server and autostarts one of them. + * + * @param initialUrl the original deep link, if known. When started from CCT, this + * is the URL included into the intent + * @param parameters autobot parameters to set during the whole flow + * @param experimentIds comma-separated set of experiments to use while running the flow + * @param intentExtras extras of the original intent + * @param overlayCoordinator if non-null, reuse existing UI elements, usually created to show + * onboarding. + * + * @return true if the flow was started, false if the controller is in a state where + * autostarting is not possible, such as can happen if a script is already running. The flow can + * still fail after this method returns true; the failure will be displayed on the UI. + */ + boolean start(String initialUrl, Map<String, String> parameters, String experimentIds, Bundle intentExtras, @Nullable AssistantOverlayCoordinator overlayCoordinator) { + if (mNativeClientAndroid == 0) return false; + checkNativeClientIsAliveOrThrow(); - nativeStart(mNativeClientAndroid, initialUrl, experimentIds, + chooseAccountAsyncIfNecessary(parameters.get(PARAMETER_USER_EMAIL), intentExtras); + return nativeStart(mNativeClientAndroid, initialUrl, experimentIds, parameters.keySet().toArray(new String[parameters.size()]), parameters.values().toArray(new String[parameters.size()]), overlayCoordinator, AutofillAssistantServiceInjector.getServiceToInject()); - chooseAccountAsync(parameters.get(PARAMETER_USER_EMAIL), intentExtras); } /** @@ -105,12 +134,58 @@ nativeTransferUITo(mNativeClientAndroid, otherWebContents); } + /** Lists available direct actions. */ + public void listDirectActions( + String experimentIds, Map<String, String> arguments, Callback<Set<String>> callback) { + if (mNativeClientAndroid == 0) { + callback.onResult(Collections.emptySet()); + return; + } + + // TODO(b/134741524): An account shouldn't be necessary to fetch the list of actions. + chooseAccountAsyncIfNecessary(null, null); + + // The native side calls sendDirectActionList() on the callback once the controller has + // results. + nativeListDirectActions(mNativeClientAndroid, experimentIds, + arguments.keySet().toArray(new String[arguments.size()]), + arguments.values().toArray(new String[arguments.size()]), callback); + } + + /** + * Performs a direct action. + * + * @param actionId id of the action + * @param experimentIds comma-separated set of experiments to use while running the flow + * @param arguments report these as autobot parameters while performing this specific action + * @param overlayCoordinator if non-null, reuse existing UI elements, usually created to show + * onboarding. + * @return true if the action was found started, false otherwise. The action can still fail + * after this method returns true; the failure will be displayed on the UI. + */ + public boolean performDirectAction(String actionId, String experimentIds, + Map<String, String> arguments, @Nullable AssistantOverlayCoordinator overlay) { + if (mNativeClientAndroid == 0) return false; + + // TODO(b/134741524): Define a way of specifying a fallback account, for when the user is + // not signed-in and allow direct actions when not signed in. + chooseAccountAsyncIfNecessary(null, null); + + return nativePerformDirectAction(mNativeClientAndroid, actionId, experimentIds, + arguments.keySet().toArray(new String[arguments.size()]), + arguments.values().toArray(new String[arguments.size()]), overlay); + } + @CalledByNative private static AutofillAssistantClient create(long nativeClientAndroid) { return new AutofillAssistantClient(nativeClientAndroid); } - private void chooseAccountAsync(@Nullable String accountFromParameter, Bundle extras) { + private void chooseAccountAsyncIfNecessary( + @Nullable String accountFromParameter, @Nullable Bundle extras) { + if (mAccountInitializationStarted) return; + mAccountInitializationStarted = true; + AccountManagerFacade.get().tryGetGoogleAccounts(accounts -> { if (mNativeClientAndroid == 0) return; if (accounts.size() == 1) { @@ -135,13 +210,15 @@ } } - for (String extra : extras.keySet()) { - // TODO(crbug.com/806868): Deprecate ACCOUNT_NAME. - if (extra.endsWith("ACCOUNT_NAME")) { - Account account = findAccountByName(accounts, extras.getString(extra)); - if (account != null) { - onAccountChosen(account); - return; + if (extras != null) { + for (String extra : extras.keySet()) { + // TODO(crbug.com/806868): Deprecate ACCOUNT_NAME. + if (extra.endsWith("ACCOUNT_NAME")) { + Account account = findAccountByName(accounts, extras.getString(extra)); + if (account != null) { + onAccountChosen(account); + return; + } } } } @@ -235,13 +312,23 @@ return null; } + /** Adds a dynamic action to the given reporter. */ + @CalledByNative + private void sendDirectActionList(Callback<Set<String>> callback, String[] names) { + Set<String> set = new HashSet<>(); + for (String name : names) { + set.add(name); + } + callback.onResult(set); + } + @CalledByNative private void clearNativePtr() { mNativeClientAndroid = 0; } private static native AutofillAssistantClient nativeFromWebContents(WebContents webContents); - private native void nativeStart(long nativeClientAndroid, String initialUrl, + private native boolean nativeStart(long nativeClientAndroid, String initialUrl, String experimentIds, String[] parameterNames, String[] parameterValues, @Nullable AssistantOverlayCoordinator overlayCoordinator, long nativeService); private native void nativeOnAccessToken( @@ -249,4 +336,9 @@ private native String nativeGetPrimaryAccountName(long nativeClientAndroid); private native void nativeDestroyUI(long nativeClientAndroid); private native void nativeTransferUITo(long nativeClientAndroid, Object otherWebContents); + private native void nativeListDirectActions(long nativeClientAndroid, String experimentIds, + String[] argumentNames, String[] argumentValues, Object callback); + private native boolean nativePerformDirectAction(long nativeClientAndroid, String actionId, + String experimentId, String[] argumentNames, String[] argumentValues, + @Nullable AssistantOverlayCoordinator overlay); }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryImpl.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryImpl.java index f415368..c7c48b2 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryImpl.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryImpl.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.autofill_assistant; +import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; @@ -11,6 +12,8 @@ import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.autofill_assistant.metrics.OnBoarding; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.widget.ScrimView; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; import org.chromium.content_public.browser.WebContents; import java.util.Map; @@ -43,4 +46,12 @@ onboardingCoordinator.transferControls()); }); } + + @Override + public AutofillAssistantActionHandler createActionHandler(Context context, + BottomSheetController bottomSheetController, ScrimView scrimView, + GetCurrentTab getCurrentTab) { + return new AutofillAssistantActionHandlerImpl( + context, bottomSheetController, scrimView, getCurrentTab); + } }
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDirectActionHandlerTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDirectActionHandlerTest.java new file mode 100644 index 0000000..906cc38a --- /dev/null +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDirectActionHandlerTest.java
@@ -0,0 +1,265 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill_assistant; + +import static android.support.test.espresso.Espresso.onView; +import static android.support.test.espresso.action.ViewActions.click; +import static android.support.test.espresso.matcher.ViewMatchers.withId; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import android.os.Bundle; +import android.support.test.filters.MediumTest; +import android.text.TextUtils; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.Callback; +import org.chromium.base.ThreadUtils; +import org.chromium.base.test.util.CallbackHelper; +import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.chrome.autofill_assistant.R; +import org.chromium.chrome.browser.ChromeActivity; +import org.chromium.chrome.browser.ChromeSwitches; +import org.chromium.chrome.browser.directactions.DirectActionHandler; +import org.chromium.chrome.browser.directactions.DirectActionReporter; +import org.chromium.chrome.browser.directactions.DirectActionReporter.Definition; +import org.chromium.chrome.browser.directactions.DirectActionReporter.Type; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; +import org.chromium.chrome.test.ChromeActivityTestRule; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** Tests the direct actions exposed by AA. */ +@RunWith(ChromeJUnit4ClassRunner.class) +@CommandLineFlags.Add(ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE) +public class AutofillAssistantDirectActionHandlerTest { + @Rule + public ChromeActivityTestRule<ChromeActivity> mActivityTestRule = + new ChromeActivityTestRule(ChromeActivity.class); + + private ChromeActivity mActivity; + private BottomSheetController mBottomSheetController; + private DirectActionHandler mHandler; + private TestingAutofillAssistantModuleEntryProvider mModuleEntryProvider; + + @Before + public void setUp() throws Exception { + mActivityTestRule.startMainActivityOnBlankPage(); + mActivity = mActivityTestRule.getActivity(); + + mBottomSheetController = ThreadUtils.runOnUiThreadBlocking( + () -> AutofillAssistantUiTestUtil.createBottomSheetController(mActivity)); + mModuleEntryProvider = new TestingAutofillAssistantModuleEntryProvider(); + mModuleEntryProvider.setCannotInstall(); + + mHandler = new AutofillAssistantDirectActionHandler(mActivity, mBottomSheetController, + mActivity.getScrim(), mActivity.getTabModelSelector()::getCurrentTab, + mModuleEntryProvider); + + AutofillAssistantPreferencesUtil.setInitialPreferences(false); + } + + @Test + @MediumTest + public void testReportAvailableDirectActions() throws Exception { + AutofillAssistantPreferencesUtil.setInitialPreferences(false); + + FakeDirectActionReporter reporter = new FakeDirectActionReporter(); + mHandler.reportAvailableDirectActions(reporter); + + assertEquals(2, reporter.mActions.size()); + + FakeDirectActionDefinition list = reporter.mActions.get(0); + assertEquals("list_assistant_actions", list.mId); + assertThat(list.mParameters, empty()); + assertEquals(1, list.mResults.size()); + assertEquals("names", list.mResults.get(0).mName); + assertEquals(Type.STRING, list.mResults.get(0).mType); + + FakeDirectActionDefinition perform = reporter.mActions.get(1); + assertEquals("perform_assistant_action", perform.mId); + assertEquals(2, perform.mParameters.size()); + assertEquals("name", perform.mParameters.get(0).mName); + assertEquals(Type.STRING, perform.mParameters.get(0).mType); + assertEquals("experiment_ids", perform.mParameters.get(1).mName); + assertEquals(Type.STRING, perform.mParameters.get(1).mType); + assertEquals(1, perform.mResults.size()); + assertEquals("success", perform.mResults.get(0).mName); + assertEquals(Type.BOOLEAN, perform.mResults.get(0).mType); + } + + @Test + @MediumTest + public void testOnboarding() throws Exception { + mModuleEntryProvider.setInstalled(); + + assertThat(listActions(), contains("onboarding")); + + acceptOnboarding(); + + assertTrue(AutofillAssistantPreferencesUtil.isAutofillOnboardingAccepted()); + } + + @Test + @MediumTest + public void testModuleNotAvailable() throws Exception { + mModuleEntryProvider.setCannotInstall(); + + assertThat(listActions(), contains("onboarding")); + assertFalse(performAction("onboarding", Bundle.EMPTY)); + } + + @Test + @MediumTest + public void testInstallModuleOnDemand() throws Exception { + mModuleEntryProvider.setNotInstalled(); + + assertThat(listActions(), contains("onboarding")); + acceptOnboarding(); + } + + private void acceptOnboarding() throws Exception { + WaitingCallback<Boolean> onboardingCallback = + performActionAsync("onboarding", Bundle.EMPTY); + + assertFalse(onboardingCallback.hasResult()); + onView(withId(R.id.button_init_ok)).perform(click()); + assertEquals(Boolean.TRUE, onboardingCallback.waitForResult("accept onboarding")); + } + + // TODO(b/134741524): Add tests that list and execute direct actions coming from scripts, once + // we have a way to fake RPCs and can create a bottom sheet controller on demand. + + /** Calls list_assistant_actions and returns the result. */ + private List<String> listActions() throws Exception { + WaitingCallback<Bundle> callback = new WaitingCallback<Bundle>(); + ThreadUtils.runOnUiThreadBlocking( + () + -> mHandler.performDirectAction( + "list_assistant_actions", Bundle.EMPTY, callback)); + return Arrays.asList(TextUtils.split( + callback.waitForResult("list_assistant_actions").getString("names", ""), ",")); + } + + /** Calls perform_assistant_action and returns the result. */ + private Boolean performAction(String name, Bundle arguments) throws Exception { + return performActionAsync(name, arguments).waitForResult("perform_assistant_action"); + } + + /** + * Calls perform_assistant_action and returns a {@link WaitingCallback} that'll eventually + * contain the result. + */ + private WaitingCallback<Boolean> performActionAsync(String name, Bundle arguments) + throws Exception { + WaitingCallback<Boolean> callback = new WaitingCallback<Boolean>(); + Bundle allArguments = new Bundle(arguments); + if (!name.isEmpty()) allArguments.putString("name", name); + ThreadUtils.runOnUiThreadBlocking( + () + -> mHandler.performDirectAction("perform_assistant_action", allArguments, + (bundle) -> callback.onResult(bundle.getBoolean("success")))); + return callback; + } + + /** + * A callback that allows waiting for the result to be available, then retrieving it. + */ + private static class WaitingCallback<T> implements Callback<T> { + private final CallbackHelper mHelper = new CallbackHelper(); + private boolean mHasResult; + private T mResult; + + @Override + public synchronized void onResult(T result) { + mResult = result; + mHasResult = true; + mHelper.notifyCalled(); + } + + synchronized T waitForResult(String msg) throws Exception { + if (!mHasResult) mHelper.waitForCallback(msg); + assertTrue(mHasResult); + return mResult; + } + + synchronized boolean hasResult() { + return mHasResult; + } + + synchronized T getResult() { + return mResult; + } + } + + /** + * An implementation of DirectActionReporter that just keeps the definitions in a field. + * + * <p>TODO(b/134740534) There should be shared test utilities for that. + */ + private static class FakeDirectActionReporter implements DirectActionReporter { + List<FakeDirectActionDefinition> mActions = new ArrayList<>(); + + @Override + public DirectActionReporter.Definition addDirectAction(String actionId) { + FakeDirectActionDefinition action = new FakeDirectActionDefinition(actionId); + mActions.add(action); + return action; + } + + @Override + public void report() {} + } + + /** A simple action definition for testing. */ + private static class FakeDirectActionDefinition implements Definition { + final String mId; + List<FakeParameter> mParameters = new ArrayList<>(); + List<FakeParameter> mResults = new ArrayList<>(); + + FakeDirectActionDefinition(String id) { + mId = id; + } + + @Override + public Definition withParameter(String name, @Type int type, boolean required) { + mParameters.add(new FakeParameter(name, type, required)); + return this; + } + + @Override + public Definition withResult(String name, @Type int type) { + mResults.add(new FakeParameter(name, type, true)); + return this; + } + } + + /** A simple parameter definition for testing. */ + private static class FakeParameter { + final String mName; + + @Type + final int mType; + final boolean mRequired; + + FakeParameter(String name, @Type int type, boolean required) { + mName = name; + mType = type; + mRequired = required; + } + } +}
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/TestingAutofillAssistantModuleEntryProvider.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/TestingAutofillAssistantModuleEntryProvider.java new file mode 100644 index 0000000..6431de65 --- /dev/null +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/TestingAutofillAssistantModuleEntryProvider.java
@@ -0,0 +1,54 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill_assistant; + +import android.content.Context; + +import org.chromium.base.Callback; +import org.chromium.chrome.browser.tab.Tab; + +/** + * Implementation of {@link AutofillAssistantModuleEntryProvider} that can be manipulated to + * simulate missing or uninstallable module. + */ +class TestingAutofillAssistantModuleEntryProvider extends AutofillAssistantModuleEntryProvider { + private boolean mNotInstalled; + private boolean mCannotInstall; + + /** The module is already installed. This is the default state. */ + public void setInstalled() { + mNotInstalled = false; + mCannotInstall = false; + } + + /** The module is not installed, but can be installed. */ + public void setNotInstalled() { + mNotInstalled = true; + mCannotInstall = false; + } + + /** The module is not installed, and cannot be installed. */ + public void setCannotInstall() { + mNotInstalled = true; + mCannotInstall = true; + } + + @Override + public AutofillAssistantModuleEntry getModuleEntryIfInstalled(Context context) { + if (mNotInstalled) return null; + return super.getModuleEntryIfInstalled(context); + } + + @Override + public void getModuleEntry( + Context context, Tab tab, Callback<AutofillAssistantModuleEntry> callback) { + if (mCannotInstall) { + callback.onResult(null); + return; + } + mNotInstalled = false; + super.getModuleEntry(context, tab, callback); + } +}
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionHandler.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionHandler.java new file mode 100644 index 0000000..3e51b25da --- /dev/null +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionHandler.java
@@ -0,0 +1,44 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill_assistant; + +import android.os.Bundle; + +import org.chromium.base.Callback; + +import java.util.Set; + +/** + * Interface that provides implementation for AA actions, triggered by direct actions. + */ +public interface AutofillAssistantActionHandler { + /** + * Returns the names of available AA actions. + * + * <p>This method starts AA on the current tab, if necessary, and waits for the first results. + * Once AA is started, the results are reported immediately. + * + * @param arguments extra arguments + * @param callback callback to report the result to + */ + void listActions(String experimentIds, Bundle arguments, Callback<Set<String>> callback); + + /** Performs onboarding and returns the result to the callback. */ + void performOnboarding(String experimentIds, Callback<Boolean> callback); + + /** + * Performs an AA action. + * + * <p>If this method returns {@code true}, a definition for the action was successfully started. + * It can still fail later, and the failure will be reported to the UI. + * + * @param name action name, might be empty to autostart + * @param experimentIds experiment ids, might be empty + * @param arguments extra arguments + * @param callback to report the result to + */ + void performAction( + String name, String experimentIds, Bundle arguments, Callback<Boolean> callback); +}
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDirectActionHandler.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDirectActionHandler.java new file mode 100644 index 0000000..1faf2f83 --- /dev/null +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDirectActionHandler.java
@@ -0,0 +1,174 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill_assistant; + +import android.content.Context; +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.text.TextUtils; + +import org.chromium.base.Callback; +import org.chromium.chrome.browser.directactions.DirectActionHandler; +import org.chromium.chrome.browser.directactions.DirectActionReporter; +import org.chromium.chrome.browser.directactions.DirectActionReporter.Type; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.widget.ScrimView; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; + +import java.util.Collections; +import java.util.Set; + +/** + * A handler that provides just enough functionality to allow on-demand loading of the module + * through direct actions. The actual implementation is in the module. + */ +public class AutofillAssistantDirectActionHandler implements DirectActionHandler { + private static final String LIST_AA_ACTIONS = "list_assistant_actions"; + private static final String LIST_AA_ACTIONS_RESULT = "names"; + private static final String PERFORM_AA_ACTION = "perform_assistant_action"; + private static final String PERFORM_AA_ACTION_RESULT = "success"; + private static final String ACTION_NAME = "name"; + private static final String EXPERIMENT_IDS = "experiment_ids"; + private static final String ONBOARDING_ACTION = "onboarding"; + + /** + * Set of actions to report when AA is not available, because of preference or + * lack of DFM. + */ + private static final Set<String> FALLBACK_ACTION_SET = Collections.singleton(ONBOARDING_ACTION); + + private final Context mContext; + private final BottomSheetController mBottomSheetController; + private final ScrimView mScrimView; + private final GetCurrentTab mGetCurrentTab; + private final AutofillAssistantModuleEntryProvider mModuleEntryProvider; + + @Nullable + private AutofillAssistantActionHandler mDelegate; + + AutofillAssistantDirectActionHandler(Context context, + BottomSheetController bottomSheetController, ScrimView scrimView, + GetCurrentTab getCurrentTab, AutofillAssistantModuleEntryProvider moduleEntryProvider) { + mContext = context; + mBottomSheetController = bottomSheetController; + mScrimView = scrimView; + mGetCurrentTab = getCurrentTab; + mModuleEntryProvider = moduleEntryProvider; + } + + @Override + public void reportAvailableDirectActions(DirectActionReporter reporter) { + reporter.addDirectAction(LIST_AA_ACTIONS).withResult(LIST_AA_ACTIONS_RESULT, Type.STRING); + + reporter.addDirectAction(PERFORM_AA_ACTION) + .withParameter(ACTION_NAME, Type.STRING, /* required= */ false) + .withParameter(EXPERIMENT_IDS, Type.STRING, /* required= */ false) + .withResult(PERFORM_AA_ACTION_RESULT, Type.BOOLEAN); + } + + @Override + public boolean performDirectAction( + String actionId, Bundle arguments, Callback<Bundle> callback) { + if (actionId.equals(LIST_AA_ACTIONS)) { + listActions(arguments, callback); + return true; + } + if (actionId.equals(PERFORM_AA_ACTION)) { + performAction(arguments, callback); + return true; + } + return false; + } + + private void listActions(Bundle arguments, Callback<Bundle> bundleCallback) { + Callback<Set<String>> namesCallback = (names) -> { + Bundle bundle = new Bundle(); + bundle.putString(LIST_AA_ACTIONS_RESULT, TextUtils.join(",", names)); + bundleCallback.onResult(bundle); + }; + + if (!AutofillAssistantPreferencesUtil.isAutofillOnboardingAccepted()) { + namesCallback.onResult(FALLBACK_ACTION_SET); + return; + } + + String experimentIds = arguments.getString(EXPERIMENT_IDS, ""); + arguments.remove(EXPERIMENT_IDS); + + getDelegate(/* installIfNecessary= */ false, (delegate) -> { + if (delegate == null) { + namesCallback.onResult(FALLBACK_ACTION_SET); + return; + } + delegate.listActions(experimentIds, arguments, namesCallback); + }); + } + + private void performAction(Bundle arguments, Callback<Bundle> bundleCallback) { + Callback<Boolean> booleanCallback = (result) -> { + Bundle bundle = new Bundle(); + bundle.putBoolean(PERFORM_AA_ACTION_RESULT, result); + bundleCallback.onResult(bundle); + }; + String name = arguments.getString(ACTION_NAME, ""); + arguments.remove(ACTION_NAME); + + String experimentIds = arguments.getString(EXPERIMENT_IDS, ""); + arguments.remove(EXPERIMENT_IDS); + + getDelegate(/* installIfNecessary= */ true, (delegate) -> { + if (delegate == null) { + booleanCallback.onResult(false); + return; + } + if (ONBOARDING_ACTION.equals(name)) { + delegate.performOnboarding(experimentIds, booleanCallback); + return; + } + delegate.performAction(name, experimentIds, arguments, booleanCallback); + }); + } + + /** + * Builds the delegate, if possible, and pass it to the callback. + * + * <p>If necessary, this function creates a delegate instance and keeps it in {@link + * #mDelegate}. + * + * @param installIfNecessary if true, install the DFM if necessary + * @param callback callback to report the delegate to + */ + private void getDelegate( + boolean installIfNecessary, Callback<AutofillAssistantActionHandler> callback) { + if (mDelegate == null) { + mDelegate = createDelegate(mModuleEntryProvider.getModuleEntryIfInstalled(mContext)); + } + if (mDelegate != null || !installIfNecessary) { + callback.onResult(mDelegate); + return; + } + + Tab tab = mGetCurrentTab.get(); + if (tab == null) { + // TODO(b/134741524): Allow DFM loading UI to work with no tabs. + callback.onResult(null); + return; + } + mModuleEntryProvider.getModuleEntry(mContext, tab, (entry) -> { + mDelegate = createDelegate(entry); + callback.onResult(mDelegate); + }); + } + + /** Creates a delegate from the given {@link AutofillAssistantModuleEntry}, if possible. */ + @Nullable + private AutofillAssistantActionHandler createDelegate( + @Nullable AutofillAssistantModuleEntry entry) { + if (entry == null) return null; + + return entry.createActionHandler( + mContext, mBottomSheetController, mScrimView, mGetCurrentTab); + } +}
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantFacade.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantFacade.java index 8b0df5d..33ca361 100644 --- a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantFacade.java +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantFacade.java
@@ -108,19 +108,22 @@ // Have an "attempted starts" baseline for the drop out histogram. AutofillAssistantMetrics.recordDropOut(DropOutReason.AA_START); waitForTabWithWebContents(activity, tab -> { - AutofillAssistantModuleEntryProvider.getModuleEntry(activity, tab, (moduleEntry) -> { - if (moduleEntry == null) { - AutofillAssistantMetrics.recordDropOut(DropOutReason.DFM_INSTALL_FAILED); - return; - } + AutofillAssistantModuleEntryProvider.INSTANCE.getModuleEntry( + activity, tab, (moduleEntry) -> { + if (moduleEntry == null) { + AutofillAssistantMetrics.recordDropOut( + DropOutReason.DFM_INSTALL_FAILED); + return; + } - Bundle bundleExtras = activity.getInitialIntent().getExtras(); - Map<String, String> parameters = extractParameters(bundleExtras); - parameters.remove(PARAMETER_ENABLED); - String initialUrl = activity.getInitialIntent().getDataString(); - moduleEntry.start(tab, tab.getWebContents(), canStartWithoutOnboarding, initialUrl, - parameters, experimentIds, activity.getInitialIntent().getExtras()); - }); + Bundle bundleExtras = activity.getInitialIntent().getExtras(); + Map<String, String> parameters = extractParameters(bundleExtras); + parameters.remove(PARAMETER_ENABLED); + String initialUrl = activity.getInitialIntent().getDataString(); + moduleEntry.start(tab, tab.getWebContents(), canStartWithoutOnboarding, + initialUrl, parameters, experimentIds, + activity.getInitialIntent().getExtras()); + }); }); } @@ -145,8 +148,10 @@ public static DirectActionHandler createDirectActionHandler(Context context, BottomSheetController bottomSheetController, ScrimView scrimView, TabModelSelector tabModelSelector) { - // TODO(crbug.com/959841): Implement AutofillAssistant support for direct actions. - return null; + // TODO(b/134740534): Consider restricting signature of createDirectActionHandler() to get + // only getCurrentTab instead of a TabModelSelector. + return new AutofillAssistantDirectActionHandler(context, bottomSheetController, scrimView, + tabModelSelector::getCurrentTab, AutofillAssistantModuleEntryProvider.INSTANCE); } /**
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntry.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntry.java index 590dc7b..0db82be9 100644 --- a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntry.java +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntry.java
@@ -4,10 +4,13 @@ package org.chromium.chrome.browser.autofill_assistant; +import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.widget.ScrimView; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; import org.chromium.components.module_installer.ModuleInterface; import org.chromium.content_public.browser.WebContents; @@ -29,4 +32,16 @@ void start(@NonNull Tab tab, @NonNull WebContents webContents, boolean skipOnboarding, String initialUrl, Map<String, String> parameters, String experimentIds, Bundle intentExtras); + /** + * Returns a {@link AutofillAssistantActionHandler} instance tied to the activity owning the + * given bottom sheet, and scrim view. + * + * @param context activity context + * @param bottomSheetController bottom sheet controller instance of the activity + * @param scrimView scrim view of the activity + * @param getCurrentTab a way to get the activity's current tab, if there is any + */ + AutofillAssistantActionHandler createActionHandler(Context context, + BottomSheetController bottomSheetController, ScrimView scrimView, + GetCurrentTab getCurrentTab); }
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java index 991c3f0..08b77481 100644 --- a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java
@@ -23,9 +23,17 @@ public class AutofillAssistantModuleEntryProvider { private static final String TAG = "AutofillAssistant"; + /** + * The real singleton instances. Using an instance instead of static methods allows modifying + * method implementation during tests. Outside of tests, this is the only instance that should + * exist. + */ + static final AutofillAssistantModuleEntryProvider INSTANCE = + new AutofillAssistantModuleEntryProvider(); + /* Returns the AA module entry, if it is already installed. */ @Nullable - /* package */ static AutofillAssistantModuleEntry getModuleEntryIfInstalled(Context context) { + /* package */ AutofillAssistantModuleEntry getModuleEntryIfInstalled(Context context) { // Required to access resources in DFM using this activity as context. ModuleInstaller.getInstance().initActivity(context); if (AutofillAssistantModule.isInstalled()) { @@ -35,7 +43,7 @@ } /** Gets the AA module entry, installing it if necessary. */ - /* package */ static void getModuleEntry( + /* package */ void getModuleEntry( Context context, Tab tab, Callback<AutofillAssistantModuleEntry> callback) { AutofillAssistantModuleEntry entry = getModuleEntryIfInstalled(context); if (entry != null) {
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/GetCurrentTab.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/GetCurrentTab.java new file mode 100644 index 0000000..9d93003 --- /dev/null +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/GetCurrentTab.java
@@ -0,0 +1,15 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill_assistant; + +import android.support.annotation.Nullable; + +import org.chromium.chrome.browser.tab.Tab; + +/** Return the activity's current tab or {@code null}. */ +interface GetCurrentTab { + @Nullable + Tab get(); +}
diff --git a/chrome/android/features/autofill_assistant/public/java_sources.gni b/chrome/android/features/autofill_assistant/public/java_sources.gni index 357f8ea..fd90a03 100644 --- a/chrome/android/features/autofill_assistant/public/java_sources.gni +++ b/chrome/android/features/autofill_assistant/public/java_sources.gni
@@ -8,4 +8,7 @@ "//chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntry.java", "//chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java", "//chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantPreferencesUtil.java", + "//chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDirectActionHandler.java", + "//chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantActionHandler.java", + "//chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/GetCurrentTab.java", ]
diff --git a/chrome/android/feed/core/DEPS b/chrome/android/feed/core/DEPS index 4e70c352..49d9287 100644 --- a/chrome/android/feed/core/DEPS +++ b/chrome/android/feed/core/DEPS
@@ -1,4 +1,5 @@ include_rules = [ + "+chrome/lib/lifecycle/public", "+components/background_task_scheduler", "+components/feature_engagement", "+components/feed",
diff --git a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java index 05cb422..c486a0d 100644 --- a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java +++ b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java
@@ -32,11 +32,13 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ActivityTabProvider; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.GlobalDiscardableReferencePool; import org.chromium.chrome.browser.feed.action.FeedActionHandler; import org.chromium.chrome.browser.feed.tooltip.BasicTooltipApi; import org.chromium.chrome.browser.gesturenav.HistoryNavigationLayout; +import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; import org.chromium.chrome.browser.native_page.ContextMenuManager; import org.chromium.chrome.browser.native_page.NativePageHost; import org.chromium.chrome.browser.ntp.NewTabPage; @@ -257,10 +259,15 @@ * @param activity The containing {@link ChromeActivity}. * @param nativePageHost The host for this native page. * @param tabModelSelector The {@link TabModelSelector} for the containing activity. + * @param activityTabProvider Allows us to check if we are the current tab. + * @param activityLifecycleDispatcher Allows us to subscribe to backgrounding events. */ public FeedNewTabPage(ChromeActivity activity, NativePageHost nativePageHost, - TabModelSelector tabModelSelector, SigninManager signinManager) { - super(activity, nativePageHost, tabModelSelector); + TabModelSelector tabModelSelector, SigninManager signinManager, + ActivityTabProvider activityTabProvider, + ActivityLifecycleDispatcher activityLifecycleDispatcher) { + super(activity, nativePageHost, tabModelSelector, activityTabProvider, + activityLifecycleDispatcher); Resources resources = activity.getResources(); mDefaultMargin =
diff --git a/chrome/android/java/monochrome_public_bundle.proguard_flags.expected b/chrome/android/java/monochrome_public_bundle.proguard_flags.expected index b830f18..7b7d0d25 100644 --- a/chrome/android/java/monochrome_public_bundle.proguard_flags.expected +++ b/chrome/android/java/monochrome_public_bundle.proguard_flags.expected
@@ -358,18 +358,9 @@ # found in the LICENSE file. # Classes are created via reflection and persisted across app updates, so their -# class names must not be obfuscated. --keepnames class ** implements org.chromium.components.background_task_scheduler.BackgroundTask {} - -# Also need to keep their default constructors. --keepclassmembers class ** implements org.chromium.components.background_task_scheduler.BackgroundTask { - public <init>(); -} - -# TODO(agrieve): Delete this rule once r8 is fixed to not discard -# GCMBackgroundTask.<init>() with only the above rules. -# https://issuetracker.google.com/issues/137890409 --keep class ** implements org.chromium.components.background_task_scheduler.BackgroundTask { +# class names must not be obfuscated, and constructors kept. +-if class ** implements org.chromium.components.background_task_scheduler.BackgroundTask +-keep class <1> { public <init>(); }
diff --git a/chrome/android/java/res/xml/sync_and_services_preferences.xml b/chrome/android/java/res/xml/sync_and_services_preferences.xml index 8dd1fd32..d8879875 100644 --- a/chrome/android/java/res/xml/sync_and_services_preferences.xml +++ b/chrome/android/java/res/xml/sync_and_services_preferences.xml
@@ -27,6 +27,11 @@ android:key="sync_error_card" android:layout="@layout/account_management_account_row" android:title="@string/sync_error_card_title"/> + <Preference + android:key="sync_disabled_by_administrator" + android:layout="@layout/account_management_account_row" + android:title="@string/sync_is_disabled_by_administrator"/> + <org.chromium.chrome.browser.preferences.ChromeSwitchPreference android:key="sync_requested" android:title="@string/sync_switch_title"
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/IntentHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/IntentHandler.java index 341b3f2..3f919981 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/IntentHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/IntentHandler.java
@@ -33,7 +33,6 @@ import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; -import org.chromium.chrome.browser.browserservices.BrowserSessionContentUtils; import org.chromium.chrome.browser.document.ChromeLauncherActivity; import org.chromium.chrome.browser.externalauth.ExternalAuthUtils; import org.chromium.chrome.browser.externalnav.ExternalNavigationDelegateImpl; @@ -532,8 +531,8 @@ } else if (isValidReferrerHeader(referrerExtra)) { return referrerExtra.toString(); } else if (IntentHandler.notSecureIsIntentChromeOrFirstParty(intent) - || BrowserSessionContentUtils.canActiveContentHandlerUseReferrer( - intent, referrerExtra)) { + || ChromeApplication.getComponent().resolveSessionDataHolder() + .canActiveHandlerUseReferrer(intent, referrerExtra)) { return referrerExtra.toString(); } return null;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java b/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java index 9946ca7..162fc3ca 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java
@@ -26,7 +26,7 @@ import org.chromium.base.StrictModeContext; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.metrics.CachedMetrics; -import org.chromium.chrome.browser.browserservices.BrowserSessionContentUtils; +import org.chromium.chrome.browser.browserservices.SessionDataHolder; import org.chromium.chrome.browser.browserservices.trustedwebactivityui.splashscreen.TwaSplashController; import org.chromium.chrome.browser.customtabs.CustomTabActivity; import org.chromium.chrome.browser.customtabs.CustomTabIntentDataProvider; @@ -304,7 +304,7 @@ // - Multiple clients hosting CCTs, // - Multiwindow mode. Class<? extends Activity> handlerClass = - BrowserSessionContentUtils.getActiveHandlerClassInCurrentTask(intent, context); + getSessionDataHolder().getActiveHandlerClassInCurrentTask(intent, context); if (handlerClass != null) { newIntent.setClassName(context, handlerClass.getName()); newIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | @@ -383,6 +383,10 @@ return newIntent; } + private static SessionDataHolder getSessionDataHolder() { + return ChromeApplication.getComponent().resolveSessionDataHolder(); + } + /** * Handles launching a {@link CustomTabActivity}, which will sit on top of a client's activity * in the same task. @@ -394,7 +398,7 @@ // The old way of delivering intents relies on calling the activity directly via a // static reference. It doesn't allow using CLEAR_TOP, and also doesn't work when an // intent brings the task to foreground. The condition above is a temporary safety net. - boolean handled = BrowserSessionContentUtils.handleBrowserServicesIntent(mIntent); + boolean handled = getSessionDataHolder().handleIntent(mIntent); if (handled) return; } maybePrefetchDnsInBackground(); @@ -418,7 +422,7 @@ // Allow disk writes during startActivity() to avoid strict mode violations on some // Samsung devices, see https://crbug.com/796548. - try (StrictModeContext smc = StrictModeContext.allowDiskWrites()) { + try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) { if (TwaSplashController.handleIntent(mActivity, launchIntent)) { return; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java index c582814..bdefd4e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java
@@ -4,242 +4,32 @@ package org.chromium.chrome.browser.browserservices; -import android.app.Activity; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; -import android.os.IBinder; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.customtabs.CustomTabsService; import android.support.customtabs.CustomTabsSessionToken; -import android.text.TextUtils; -import android.util.SparseArray; -import android.widget.RemoteViews; -import org.chromium.base.Callback; -import org.chromium.base.Log; -import org.chromium.base.ThreadUtils; -import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeApplication; -import org.chromium.chrome.browser.IntentHandler; -import org.chromium.chrome.browser.customtabs.CustomTabsConnection; -import org.chromium.chrome.browser.util.UrlConstants; -import org.chromium.content_public.browser.LoadUrlParams; /** - * Utilies for managing the active {@link BrowserSessionContentHandler}. This is an interface owned - * by the currently focused {@link ChromeActivity} has a linkage to a third party client app through - * a session. + * Remnants of the old class that ensure downstream doesn't get broken. To be removed soon. */ +@Deprecated public class BrowserSessionContentUtils { - private static final String TAG = "BrowserSession_Utils"; - private static final SparseArray<ContentHandlerData> sTaskIdToHandlerData = new SparseArray<>(); - - @Nullable - private static BrowserSessionContentHandler sActiveContentHandler; - - @Nullable - private static Callback<CustomTabsSessionToken> sSessionDisconnectCallback; - - /** - * The data associated with the content handler necessary to pass new intents to it. - */ - private static class ContentHandlerData { - public final CustomTabsSessionToken session; - - // Content handlers can reside in Activities of different types, so we need to store the - // Activity class to be able to route new intents into it. - public final Class<? extends Activity> activityClass; - - private ContentHandlerData(CustomTabsSessionToken session, - Class<? extends Activity> activityClass) { - this.session = session; - this.activityClass = activityClass; - } - } - - /** - * Sets the currently active {@link BrowserSessionContentHandler} in focus. - * @param contentHandler {@link BrowserSessionContentHandler} to set. - */ - public static void setActiveContentHandler( - @NonNull BrowserSessionContentHandler contentHandler) { - sActiveContentHandler = contentHandler; - CustomTabsSessionToken session = sActiveContentHandler.getSession(); - if (session != null) { - sTaskIdToHandlerData.append(sActiveContentHandler.getTaskId(), - new ContentHandlerData(session, sActiveContentHandler.getActivityClass())); - } - ensureSessionCleanUpOnDisconnects(); - } - - /** - * Notifies that given {@link BrowserSessionContentHandler} no longer has focus. - */ - public static void removeActiveContentHandler(BrowserSessionContentHandler contentHandler) { - if (sActiveContentHandler == contentHandler) { - sActiveContentHandler = null; - } // else this contentHandler has already been replaced. - - // Intentionally not removing from sTaskIdToHandlerData to handle cases when the task is - // brought to foreground by a new intent - the CCT might not be able to call - // setActiveContentHandler in time. - } - - /** - * Returns the class of Activity with a matching session running in the same task as the given - * intent is being launched from, or null if no such Activity present. - */ - @Nullable - public static Class<? extends Activity> getActiveHandlerClassInCurrentTask(Intent intent, - Context context) { - if (!(context instanceof Activity)) return null; - int taskId = ((Activity) context).getTaskId(); - ContentHandlerData handlerDataInCurrentTask = sTaskIdToHandlerData.get(taskId); - if (handlerDataInCurrentTask == null || !handlerDataInCurrentTask.session.equals( - CustomTabsSessionToken.getSessionTokenFromIntent(intent))) { - return null; - } - return handlerDataInCurrentTask.activityClass; - } - - /** - * Called when a Browser Services intent is handled. - * - * Used to check whether an incoming intent can be handled by the current - * {@link BrowserSessionContentHandler}, and to perform action on new Intent. - * - * @return Whether the active {@link BrowserSessionContentHandler} has handled the intent. - */ - public static boolean handleBrowserServicesIntent(Intent intent) { - String url = IntentHandler.getUrlFromIntent(intent); - if (TextUtils.isEmpty(url)) return false; - - CustomTabsSessionToken session = CustomTabsSessionToken.getSessionTokenFromIntent(intent); - return handleExternalIntent(intent, url, session); - } - - private static boolean handleExternalIntent(Intent intent, String url, - @Nullable CustomTabsSessionToken session) { - if (!sessionMatchesActiveContent(session)) return false; - if (sActiveContentHandler.shouldIgnoreIntent(intent)) { - Log.w(TAG, "Incoming intent to Custom Tab was ignored."); - return false; - } - sActiveContentHandler.loadUrlAndTrackFromTimestamp( - new LoadUrlParams(url), IntentHandler.getTimestampFromIntent(intent)); - return true; - } - - private static boolean sessionMatchesActiveContent(@Nullable CustomTabsSessionToken session) { - return session != null && sActiveContentHandler != null && - session.equals(sActiveContentHandler.getSession()); - } - - /** - * @return Whether the given session is the currently active session. - */ + /** See {@link SessionDataHolder#isActiveSession} */ public static boolean isActiveSession(CustomTabsSessionToken session) { - if (sActiveContentHandler == null) return false; - if (session == null || sActiveContentHandler.getSession() == null) return false; - return sActiveContentHandler.getSession().equals(session); + return getHolder().isActiveSession(session); } - /** - * Checks whether the given referrer can be used as valid within the Activity launched by the - * given intent. For this to be true, the intent should be for a {@link CustomTabsSessionToken} - * that is the currently in focus custom tab and also the related client should have a verified - * relationship with the referrer origin. This can only be true for https:// origins. - * - * @param intent The intent that was used to launch the Activity in question. - * @param referrer The referrer url that is to be used. - * @return Whether the given referrer is a valid first party url to the client that launched - * the activity. - */ - public static boolean canActiveContentHandlerUseReferrer(Intent intent, Uri referrer) { - if (sActiveContentHandler == null) return false; - CustomTabsSessionToken session = CustomTabsSessionToken.getSessionTokenFromIntent(intent); - if (session == null || !session.equals(sActiveContentHandler.getSession())) return false; - String packageName = - CustomTabsConnection.getInstance().getClientPackageNameForSession(session); - if (TextUtils.isEmpty(packageName)) return false; - boolean valid = OriginVerifier.wasPreviouslyVerified( - packageName, new Origin(referrer), CustomTabsService.RELATION_USE_AS_ORIGIN); - - // OriginVerifier should only be allowing https schemes. - assert valid == UrlConstants.HTTPS_SCHEME.equals(referrer.getScheme()); - - return valid; - } - - /** - * @return The url for the page displayed using the current {@link - * BrowserSessionContentHandler}. - */ + /** See {@link SessionDataHolder#getCurrentUrlForActiveBrowserSession} */ public static String getCurrentUrlForActiveBrowserSession() { - if (sActiveContentHandler == null) return null; - return sActiveContentHandler.getCurrentUrl(); + return getHolder().getCurrentUrlForActiveBrowserSession(); } - /** - * @return The pending url for the page about to be displayed using the current {@link - * BrowserSessionContentHandler}. - */ + /** See {@link SessionDataHolder#getPendingUrlForActiveBrowserSession} */ public static String getPendingUrlForActiveBrowserSession() { - if (sActiveContentHandler == null) return null; - return sActiveContentHandler.getPendingUrl(); + return getHolder().getPendingUrlForActiveBrowserSession(); } - /** - * Checks whether the active {@link BrowserSessionContentHandler} belongs to the given session, - * and if true, update toolbar's custom button. - * @param session The {@link IBinder} that the calling client represents. - * @param bitmap The new icon for action button. - * @param description The new content description for the action button. - * @return Whether the update is successful. - */ - public static boolean updateCustomButton( - CustomTabsSessionToken session, int id, Bitmap bitmap, String description) { - ThreadUtils.assertOnUiThread(); - // Do nothing if there is no activity or the activity does not belong to this session. - if (sActiveContentHandler == null || !sActiveContentHandler.getSession().equals(session)) { - return false; - } - return sActiveContentHandler.updateCustomButton(id, bitmap, description); - } - - /** - * Checks whether the active {@link BrowserSessionContentHandler} belongs to the given session, - * and if true, updates {@link RemoteViews} on the secondary toolbar. - * @return Whether the update is successful. - */ - public static boolean updateRemoteViews(CustomTabsSessionToken session, RemoteViews remoteViews, - int[] clickableIDs, PendingIntent pendingIntent) { - ThreadUtils.assertOnUiThread(); - // Do nothing if there is no activity or the activity does not belong to this session. - if (sActiveContentHandler == null || !sActiveContentHandler.getSession().equals(session)) { - return false; - } - return sActiveContentHandler.updateRemoteViews(remoteViews, clickableIDs, pendingIntent); - } - - private static void ensureSessionCleanUpOnDisconnects() { - if (sSessionDisconnectCallback != null) return; - sSessionDisconnectCallback = (session) -> { - if (session == null) { - return; - } - for (int i = 0; i < sTaskIdToHandlerData.size(); i++) { - if (session.equals(sTaskIdToHandlerData.valueAt(i).session)) { - sTaskIdToHandlerData.removeAt(i); - } - } - }; - ChromeApplication.getComponent().resolveCustomTabsConnection() - .setDisconnectCallback(sSessionDisconnectCallback); + private static SessionDataHolder getHolder() { + return ChromeApplication.getComponent().resolveSessionDataHolder(); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/SessionDataHolder.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/SessionDataHolder.java new file mode 100644 index 0000000..d819ca9 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/SessionDataHolder.java
@@ -0,0 +1,196 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.browserservices; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.customtabs.CustomTabsSessionToken; +import android.util.SparseArray; + +import org.chromium.base.Callback; +import org.chromium.chrome.browser.customtabs.CustomTabsConnection; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import dagger.Lazy; + +/** + * Holds the currently active {@link SessionHandler} and redirects relevant intents + * and calls into it. {@link SessionHandler} is an interface owned by the currently + * focused activity that has a linkage to a third party client app through a session. + */ +@Singleton +public class SessionDataHolder { + private final Lazy<CustomTabsConnection> mConnection; + private final SparseArray<SessionData> mTaskIdToSessionData = new SparseArray<>(); + + @Nullable + private SessionHandler mActiveContentHandler; + + @Nullable + private Callback<CustomTabsSessionToken> mSessionDisconnectCallback; + + @Inject + public SessionDataHolder(Lazy<CustomTabsConnection> connection) { + mConnection = connection; + } + + /** + * Data associated with a {@link SessionHandler} necessary to pass new intents to it. + */ + private static class SessionData { + public final CustomTabsSessionToken session; + + // Content handlers can reside in Activities of different types, so we need to store the + // Activity class to be able to route new intents into it. + public final Class<? extends Activity> activityClass; + + private SessionData(CustomTabsSessionToken session, + Class<? extends Activity> activityClass) { + this.session = session; + this.activityClass = activityClass; + } + } + + /** + * Sets the currently active {@link SessionHandler} in focus. + * @param contentHandler {@link SessionHandler} to set. + */ + public void setActiveHandler(@NonNull SessionHandler contentHandler) { + mActiveContentHandler = contentHandler; + CustomTabsSessionToken session = contentHandler.getSession(); + if (session == null) return; + + mTaskIdToSessionData.append(contentHandler.getTaskId(), + new SessionData(session, contentHandler.getActivityClass())); + ensureSessionCleanUpOnDisconnects(); + } + + /** + * Notifies that given {@link SessionHandler} no longer has focus. + */ + public void removeActiveHandler(SessionHandler contentHandler) { + if (mActiveContentHandler == contentHandler) { + mActiveContentHandler = null; + } // else this contentHandler has already been replaced. + + // Intentionally not removing from mTaskIdToSessionData to handle cases when the task is + // brought to foreground by a new intent - the CCT might not be able to call + // setActiveHandler in time. + } + + /** + * Returns the class of Activity with a matching session running in the same task as the given + * intent is being launched from, or null if no such Activity present. + */ + @Nullable + public Class<? extends Activity> getActiveHandlerClassInCurrentTask(Intent intent, + Context context) { + if (!(context instanceof Activity)) return null; + int taskId = ((Activity) context).getTaskId(); + SessionData handlerDataInCurrentTask = mTaskIdToSessionData.get(taskId); + if (handlerDataInCurrentTask == null || !handlerDataInCurrentTask.session.equals( + CustomTabsSessionToken.getSessionTokenFromIntent(intent))) { + return null; + } + return handlerDataInCurrentTask.activityClass; + } + + /** + * Attempts to handle an Intent. + * + * Checks whether an incoming intent can be handled by the current {@link SessionHandler}, and + * if so, delegates the handling to it. + * + * @return Whether the active {@link SessionHandler} has handled the intent. + */ + public boolean handleIntent(Intent intent) { + SessionHandler handler = getActiveHandlerForIntent(intent); + return handler != null && handler.handleIntent(intent); + } + + /** + * Returns whether the given session is the currently active session. + */ + public boolean isActiveSession(@Nullable CustomTabsSessionToken session) { + return getActiveHandler(session) != null; + } + + /** + * Returns the active session handler if it is associated with given session, null otherwise. + */ + @Nullable + public SessionHandler getActiveHandler(@Nullable CustomTabsSessionToken session) { + if (mActiveContentHandler == null) return null; + CustomTabsSessionToken activeSession = mActiveContentHandler.getSession(); + if (activeSession == null || !activeSession.equals(session)) return null; + return mActiveContentHandler; + } + + @Nullable + private SessionHandler getActiveHandlerForIntent(Intent intent) { + return getActiveHandler(CustomTabsSessionToken.getSessionTokenFromIntent(intent)); + } + + /** + * Checks whether the given referrer can be used as valid within the Activity launched by the + * given intent. For this to be true, the intent should be for a {@link CustomTabsSessionToken} + * that is the currently in focus custom tab and also the related client should have a verified + * relationship with the referrer origin. This can only be true for https:// origins. + * + * @param intent The intent that was used to launch the Activity in question. + * @param referrer The referrer url that is to be used. + * @return Whether the given referrer is a valid first party url to the client that launched + * the activity. + */ + public boolean canActiveHandlerUseReferrer(Intent intent, Uri referrer) { + SessionHandler handler = getActiveHandlerForIntent(intent); + return handler != null && handler.canUseReferrer(referrer); + } + + /** + * @return The url for the page displayed using the current {@link + * SessionHandler}. + * + * @deprecated This will be removed once downstream usages change. + */ + @Deprecated + public String getCurrentUrlForActiveBrowserSession() { + if (mActiveContentHandler == null) return null; + return mActiveContentHandler.getCurrentUrl(); + } + + /** + * @return The pending url for the page about to be displayed using the current {@link + * SessionHandler}. + * + * @deprecated This will be removed once downstream usages change. + */ + @Deprecated + public String getPendingUrlForActiveBrowserSession() { + if (mActiveContentHandler == null) return null; + return mActiveContentHandler.getPendingUrl(); + } + + private void ensureSessionCleanUpOnDisconnects() { + if (mSessionDisconnectCallback != null) return; + mSessionDisconnectCallback = (session) -> { + if (session == null) { + return; + } + for (int i = 0; i < mTaskIdToSessionData.size(); i++) { + if (session.equals(mTaskIdToSessionData.valueAt(i).session)) { + mTaskIdToSessionData.removeAt(i); + } + } + }; + mConnection.get().setDisconnectCallback(mSessionDisconnectCallback); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/SessionHandler.java similarity index 67% rename from chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentHandler.java rename to chrome/android/java/src/org/chromium/chrome/browser/browserservices/SessionHandler.java index 2ac7b47..fcc8cc95 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/SessionHandler.java
@@ -8,40 +8,23 @@ import android.app.PendingIntent; import android.content.Intent; import android.graphics.Bitmap; +import android.net.Uri; import android.support.annotation.Nullable; import android.support.customtabs.CustomTabsSessionToken; import android.widget.RemoteViews; -import org.chromium.content_public.browser.LoadUrlParams; - /** * Interface to handle browser services calls whenever the session id matched. * TODO(yusufo): Add a way to handle mayLaunchUrl as well. */ -public interface BrowserSessionContentHandler { - /** - * Loads a new url inside the {@link BrowserSessionContentHandler}, and tracks - * its load time. - * - * @param params The params to use while loading the url. - * @param timestamp The intent arrival timestamp, as returned by - * {@link SystemClock#elapsedRealtime()}. - */ - void loadUrlAndTrackFromTimestamp(LoadUrlParams params, long timestamp); +public interface SessionHandler { /** - * @return The session this {@link BrowserSessionContentHandler} is associated with. + * @return The session this {@link SessionHandler} is associated with. */ CustomTabsSessionToken getSession(); /** - * Check whether an intent is valid or should be ignored within this content handler. - * @param intent The intent to check. - * @return Whether the intent should be ignored. - */ - boolean shouldIgnoreIntent(Intent intent); - - /** * Finds the action button with the given id, and updates it with the new content. * @return Whether the action button has been updated. */ @@ -73,4 +56,16 @@ * @return the class of the Activity the content handler is running in. */ Class<? extends Activity> getActivityClass(); + + /** + * Attempts to handles a new intent (without starting a new activity). + * Returns whether has handled. + */ + boolean handleIntent(Intent intent); + + /** + * Checks whether the given referrer can be used as valid within the Activity hosting this + * handler. + */ + boolean canUseReferrer(Uri referrer); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index ce03ffe3..f3ac4ff9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -25,6 +25,7 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.customtabs.CustomTabsIntent; +import android.support.customtabs.CustomTabsService; import android.support.customtabs.CustomTabsSessionToken; import android.text.TextUtils; import android.util.Pair; @@ -50,8 +51,10 @@ import org.chromium.chrome.browser.LaunchIntentDispatcher; import org.chromium.chrome.browser.appmenu.AppMenuPropertiesDelegate; import org.chromium.chrome.browser.autofill_assistant.AutofillAssistantFacade; -import org.chromium.chrome.browser.browserservices.BrowserSessionContentHandler; -import org.chromium.chrome.browser.browserservices.BrowserSessionContentUtils; +import org.chromium.chrome.browser.browserservices.Origin; +import org.chromium.chrome.browser.browserservices.OriginVerifier; +import org.chromium.chrome.browser.browserservices.SessionDataHolder; +import org.chromium.chrome.browser.browserservices.SessionHandler; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityTabController; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityTabFactory; @@ -106,7 +109,7 @@ private CustomTabIntentDataProvider mIntentDataProvider; private CustomTabsSessionToken mSession; - private BrowserSessionContentHandler mBrowserSessionContentHandler; + private SessionHandler mSessionHandler; private CustomTabBottomBarDelegate mBottomBarDelegate; private CustomTabActivityTabController mTabController; private CustomTabActivityTabProvider mTabProvider; @@ -114,6 +117,7 @@ private CustomTabActivityNavigationController mNavigationController; private CustomTabStatusBarColorProvider mCustomTabStatusBarColorProvider; private CustomTabToolbarCoordinator mToolbarCoordinator; + private SessionDataHolder mSessionDataHolder; // This is to give the right package name while using the client's resources during an // overridePendingTransition call. @@ -300,15 +304,7 @@ mDynamicModuleCoordinator = getComponent().resolveDynamicModuleCoordinator(); } - mBrowserSessionContentHandler = new BrowserSessionContentHandler() { - @Override - public void loadUrlAndTrackFromTimestamp(LoadUrlParams params, long timestamp) { - if (!TextUtils.isEmpty(params.getUrl())) { - params.setUrl(DataReductionProxySettings.getInstance() - .maybeRewriteWebliteUrl(params.getUrl())); - } - mNavigationController.navigate(params, timestamp); - } + mSessionHandler = new SessionHandler() { @Override public CustomTabsSessionToken getSession() { @@ -316,11 +312,6 @@ } @Override - public boolean shouldIgnoreIntent(Intent intent) { - return mIntentHandler.shouldIgnoreIntent(intent); - } - - @Override public boolean updateCustomButton(int id, Bitmap bitmap, String description) { CustomButtonParams params = mIntentDataProvider.getButtonParamsForId(id); if (params == null) { @@ -369,6 +360,31 @@ public Class<? extends Activity> getActivityClass() { return CustomTabActivity.this.getClass(); } + + @Override + public boolean handleIntent(Intent intent) { + if (mIntentHandler.shouldIgnoreIntent(intent)) { + Log.w(TAG, "Incoming intent to Custom Tab was ignored."); + return false; + } + String url = IntentHandler.getUrlFromIntent(intent); + if (TextUtils.isEmpty(url)) return false; + LoadUrlParams params = new LoadUrlParams(url); + + params.setUrl(DataReductionProxySettings.getInstance() + .maybeRewriteWebliteUrl(params.getUrl())); + mNavigationController.navigate(params, + IntentHandler.getTimestampFromIntent(intent)); + return true; + } + + @Override + public boolean canUseReferrer(Uri referrer) { + String packageName = mConnection.getClientPackageNameForSession(mSession); + if (TextUtils.isEmpty(packageName)) return false; + return OriginVerifier.wasPreviouslyVerified( + packageName, new Origin(referrer), CustomTabsService.RELATION_USE_AS_ORIGIN); + } }; mConnection.showSignInToastIfNecessary(mSession, getIntent()); @@ -404,8 +420,8 @@ @Override public void onNewIntentWithNative(Intent intent) { super.onNewIntentWithNative(intent); - BrowserSessionContentUtils.setActiveContentHandler(mBrowserSessionContentHandler); - if (!BrowserSessionContentUtils.handleBrowserServicesIntent(intent)) { + mSessionDataHolder.setActiveHandler(mSessionHandler); + if (!mSessionDataHolder.handleIntent(intent)) { int flagsToRemove = Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP; intent.setFlags(intent.getFlags() & ~flagsToRemove); startActivity(intent); @@ -433,7 +449,7 @@ @Override public void onStartWithNative() { super.onStartWithNative(); - BrowserSessionContentUtils.setActiveContentHandler(mBrowserSessionContentHandler); + mSessionDataHolder.setActiveHandler(mSessionHandler); @TabCreationMode int mode = mTabProvider.getInitialTabCreationMode(); boolean earlyCreatedTabIsReady = (mode == TabCreationMode.HIDDEN || mode == TabCreationMode.EARLY) @@ -444,7 +460,7 @@ @Override public void onStopWithNative() { super.onStopWithNative(); - BrowserSessionContentUtils.removeActiveContentHandler(mBrowserSessionContentHandler); + mSessionDataHolder.removeActiveHandler(mSessionHandler); } @Override @@ -770,6 +786,7 @@ handleFinishAndClose(); }); component.resolveInitialPageLoader(); + mSessionDataHolder = component.getParent().resolveSessionDataHolder(); if (mIntentDataProvider.isTrustedWebActivity()) { component.resolveTrustedWebActivityCoordinator();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java index 353c194..1a0f1ba 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java
@@ -53,7 +53,8 @@ import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.WarmupManager; -import org.chromium.chrome.browser.browserservices.BrowserSessionContentUtils; +import org.chromium.chrome.browser.browserservices.SessionHandler; +import org.chromium.chrome.browser.browserservices.SessionDataHolder; import org.chromium.chrome.browser.browserservices.Origin; import org.chromium.chrome.browser.browserservices.PostMessageHandler; import org.chromium.chrome.browser.customtabs.dynamicmodule.ModuleLoader; @@ -200,6 +201,7 @@ private final HiddenTabHolder mHiddenTabHolder = new HiddenTabHolder(); /** @deprecated Use {@link ContextUtils} instead */ protected final Context mContext; + protected final SessionDataHolder mSessionDataHolder; @VisibleForTesting final ClientManager mClientManager; protected final boolean mLogRequests; @@ -226,6 +228,8 @@ mContext = ContextUtils.getApplicationContext(); mClientManager = new ClientManager(); mLogRequests = CommandLine.getInstance().hasSwitch(LOG_SERVICE_REQUESTS); + mSessionDataHolder = + ChromeApplication.getComponent().resolveSessionDataHolder(); } /** @@ -610,6 +614,9 @@ public boolean updateVisuals(final CustomTabsSessionToken session, Bundle bundle) { if (mLogRequests) Log.w(TAG, "updateVisuals: %s", bundleToJson(bundle)); + SessionHandler handler = mSessionDataHolder.getActiveHandler(session); + if (handler == null) return false; + final Bundle actionButtonBundle = IntentUtils.safeGetBundle(bundle, CustomTabsIntent.EXTRA_ACTION_BUTTON_BUNDLE); boolean result = true; @@ -653,8 +660,8 @@ result &= PostTask.runSynchronously(UiThreadTaskTraits.DEFAULT, () -> { boolean res = true; for (int i = 0; i < ids.size(); i++) { - res &= BrowserSessionContentUtils.updateCustomButton( - session, ids.get(i), icons.get(i), descriptions.get(i)); + res &= handler.updateCustomButton(ids.get(i), icons.get(i), + descriptions.get(i)); } return res; }); @@ -667,10 +674,9 @@ CustomTabsIntent.EXTRA_REMOTEVIEWS_VIEW_IDS); final PendingIntent pendingIntent = IntentUtils.safeGetParcelable(bundle, CustomTabsIntent.EXTRA_REMOTEVIEWS_PENDINGINTENT); - result &= PostTask.runSynchronously(UiThreadTaskTraits.DEFAULT, () -> { - return BrowserSessionContentUtils.updateRemoteViews( - session, remoteViews, clickableIDs, pendingIntent); - }); + result &= PostTask.runSynchronously(UiThreadTaskTraits.DEFAULT, () -> + handler.updateRemoteViews(remoteViews, clickableIDs, pendingIntent) + ); } logCall("updateVisuals()", result); return result; @@ -687,7 +693,7 @@ private boolean requestPostMessageChannelInternal(final CustomTabsSessionToken session, final Origin postMessageOrigin) { if (!mWarmupHasBeenCalled.get()) return false; - if (!isCallerForegroundOrSelf() && !BrowserSessionContentUtils.isActiveSession(session)) { + if (!isCallerForegroundOrSelf() && !mSessionDataHolder.isActiveSession(session)) { return false; } if (!mClientManager.bindToPostMessageServiceForSession(session)) return false; @@ -728,7 +734,7 @@ public int postMessage(CustomTabsSessionToken session, String message, Bundle extras) { int result; if (!mWarmupHasBeenCalled.get()) result = CustomTabsService.RESULT_FAILURE_DISALLOWED; - if (!isCallerForegroundOrSelf() && !BrowserSessionContentUtils.isActiveSession(session)) { + if (!isCallerForegroundOrSelf() && !mSessionDataHolder.isActiveSession(session)) { result = CustomTabsService.RESULT_FAILURE_DISALLOWED; } // If called before a validatePostMessageOrigin, the post message origin will be invalid and @@ -1260,7 +1266,7 @@ String controllerName = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? "cpuset" : "cpu"; // Reading from /proc does not cause disk IO, but strict mode doesn't like it. // crbug.com/567143 - try (StrictModeContext ctx = StrictModeContext.allowDiskReads(); + try (StrictModeContext ignored = StrictModeContext.allowDiskReads(); BufferedReader reader = new BufferedReader(new FileReader(cgroupFilename))) { String line = null; while ((line = reader.readLine()) != null) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/ChromeAppComponent.java b/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/ChromeAppComponent.java index c881e96..a2976f4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/ChromeAppComponent.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/ChromeAppComponent.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.dependency_injection; import org.chromium.chrome.browser.AppHooksModule; +import org.chromium.chrome.browser.browserservices.SessionDataHolder; import org.chromium.chrome.browser.browserservices.ClearDataDialogResultRecorder; import org.chromium.chrome.browser.browserservices.TrustedWebActivityClient; import org.chromium.chrome.browser.browserservices.permissiondelegation.NotificationPermissionUpdater; @@ -41,4 +42,5 @@ ExternalAuthUtils resolveExternalAuthUtils(); CustomTabsClientFileProcessor resolveCustomTabsFileProcessor(); + SessionDataHolder resolveSessionDataHolder(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/native_page/NativePageFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/native_page/NativePageFactory.java index f367873..eb3a9ed 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/native_page/NativePageFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/native_page/NativePageFactory.java
@@ -8,6 +8,7 @@ import android.support.annotation.IntDef; import org.chromium.base.VisibleForTesting; +import org.chromium.chrome.browser.ActivityTabProvider; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.TabLoadStatus; @@ -17,6 +18,7 @@ import org.chromium.chrome.browser.feed.FeedNewTabPage; import org.chromium.chrome.browser.gesturenav.HistoryNavigationDelegate; import org.chromium.chrome.browser.history.HistoryPage; +import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; import org.chromium.chrome.browser.ntp.IncognitoNewTabPage; import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.ntp.RecentTabsManager; @@ -43,6 +45,10 @@ static class NativePageBuilder { protected NativePage buildNewTabPage(ChromeActivity activity, Tab tab, TabModelSelector tabModelSelector) { + ActivityTabProvider activityTabProvider = activity.getActivityTabProvider(); + ActivityLifecycleDispatcher activityLifecycleDispatcher = + activity.getLifecycleDispatcher(); + if (tab.isIncognito()) { return new IncognitoNewTabPage(activity, new TabShim(tab)); } @@ -53,10 +59,12 @@ if (ChromeFeatureList.isEnabled(ChromeFeatureList.INTEREST_FEED_CONTENT_SUGGESTIONS)) { return new FeedNewTabPage(activity, new TabShim(tab), tabModelSelector, - IdentityServicesProvider.getSigninManager()); + IdentityServicesProvider.getSigninManager(), activityTabProvider, + activityLifecycleDispatcher); } - return new NewTabPage(activity, new TabShim(tab), tabModelSelector); + return new NewTabPage(activity, new TabShim(tab), tabModelSelector, activityTabProvider, + activityLifecycleDispatcher); } protected NativePage buildBookmarksPage(ChromeActivity activity, Tab tab) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java index 7e9b56e1..4b09297e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java
@@ -25,11 +25,15 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ActivityTabProvider; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.GlobalDiscardableReferencePool; import org.chromium.chrome.browser.compositor.layouts.content.InvalidationAwareThumbnailProvider; import org.chromium.chrome.browser.download.DownloadManagerService; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; +import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; +import org.chromium.chrome.browser.lifecycle.LifecycleObserver; +import org.chromium.chrome.browser.lifecycle.PauseResumeWithNativeObserver; import org.chromium.chrome.browser.native_page.NativePage; import org.chromium.chrome.browser.native_page.NativePageHost; import org.chromium.chrome.browser.ntp.NewTabPageView.NewTabPageManager; @@ -81,6 +85,8 @@ public static final String CONTEXT_MENU_USER_ACTION_PREFIX = "Suggestions"; protected final Tab mTab; + private final ActivityTabProvider mActivityTabProvider; + private final ActivityLifecycleDispatcher mActivityLifecycleDispatcher; private final String mTitle; private final int mBackgroundColor; @@ -95,6 +101,7 @@ private @Nullable NewTabPageView mNewTabPageView; protected NewTabPageLayout mNewTabPageLayout; private TabObserver mTabObserver; + private LifecycleObserver mLifecycleObserver; protected boolean mSearchProviderHasLogo; protected FakeboxDelegate mFakeboxDelegate; @@ -283,12 +290,17 @@ * @param activity The activity used for context to create the new tab page's View. * @param nativePageHost The host that is showing this new tab page. * @param tabModelSelector The TabModelSelector used to open tabs. + * @param activityTabProvider Allows us to check if we are the current tab. + * @param activityLifecycleDispatcher Allows us to subscribe to backgrounding events. */ public NewTabPage(ChromeActivity activity, NativePageHost nativePageHost, - TabModelSelector tabModelSelector) { + TabModelSelector tabModelSelector, ActivityTabProvider activityTabProvider, + ActivityLifecycleDispatcher activityLifecycleDispatcher) { mConstructedTimeNs = System.nanoTime(); TraceEvent.begin(TAG); + mActivityTabProvider = activityTabProvider; + mActivityLifecycleDispatcher = activityLifecycleDispatcher; mTab = nativePageHost.getActiveTab(); Profile profile = mTab.getProfile(); @@ -334,8 +346,22 @@ } }; mTab.addObserver(mTabObserver); - updateSearchProviderHasLogo(); + mLifecycleObserver = new PauseResumeWithNativeObserver() { + @Override + public void onResumeWithNative() {} + + @Override + public void onPauseWithNative() { + // Only record when this tab is the current tab. + if (mActivityTabProvider.get() == mTab) { + RecordUserAction.record("MobileNTPPaused"); + } + } + }; + mActivityLifecycleDispatcher.register(mLifecycleObserver); + + updateSearchProviderHasLogo(); initializeMainView(activity, nativePageHost); mFullscreenManager = activity.getFullscreenManager(); @@ -681,6 +707,8 @@ TemplateUrlServiceFactory.get().removeObserver(this); mTab.removeObserver(mTabObserver); mTabObserver = null; + mActivityLifecycleDispatcher.unregister(mLifecycleObserver); + mLifecycleObserver = null; mFullscreenManager.removeListener(this); mIsDestroyed = true; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SyncAndServicesPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SyncAndServicesPreferences.java index 8363c9e..da27bedb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SyncAndServicesPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SyncAndServicesPreferences.java
@@ -41,8 +41,10 @@ import org.chromium.chrome.browser.help.HelpAndFeedback; import org.chromium.chrome.browser.invalidation.InvalidationController; import org.chromium.chrome.browser.metrics.UmaSessionStats; +import org.chromium.chrome.browser.preferences.ChromeBasePreference; import org.chromium.chrome.browser.preferences.ChromeSwitchPreference; import org.chromium.chrome.browser.preferences.ManagedPreferenceDelegate; +import org.chromium.chrome.browser.preferences.ManagedPreferencesUtils; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.preferences.PreferenceUtils; import org.chromium.chrome.browser.preferences.Preferences; @@ -84,7 +86,10 @@ private static final String PREF_SYNC_CATEGORY = "sync_category"; private static final String PREF_SYNC_ERROR_CARD = "sync_error_card"; + private static final String PREF_SYNC_DISABLED_BY_ADMINISTRATOR = + "sync_disabled_by_administrator"; private static final String PREF_SYNC_REQUESTED = "sync_requested"; + private static final String PREF_MANAGE_SYNC = "manage_sync"; private static final String PREF_SERVICES_CATEGORY = "services_category"; private static final String PREF_SEARCH_SUGGESTIONS = "search_suggestions"; @@ -122,7 +127,9 @@ private PreferenceCategory mSyncCategory; private Preference mSyncErrorCard; + private Preference mSyncDisabledByAdministrator; private ChromeSwitchPreference mSyncRequested; + private ChromeBasePreference mManageSync; private ChromeSwitchPreference mSearchSuggestions; private ChromeSwitchPreference mNavigationError; @@ -181,8 +188,12 @@ getActivity(), R.drawable.ic_sync_error_40dp, R.color.default_red)); mSyncErrorCard.setOnPreferenceClickListener( SyncPreferenceUtils.toOnClickListener(this, this::onSyncErrorCardClicked)); + mSyncDisabledByAdministrator = findPreference(PREF_SYNC_DISABLED_BY_ADMINISTRATOR); + mSyncDisabledByAdministrator.setIcon( + ManagedPreferencesUtils.getManagedByEnterpriseIconId()); mSyncRequested = (ChromeSwitchPreference) findPreference(PREF_SYNC_REQUESTED); mSyncRequested.setOnPreferenceChangeListener(this); + mManageSync = (ChromeBasePreference) findPreference(PREF_MANAGE_SYNC); mSearchSuggestions = (ChromeSwitchPreference) findPreference(PREF_SEARCH_SUGGESTIONS); mSearchSuggestions.setOnPreferenceChangeListener(this); @@ -524,8 +535,19 @@ getPreferenceScreen().removePreference(mSyncCategory); return; } + getPreferenceScreen().addPreference(mManageYourGoogleAccount); getPreferenceScreen().addPreference(mSyncCategory); + if (ProfileSyncService.get().isSyncDisabledByEnterprisePolicy()) { + mSyncCategory.addPreference(mSyncDisabledByAdministrator); + mSyncCategory.removePreference(mSyncErrorCard); + mSyncCategory.removePreference(mSyncRequested); + mSyncCategory.removePreference(mManageSync); + return; + } + mSyncCategory.removePreference(mSyncDisabledByAdministrator); + mSyncCategory.addPreference(mSyncRequested); + mSyncCategory.addPreference(mManageSync); mCurrentSyncError = getSyncError(); if (mCurrentSyncError == SyncError.NO_ERROR) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SyncPreferenceUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SyncPreferenceUtils.java index db2bbb5..00a257a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SyncPreferenceUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SyncPreferenceUtils.java
@@ -83,6 +83,10 @@ return res.getString(R.string.sync_is_disabled); } + if (profileSyncService.isSyncDisabledByEnterprisePolicy()) { + return res.getString(R.string.sync_is_disabled_by_administrator); + } + if (profileSyncService.getAuthError() != GoogleServiceAuthError.State.NONE) { return res.getString( GoogleServiceAuthError.getMessageID(profileSyncService.getAuthError())); @@ -124,6 +128,11 @@ context, R.drawable.ic_sync_green_40dp, R.color.default_icon_color); } + if (profileSyncService.isSyncDisabledByEnterprisePolicy()) { + return UiUtils.getTintedDrawable( + context, R.drawable.ic_sync_error_40dp, R.color.default_icon_color); + } + if (profileSyncService.isEngineInitialized() && (profileSyncService.hasUnrecoverableError() || profileSyncService.getAuthError() != GoogleServiceAuthError.State.NONE
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sharing/click_to_call/ClickToCallMessageHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/sharing/click_to_call/ClickToCallMessageHandler.java index 54d0fec..51decac 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sharing/click_to_call/ClickToCallMessageHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sharing/click_to_call/ClickToCallMessageHandler.java
@@ -16,6 +16,7 @@ import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.metrics.CachedMetrics; import org.chromium.chrome.R; import org.chromium.chrome.browser.notifications.ChromeNotification; import org.chromium.chrome.browser.notifications.ChromeNotificationBuilder; @@ -49,6 +50,8 @@ } dialIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ContextUtils.getApplicationContext().startActivity(dialIntent); + new CachedMetrics.BooleanHistogramSample("Sharing.ClickToCallDialIntent") + .record(TextUtils.isEmpty(phoneNumber)); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java index 5b50cb1..1d63693 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java
@@ -26,10 +26,12 @@ import org.chromium.base.annotations.NativeMethods; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.PostTask; import org.chromium.components.signin.AccountIdProvider; import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.AccountTrackerService; import org.chromium.components.signin.ChromeSigninController; +import org.chromium.content_public.browser.UiThreadTaskTraits; import java.util.ArrayList; import java.util.List; @@ -338,8 +340,7 @@ } private void notifySignInAllowedChanged() { - // TODO(crbug.com/981470) Use PostTask and CurrentThread traits. - ThreadUtils.postOnUiThread(() -> { + PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> { for (SignInAllowedObserver observer : mSignInAllowedObservers) { observer.onSignInAllowedChanged(); } @@ -523,15 +524,13 @@ mCallbacksWaitingForPendingOperation.add(runnable); return; } - // TODO(crbug.com/981470) Use PostTask and CurrentThread traits - ThreadUtils.postOnUiThread(runnable); + PostTask.postTask(UiThreadTaskTraits.DEFAULT, runnable); } private void notifyCallbacksWaitingForOperation() { ThreadUtils.assertOnUiThread(); for (Runnable callback : mCallbacksWaitingForPendingOperation) { - // TODO(crbug.com/981470) Use PostTask and CurrentThread traits. - ThreadUtils.postOnUiThread(callback); + PostTask.postTask(UiThreadTaskTraits.DEFAULT, callback); } mCallbacksWaitingForPendingOperation.clear(); } @@ -665,8 +664,7 @@ assert mSignOutState != null; if (mSignOutState.mCallback != null) { - // TODO(crbug.com/981470) Use PostTask and CurrentThread traits. - ThreadUtils.postOnUiThread(mSignOutState.mCallback); + PostTask.postTask(UiThreadTaskTraits.DEFAULT, mSignOutState.mCallback); } mSignOutState = null; notifyCallbacksWaitingForOperation();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/ProfileSyncService.java b/chrome/android/java/src/org/chromium/chrome/browser/sync/ProfileSyncService.java index f105055c..d14bb2f0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/ProfileSyncService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/ProfileSyncService.java
@@ -419,6 +419,16 @@ } /** + * Checks whether Sync is disabled by enterprise policy (through prefs) or account policy + * received from the sync server. + * + * @return true if Sync is disabled, false otherwise. + */ + public boolean isSyncDisabledByEnterprisePolicy() { + return nativeIsSyncDisabledByEnterprisePolicy(mNativeProfileSyncServiceAndroid); + } + + /** * Instances of this class keep sync paused until {@link #close} is called. Use * {@link ProfileSyncService#getSetupInProgressHandle} to create. Please note that * {@link #close} should be called on every instance of this class. @@ -650,6 +660,8 @@ private native boolean nativeIsSyncRequested(long nativeProfileSyncServiceAndroid); private native boolean nativeCanSyncFeatureStart(long nativeProfileSyncServiceAndroid); private native boolean nativeIsSyncActive(long nativeProfileSyncServiceAndroid); + private native boolean nativeIsSyncDisabledByEnterprisePolicy( + long nativeProfileSyncServiceAndroid); private native boolean nativeHasKeepEverythingSynced(long nativeProfileSyncServiceAndroid); private native boolean nativeHasUnrecoverableError(long nativeProfileSyncServiceAndroid); private native boolean nativeIsPassphrasePrompted(long nativeProfileSyncServiceAndroid);
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index d007442e..4ddbef68 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -1529,6 +1529,9 @@ <message name="IDS_SYNC_IS_DISABLED" desc="Message to show when Chrome sync is disabled"> Sync is off </message> + <message name="IDS_SYNC_IS_DISABLED_BY_ADMINISTRATOR" desc="Message to show when Chrome sync is disabled by administrator"> + Sync is disabled by your administrator + </message> <message name="IDS_SYNC_NEED_PASSPHRASE" desc="Error message when a passphrase is needed for decrypting sync data."> Passphrase required </message>
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_SYNC_IS_DISABLED_BY_ADMINISTRATOR.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SYNC_IS_DISABLED_BY_ADMINISTRATOR.png.sha1 new file mode 100644 index 0000000..05bf9b8 --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SYNC_IS_DISABLED_BY_ADMINISTRATOR.png.sha1
@@ -0,0 +1 @@ +e7410e31716cc905f8f717b839bf633ea6eaf94f \ No newline at end of file
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java index ec2bf52f..2dd5efa 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java
@@ -79,6 +79,7 @@ import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; +import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.ChromeTabbedActivity; @@ -88,7 +89,7 @@ import org.chromium.chrome.browser.appmenu.AppMenuCoordinator; import org.chromium.chrome.browser.appmenu.AppMenuHandler; import org.chromium.chrome.browser.appmenu.AppMenuTestSupport; -import org.chromium.chrome.browser.browserservices.BrowserSessionContentUtils; +import org.chromium.chrome.browser.browserservices.SessionDataHolder; import org.chromium.chrome.browser.browserservices.Origin; import org.chromium.chrome.browser.browserservices.OriginVerifier; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController.FinishReason; @@ -1167,7 +1168,7 @@ assertEquals(getActivity().getIntentDataProvider().getSession(), session); Assert.assertFalse("CustomTabContentHandler handled intent with wrong session", TestThreadUtils.runOnUiThreadBlockingNoException(() -> { - return BrowserSessionContentUtils.handleBrowserServicesIntent( + return getSessionDataHolder().handleIntent( CustomTabsTestUtils.createMinimalCustomTabIntent(context, mTestPage2)); })); CriteriaHelper.pollInstrumentationThread( @@ -1175,7 +1176,7 @@ Assert.assertTrue("CustomTabContentHandler can't handle intent with same session", TestThreadUtils.runOnUiThreadBlockingNoException(() -> { intent.setData(Uri.parse(mTestPage2)); - return BrowserSessionContentUtils.handleBrowserServicesIntent(intent); + return getSessionDataHolder().handleIntent(intent); })); final Tab tab = getActivity().getActivityTab(); final CallbackHelper pageLoadFinishedHelper = new CallbackHelper(); @@ -1249,7 +1250,8 @@ }); Assert.assertTrue("CustomTabContentHandler can't handle intent with same session", TestThreadUtils.runOnUiThreadBlockingNoException( - () -> BrowserSessionContentUtils.handleBrowserServicesIntent(intent))); + () -> getSessionDataHolder() + .handleIntent(intent))); pageLoadFinishedHelper.waitForCallback(0); } @@ -1289,7 +1291,8 @@ }); Assert.assertTrue("CustomTabContentHandler can't handle intent with same session", TestThreadUtils.runOnUiThreadBlockingNoException( - () -> BrowserSessionContentUtils.handleBrowserServicesIntent(intent))); + () -> getSessionDataHolder() + .handleIntent(intent))); pageLoadFinishedHelper.waitForCallback(0); } @@ -2887,4 +2890,8 @@ Tab currentTab = getActivity().getActivityTab(); ChromeTabUtils.waitForTitle(currentTab, newTitle); } + + private SessionDataHolder getSessionDataHolder() { + return ChromeApplication.getComponent().resolveSessionDataHolder(); + } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/browserservices/SessionDataHolderTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/browserservices/SessionDataHolderTest.java new file mode 100644 index 0000000..2297878 --- /dev/null +++ b/chrome/android/junit/src/org/chromium/chrome/browser/browserservices/SessionDataHolderTest.java
@@ -0,0 +1,198 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.browserservices; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import android.app.Activity; +import android.app.PendingIntent; +import android.content.Intent; +import android.support.customtabs.CustomTabsIntent; +import android.support.customtabs.CustomTabsSessionToken; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.annotation.Config; + +import org.chromium.base.Callback; +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.chrome.browser.customtabs.CustomTabActivity; +import org.chromium.chrome.browser.customtabs.CustomTabsConnection; +import org.chromium.chrome.browser.customtabs.TranslucentCustomTabActivity; + +/** Unit tests for {@link SessionDataHolder}. */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE) +public class SessionDataHolderTest { + + private static final int TASK_ID_1 = 10; + private static final int TASK_ID_2 = 20; + + private Intent mIntent1; + private Intent mIntent2; + private CustomTabsSessionToken mSession1; + private CustomTabsSessionToken mSession2; + + @Mock CustomTabsConnection mConnection; + @Mock + SessionHandler mHandler1; + @Mock + SessionHandler mHandler2; + @Mock Activity mActivityInTask1; + @Mock Activity mActivityInTask2; + @Captor ArgumentCaptor<Callback<CustomTabsSessionToken>> mDisconnectCallbackCaptor; + + private SessionDataHolder mHolder; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + mIntent1 = createIntentWithSessionId(1); + mSession1 = CustomTabsSessionToken.getSessionTokenFromIntent(mIntent1); + mIntent2 = createIntentWithSessionId(2); + mSession2 = CustomTabsSessionToken.getSessionTokenFromIntent(mIntent2); + when(mHandler1.getSession()).thenReturn(mSession1); + when(mHandler2.getSession()).thenReturn(mSession2); + when(mHandler1.getActivityClass()).thenReturn((Class) CustomTabActivity.class); + when(mHandler2.getActivityClass()).thenReturn((Class) TranslucentCustomTabActivity.class); + when(mActivityInTask1.getTaskId()).thenReturn(TASK_ID_1); + when(mActivityInTask2.getTaskId()).thenReturn(TASK_ID_2); + doNothing().when(mConnection).setDisconnectCallback(mDisconnectCallbackCaptor.capture()); + mHolder = new SessionDataHolder(() -> mConnection); + } + + private Intent createIntentWithSessionId(int id) { + PendingIntent pi = PendingIntent.getActivity(RuntimeEnvironment.systemContext, id, + new Intent(), 0); + return new Intent().putExtra(CustomTabsIntent.EXTRA_SESSION_ID, pi); + } + + + @Test + public void returnsActiveHandler_IfSessionsMatch() { + startActivity1(); + assertEquals(mHandler1, mHolder.getActiveHandler(mSession1)); + } + + @Test + public void doesntReturnActiveHandler_IfSessionsDontMatch() { + startActivity2(); + assertNull(mHolder.getActiveHandler(mSession1)); + } + + @Test + public void doesntReturnActiveHandler_IfItWasRemoved() { + startActivity1(); + stopActivity1(); + assertNull(mHolder.getActiveHandler(mSession1)); + } + + @Test + public void switchingFromOneCustomTabToAnother_MakesTheSecondOneTheActiveHandler() { + startActivity1(); + + // The order is important: onStart of foregrounded activity is called before onStop of the + // backgrounded one. + startActivity2(); + stopActivity1(); + assertEquals(mHandler2, mHolder.getActiveHandler(mSession2)); + } + + @Test + public void returnsActivityClassOfActiveHandler_WithMatchingSession() { + when(mHandler1.getTaskId()).thenReturn(TASK_ID_1); + startActivity1(); + Class<? extends Activity> activity = + mHolder.getActiveHandlerClassInCurrentTask(mIntent1, mActivityInTask1); + assertEquals(CustomTabActivity.class, activity); + } + + @Test + public void returnsActivityClassOfActiveHandler_EvenIfItsNotFocused() { + when(mHandler1.getTaskId()).thenReturn(TASK_ID_1); + startActivity1(); + stopActivity1(); + + // New intent arrives, bringing task 1 to foreground, but onStart was not yet called. + Class<? extends Activity> activity = + mHolder.getActiveHandlerClassInCurrentTask(mIntent1, mActivityInTask1); + assertEquals(CustomTabActivity.class, activity); + } + + @Test + public void returnsNullActivityClass_IfSessionsDontMatch() { + when(mHandler1.getTaskId()).thenReturn(TASK_ID_1); + startActivity1(); + + Class<? extends Activity> activity = + mHolder.getActiveHandlerClassInCurrentTask(mIntent2, mActivityInTask1); + assertNull(activity); + } + + @Test + public void returnsNullActivityClass_IfActivityWithMatchingSession_IsInAnotherTask() { + when(mHandler1.getTaskId()).thenReturn(TASK_ID_1); + when(mHandler2.getTaskId()).thenReturn(TASK_ID_2); + + startActivity1(); + startActivity2(); + + Class<? extends Activity> activity = + mHolder.getActiveHandlerClassInCurrentTask(mIntent2, mActivityInTask1); + assertNull(activity); + } + + @Test + public void returnsNullActivityClass_IfActivityWithMatchingSession_IsNotTopmostInTask() { + when(mHandler1.getTaskId()).thenReturn(TASK_ID_1); + when(mHandler2.getTaskId()).thenReturn(TASK_ID_1); // Note: same task. + + startActivity1(); + startActivity2(); + + Class<? extends Activity> activity = + mHolder.getActiveHandlerClassInCurrentTask(mIntent1, mActivityInTask1); + assertNull(activity); + } + + @Test + public void returnsNullActivityClass_IfSessionWasTerminated() { + when(mHandler1.getTaskId()).thenReturn(TASK_ID_1); + startActivity1(); + disconnect(mSession1); + Class<? extends Activity> activity = + mHolder.getActiveHandlerClassInCurrentTask(mIntent1, mActivityInTask1); + assertNull(activity); + } + + private void disconnect(CustomTabsSessionToken session) { + Callback<CustomTabsSessionToken> callback = mDisconnectCallbackCaptor.getValue(); + if (callback != null) { + callback.onResult(session); + } + } + + private void startActivity1() { + mHolder.setActiveHandler(mHandler1); + } + + private void startActivity2() { + mHolder.setActiveHandler(mHandler2); + } + + private void stopActivity1() { + mHolder.removeActiveHandler(mHandler1); + } +} +
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/tasks/EngagementTimeUtilTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/tasks/EngagementTimeUtilTest.java index e694ae2..2fec409ff 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/tasks/EngagementTimeUtilTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/tasks/EngagementTimeUtilTest.java
@@ -42,9 +42,10 @@ @Test public void timeSinceLastEngagement_shouldReportElapsedTimeBetweenTimestamps() { + long currentTimeMillis = System.currentTimeMillis(); assertEquals(TEST_ELAPSED_MS, mEngagementTimeUtil.timeSinceLastEngagement( - System.currentTimeMillis() - (2L * TEST_ELAPSED_MS), - System.currentTimeMillis() - TEST_ELAPSED_MS)); + currentTimeMillis - (2L * TEST_ELAPSED_MS), + currentTimeMillis - TEST_ELAPSED_MS)); } }
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessUrlUtilities.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessUrlUtilities.java index 40ae80f..1cbde5e1 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessUrlUtilities.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessUrlUtilities.java
@@ -7,17 +7,22 @@ import android.net.Uri; import android.text.TextUtils; +import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.util.UrlUtilities; import org.chromium.components.url_formatter.UrlFormatter; /** URL utilities used for touchless devices. **/ public class TouchlessUrlUtilities { + private static String sUrlForDisplayForTest; + /** * Formats a given URL for displaying in touchless. This formatting cuts the URL to its eTLD+1. * For example, for "https://chromium-review.googlesource.com/dashboard/", this will return * "googlesource.com". **/ public static String getUrlForDisplay(String url) { + if (sUrlForDisplayForTest != null) return sUrlForDisplayForTest; + if (TextUtils.isEmpty(url)) return url; String domainAndRegistry = UrlUtilities.getDomainAndRegistry(url, false); @@ -25,4 +30,14 @@ return UrlFormatter.formatUrlForSecurityDisplayOmitScheme( parsed.getScheme() + "://" + domainAndRegistry); } + + /** + * Set a display url for testing. When set, + * {@link TouchlessUrlUtilities#getUrlForDisplay(String)} will always return this. + * Please ensure to reset this by passing null as part of your test teardown. + */ + @VisibleForTesting + public static void setUrlForDisplayForTest(String urlForDisplay) { + sUrlForDisplayForTest = urlForDisplay; + } }
diff --git a/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java b/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java index 7289a3fa..1950806d 100644 --- a/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java +++ b/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java
@@ -23,8 +23,8 @@ import org.chromium.chrome.browser.ActivityTabProvider; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabObserver; +import org.chromium.chrome.browser.touchless.TouchlessUrlUtilities; import org.chromium.chrome.browser.util.UrlConstants; -import org.chromium.chrome.browser.util.test.ShadowUrlUtilities; import org.chromium.content_public.browser.NavigationHandle; import org.chromium.ui.modelutil.PropertyModel; @@ -32,7 +32,7 @@ * Unit tests for the {@link ProgressBarMediator} class. */ @RunWith(BaseRobolectricTestRunner.class) -@Config(manifest = Config.NONE, shadows = {ShadowUrlUtilities.class, ShadowPostTask.class}) +@Config(manifest = Config.NONE, shadows = {ShadowPostTask.class}) public class ProgressBarMediatorTest { private static final String SAMPLE_URL = "https://www.google.com/chrome"; private static final String SAMPLE_URL_SHORT = "google.com"; @@ -44,14 +44,7 @@ @Before public void setUp() { - ShadowUrlUtilities.setTestImpl(new ShadowUrlUtilities.TestImpl() { - @Override - public String getDomainAndRegistry(String uri, boolean includePrivateRegistries) { - if (uri.equals(SAMPLE_URL)) return SAMPLE_URL_SHORT; - - return uri; - } - }); + TouchlessUrlUtilities.setUrlForDisplayForTest(SAMPLE_URL_SHORT); mModel = new PropertyModel.Builder(ProgressBarProperties.ALL_KEYS).build(); mTabObserver = ArgumentCaptor.forClass(TabObserver.class); mTab = mock(Tab.class); @@ -61,6 +54,11 @@ verify(mTab).addObserver(mTabObserver.capture()); } + @After + public void tearDown() { + TouchlessUrlUtilities.setUrlForDisplayForTest(null); + } + @Test public void visibilityTest() { NavigationHandle navigationHandle = mock(NavigationHandle.class); @@ -130,9 +128,4 @@ Assert.assertEquals(mModel.get(ProgressBarProperties.PROGRESS_FRACTION), .1, .001); Assert.assertEquals(mModel.get(ProgressBarProperties.URL), SAMPLE_URL_SHORT); } - - @After - public void tearDown() { - ShadowUrlUtilities.reset(); - } }
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 049708b9..0389149f 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -4109,7 +4109,7 @@ #if defined(OS_ANDROID) {"touch-to-fill", flag_descriptions::kTouchToFillAndroidName, flag_descriptions::kTouchToFillAndroidDescription, kOsAndroid, - FEATURE_VALUE_TYPE(password_manager::features::kTouchToFillAndroid)}, + FEATURE_VALUE_TYPE(autofill::features::kTouchToFillAndroid)}, #endif // defined(OS_ANDROID) {"enable-sync-uss-nigori", flag_descriptions::kEnableSyncUSSNigoriName,
diff --git a/chrome/browser/android/autofill_assistant/client_android.cc b/chrome/browser/android/autofill_assistant/client_android.cc index a24dd9e..3c56c48d 100644 --- a/chrome/browser/android/autofill_assistant/client_android.cc +++ b/chrome/browser/android/autofill_assistant/client_android.cc
@@ -11,6 +11,7 @@ #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/locale_utils.h" +#include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/command_line.h" #include "base/metrics/field_trial_params.h" @@ -52,10 +53,10 @@ "https://automate-pa.googleapis.com"; // Fills a map from two Java arrays of strings of the same length. -void FillParametersFromJava(JNIEnv* env, - const JavaRef<jobjectArray>& names, - const JavaRef<jobjectArray>& values, - std::map<std::string, std::string>* parameters) { +void FillStringMapFromJava(JNIEnv* env, + const JavaRef<jobjectArray>& names, + const JavaRef<jobjectArray>& values, + std::map<std::string, std::string>* parameters) { std::vector<std::string> names_vector; base::android::AppendJavaStringArrayToStringVector(env, names, &names_vector); std::vector<std::string> values_vector; @@ -67,6 +68,18 @@ } } +std::unique_ptr<TriggerContext> CreateTriggerContext( + JNIEnv* env, + const base::android::JavaParamRef<jstring>& jexperiment_ids, + const base::android::JavaParamRef<jobjectArray>& jparameter_names, + const base::android::JavaParamRef<jobjectArray>& jparameter_values) { + std::map<std::string, std::string> parameters; + FillStringMapFromJava(env, jparameter_names, jparameter_values, ¶meters); + return TriggerContext::Create( + std::move(parameters), + base::android::ConvertJavaStringToUTF8(env, jexperiment_ids)); +} + } // namespace static base::android::ScopedJavaLocalRef<jobject> @@ -106,12 +119,12 @@ return base::android::ScopedJavaLocalRef<jobject>(java_object_); } -void ClientAndroid::Start(JNIEnv* env, +bool ClientAndroid::Start(JNIEnv* env, const JavaParamRef<jobject>& jcaller, const JavaParamRef<jstring>& jinitial_url, const JavaParamRef<jstring>& jexperiment_ids, - const JavaParamRef<jobjectArray>& parameterNames, - const JavaParamRef<jobjectArray>& parameterValues, + const JavaParamRef<jobjectArray>& parameter_names, + const JavaParamRef<jobjectArray>& parameter_values, const JavaParamRef<jobject>& joverlay_coordinator, jlong jservice) { std::unique_ptr<Service> service = nullptr; @@ -126,12 +139,9 @@ } GURL initial_url(base::android::ConvertJavaStringToUTF8(env, jinitial_url)); - std::map<std::string, std::string> parameters; - FillParametersFromJava(env, parameterNames, parameterValues, ¶meters); - controller_->Start(initial_url, TriggerContext::Create( - std::move(parameters), - base::android::ConvertJavaStringToUTF8( - env, jexperiment_ids))); + return controller_->Start( + initial_url, CreateTriggerContext(env, jexperiment_ids, parameter_names, + parameter_values)); } void ClientAndroid::DestroyUI( @@ -187,6 +197,84 @@ } } +void ClientAndroid::ListDirectActions( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jcaller, + const base::android::JavaParamRef<jstring>& jexperiment_ids, + const base::android::JavaParamRef<jobjectArray>& jargument_names, + const base::android::JavaParamRef<jobjectArray>& jargument_values, + const base::android::JavaParamRef<jobject>& jcallback) { + if (!controller_) + CreateController(nullptr); + + base::android::ScopedJavaGlobalRef<jobject> scoped_jcallback(env, jcallback); + controller_->Track( + CreateTriggerContext(env, jexperiment_ids, jargument_names, + jargument_values), + base::BindOnce(&ClientAndroid::OnListDirectActions, + weak_ptr_factory_.GetWeakPtr(), scoped_jcallback)); +} + +void ClientAndroid::OnListDirectActions( + const base::android::JavaRef<jobject>& jcallback) { + // Using a set here helps remove duplicates. + std::set<std::string> names; + for (const UserAction& user_action : controller_->GetUserActions()) { + if (!user_action.enabled()) + continue; + + for (const std::string& name : user_action.direct_action().names) { + names.insert(name); + } + } + + JNIEnv* env = AttachCurrentThread(); + Java_AutofillAssistantClient_sendDirectActionList( + env, java_object_, jcallback, + base::android::ToJavaArrayOfStrings( + env, std::vector<std::string>(names.begin(), names.end()))); +} + +bool ClientAndroid::PerformDirectAction( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jcaller, + const base::android::JavaParamRef<jstring>& jaction_name, + const base::android::JavaParamRef<jstring>& jexperiment_ids, + const base::android::JavaParamRef<jobjectArray>& jargument_names, + const base::android::JavaParamRef<jobjectArray>& jargument_values, + const base::android::JavaParamRef<jobject>& joverlay_coordinator) { + // It's too late to create a controller. This should have been done in + // ListDirectActions. + if (!controller_) + return false; + + std::string action_name = + base::android::ConvertJavaStringToUTF8(env, jaction_name); + + const std::vector<UserAction>& user_actions = controller_->GetUserActions(); + int user_action_count = user_actions.size(); + for (int i = 0; i < user_action_count; i++) { + const UserAction& user_action = user_actions[i]; + if (!user_action.enabled()) + continue; + + const std::set<std::string>& action_names = + user_action.direct_action().names; + if (action_names.count(action_name) != 0) { + // If an overlay is already shown, then show the rest of the UI + // immediately. + if (joverlay_coordinator) { + AttachUI(joverlay_coordinator); + } + + return controller_->PerformUserActionWithContext( + i, CreateTriggerContext(env, jexperiment_ids, jargument_names, + jargument_values)); + } + } + return false; +} + void ClientAndroid::AttachUI() { AttachUI(nullptr); }
diff --git a/chrome/browser/android/autofill_assistant/client_android.h b/chrome/browser/android/autofill_assistant/client_android.h index cadaaecd..d2c5ca96 100644 --- a/chrome/browser/android/autofill_assistant/client_android.h +++ b/chrome/browser/android/autofill_assistant/client_android.h
@@ -38,12 +38,12 @@ // Returns the corresponding Java AutofillAssistantClient. base::android::ScopedJavaLocalRef<jobject> GetJavaObject(); - void Start(JNIEnv* env, + bool Start(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, const base::android::JavaParamRef<jstring>& jinitial_url, const base::android::JavaParamRef<jstring>& jexperiment_ids, - const base::android::JavaParamRef<jobjectArray>& parameterNames, - const base::android::JavaParamRef<jobjectArray>& parameterValues, + const base::android::JavaParamRef<jobjectArray>& parameter_names, + const base::android::JavaParamRef<jobjectArray>& parameter_values, const base::android::JavaParamRef<jobject>& joverlay_coordinator, jlong jservice); void DestroyUI(JNIEnv* env, @@ -61,6 +61,23 @@ jboolean success, const base::android::JavaParamRef<jstring>& access_token); + void ListDirectActions( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jcaller, + const base::android::JavaParamRef<jstring>& jexperiment_ids, + const base::android::JavaParamRef<jobjectArray>& jargument_names, + const base::android::JavaParamRef<jobjectArray>& jargument_values, + const base::android::JavaParamRef<jobject>& jcallback); + + bool PerformDirectAction( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jcaller, + const base::android::JavaParamRef<jstring>& jaction_id, + const base::android::JavaParamRef<jstring>& jexperiment_ids, + const base::android::JavaParamRef<jobjectArray>& jargument_names, + const base::android::JavaParamRef<jobjectArray>& jargument_values, + const base::android::JavaParamRef<jobject>& joverlay_coordinator); + // Overrides Client void AttachUI() override; void DestroyUI() override; @@ -87,6 +104,7 @@ void AttachUI( const base::android::JavaParamRef<jobject>& joverlay_coordinator); bool NeedsUI(); + void OnListDirectActions(const base::android::JavaRef<jobject>& jcallback); WEB_CONTENTS_USER_DATA_KEY_DECL();
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index 1b32285..68ac467 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -60,6 +60,7 @@ &autofill::features::kAutofillEnableCompanyName, &autofill_assistant::features::kAutofillAssistant, &autofill_assistant::features::kAutofillAssistantDirectActions, + &autofill::features::kTouchToFillAndroid, &download::features::kDownloadAutoResumptionNative, &download::features::kUseDownloadOfflineContentProvider, &features::kAppNotificationStatusMessaging, @@ -212,7 +213,6 @@ &omnibox::kOmniboxSearchEngineLogo, &password_manager::features::kGooglePasswordManager, &password_manager::features::kPasswordEditingAndroid, - &password_manager::features::kTouchToFillAndroid, &safe_browsing::kCaptureSafetyNetId, &signin::kMiceFeature, &switches::kSyncSendTabToSelf,
diff --git a/chrome/browser/android/feed/feed_host_service_factory.cc b/chrome/browser/android/feed/feed_host_service_factory.cc index a617c43..9f0720f 100644 --- a/chrome/browser/android/feed/feed_host_service_factory.cc +++ b/chrome/browser/android/feed/feed_host_service_factory.cc
@@ -78,7 +78,7 @@ content::StoragePartition* storage_partition = content::BrowserContext::GetDefaultStoragePartition(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); std::string api_key; if (google_apis::IsGoogleChromeAPIKeyUsed()) {
diff --git a/chrome/browser/android/metrics/android_profile_session_durations_service.cc b/chrome/browser/android/metrics/android_profile_session_durations_service.cc index 96bd2cd..fcde6bcb 100644 --- a/chrome/browser/android/metrics/android_profile_session_durations_service.cc +++ b/chrome/browser/android/metrics/android_profile_session_durations_service.cc
@@ -6,7 +6,7 @@ AndroidProfileSessionDurationsService::AndroidProfileSessionDurationsService( syncer::SyncService* sync_service, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : metrics_recorder_( std::make_unique<syncer::SyncSessionDurationsMetricsRecorder>( sync_service,
diff --git a/chrome/browser/android/metrics/android_profile_session_durations_service.h b/chrome/browser/android/metrics/android_profile_session_durations_service.h index 59813b5a..de1bb9e 100644 --- a/chrome/browser/android/metrics/android_profile_session_durations_service.h +++ b/chrome/browser/android/metrics/android_profile_session_durations_service.h
@@ -9,7 +9,7 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/sync/driver/sync_session_durations_metrics_recorder.h" -namespace identity { +namespace signin { class IdentityManager; } namespace syncer { @@ -23,7 +23,7 @@ // Callers must ensure that the parameters outlive this object. AndroidProfileSessionDurationsService( syncer::SyncService* sync_service, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~AndroidProfileSessionDurationsService() override; // KeyedService:
diff --git a/chrome/browser/android/metrics/android_profile_session_durations_service_factory.cc b/chrome/browser/android/metrics/android_profile_session_durations_service_factory.cc index d0f24e4..d19ffbb8 100644 --- a/chrome/browser/android/metrics/android_profile_session_durations_service_factory.cc +++ b/chrome/browser/android/metrics/android_profile_session_durations_service_factory.cc
@@ -51,7 +51,7 @@ Profile* profile = Profile::FromBrowserContext(context); syncer::SyncService* sync_service = ProfileSyncServiceFactory::GetForProfile(profile); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); return new AndroidProfileSessionDurationsService(sync_service, identity_manager);
diff --git a/chrome/browser/android/profiles/profile_downloader_android.cc b/chrome/browser/android/profiles/profile_downloader_android.cc index 83cfcf7a..1f2a15a 100644 --- a/chrome/browser/android/profiles/profile_downloader_android.cc +++ b/chrome/browser/android/profiles/profile_downloader_android.cc
@@ -63,7 +63,7 @@ return desired_image_side_pixels_; } - identity::IdentityManager* GetIdentityManager() override { + signin::IdentityManager* GetIdentityManager() override { return IdentityManagerFactory::GetForProfile(profile_); }
diff --git a/chrome/browser/android/signin/chrome_signin_manager_delegate.h b/chrome/browser/android/signin/chrome_signin_manager_delegate.h index c3110d1..b437756 100644 --- a/chrome/browser/android/signin/chrome_signin_manager_delegate.h +++ b/chrome/browser/android/signin/chrome_signin_manager_delegate.h
@@ -11,7 +11,7 @@ #include "chrome/browser/android/signin/signin_manager_delegate.h" #include "components/signin/public/identity_manager/account_info.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -104,7 +104,7 @@ Profile* const profile_ = nullptr; - identity::IdentityManager* const identity_manager_ = nullptr; + signin::IdentityManager* const identity_manager_ = nullptr; policy::UserCloudPolicyManager* const user_cloud_policy_manager_ = nullptr; policy::UserPolicySigninService* const user_policy_signin_service_ = nullptr;
diff --git a/chrome/browser/android/signin/signin_manager_android.cc b/chrome/browser/android/signin/signin_manager_android.cc index b2450c27..879b1220 100644 --- a/chrome/browser/android/signin/signin_manager_android.cc +++ b/chrome/browser/android/signin/signin_manager_android.cc
@@ -32,7 +32,7 @@ SigninManagerAndroid::SigninManagerAndroid( SigninClient* signin_client, PrefService* local_state_pref_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<SigninManagerDelegate> signin_manager_delegate) : signin_client_(signin_client), identity_manager_(identity_manager), @@ -91,7 +91,7 @@ // GetPrimaryAccountMutator() returns nullptr on ChromeOS only. DCHECK(account_mutator); account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, static_cast<signin_metrics::ProfileSignout>(signoutReason), // Always use IGNORE_METRIC for the profile deletion argument. Chrome // Android has just a single-profile which is never deleted upon
diff --git a/chrome/browser/android/signin/signin_manager_android.h b/chrome/browser/android/signin/signin_manager_android.h index a03d97e..616fa244 100644 --- a/chrome/browser/android/signin/signin_manager_android.h +++ b/chrome/browser/android/signin/signin_manager_android.h
@@ -26,12 +26,12 @@ // // This class implements parts of the sign-in flow, to make sure that policy // is available before sign-in completes. -class SigninManagerAndroid : public identity::IdentityManager::Observer { +class SigninManagerAndroid : public signin::IdentityManager::Observer { public: SigninManagerAndroid( SigninClient* signin_client, PrefService* local_state_prefs_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<SigninManagerDelegate> signin_manager_delegate); ~SigninManagerAndroid() override; @@ -67,7 +67,7 @@ jboolean IsSignedInOnNative(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) override; @@ -84,7 +84,7 @@ // State, not in user prefs. BooleanPrefMember force_browser_signin_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; std::unique_ptr<SigninManagerDelegate> signin_manager_delegate_;
diff --git a/chrome/browser/apps/app_service/built_in_chromeos_apps.cc b/chrome/browser/apps/app_service/built_in_chromeos_apps.cc index 03924e5..6eb7ec55 100644 --- a/chrome/browser/apps/app_service/built_in_chromeos_apps.cc +++ b/chrome/browser/apps/app_service/built_in_chromeos_apps.cc
@@ -84,6 +84,15 @@ profile_ = profile; } +bool BuiltInChromeOsApps::hide_settings_app_for_testing_ = false; + +// static +bool BuiltInChromeOsApps::SetHideSettingsAppForTesting(bool hide) { + bool old_value = hide_settings_app_for_testing_; + hide_settings_app_for_testing_ = hide; + return old_value; +} + void BuiltInChromeOsApps::Connect(apps::mojom::SubscriberPtr subscriber, apps::mojom::ConnectOptionsPtr opts) { std::vector<apps::mojom::AppPtr> apps; @@ -103,6 +112,11 @@ apps::mojom::AppPtr app = Convert(internal_app); if (!app.is_null()) { + if (hide_settings_app_for_testing_ && + (internal_app.internal_app_name == + app_list::InternalAppName::kSettings)) { + app->show_in_search = apps::mojom::OptionalBool::kFalse; + } apps.push_back(std::move(app)); } }
diff --git a/chrome/browser/apps/app_service/built_in_chromeos_apps.h b/chrome/browser/apps/app_service/built_in_chromeos_apps.h index 232c261..9d3bee6d 100644 --- a/chrome/browser/apps/app_service/built_in_chromeos_apps.h +++ b/chrome/browser/apps/app_service/built_in_chromeos_apps.h
@@ -26,6 +26,8 @@ void Initialize(const apps::mojom::AppServicePtr& app_service, Profile* profile); + static bool SetHideSettingsAppForTesting(bool hide); + private: // apps::mojom::Publisher overrides. void Connect(apps::mojom::SubscriberPtr subscriber, @@ -49,6 +51,67 @@ Profile* profile_; + // Hack to hide the settings app from the app list search box. This is only + // intended to be used in tests. + // + // BuiltInChromeOsApps assumes that the list of internal apps doesn't change + // over the lifetime of the Profile. For example, + // chrome/browser/ui/app_list/internal_app/internal_app_metadata.{cc,h} + // doesn't expose any observer mechanism to be notified if it did change. + // + // Separately, WebAppUiServiceMigrationBrowserTest's + // SettingsSystemWebAppMigration test exercises the case where the + // *implementation* of the built-in Settings app changes, from an older + // technology to being a Web App. Even though there are two implementations, + // any given Profile will typically use only one, depending on whether + // features::kSystemWebApps is enabled, typically via the command line. + // Again, the App Service's BuiltInChromeOsApps handles this, in practice, as + // whether or not it's enabled ought to stay unchanged throughout a session. + // + // Specifically, though, that test (1) starts with features::kSystemWebApps + // disabled (during SetUp) but then (2) enables it (during the test + // function). This isn't in order to explicitly exercise a run-time flag + // change, but it was simply an expedient way to test data migration: + // situation (1) creates some persistent data (in the test's temporary + // storage) in the old implementation's format, and flipping to situation (2) + // checks that the new implementation correctly migrates that data. + // + // An unfortunate side effect of that flip is that the list of internal apps + // changed. The SettingsSystemWebAppMigration test involves an + // AppListModelUpdater, which calls into its AppSearchProvider's and thus the + // App Service (when the App Service is enabled), which then panics because a + // built-in app it previously knew about and exposed via app list search, in + // situation (1), has mysteriously vanished, in situation (2). + // + // A 'proper' fix could be to add an observer mechanism to the list of + // internal apps, and break the previously held simplifying assumption that + // BuiltInChromeOsApps can be relatively stateless as that list does not + // change. There's also some subtlety because App Service methods are + // generally asynchronous (because they're potentially Mojo IPC), so some + // care still needs to be taken where some parts of the system might have + // seen any given app update but others might not yet have. + // + // Doing a 'proper' fix is probably more trouble than it's worth. Given that + // this "change the implementation of the built-in Settings app" will only + // temporarily have two separate implementations, say for a couple of months, + // and a runtime flag flip isn't supported in production, and is only + // exercised in a single test, the simpler (temporary) fix is to opt in to + // hiding the internal Settings app from search. + // + // Note that we only hide it from search. We don't remove the app entirely + // from the list of apps that the BuiltInChromeOsApps publishes, since the + // migration test (and its AppListModelUpdater) still needs to be able to + // refer to the (artificial) situation where both apps co-exist. + // + // TODO(calamity/nigeltao): remove this hack once the System Web App has + // completely replaced the Settings Internal App, hopefully some time in + // 2019Q3. + // + // See also the "web_app::SystemWebAppManager::IsEnabled()" if-check in + // internal_app_metadata.cc. Once that condition is removed, we can probably + // remove this hack too. + static bool hide_settings_app_for_testing_; + DISALLOW_COPY_AND_ASSIGN(BuiltInChromeOsApps); };
diff --git a/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc b/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc index a19e0848..2f7279d 100644 --- a/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc +++ b/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc
@@ -40,7 +40,7 @@ ~FakeDriveServiceFactory() override {} std::unique_ptr<drive::DriveServiceInterface> CreateDriveService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, base::SequencedTaskRunner* blocking_task_runner) override { std::unique_ptr<drive::FakeDriveService> drive_service( @@ -82,7 +82,7 @@ std::unique_ptr<drive_backend::SyncEngine::DriveServiceFactory> drive_service_factory(new FakeDriveServiceFactory(this)); - identity_test_env_.reset(new identity::IdentityTestEnvironment); + identity_test_env_.reset(new signin::IdentityTestEnvironment); remote_service_ = new drive_backend::SyncEngine( base::ThreadTaskRunnerHandle::Get(), // ui_task_runner @@ -136,7 +136,7 @@ run_loop.Run(); } - identity::IdentityManager* identity_manager() const { + signin::IdentityManager* identity_manager() const { return identity_test_env_->identity_manager(); } @@ -144,7 +144,7 @@ base::ScopedTempDir base_dir_; std::unique_ptr<leveldb::Env> in_memory_env_; - std::unique_ptr<identity::IdentityTestEnvironment> identity_test_env_; + std::unique_ptr<signin::IdentityTestEnvironment> identity_test_env_; drive_backend::SyncEngine* remote_service_;
diff --git a/chrome/browser/autocomplete/document_suggestions_service_factory.cc b/chrome/browser/autocomplete/document_suggestions_service_factory.cc index 2b44881..7caa02f 100644 --- a/chrome/browser/autocomplete/document_suggestions_service_factory.cc +++ b/chrome/browser/autocomplete/document_suggestions_service_factory.cc
@@ -29,7 +29,7 @@ content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); return new DocumentSuggestionsService( identity_manager,
diff --git a/chrome/browser/autocomplete/remote_suggestions_service_factory.cc b/chrome/browser/autocomplete/remote_suggestions_service_factory.cc index 8884ab1..17d710d 100644 --- a/chrome/browser/autocomplete/remote_suggestions_service_factory.cc +++ b/chrome/browser/autocomplete/remote_suggestions_service_factory.cc
@@ -28,7 +28,7 @@ KeyedService* RemoteSuggestionsServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); return new RemoteSuggestionsService( identity_manager,
diff --git a/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc b/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc index 5231a88..e8d8bdd 100644 --- a/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc +++ b/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc
@@ -581,11 +581,11 @@ auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (is_primary) { DCHECK(!identity_manager->HasPrimaryAccount()); - return identity::MakePrimaryAccountAvailable(identity_manager, - account_id + "@gmail.com"); + return signin::MakePrimaryAccountAvailable(identity_manager, + account_id + "@gmail.com"); } auto account_info = - identity::MakeAccountAvailable(identity_manager, account_id); + signin::MakeAccountAvailable(identity_manager, account_id); DCHECK( identity_manager->HasAccountWithRefreshToken(account_info.account_id)); return account_info; @@ -627,7 +627,7 @@ // Clear cookies. RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_COOKIES); // Check that the Sync account was not removed and Sync was paused. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); EXPECT_TRUE( identity_manager->HasAccountWithRefreshToken(primary_account.account_id)); @@ -685,7 +685,7 @@ AccountInfo primary_account = AddAccountToProfile(kAccountId, profile, /*is_primary=*/true); auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager, primary_account.account_id, GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason::
diff --git a/chrome/browser/chromeos/account_manager/account_manager_migrator.cc b/chrome/browser/chromeos/account_manager/account_manager_migrator.cc index 5e1de51..c43e864 100644 --- a/chrome/browser/chromeos/account_manager/account_manager_migrator.cc +++ b/chrome/browser/chromeos/account_manager/account_manager_migrator.cc
@@ -88,7 +88,7 @@ public: AccountMigrationBaseStep(const std::string& id, AccountManager* account_manager, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : AccountMigrationRunner::Step(id), account_manager_(account_manager), identity_manager_(identity_manager), @@ -125,7 +125,7 @@ AccountManager* account_manager() { return account_manager_; } - identity::IdentityManager* identity_manager() { return identity_manager_; } + signin::IdentityManager* identity_manager() { return identity_manager_; } private: // Implementations should use this to start their migration flow, instead of @@ -154,7 +154,7 @@ AccountManager* const account_manager_; // Non-owning pointer. - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; // A temporary cache of accounts in |AccountManager|, guaranteed to be // up-to-date when |StartMigration| is called. @@ -172,7 +172,7 @@ DeviceAccountMigration(const AccountManager::AccountKey& device_account, const std::string& device_account_raw_email, AccountManager* account_manager, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<TokenWebData> token_web_data) : AccountMigrationBaseStep(kDeviceAccountMigration, account_manager, @@ -269,10 +269,10 @@ // to |AccountManager|. The objective is to migrate the account names only. We // cannot migrate any credentials (cookies). class ContentAreaAccountsMigration : public AccountMigrationBaseStep, - identity::IdentityManager::Observer { + signin::IdentityManager::Observer { public: ContentAreaAccountsMigration(AccountManager* account_manager, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : AccountMigrationBaseStep(kContentAreaAccountsMigration, account_manager, identity_manager), @@ -286,7 +286,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); identity_manager_->AddObserver(this); - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = identity_manager_->GetAccountsInCookieJar(); if (accounts_in_cookie_jar_info.accounts_are_fresh) { OnAccountsInCookieUpdated( @@ -296,7 +296,7 @@ } void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // We should not have reached here without |OnGetAccounts| having been @@ -326,7 +326,7 @@ } // A non-owning pointer to |IdentityManager|. - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; SEQUENCE_CHECKER(sequence_checker_); @@ -343,7 +343,7 @@ public arc::ArcSessionManager::Observer { public: ArcAccountsMigration(AccountManager* account_manager, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, arc::ArcAuthService* arc_auth_service) : AccountMigrationBaseStep(kArcAccountsMigration, account_manager, @@ -523,7 +523,7 @@ g_browser_process->platform_part()->GetAccountManagerFactory(); chromeos::AccountManager* account_manager = factory->GetAccountManager(profile_->GetPath().value()); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); migration_runner_.AddStep(std::make_unique<DeviceAccountMigration>(
diff --git a/chrome/browser/chromeos/account_manager/account_manager_policy_controller_browsertest.cc b/chrome/browser/chromeos/account_manager/account_manager_policy_controller_browsertest.cc index 686d09e..e5b5f1e 100644 --- a/chrome/browser/chromeos/account_manager/account_manager_policy_controller_browsertest.cc +++ b/chrome/browser/chromeos/account_manager/account_manager_policy_controller_browsertest.cc
@@ -105,7 +105,7 @@ Profile* profile() { return profile_.get(); } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return identity_test_environment_adaptor_->identity_test_env() ->identity_manager(); }
diff --git a/chrome/browser/chromeos/arc/arc_play_store_enabled_preference_handler.cc b/chrome/browser/chromeos/arc/arc_play_store_enabled_preference_handler.cc index 95571505..02fce5a 100644 --- a/chrome/browser/chromeos/arc/arc_play_store_enabled_preference_handler.cc +++ b/chrome/browser/chromeos/arc/arc_play_store_enabled_preference_handler.cc
@@ -125,7 +125,7 @@ chrome_launcher_controller->UnpinAppWithID(kPlayStoreAppId); // Tell Consent Auditor that the Play Store consent was revoked. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); // TODO(crbug.com/850297): Fix unrelated tests that are not properly // setting up the state of identity_manager and enable the DCHECK instead
diff --git a/chrome/browser/chromeos/arc/arc_session_manager_browsertest.cc b/chrome/browser/chromeos/arc/arc_session_manager_browsertest.cc index ee70227..171b8da8 100644 --- a/chrome/browser/chromeos/arc/arc_session_manager_browsertest.cc +++ b/chrome/browser/chromeos/arc/arc_session_manager_browsertest.cc
@@ -198,7 +198,7 @@ Profile* profile() { return profile_.get(); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_environment_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/chromeos/arc/arc_support_host_unittest.cc b/chrome/browser/chromeos/arc/arc_support_host_unittest.cc index 751b89eb..452814bf 100644 --- a/chrome/browser/chromeos/arc/arc_support_host_unittest.cc +++ b/chrome/browser/chromeos/arc/arc_support_host_unittest.cc
@@ -75,7 +75,7 @@ BrowserWithTestWindowTest::SetUp(); user_manager_enabler_ = std::make_unique<user_manager::ScopedUserManager>( std::make_unique<chromeos::FakeChromeUserManager>()); - identity::MakePrimaryAccountAvailable( + signin::MakePrimaryAccountAvailable( IdentityManagerFactory::GetForProfile(profile()), "testing@account.com");
diff --git a/chrome/browser/chromeos/arc/auth/arc_auth_context.cc b/chrome/browser/chromeos/arc/auth/arc_auth_context.cc index 553fa4d..087067a 100644 --- a/chrome/browser/chromeos/arc/auth/arc_auth_context.cc +++ b/chrome/browser/chromeos/arc/auth/arc_auth_context.cc
@@ -92,15 +92,15 @@ StartFetchers(); } -std::unique_ptr<identity::AccessTokenFetcher> +std::unique_ptr<signin::AccessTokenFetcher> ArcAuthContext::CreateAccessTokenFetcher( const std::string& consumer_name, const identity::ScopeSet& scopes, - identity::AccessTokenFetcher::TokenCallback callback) { + signin::AccessTokenFetcher::TokenCallback callback) { DCHECK(identity_manager_->HasAccountWithRefreshToken(account_id_)); return identity_manager_->CreateAccessTokenFetcherForAccount( account_id_, consumer_name, scopes, std::move(callback), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } void ArcAuthContext::OnRefreshTokenUpdatedForAccount(
diff --git a/chrome/browser/chromeos/arc/auth/arc_auth_context.h b/chrome/browser/chromeos/arc/auth/arc_auth_context.h index 57c2d5e..bd60013 100644 --- a/chrome/browser/chromeos/arc/auth/arc_auth_context.h +++ b/chrome/browser/chromeos/arc/auth/arc_auth_context.h
@@ -25,7 +25,7 @@ namespace arc { class ArcAuthContext : public GaiaAuthConsumer, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // Creates an |ArcAuthContext| for the given |account_id|. This |account_id| // must be the |account_id| used by the OAuth Token Service chain. @@ -44,12 +44,12 @@ // Creates and starts a request to fetch an access token for the given // |scopes|. The caller owns the returned request. |callback| will be // called with results if the returned request is not deleted. - std::unique_ptr<identity::AccessTokenFetcher> CreateAccessTokenFetcher( + std::unique_ptr<signin::AccessTokenFetcher> CreateAccessTokenFetcher( const std::string& consumer_name, const identity::ScopeSet& scopes, - identity::AccessTokenFetcher::TokenCallback callback); + signin::AccessTokenFetcher::TokenCallback callback); - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info) override; void OnRefreshTokensLoaded() override; @@ -76,7 +76,7 @@ // Unowned pointer. Profile* const profile_; const std::string account_id_; - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; // Whether the merge session should be skipped. Set to true only in testing. bool skip_merge_session_for_testing_ = false;
diff --git a/chrome/browser/chromeos/arc/auth/arc_auth_service.cc b/chrome/browser/chromeos/arc/auth/arc_auth_service.cc index 08640b5..2376bdf0 100644 --- a/chrome/browser/chromeos/arc/auth/arc_auth_service.cc +++ b/chrome/browser/chromeos/arc/auth/arc_auth_service.cc
@@ -158,7 +158,7 @@ } bool IsPrimaryOrDeviceLocalAccount( - const identity::IdentityManager* identity_manager, + const signin::IdentityManager* identity_manager, const std::string& account_name) { // |GetPrimaryUser| is fine because ARC is only available on the first // (Primary) account that participates in multi-signin.
diff --git a/chrome/browser/chromeos/arc/auth/arc_auth_service.h b/chrome/browser/chromeos/arc/auth/arc_auth_service.h index a845e57..d4f1636 100644 --- a/chrome/browser/chromeos/arc/auth/arc_auth_service.h +++ b/chrome/browser/chromeos/arc/auth/arc_auth_service.h
@@ -27,9 +27,9 @@ class BrowserContext; } // namespace content -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -46,7 +46,7 @@ class ArcAuthService : public KeyedService, public mojom::AuthHost, public ConnectionObserver<mojom::AuthInstance>, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public ArcSessionManager::Observer { public: using GetGoogleAccountsInArcCallback = @@ -190,7 +190,7 @@ // Non-owning pointers. Profile* const profile_; - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; ArcBridgeService* const arc_bridge_service_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
diff --git a/chrome/browser/chromeos/arc/auth/arc_auth_service_browsertest.cc b/chrome/browser/chromeos/arc/auth/arc_auth_service_browsertest.cc index 1973c94e..f5dd7536 100644 --- a/chrome/browser/chromeos/arc/auth/arc_auth_service_browsertest.cc +++ b/chrome/browser/chromeos/arc/auth/arc_auth_service_browsertest.cc
@@ -600,7 +600,7 @@ EXPECT_EQ(0, auth_instance().num_account_removed_calls()); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile()); base::Optional<AccountInfo> maybe_account_info = identity_manager->FindAccountInfoForAccountWithRefreshTokenByEmailAddress(
diff --git a/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.cc b/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.cc index 0655921a..684a56b2 100644 --- a/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.cc +++ b/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.cc
@@ -87,7 +87,7 @@ void ArcBackgroundAuthCodeFetcher::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { ResetFetchers(); if (error.state() != GoogleServiceAuthError::NONE) {
diff --git a/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.h b/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.h index 5a8ef516..3c1e767 100644 --- a/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.h +++ b/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.h
@@ -18,10 +18,10 @@ class Profile; -namespace identity { +namespace signin { class AccessTokenFetcher; struct AccessTokenInfo; -} // namespace identity +} // namespace signin namespace network { class SimpleURLLoader; @@ -56,7 +56,7 @@ void OnPrepared(bool success); void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); void OnSimpleLoaderComplete(std::unique_ptr<std::string> response_body); @@ -69,7 +69,7 @@ ArcAuthContext context_; FetchCallback callback_; - std::unique_ptr<identity::AccessTokenFetcher> access_token_fetcher_; + std::unique_ptr<signin::AccessTokenFetcher> access_token_fetcher_; std::unique_ptr<network::SimpleURLLoader> simple_url_loader_; // Keeps context of account code request. |initial_signin_| is true if request
diff --git a/chrome/browser/chromeos/arc/optin/arc_terms_of_service_default_negotiator_unittest.cc b/chrome/browser/chromeos/arc/optin/arc_terms_of_service_default_negotiator_unittest.cc index c464cee..324006d 100644 --- a/chrome/browser/chromeos/arc/optin/arc_terms_of_service_default_negotiator_unittest.cc +++ b/chrome/browser/chromeos/arc/optin/arc_terms_of_service_default_negotiator_unittest.cc
@@ -63,7 +63,7 @@ BrowserWithTestWindowTest::SetUp(); user_manager_enabler_ = std::make_unique<user_manager::ScopedUserManager>( std::make_unique<chromeos::FakeChromeUserManager>()); - identity::MakePrimaryAccountAvailable( + signin::MakePrimaryAccountAvailable( IdentityManagerFactory::GetForProfile(profile()), "testing@account.com");
diff --git a/chrome/browser/chromeos/arc/policy/arc_android_management_checker.h b/chrome/browser/chromeos/arc/policy/arc_android_management_checker.h index 812a865..bda063f1 100644 --- a/chrome/browser/chromeos/arc/policy/arc_android_management_checker.h +++ b/chrome/browser/chromeos/arc/policy/arc_android_management_checker.h
@@ -18,7 +18,7 @@ namespace arc { -class ArcAndroidManagementChecker : public identity::IdentityManager::Observer { +class ArcAndroidManagementChecker : public signin::IdentityManager::Observer { public: ArcAndroidManagementChecker(Profile* profile, bool retry_on_error); ~ArcAndroidManagementChecker() override; @@ -42,14 +42,14 @@ // Ensures the refresh token is loaded in the |identity_manager|. void EnsureRefreshTokenLoaded(); - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info) override; void OnRefreshTokensLoaded() override; // Unowned pointers. Profile* profile_; - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; const std::string device_account_id_;
diff --git a/chrome/browser/chromeos/crostini/crostini_pref_names.cc b/chrome/browser/chromeos/crostini/crostini_pref_names.cc index 6d64197..46456db 100644 --- a/chrome/browser/chromeos/crostini/crostini_pref_names.cc +++ b/chrome/browser/chromeos/crostini/crostini_pref_names.cc
@@ -33,6 +33,11 @@ // the crostini export / import UI. const char kUserCrostiniExportImportUIAllowedByPolicy[] = "crostini.user_export_import_ui_allowed_by_policy"; +// A boolean preference representing a user level enterprise policy to allow +// Crostini root access. +// TODO(https://crbug.com/983998): The features that have to be implemented. +const char kUserCrostiniRootAccessAllowedByPolicy[] = + "crostini.user_root_access_allowed_by_policy"; // A boolean preference controlling Crostini usage reporting. const char kReportCrostiniUsageEnabled[] = "crostini.usage_reporting_enabled"; @@ -81,6 +86,7 @@ registry->RegisterBooleanPref(kUserCrostiniAllowedByPolicy, true); registry->RegisterBooleanPref(kUserCrostiniExportImportUIAllowedByPolicy, true); + registry->RegisterBooleanPref(kUserCrostiniRootAccessAllowedByPolicy, true); } } // namespace prefs
diff --git a/chrome/browser/chromeos/crostini/crostini_pref_names.h b/chrome/browser/chromeos/crostini/crostini_pref_names.h index caae53e..5c7cd78 100644 --- a/chrome/browser/chromeos/crostini/crostini_pref_names.h +++ b/chrome/browser/chromeos/crostini/crostini_pref_names.h
@@ -20,6 +20,7 @@ extern const char kUserCrostiniAllowedByPolicy[]; extern const char kUserCrostiniExportImportUIAllowedByPolicy[]; +extern const char kUserCrostiniRootAccessAllowedByPolicy[]; extern const char kReportCrostiniUsageEnabled[]; extern const char kCrostiniLastLaunchTerminaComponentVersion[];
diff --git a/chrome/browser/chromeos/drive/drive_integration_service.cc b/chrome/browser/chromeos/drive/drive_integration_service.cc index 5152c62..372a6a3 100644 --- a/chrome/browser/chromeos/drive/drive_integration_service.cc +++ b/chrome/browser/chromeos/drive/drive_integration_service.cc
@@ -693,7 +693,7 @@ return; } - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (test_drive_service) { @@ -1148,7 +1148,7 @@ return; } - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); drive_service_->Initialize(identity_manager->GetPrimaryAccountId());
diff --git a/chrome/browser/chromeos/extensions/file_manager/file_manager_private_apitest.cc b/chrome/browser/chromeos/extensions/file_manager/file_manager_private_apitest.cc index e96a92b..7c38500 100644 --- a/chrome/browser/chromeos/extensions/file_manager/file_manager_private_apitest.cc +++ b/chrome/browser/chromeos/extensions/file_manager/file_manager_private_apitest.cc
@@ -351,7 +351,7 @@ crostini::prefs::kCrostiniEnabled, true); scoped_feature_list->InitWithFeatures({features::kCrostini}, {}); // Profile must be signed in with email for crostini. - identity::SetPrimaryAccount( + signin::SetPrimaryAccount( IdentityManagerFactory::GetForProfileIfExists(browser()->profile()), "testuser@gmail.com"); }
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc index a5584ec..c65b8493 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc
@@ -1815,7 +1815,7 @@ } download_url_ = std::move(download_url); const ChromeExtensionFunctionDetails chrome_details(this); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(chrome_details.GetProfile()); const std::string& account_id = identity_manager->GetPrimaryAccountId(); std::vector<std::string> scopes;
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc index 6ad4a7b..3fa8f58 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_misc.cc
@@ -385,7 +385,7 @@ std::vector<std::string> scopes; scopes.emplace_back(kCWSScope); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(chrome_details_.GetProfile()); if (!identity_manager) {
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc index fb70823..06b852e 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
@@ -1184,10 +1184,10 @@ account_id, base::UTF8ToUTF16(info.display_name)); Profile* profile = chromeos::ProfileHelper::GetProfileByUserIdHashForTest(info.hash); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (!identity_manager->HasPrimaryAccount()) - identity::MakePrimaryAccountAvailable(identity_manager, info.email); + signin::MakePrimaryAccountAvailable(identity_manager, info.email); } GuestMode GetGuestMode() const override { return NOT_IN_GUEST_MODE; }
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.cc b/chrome/browser/chromeos/login/session/user_session_manager.cc index 3244154..52cb53d6 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.cc +++ b/chrome/browser/chromeos/login/session/user_session_manager.cc
@@ -949,7 +949,7 @@ OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile); bool connection_error = false; - identity::IdentityManager* const identity_manager = + signin::IdentityManager* const identity_manager = IdentityManagerFactory::GetForProfile(user_profile); switch (state) { case OAuth2LoginManager::SESSION_RESTORE_DONE: @@ -1307,7 +1307,7 @@ // not be available when unlocking a previously opened profile, or when // creating a supervised users. However, in these cases the gaia_id should // be already available in the account tracker. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); std::string gaia_id = user_context.GetGaiaID(); if (gaia_id.empty()) {
diff --git a/chrome/browser/chromeos/login/signin/auth_sync_observer.cc b/chrome/browser/chromeos/login/signin/auth_sync_observer.cc index 9eaa5c8..172503f 100644 --- a/chrome/browser/chromeos/login/signin/auth_sync_observer.cc +++ b/chrome/browser/chromeos/login/signin/auth_sync_observer.cc
@@ -68,7 +68,7 @@ void AuthSyncObserver::OnErrorChanged() { // This notification could have come for any account but we are only // interested in errors for the Primary Account. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); HandleAuthError(identity_manager->GetErrorStateOfRefreshTokenForAccount( identity_manager->GetPrimaryAccountId()));
diff --git a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc index a26c1fe..661dfc0 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc
@@ -329,7 +329,7 @@ WaitForMergeSessionCompletion(OAuth2LoginManager::SESSION_RESTORE_DONE); // Check for existence of refresh token. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken(account_id)); @@ -529,7 +529,7 @@ /*is_under_advanced_protection=*/false); // Check for existence of refresh token. std::string account_id = PickAccountId(GetProfile(), kTestGaiaId, kTestEmail); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile()); EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken(account_id)); @@ -636,7 +636,7 @@ GetSessionRestoreStrategy()); // Checks that refresh token is not yet loaded. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile()); const std::string account_id = PickAccountId(GetProfile(), kTestGaiaId, kTestEmail); @@ -760,7 +760,7 @@ ASSERT_NE(OAuth2LoginManager::SESSION_RESTORE_DONE, login_manager->state()); // Generate an auth error. - identity::SetInvalidRefreshTokenForAccount( + signin::SetInvalidRefreshTokenForAccount( IdentityManagerFactory::GetInstance()->GetForProfile(GetProfile()), kTestEmail);
diff --git a/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc b/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc index 0e07a3e4..61c8f56 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc
@@ -83,7 +83,7 @@ } void OAuth2LoginManager::RestoreSessionFromSavedTokens() { - identity::IdentityManager* identity_manager = GetIdentityManager(); + signin::IdentityManager* identity_manager = GetIdentityManager(); if (identity_manager->HasPrimaryAccountWithRefreshToken()) { VLOG(1) << "OAuth2 refresh token is already loaded."; VerifySessionCookies(); @@ -147,7 +147,7 @@ } } -identity::IdentityManager* OAuth2LoginManager::GetIdentityManager() { +signin::IdentityManager* OAuth2LoginManager::GetIdentityManager() { return IdentityManagerFactory::GetForProfile(user_profile_); } @@ -184,7 +184,7 @@ } else { // TODO(sinhak): Remove this when Account Manager is enabled by default. - identity::IdentityManager* identity_manager = GetIdentityManager(); + signin::IdentityManager* identity_manager = GetIdentityManager(); DCHECK(identity_manager->HasPrimaryAccount()); // On ChromeOS, the primary account is set via
diff --git a/chrome/browser/chromeos/login/signin/oauth2_login_manager.h b/chrome/browser/chromeos/login/signin/oauth2_login_manager.h index 2d912cf18..27e483b 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_login_manager.h +++ b/chrome/browser/chromeos/login/signin/oauth2_login_manager.h
@@ -25,7 +25,7 @@ // OAuth2 refresh tokens or pre-authenticated cookie jar. class OAuth2LoginManager : public KeyedService, public OAuth2LoginVerifier::Delegate, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // Session restore states. enum SessionRestoreState { @@ -152,7 +152,7 @@ const std::vector<gaia::ListedAccount>& accounts) override; void OnListAccountsFailure(bool connection_error) override; - // identity::IdentityManager::Observer implementation: + // signin::IdentityManager::Observer implementation: void OnRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info) override; @@ -161,7 +161,7 @@ void CompleteAuthentication(); // Retrieves IdentityManager for |user_profile_|. - identity::IdentityManager* GetIdentityManager(); + signin::IdentityManager* GetIdentityManager(); // Retrieves the primary account for |user_profile_|. std::string GetPrimaryAccountId();
diff --git a/chrome/browser/chromeos/login/signin/oauth2_login_verifier.cc b/chrome/browser/chromeos/login/signin/oauth2_login_verifier.cc index 397f8c8..130b658 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_login_verifier.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_login_verifier.cc
@@ -18,7 +18,7 @@ OAuth2LoginVerifier::OAuth2LoginVerifier( OAuth2LoginVerifier::Delegate* delegate, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const CoreAccountId& primary_account_id, const std::string& oauthlogin_access_token) : delegate_(delegate), @@ -39,7 +39,7 @@ std::vector<gaia::ListedAccount> accounts; std::vector<gaia::ListedAccount> signed_out_accounts; - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = identity_manager_->GetAccountsInCookieJar(); if (accounts_in_cookie_jar_info.accounts_are_fresh) { OnAccountsInCookieUpdated( @@ -51,7 +51,7 @@ void OAuth2LoginVerifier::VerifyProfileTokens() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - identity::AccountsCookieMutator::AddAccountToCookieCompletedCallback + signin::AccountsCookieMutator::AddAccountToCookieCompletedCallback completion_callback = base::BindOnce(&OAuth2LoginVerifier::OnAddAccountToCookieCompleted, weak_ptr_factory_.GetWeakPtr()); @@ -84,7 +84,7 @@ } void OAuth2LoginVerifier::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { if (error.state() == GoogleServiceAuthError::State::NONE) { VLOG(1) << "ListAccounts successful.";
diff --git a/chrome/browser/chromeos/login/signin/oauth2_login_verifier.h b/chrome/browser/chromeos/login/signin/oauth2_login_verifier.h index 951dbbb6..5b912729 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_login_verifier.h +++ b/chrome/browser/chromeos/login/signin/oauth2_login_verifier.h
@@ -19,7 +19,7 @@ // Given GCMS and primary account id, this class verifies GAIA credentials // (APISID) and rebuild current session's cookie jar for the primary account. -class OAuth2LoginVerifier : public identity::IdentityManager::Observer { +class OAuth2LoginVerifier : public signin::IdentityManager::Observer { public: class Delegate { public: @@ -40,7 +40,7 @@ }; OAuth2LoginVerifier(OAuth2LoginVerifier::Delegate* delegate, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const CoreAccountId& primary_account_id, const std::string& oauthlogin_access_token); ~OAuth2LoginVerifier() override; @@ -55,14 +55,14 @@ private: // IdentityManager::Observer void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; void OnAddAccountToCookieCompleted(const CoreAccountId& account_id, const GoogleServiceAuthError& error); OAuth2LoginVerifier::Delegate* delegate_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; const CoreAccountId primary_account_id_; const std::string access_token_;
diff --git a/chrome/browser/chromeos/login/signin/token_handle_fetcher.cc b/chrome/browser/chromeos/login/signin/token_handle_fetcher.cc index 1cde81c..0ed115b 100644 --- a/chrome/browser/chromeos/login/signin/token_handle_fetcher.cc +++ b/chrome/browser/chromeos/login/signin/token_handle_fetcher.cc
@@ -76,17 +76,17 @@ // owned by this object (thus destroyed when this object is destroyed) and // PrimaryAccountAccessTokenFetcher guarantees that it doesn't invoke its // callback after it is destroyed. - access_token_fetcher_ = std::make_unique< - identity::PrimaryAccountAccessTokenFetcher>( - kAccessTokenFetchId, identity_manager_, scopes, - base::BindOnce(&TokenHandleFetcher::OnAccessTokenFetchComplete, - base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + access_token_fetcher_ = + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( + kAccessTokenFetchId, identity_manager_, scopes, + base::BindOnce(&TokenHandleFetcher::OnAccessTokenFetchComplete, + base::Unretained(this)), + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void TokenHandleFetcher::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) {
diff --git a/chrome/browser/chromeos/login/signin/token_handle_fetcher.h b/chrome/browser/chromeos/login/signin/token_handle_fetcher.h index 7daf142..9ff3cbc1 100644 --- a/chrome/browser/chromeos/login/signin/token_handle_fetcher.h +++ b/chrome/browser/chromeos/login/signin/token_handle_fetcher.h
@@ -16,7 +16,7 @@ #include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h" #include "google_apis/gaia/gaia_oauth_client.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -47,7 +47,7 @@ private: // AccessTokenFetcher::TokenCallback for PrimaryAccountAccessTokenFetcher. void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); // GaiaOAuthClient::Delegate overrides: void OnOAuthError() override; @@ -62,13 +62,13 @@ TokenHandleUtil* token_handle_util_ = nullptr; AccountId account_id_; - identity::IdentityManager* identity_manager_ = nullptr; + signin::IdentityManager* identity_manager_ = nullptr; Profile* profile_ = nullptr; base::TimeTicks tokeninfo_response_start_time_ = base::TimeTicks(); TokenFetchingCallback callback_; std::unique_ptr<gaia::GaiaOAuthClient> gaia_client_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; std::unique_ptr<KeyedServiceShutdownNotifier::Subscription> profile_shutdown_notification_;
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc index dc71f085..9e21f33 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc
@@ -210,7 +210,7 @@ fake_gaia_.fake_gaia()->IssueOAuthToken(kRandomTokenStrForTesting, token_info); fake_gaia_.fake_gaia()->MapEmailToGaiaId( - kTestUserEmail1, identity::GetTestGaiaIdForEmail(kTestUserEmail1)); + kTestUserEmail1, signin::GetTestGaiaIdForEmail(kTestUserEmail1)); } void TearDownOnMainThread() override { @@ -273,8 +273,8 @@ void UpdatePrimaryAccountInfo(Profile* profile) { auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); - identity::SetRefreshTokenForPrimaryAccount(identity_manager, - kRandomTokenStrForTesting); + signin::SetRefreshTokenForPrimaryAccount(identity_manager, + kRandomTokenStrForTesting); CoreAccountInfo core_info = identity_manager->GetPrimaryAccountInfo(); AccountInfo account_info; account_info.email = core_info.email; @@ -289,7 +289,7 @@ account_info.picture_url = embedded_test_server()->GetURL("/avatar.jpg").spec(); account_info.is_child_account = false; - identity::UpdateAccountInfoForAccount(identity_manager, account_info); + signin::UpdateAccountInfoForAccount(identity_manager, account_info); } // Completes the download of the currently logged-in user's profile image. @@ -333,13 +333,13 @@ const AccountId test_account_id1_ = AccountId::FromUserEmailGaiaId( kTestUserEmail1, - identity::GetTestGaiaIdForEmail(kTestUserEmail1)); + signin::GetTestGaiaIdForEmail(kTestUserEmail1)); const AccountId test_account_id2_ = AccountId::FromUserEmailGaiaId( kTestUserEmail2, - identity::GetTestGaiaIdForEmail(kTestUserEmail2)); + signin::GetTestGaiaIdForEmail(kTestUserEmail2)); const AccountId enterprise_account_id_ = AccountId::FromUserEmailGaiaId( FakeGaiaMixin::kEnterpriseUser1, - identity::GetTestGaiaIdForEmail(FakeGaiaMixin::kEnterpriseUser1)); + signin::GetTestGaiaIdForEmail(FakeGaiaMixin::kEnterpriseUser1)); const cryptohome::AccountIdentifier cryptohome_id_ = cryptohome::CreateAccountIdentifierFromAccountId(enterprise_account_id_);
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc index 5300fb3..25d532f8 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc
@@ -793,7 +793,7 @@ return GetCurrentUserImageSize(); } -identity::IdentityManager* UserImageManagerImpl::GetIdentityManager() { +signin::IdentityManager* UserImageManagerImpl::GetIdentityManager() { return IdentityManagerFactory::GetForProfile( ProfileHelper::Get()->GetProfileByUserUnsafe(GetUser())); }
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h b/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h index e94a364..cf98572 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h
@@ -94,7 +94,7 @@ // ProfileDownloaderDelegate: bool NeedsProfilePicture() const override; int GetDesiredImageSideLength() const override; - identity::IdentityManager* GetIdentityManager() override; + signin::IdentityManager* GetIdentityManager() override; network::mojom::URLLoaderFactory* GetURLLoaderFactory() override; std::string GetCachedPictureURL() const override; bool IsPreSignin() const override;
diff --git a/chrome/browser/chromeos/policy/android_management_client.cc b/chrome/browser/chromeos/policy/android_management_client.cc index 6e26fac..9d4d5d1 100644 --- a/chrome/browser/chromeos/policy/android_management_client.cc +++ b/chrome/browser/chromeos/policy/android_management_client.cc
@@ -29,7 +29,7 @@ DeviceManagementService* device_management_service, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::string& account_id, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : device_management_service_(device_management_service), url_loader_factory_(url_loader_factory), account_id_(account_id), @@ -49,7 +49,7 @@ void AndroidManagementClient::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) { @@ -75,7 +75,7 @@ account_id_, "android_management_client", scopes, base::BindOnce(&AndroidManagementClient::OnAccessTokenFetchComplete, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } void AndroidManagementClient::CheckAndroidManagement(
diff --git a/chrome/browser/chromeos/policy/android_management_client.h b/chrome/browser/chromeos/policy/android_management_client.h index 9616564..3d1b8b55 100644 --- a/chrome/browser/chromeos/policy/android_management_client.h +++ b/chrome/browser/chromeos/policy/android_management_client.h
@@ -20,11 +20,11 @@ class DeviceManagementResponse; } -namespace identity { +namespace signin { class AccessTokenFetcher; class IdentityManager; struct AccessTokenInfo; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -53,7 +53,7 @@ DeviceManagementService* service, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::string& account_id, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~AndroidManagementClient(); // Starts sending of check Android management request to DM server, issues @@ -67,7 +67,7 @@ private: void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); // Requests an access token. void RequestAccessToken(); @@ -90,8 +90,8 @@ // The account ID that will be used for the access token fetch. const std::string account_id_; - identity::IdentityManager* identity_manager_; - std::unique_ptr<identity::AccessTokenFetcher> access_token_fetcher_; + signin::IdentityManager* identity_manager_; + std::unique_ptr<signin::AccessTokenFetcher> access_token_fetcher_; StatusCallback callback_;
diff --git a/chrome/browser/chromeos/policy/android_management_client_unittest.cc b/chrome/browser/chromeos/policy/android_management_client_unittest.cc index 997b293..c5e202f 100644 --- a/chrome/browser/chromeos/policy/android_management_client_unittest.cc +++ b/chrome/browser/chromeos/policy/android_management_client_unittest.cc
@@ -69,7 +69,7 @@ std::unique_ptr<AndroidManagementClient> client_; network::TestURLLoaderFactory url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_environment_; + signin::IdentityTestEnvironment identity_test_environment_; }; TEST_F(AndroidManagementClientTest, CheckAndroidManagementCall) {
diff --git a/chrome/browser/chromeos/policy/remote_commands/crd_host_delegate.cc b/chrome/browser/chromeos/policy/remote_commands/crd_host_delegate.cc index 90bcd00c..26661a8 100644 --- a/chrome/browser/chromeos/policy/remote_commands/crd_host_delegate.cc +++ b/chrome/browser/chromeos/policy/remote_commands/crd_host_delegate.cc
@@ -22,7 +22,6 @@ #include "content/public/browser/storage_partition.h" #include "extensions/browser/api/messaging/native_message_host.h" #include "google_apis/gaia/gaia_constants.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "net/base/load_flags.h" #include "net/http/http_request_headers.h" #include "remoting/host/it2me/it2me_native_messaging_host_chromeos.h"
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc index bb57345e..9a45d9819 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc
@@ -415,7 +415,7 @@ // token using the IdentityManager and forwards it to the // UserCloudPolicyManagerChromeOS. This service is automatically created // for regular Profiles but not for testing Profiles. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); ASSERT_TRUE(identity_manager); token_forwarder_ = std::make_unique<UserCloudPolicyTokenForwarder>( @@ -433,7 +433,7 @@ return &test_system_url_loader_factory_; } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_profile_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.cc b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.cc index ff11ad9..fc0bf1c1 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.cc
@@ -38,7 +38,7 @@ UserCloudPolicyTokenForwarder::UserCloudPolicyTokenForwarder( UserCloudPolicyManagerChromeOS* manager, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : manager_(manager), identity_manager_(identity_manager), refresh_oauth_token_timer_(std::make_unique<base::RepeatingTimer>()), @@ -104,18 +104,18 @@ identity::ScopeSet scopes; scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth); scopes.insert(GaiaConstants::kOAuthWrapBridgeUserInfoScope); - access_token_fetcher_ = std::make_unique< - identity::PrimaryAccountAccessTokenFetcher>( - "policy_token_forwarder", identity_manager_, scopes, - base::BindOnce( - &UserCloudPolicyTokenForwarder::OnAccessTokenFetchCompleted, - base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + access_token_fetcher_ = + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( + "policy_token_forwarder", identity_manager_, scopes, + base::BindOnce( + &UserCloudPolicyTokenForwarder::OnAccessTokenFetchCompleted, + base::Unretained(this)), + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void UserCloudPolicyTokenForwarder::OnAccessTokenFetchCompleted( GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { DCHECK(access_token_fetcher_); if (error.state() == GoogleServiceAuthError::NONE) {
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h index 5e4890a7..9149859 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h +++ b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h
@@ -25,7 +25,7 @@ class TimeDelta; } // namespace base -namespace identity { +namespace signin { class PrimaryAccountAccessTokenFetcher; } @@ -54,7 +54,7 @@ // so this object will be Shutdown() first and these pointers can be used // until that point. UserCloudPolicyTokenForwarder(UserCloudPolicyManagerChromeOS* manager, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~UserCloudPolicyTokenForwarder() override; // KeyedService: @@ -82,15 +82,15 @@ private: void StartRequest(); void OnAccessTokenFetchCompleted(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); UserCloudPolicyManagerChromeOS* manager_; - identity::IdentityManager* identity_manager_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + signin::IdentityManager* identity_manager_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; // Last fetched OAuth token. - base::Optional<identity::AccessTokenInfo> oauth_token_; + base::Optional<signin::AccessTokenInfo> oauth_token_; // Timer that measures time to the next OAuth token refresh. Not initialized // if token refresh is not scheduled.
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder_factory.cc b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder_factory.cc index 300e413..fd0011d 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder_factory.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder_factory.cc
@@ -33,7 +33,7 @@ Profile* profile = static_cast<Profile*>(context); UserCloudPolicyManagerChromeOS* manager = profile->GetUserCloudPolicyManagerChromeOS(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (!manager || !identity_manager) return nullptr;
diff --git a/chrome/browser/download/notification/download_notification_browsertest.cc b/chrome/browser/download/notification/download_notification_browsertest.cc index 49508d0..9e8040f 100644 --- a/chrome/browser/download/notification/download_notification_browsertest.cc +++ b/chrome/browser/download/notification/download_notification_browsertest.cc
@@ -1046,10 +1046,10 @@ Profile* profile = chromeos::ProfileHelper::GetProfileByUserIdHashForTest(info.hash); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (!identity_manager->HasPrimaryAccount()) - identity::MakePrimaryAccountAvailable(identity_manager, info.email); + signin::MakePrimaryAccountAvailable(identity_manager, info.email); } std::unique_ptr<NotificationDisplayServiceTester> display_service1_;
diff --git a/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc b/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc index 88842c39..e72b5ae 100644 --- a/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc +++ b/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc
@@ -95,12 +95,12 @@ const char kPrimaryAccountEmail[] = "primary@email.com"; const char kSecondaryAccountEmail[] = "secondary@email.com"; - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); - AccountInfo primary_account_info = identity::MakePrimaryAccountAvailable( + AccountInfo primary_account_info = signin::MakePrimaryAccountAvailable( identity_manager, kPrimaryAccountEmail); AccountInfo secondary_account_info = - identity::MakeAccountAvailable(identity_manager, kSecondaryAccountEmail); + signin::MakeAccountAvailable(identity_manager, kSecondaryAccountEmail); // Sync is running. syncer::SyncService* sync_service = @@ -132,11 +132,11 @@ ASSERT_TRUE(SetGaiaCookieForProfile(profile)); // Set a Sync account with authentication error. const char kAccountEmail[] = "account@email.com"; - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); AccountInfo account_info = - identity::MakePrimaryAccountAvailable(identity_manager, kAccountEmail); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::MakePrimaryAccountAvailable(identity_manager, kAccountEmail); + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager, account_info.account_id, GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason:: @@ -168,7 +168,7 @@ const char kAccountEmail[] = "account@email.com"; auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); AccountInfo account_info = - identity::MakeAccountAvailable(identity_manager, kAccountEmail); + signin::MakeAccountAvailable(identity_manager, kAccountEmail); // Clear browsing data. auto function = base::MakeRefCounted<BrowsingDataRemoveFunction>(); EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc b/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc index e253961..5fa0fffc2 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
@@ -174,7 +174,7 @@ // Derived classes can override this method to set the required authenticated // user in the IdentityManager class. virtual void SetAuthenticatedUser() { - identity::MakePrimaryAccountAvailable( + signin::MakePrimaryAccountAvailable( IdentityManagerFactory::GetForProfile(browser()->profile()), kUserEmail); } @@ -588,7 +588,7 @@ : public EPKChallengeMachineKeyTest { protected: void SetAuthenticatedUser() override { - identity::MakePrimaryAccountAvailable( + signin::MakePrimaryAccountAvailable( IdentityManagerFactory::GetForProfile(browser()->profile()), account_id_.GetUserEmail()); } @@ -601,7 +601,7 @@ const std::string email = "test@chromium.com"; const AccountId account_id_ = AccountId::FromUserEmailGaiaId(email, - identity::GetTestGaiaIdForEmail(email)); + signin::GetTestGaiaIdForEmail(email)); }; TEST_F(EPKChallengeMachineKeyUnmanagedUserTest, UserNotManaged) { @@ -612,7 +612,7 @@ class EPKChallengeUserKeyUnmanagedUserTest : public EPKChallengeUserKeyTest { protected: void SetAuthenticatedUser() override { - identity::MakePrimaryAccountAvailable( + signin::MakePrimaryAccountAvailable( IdentityManagerFactory::GetForProfile(browser()->profile()), account_id_.GetUserEmail()); } @@ -625,7 +625,7 @@ const std::string email = "test@chromium.com"; const AccountId account_id_ = AccountId::FromUserEmailGaiaId(email, - identity::GetTestGaiaIdForEmail(email)); + signin::GetTestGaiaIdForEmail(email)); }; TEST_F(EPKChallengeUserKeyUnmanagedUserTest, UserNotManaged) {
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc index c7e7ecd..3dc0c29 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
@@ -206,7 +206,7 @@ virtual void SetAuthenticatedUser() { auto* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); - identity::MakePrimaryAccountAvailable(identity_manager, kUserEmail); + signin::MakePrimaryAccountAvailable(identity_manager, kUserEmail); } chromeos::FakeCryptohomeClient cryptohome_client_; @@ -589,8 +589,8 @@ void SetAuthenticatedUser() override { auto* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); - identity::MakePrimaryAccountAvailable(identity_manager, - account_id_.GetUserEmail()); + signin::MakePrimaryAccountAvailable(identity_manager, + account_id_.GetUserEmail()); } TestingProfile* CreateProfile() override { @@ -602,7 +602,7 @@ const std::string kOtherEmail = "test@chromium.com"; const AccountId account_id_ = AccountId::FromUserEmailGaiaId( kOtherEmail, - identity::GetTestGaiaIdForEmail(kOtherEmail)); + signin::GetTestGaiaIdForEmail(kOtherEmail)); }; TEST_F(EPKPChallengeMachineKeyUnmanagedUserTest, UserNotManaged) { @@ -615,8 +615,8 @@ void SetAuthenticatedUser() override { auto* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); - identity::MakePrimaryAccountAvailable(identity_manager, - account_id_.GetUserEmail()); + signin::MakePrimaryAccountAvailable(identity_manager, + account_id_.GetUserEmail()); } TestingProfile* CreateProfile() override { @@ -628,7 +628,7 @@ const std::string kOtherEmail = "test@chromium.com"; const AccountId account_id_ = AccountId::FromUserEmailGaiaId( kOtherEmail, - identity::GetTestGaiaIdForEmail(kOtherEmail)); + signin::GetTestGaiaIdForEmail(kOtherEmail)); }; TEST_F(EPKPChallengeUserKeyUnmanagedUserTest, UserNotManaged) {
diff --git a/chrome/browser/extensions/api/identity/identity_api.h b/chrome/browser/extensions/api/identity/identity_api.h index d766319..3ebdb2d 100644 --- a/chrome/browser/extensions/api/identity/identity_api.h +++ b/chrome/browser/extensions/api/identity/identity_api.h
@@ -79,7 +79,7 @@ }; class IdentityAPI : public BrowserContextKeyedAPI, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: typedef std::map<ExtensionTokenKey, IdentityTokenCacheValue> CachedTokens; @@ -128,7 +128,7 @@ static const char* service_name() { return "IdentityAPI"; } static const bool kServiceIsNULLWhileTesting = true; - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info) override; // NOTE: This class must listen for this callback rather than
diff --git a/chrome/browser/extensions/api/identity/identity_apitest.cc b/chrome/browser/extensions/api/identity/identity_apitest.cc index 14ec9eb52..99e6d39 100644 --- a/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chrome/browser/extensions/api/identity/identity_apitest.cc
@@ -353,7 +353,7 @@ // Fix auth error on secondary account or add a new account. void FixOrAddSecondaryAccount() { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile()); std::vector<CoreAccountInfo> accounts = identity_manager->GetAccountsWithRefreshTokens(); @@ -373,7 +373,7 @@ } } if (!fixed_auth_error) { - identity::MakeAccountAvailable(identity_manager, "secondary@example.com"); + signin::MakeAccountAvailable(identity_manager, "secondary@example.com"); } } @@ -382,15 +382,15 @@ EXPECT_FALSE(login_ui_shown_); login_ui_shown_ = true; if (login_ui_result_) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile()); if (IdentityAPI::GetFactoryInstance() ->Get(GetProfile()) ->AreExtensionsRestrictedToPrimaryAccount()) { // Set a primary account. ASSERT_FALSE(identity_manager->HasPrimaryAccount()); - identity::MakeAccountAvailable(identity_manager, "primary@example.com"); - identity::SetPrimaryAccount(identity_manager, "primary@example.com"); + signin::MakeAccountAvailable(identity_manager, "primary@example.com"); + signin::SetPrimaryAccount(identity_manager, "primary@example.com"); } else { FixOrAddSecondaryAccount(); } @@ -495,7 +495,7 @@ return IdentityAPI::GetFactoryInstance()->Get(browser()->profile()); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_profile_adaptor_->identity_test_env(); } @@ -717,7 +717,7 @@ class GetAuthTokenFunctionTest : public IdentityTestWithSignin, - public identity::IdentityManager::DiagnosticsObserver { + public signin::IdentityManager::DiagnosticsObserver { public: GetAuthTokenFunctionTest() { #if BUILDFLAG(ENABLE_DICE_SUPPORT) @@ -814,7 +814,7 @@ base::OnceClosure on_access_token_requested_; private: - // identity::IdentityManager::DiagnosticsObserver: + // signin::IdentityManager::DiagnosticsObserver: void OnAccessTokenRequested(const CoreAccountId& account_id, const std::string& consumer_id, const identity::ScopeSet& scopes) override { @@ -1523,7 +1523,7 @@ signin::SetListAccountsResponseOneAccount( account_info.email, account_info.gaia, &test_url_loader_factory_); auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); - identity::SetFreshnessOfAccountsInGaiaCookie(identity_manager, false); + signin::SetFreshnessOfAccountsInGaiaCookie(identity_manager, false); scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<FakeGetAuthTokenFunction> func(new FakeGetAuthTokenFunction());
diff --git a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc index 59bf1b8..2efd2f7 100644 --- a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc +++ b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc
@@ -184,7 +184,7 @@ // No primary account, try the first account in cookies. DCHECK_EQ(AccountListeningMode::kNotListening, account_listening_mode_); account_listening_mode_ = AccountListeningMode::kListeningCookies; - identity::AccountsInCookieJarInfo accounts_in_cookies = + signin::AccountsInCookieJarInfo accounts_in_cookies = identity_manager->GetAccountsInCookieJar(); if (accounts_in_cookies.accounts_are_fresh) { OnAccountsInCookieUpdated(accounts_in_cookies, @@ -242,7 +242,7 @@ } void IdentityGetAuthTokenFunction::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { if (account_listening_mode_ != AccountListeningMode::kListeningCookies) return; @@ -707,7 +707,7 @@ void IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { token_key_account_access_token_fetcher_.reset(); if (error.state() == GoogleServiceAuthError::NONE) { OnGetAccessTokenComplete(access_token_info.token, @@ -773,7 +773,7 @@ base::BindOnce( &IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); return; } } @@ -786,7 +786,7 @@ base::BindOnce( &IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } void IdentityGetAuthTokenFunction::StartGaiaRequest(
diff --git a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h index 1edfd38..0eb440b 100644 --- a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h +++ b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h
@@ -21,10 +21,10 @@ #include "google_apis/gaia/oauth2_access_token_manager.h" #include "google_apis/gaia/oauth2_mint_token_flow.h" -namespace identity { +namespace signin { class AccessTokenFetcher; struct AccessTokenInfo; -} // namespace identity +} // namespace signin namespace extensions { @@ -48,7 +48,7 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction, public GaiaWebAuthFlow::Delegate, public IdentityMintRequestQueue::Request, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, #if defined(OS_CHROMEOS) public OAuth2AccessTokenManager::Consumer, #endif @@ -90,7 +90,7 @@ #endif void OnAccessTokenFetchCompleted(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // Invoked on completion of the access token fetcher. // Exposed for testing. @@ -113,7 +113,7 @@ // Pending fetcher for an access token for |token_key_.account_id| (via // IdentityManager). - std::unique_ptr<identity::AccessTokenFetcher> + std::unique_ptr<signin::AccessTokenFetcher> token_key_account_access_token_fetcher_; private: @@ -136,11 +136,11 @@ // Called when the AccountInfo that this instance should use is available. void OnReceivedExtensionAccountInfo(const CoreAccountInfo* account_info); - // identity::IdentityManager::Observer implementation: + // signin::IdentityManager::Observer implementation: void OnRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info) override; void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; void OnPrimaryAccountSet( const CoreAccountInfo& primary_account_info) override; @@ -218,7 +218,7 @@ std::unique_ptr<base::CallbackList<void()>::Subscription> identity_api_shutdown_subscription_; - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> scoped_identity_manager_observer_; // This class can be listening to account changes, but only for one type of
diff --git a/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h b/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h index f029351..aa24739 100644 --- a/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h +++ b/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h
@@ -21,7 +21,7 @@ class EventRouter; } -namespace identity { +namespace signin { class IdentityManager; } @@ -103,7 +103,7 @@ std::string GetProfileUserName(); content::BrowserContext* context_; - identity::IdentityManager* identity_manager_ = nullptr; + signin::IdentityManager* identity_manager_ = nullptr; EventRouter* event_router_ = nullptr; std::unique_ptr<policy::CloudPolicyClient> client_;
diff --git a/chrome/browser/extensions/updater/extension_updater_unittest.cc b/chrome/browser/extensions/updater/extension_updater_unittest.cc index 4cf9511..cc7a34b 100644 --- a/chrome/browser/extensions/updater/extension_updater_unittest.cc +++ b/chrome/browser/extensions/updater/extension_updater_unittest.cc
@@ -266,7 +266,7 @@ PrefService* pref_service() { return prefs_->pref_service(); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_.get(); } @@ -328,7 +328,7 @@ std::unique_ptr<ExtensionDownloader> CreateExtensionDownloaderWithIdentity( ExtensionDownloaderDelegate* delegate) { - identity_test_env_ = std::make_unique<identity::IdentityTestEnvironment>(); + identity_test_env_ = std::make_unique<signin::IdentityTestEnvironment>(); account_info_ = identity_test_env_->MakePrimaryAccountAvailable( "bobloblaw@lawblog.example.com"); @@ -339,7 +339,7 @@ } AccountInfo account_info_; - std::unique_ptr<identity::IdentityTestEnvironment> identity_test_env_; + std::unique_ptr<signin::IdentityTestEnvironment> identity_test_env_; ExtensionDownloaderDelegate* downloader_delegate_override_;
diff --git a/chrome/browser/feedback/feedback_uploader_chrome.cc b/chrome/browser/feedback/feedback_uploader_chrome.cc index 61507172..277564fa 100644 --- a/chrome/browser/feedback/feedback_uploader_chrome.cc +++ b/chrome/browser/feedback/feedback_uploader_chrome.cc
@@ -32,7 +32,7 @@ void FeedbackUploaderChrome::AccessTokenAvailable( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { DCHECK(token_fetcher_); token_fetcher_.reset(); if (error.state() == GoogleServiceAuthError::NONE) { @@ -56,18 +56,17 @@ // ctor. Profile* profile = Profile::FromBrowserContext(context()); DCHECK(profile); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (identity_manager && identity_manager->HasPrimaryAccount()) { identity::ScopeSet scopes; scopes.insert("https://www.googleapis.com/auth/supportcontent"); - token_fetcher_ = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( - "feedback_uploader_chrome", identity_manager, scopes, - base::BindOnce(&FeedbackUploaderChrome::AccessTokenAvailable, - base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( + "feedback_uploader_chrome", identity_manager, scopes, + base::BindOnce(&FeedbackUploaderChrome::AccessTokenAvailable, + base::Unretained(this)), + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); return; }
diff --git a/chrome/browser/feedback/feedback_uploader_chrome.h b/chrome/browser/feedback/feedback_uploader_chrome.h index c83333a..fa864d28 100644 --- a/chrome/browser/feedback/feedback_uploader_chrome.h +++ b/chrome/browser/feedback/feedback_uploader_chrome.h
@@ -12,9 +12,9 @@ #include "components/feedback/feedback_uploader.h" #include "components/signin/public/identity_manager/access_token_info.h" -namespace identity { +namespace signin { class PrimaryAccountAccessTokenFetcher; -} // namespace identity +} // namespace signin class GoogleServiceAuthError; @@ -48,9 +48,9 @@ network::ResourceRequest* resource_request) override; void AccessTokenAvailable(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; std::string access_token_;
diff --git a/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service.cc b/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service.cc index 4b20f69..ca74d5d 100644 --- a/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service.cc +++ b/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service.cc
@@ -13,7 +13,7 @@ DesktopProfileSessionDurationsService::DesktopProfileSessionDurationsService( syncer::SyncService* sync_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, DesktopSessionDurationTracker* tracker) : metrics_recorder_( std::make_unique<syncer::SyncSessionDurationsMetricsRecorder>( @@ -41,7 +41,8 @@ } void DesktopProfileSessionDurationsService::OnSessionEnded( - base::TimeDelta session_length) { + base::TimeDelta session_length, + base::TimeTicks session_end) { metrics_recorder_->OnSessionEnded(session_length); }
diff --git a/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service.h b/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service.h index 37a2a2a..8634270 100644 --- a/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service.h +++ b/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service.h
@@ -10,7 +10,7 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/sync/driver/sync_session_durations_metrics_recorder.h" -namespace identity { +namespace signin { class IdentityManager; } namespace syncer { @@ -28,13 +28,14 @@ // Callers must ensure that the parameters outlive this object. DesktopProfileSessionDurationsService( syncer::SyncService* sync_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, DesktopSessionDurationTracker* tracker); ~DesktopProfileSessionDurationsService() override; // DesktopSessionDurationtracker::Observer: void OnSessionStarted(base::TimeTicks session_start) override; - void OnSessionEnded(base::TimeDelta session_length) override; + void OnSessionEnded(base::TimeDelta session_length, + base::TimeTicks session_end) override; // KeyedService: void Shutdown() override;
diff --git a/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service_factory.cc b/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service_factory.cc index 3fe21332..6cc70cc 100644 --- a/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service_factory.cc +++ b/chrome/browser/metrics/desktop_session_duration/desktop_profile_session_durations_service_factory.cc
@@ -47,7 +47,7 @@ syncer::SyncService* sync_service = ProfileSyncServiceFactory::GetForProfile(profile); DesktopSessionDurationTracker* tracker = DesktopSessionDurationTracker::Get(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); return new DesktopProfileSessionDurationsService(sync_service, identity_manager, tracker);
diff --git a/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.cc b/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.cc index 2fbf85d5..161fd20 100644 --- a/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.cc +++ b/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.cc
@@ -156,7 +156,7 @@ delta = base::TimeDelta(); for (Observer& observer : observer_list_) - observer.OnSessionEnded(delta); + observer.OnSessionEnded(delta, session_start_ + delta); DVLOG(4) << "Logging session length of " << delta.InSeconds() << " seconds.";
diff --git a/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h b/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h index 4a4f4a9..3764284 100644 --- a/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h +++ b/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h
@@ -24,7 +24,8 @@ public: virtual ~Observer() {} virtual void OnSessionStarted(base::TimeTicks session_start) {} - virtual void OnSessionEnded(base::TimeDelta session_length) {} + virtual void OnSessionEnded(base::TimeDelta session_length, + base::TimeTicks session_end) {} }; // Creates the |DesktopSessionDurationTracker| instance and initializes the
diff --git a/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker_unittest.cc b/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker_unittest.cc index 8a7fb2b..225527f 100644 --- a/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker_unittest.cc +++ b/chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker_unittest.cc
@@ -52,7 +52,8 @@ void OnSessionStarted(base::TimeTicks session_start) override { session_started_count_ = true; } - void OnSessionEnded(base::TimeDelta session_length) override { + void OnSessionEnded(base::TimeDelta session_length, + base::TimeTicks session_end) override { session_ended_count_ = true; }
diff --git a/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc b/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc index c2e3227..dc50093 100644 --- a/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc +++ b/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc
@@ -141,7 +141,7 @@ } PrefService* pref_service = profile->GetPrefs(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); UrlLanguageHistogram* language_histogram = UrlLanguageHistogramFactory::GetForBrowserContext(profile); @@ -270,7 +270,7 @@ g_browser_process->local_state(), base::DefaultClock::GetInstance()); // Create the ContentSuggestionsService. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); HistoryService* history_service = HistoryServiceFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS);
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc index 346a34a..ab0694d6 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc
@@ -54,14 +54,6 @@ handle->GetFrameTreeNodeId()); } -void RecordSingleFeatureUsage(content::RenderFrameHost* rfh, - blink::mojom::WebFeature web_feature) { - page_load_metrics::mojom::PageLoadFeatures page_load_features( - {web_feature}, {} /* css_properties */, {} /* animated_css_properties */); - page_load_metrics::MetricsWebContentsObserver::RecordFeatureUsage( - rfh, page_load_features); -} - using ResourceMimeType = AdsPageLoadMetricsObserver::ResourceMimeType; } // namespace @@ -517,13 +509,6 @@ resource, process_id, GetDelegate()->GetResourceTracker()); if (unaccounted_ad_bytes) ancestor_data->AdjustAdBytes(unaccounted_ad_bytes, mime_type); - - if (ancestor_data->size_intervention_status() == - FrameData::FrameSizeInterventionStatus::kTriggered) { - RecordSingleFeatureUsage( - GetDelegate()->GetWebContents()->GetMainFrame(), - blink::mojom::WebFeature::kAdFrameSizeIntervention); - } } void AdsPageLoadMetricsObserver::RecordAdFrameUkm(ukm::SourceId source_id) { @@ -805,16 +790,6 @@ UMA_HISTOGRAM_COUNTS_10000, visibility, std::min(ad_frame_data.frame_size().width(), ad_frame_data.frame_size().height())); - ADS_HISTOGRAM("FrameCounts.AdFrames.PerFrame.SizeIntervention", - UMA_HISTOGRAM_ENUMERATION, visibility, - ad_frame_data.size_intervention_status()); - - if (ad_frame_data.size_intervention_status() == - FrameData::FrameSizeInterventionStatus::kTriggered) { - ADS_HISTOGRAM( - "FrameCounts.AdFrames.PerFrame.SizeIntervention.MediaStatus", - UMA_HISTOGRAM_ENUMERATION, visibility, ad_frame_data.media_status()); - } ADS_HISTOGRAM("Bytes.AdFrames.PerFrame.Total", PAGE_BYTES_HISTOGRAM, visibility, ad_frame_data.bytes());
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc index 2ad372a..f00f7f01 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc
@@ -63,14 +63,6 @@ "PageLoad.Clients.Ads.FrameCounts.AdFrames.PerFrame." "SmallestDimension"; -const char kAdFrameSizeInterventionHistogramId[] = - "PageLoad.Clients.Ads.FrameCounts.AdFrames.PerFrame." - "SizeIntervention"; - -const char kAdFrameSizeInterventionMediaStatusHistogramId[] = - "PageLoad.Clients.Ads.FrameCounts.AdFrames.PerFrame." - "SizeIntervention.MediaStatus"; - const char kAggregateCpuPercentHistogramId[] = "PageLoad.Clients.Ads.Cpu.FullPage.PercentUsage"; @@ -533,6 +525,68 @@ "PageLoad.Clients.Ads.Bytes.FullPage.PercentSameOrigin", 12.5, 1); } +IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest, + AdFrameRecordMediaStatusNotPlayed) { + ukm::TestAutoSetUkmRecorder ukm_recorder; + auto waiter = CreatePageLoadMetricsTestWaiter(); + + ui_test_utils::NavigateToURL( + browser(), + embedded_test_server()->GetURL("/ads_observer/same_origin_ad.html")); + + waiter->AddMinimumCompleteResourcesExpectation(4); + waiter->Wait(); + + ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); + + auto entries = + ukm_recorder.GetEntriesByName(ukm::builders::AdFrameLoad::kEntryName); + EXPECT_EQ(1u, entries.size()); + ukm_recorder.ExpectEntryMetric( + entries.front(), ukm::builders::AdFrameLoad::kStatus_MediaName, + static_cast<int>(FrameData::MediaStatus::kNotPlayed)); +} + +// Flaky on all platforms, http://crbug.com/972822. +IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest, + DISABLED_AdFrameRecordMediaStatusPlayed) { + base::HistogramTester histogram_tester; + ukm::TestAutoSetUkmRecorder ukm_recorder; + auto waiter = CreatePageLoadMetricsTestWaiter(); + ui_test_utils::NavigateToURL( + browser(), + embedded_test_server()->GetURL("/ad_tagging/frame_factory.html")); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + + // Create a second frame that will not receive activation. + EXPECT_TRUE(content::ExecuteScriptWithoutUserGesture( + web_contents, + "createAdFrame('/ad_tagging/multiple_mimes.html', 'test');")); + + waiter->AddMinimumCompleteResourcesExpectation(8); + waiter->Wait(); + + // Wait for the video to autoplay in the frame. + content::RenderFrameHost* ad_frame = + ChildFrameAt(web_contents->GetMainFrame(), 0); + const std::string play_script = + "var video = document.getElementsByTagName('video')[0];" + "video.onplaying = () => { " + "window.domAutomationController.send('true'); };" + "video.play();"; + EXPECT_EQ("true", content::EvalJsWithManualReply(ad_frame, play_script)); + + ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); + + auto entries = + ukm_recorder.GetEntriesByName(ukm::builders::AdFrameLoad::kEntryName); + EXPECT_EQ(1u, entries.size()); + ukm_recorder.ExpectEntryMetric( + entries.front(), ukm::builders::AdFrameLoad::kStatus_MediaName, + static_cast<int>(FrameData::MediaStatus::kPlayed)); +} + class AdsPageLoadMetricsTestWaiter : public page_load_metrics::PageLoadMetricsTestWaiter { public: @@ -811,207 +865,6 @@ entries.front(), ukm::builders::AdFrameLoad::kLoading_CacheBytesName, 0); } -IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverResourceBrowserTest, - AdFrameSizeInterventionTriggered) { - base::HistogramTester histogram_tester; - ukm::TestAutoSetUkmRecorder ukm_recorder; - SetRulesetWithRules( - {subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js")}); - embedded_test_server()->ServeFilesFromSourceDirectory( - "chrome/test/data/ads_observer"); - content::SetupCrossSiteRedirector(embedded_test_server()); - - const char kHttpResponseHeader[] = - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/html; charset=utf-8\r\n" - "\r\n"; - auto resource_response = - std::make_unique<net::test_server::ControllableHttpResponse>( - embedded_test_server(), "/incomplete_resource.js", - true /*relative_url_is_prefix*/); - ASSERT_TRUE(embedded_test_server()->Start()); - - auto waiter = CreateAdsPageLoadMetricsTestWaiter(); - - browser()->OpenURL(content::OpenURLParams( - embedded_test_server()->GetURL("/ad_with_incomplete_resource.html"), - content::Referrer(), WindowOpenDisposition::CURRENT_TAB, - ui::PAGE_TRANSITION_TYPED, false)); - - waiter->AddMinimumCompleteResourcesExpectation(3); - waiter->Wait(); - - // Load a resource large enough to trigger intervention. - resource_response->WaitForRequest(); - resource_response->Send(kHttpResponseHeader); - resource_response->Send( - std::string(FrameData::kFrameSizeInterventionByteThreshold, ' ')); - resource_response->Done(); - - // Wait for the resource to finish loading. - waiter->AddMinimumCompleteResourcesExpectation(4); - waiter->Wait(); - - // Close all tabs to report metrics. - browser()->tab_strip_model()->CloseAllTabs(); - - histogram_tester.ExpectBucketCount( - kAdFrameSizeInterventionHistogramId, - FrameData::FrameSizeInterventionStatus::kTriggered, 1); - histogram_tester.ExpectBucketCount( - kAdFrameSizeInterventionMediaStatusHistogramId, - FrameData::MediaStatus::kNotPlayed, 1); - histogram_tester.ExpectBucketCount( - "Blink.UseCounter.Features", - blink::mojom::WebFeature::kAdFrameSizeIntervention, 1); - - auto entries = - ukm_recorder.GetEntriesByName(ukm::builders::AdFrameLoad::kEntryName); - EXPECT_EQ(1u, entries.size()); - ukm_recorder.ExpectEntryMetric( - entries.front(), ukm::builders::AdFrameLoad::kStatus_MediaName, - static_cast<int>(FrameData::MediaStatus::kNotPlayed)); -} - -// Flaky on all platforms, http://crbug.com/972822. -IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverResourceBrowserTest, - DISABLED_AdFrameSizeInterventionMediaStatusPlayed) { - base::HistogramTester histogram_tester; - ukm::TestAutoSetUkmRecorder ukm_recorder; - embedded_test_server()->ServeFilesFromSourceDirectory( - "chrome/test/data/ad_tagging"); - content::SetupCrossSiteRedirector(embedded_test_server()); - - const char kHttpResponseHeader[] = - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/html; charset=utf-8\r\n" - "\r\n"; - auto resource_response = - std::make_unique<net::test_server::ControllableHttpResponse>( - embedded_test_server(), "/style.css", - true /*relative_url_is_prefix*/); - ASSERT_TRUE(embedded_test_server()->Start()); - - auto waiter = CreateAdsPageLoadMetricsTestWaiter(); - - content::WebContents* contents = - browser()->tab_strip_model()->GetActiveWebContents(); - GURL url = embedded_test_server()->GetURL("foo.com", "/frame_factory.html"); - ui_test_utils::NavigateToURL(browser(), url); - - // This frame will load a video. - EXPECT_TRUE( - ExecJs(contents, "createAdFrame('multiple_mimes.html', 'test');")); - - // Intercept one of the resources loaded by "multiple_mimes.html" and load - // enough bytes to trigger the intervention. - resource_response->WaitForRequest(); - resource_response->Send(kHttpResponseHeader); - resource_response->Send( - std::string(FrameData::kFrameSizeInterventionByteThreshold, ' ')); - resource_response->Done(); - - waiter->AddMinimumAdResourceExpectation(8); - waiter->Wait(); - - // Wait for the video to autoplay in the frame. - content::RenderFrameHost* ad_frame = - ChildFrameAt(contents->GetMainFrame(), 0); - EXPECT_EQ("true", content::EvalJsWithManualReply( - ad_frame, - "var video = document.getElementsByTagName('video')[0];" - "video.onplaying = () => { " - "window.domAutomationController.send('true'); };" - "video.play();", - content::EXECUTE_SCRIPT_NO_USER_GESTURE)); - - // Close all tabs to report metrics. - browser()->tab_strip_model()->CloseAllTabs(); - - histogram_tester.ExpectBucketCount( - kAdFrameSizeInterventionHistogramId, - FrameData::FrameSizeInterventionStatus::kTriggered, 1); - histogram_tester.ExpectBucketCount( - kAdFrameSizeInterventionMediaStatusHistogramId, - FrameData::MediaStatus::kPlayed, 1); - histogram_tester.ExpectBucketCount( - "Blink.UseCounter.Features", - blink::mojom::WebFeature::kAdFrameSizeIntervention, 1); - - auto entries = - ukm_recorder.GetEntriesByName(ukm::builders::AdFrameLoad::kEntryName); - EXPECT_EQ(1u, entries.size()); - ukm_recorder.ExpectEntryMetric( - entries.front(), ukm::builders::AdFrameLoad::kStatus_MediaName, - static_cast<int>(FrameData::MediaStatus::kPlayed)); -} - -IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverResourceBrowserTest, - AdFrameSizeInterventionNotActivatedOnFrameWithGesture) { - base::HistogramTester histogram_tester; - ukm::TestAutoSetUkmRecorder ukm_recorder; - SetRulesetWithRules( - {subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js")}); - embedded_test_server()->ServeFilesFromSourceDirectory( - "chrome/test/data/ads_observer"); - content::SetupCrossSiteRedirector(embedded_test_server()); - - const char kHttpResponseHeader[] = - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/html; charset=utf-8\r\n" - "\r\n"; - auto resource_response = - std::make_unique<net::test_server::ControllableHttpResponse>( - embedded_test_server(), "/incomplete_resource.js", - true /*relative_url_is_prefix*/); - ASSERT_TRUE(embedded_test_server()->Start()); - - auto waiter = CreateAdsPageLoadMetricsTestWaiter(); - - browser()->OpenURL(content::OpenURLParams( - embedded_test_server()->GetURL("/ad_with_incomplete_resource.html"), - content::Referrer(), WindowOpenDisposition::CURRENT_TAB, - ui::PAGE_TRANSITION_TYPED, false)); - - waiter->AddMinimumCompleteResourcesExpectation(3); - waiter->Wait(); - - // Activate one frame by executing a dummy script. - content::RenderFrameHost* ad_frame = - ChildFrameAt(web_contents()->GetMainFrame(), 0); - const std::string no_op_script = "// No-op script"; - EXPECT_TRUE(ExecuteScript(ad_frame, no_op_script)); - - // Load a resource large enough to trigger intervention. - resource_response->WaitForRequest(); - resource_response->Send(kHttpResponseHeader); - resource_response->Send( - std::string(FrameData::kFrameSizeInterventionByteThreshold, ' ')); - resource_response->Done(); - - // Wait for the resource to finish loading. - waiter->AddMinimumCompleteResourcesExpectation(4); - waiter->Wait(); - - // Close all tabs to report metrics. - browser()->tab_strip_model()->CloseAllTabs(); - - histogram_tester.ExpectBucketCount( - kAdFrameSizeInterventionHistogramId, - FrameData::FrameSizeInterventionStatus::kNone, 1); - histogram_tester.ExpectTotalCount( - kAdFrameSizeInterventionMediaStatusHistogramId, 0); - histogram_tester.ExpectBucketCount( - "Blink.UseCounter.Features", - blink::mojom::WebFeature::kAdFrameSizeIntervention, 0); - auto entries = - ukm_recorder.GetEntriesByName(ukm::builders::AdFrameLoad::kEntryName); - EXPECT_EQ(1u, entries.size()); - ukm_recorder.ExpectEntryMetric( - entries.front(), ukm::builders::AdFrameLoad::kStatus_UserActivationName, - static_cast<int>(FrameData::UserActivationStatus::kReceivedActivation)); -} - // Verify that UKM metrics are recorded correctly. IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverResourceBrowserTest, RecordedUKMMetrics) {
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc index d5eab50..8ef3b3d 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc
@@ -63,8 +63,7 @@ user_activation_status_(UserActivationStatus::kNoActivation), is_display_none_(false), visibility_(FrameVisibility::kVisible), - frame_size_(gfx::Size()), - size_intervention_status_(FrameSizeInterventionStatus::kNone) {} + frame_size_(gfx::Size()) {} FrameData::~FrameData() = default; @@ -118,11 +117,6 @@ same_origin_bytes_ += resource->encoded_body_length; } - if (bytes_ > kFrameSizeInterventionByteThreshold && - user_activation_status_ == UserActivationStatus::kNoActivation) { - size_intervention_status_ = FrameSizeInterventionStatus::kTriggered; - } - if (resource->reported_as_ad_resource) { ad_network_bytes_ += resource->delta_bytes; ad_bytes_ += resource->delta_bytes;
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h index 3f50ff8..4a4d143 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h
@@ -34,15 +34,6 @@ kMaxValue = kAnyVisibility, }; - // Whether or not the frame size intervention would have triggered on - // this frame. These values are persisted to logs. Entries should not be - // renumbered and numeric values should never be reused. - enum class FrameSizeInterventionStatus { - kNone = 0, - kTriggered = 1, - kMaxValue = kTriggered, - }; - // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. For any additions, also update the // corresponding PageEndReason enum in enums.xml. @@ -80,9 +71,6 @@ kMaxValue = kPlayed, }; - // Maximum number of bytes allowed to be loaded by a frame. - static const int kFrameSizeInterventionByteThreshold = 1050 * 1024; - // Window over which to consider cpu time spent in an ad_frame. static constexpr base::TimeDelta kCpuWindowSize = base::TimeDelta::FromSeconds(30); @@ -179,10 +167,6 @@ gfx::Size frame_size() const { return frame_size_; } - FrameSizeInterventionStatus size_intervention_status() const { - return size_intervention_status_; - } - MediaStatus media_status() const { return media_status_; } void set_media_status(MediaStatus media_status) { @@ -265,10 +249,6 @@ url::Origin origin_; MediaStatus media_status_ = MediaStatus::kNotPlayed; - // Indicates whether or not this frame would have triggered a size - // intervention. - FrameSizeInterventionStatus size_intervention_status_; - DISALLOW_COPY_AND_ASSIGN(FrameData); };
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index 61b24e9..04aa289 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -142,7 +142,7 @@ return nullptr; } -const identity::IdentityManager* GetIdentityManagerForOriginalProfile( +const signin::IdentityManager* GetIdentityManagerForOriginalProfile( Profile* profile) { return IdentityManagerFactory::GetForProfile(profile->GetOriginalProfile()); }
diff --git a/chrome/browser/password_manager/password_store_signin_notifier_impl.cc b/chrome/browser/password_manager/password_store_signin_notifier_impl.cc index d6c1a45c..64d58db28 100644 --- a/chrome/browser/password_manager/password_store_signin_notifier_impl.cc +++ b/chrome/browser/password_manager/password_store_signin_notifier_impl.cc
@@ -9,7 +9,7 @@ namespace password_manager { PasswordStoreSigninNotifierImpl::PasswordStoreSigninNotifierImpl( - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : identity_manager_(identity_manager) { DCHECK(identity_manager_); }
diff --git a/chrome/browser/password_manager/password_store_signin_notifier_impl.h b/chrome/browser/password_manager/password_store_signin_notifier_impl.h index a430019..f1e06c3 100644 --- a/chrome/browser/password_manager/password_store_signin_notifier_impl.h +++ b/chrome/browser/password_manager/password_store_signin_notifier_impl.h
@@ -15,10 +15,10 @@ // PasswordStore. class PasswordStoreSigninNotifierImpl : public PasswordStoreSigninNotifier, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: explicit PasswordStoreSigninNotifierImpl( - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~PasswordStoreSigninNotifierImpl() override; // PasswordStoreSigninNotifier implementations. @@ -30,7 +30,7 @@ void OnExtendedAccountInfoRemoved(const AccountInfo& info) override; private: - identity::IdentityManager* identity_manager_ = nullptr; + signin::IdentityManager* identity_manager_ = nullptr; }; } // namespace password_manager
diff --git a/chrome/browser/password_manager/password_store_signin_notifier_impl_unittest.cc b/chrome/browser/password_manager/password_store_signin_notifier_impl_unittest.cc index c5e6407..8552ace 100644 --- a/chrome/browser/password_manager/password_store_signin_notifier_impl_unittest.cc +++ b/chrome/browser/password_manager/password_store_signin_notifier_impl_unittest.cc
@@ -27,17 +27,17 @@ store_->ShutdownOnUIThread(); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return identity_test_env()->identity_manager(); } protected: base::test::ScopedTaskEnvironment scoped_task_environment_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; scoped_refptr<MockPasswordStore> store_; };
diff --git a/chrome/browser/password_manager/touch_to_fill_controller.cc b/chrome/browser/password_manager/touch_to_fill_controller.cc index 7e754a7..53f91b5 100644 --- a/chrome/browser/password_manager/touch_to_fill_controller.cc +++ b/chrome/browser/password_manager/touch_to_fill_controller.cc
@@ -16,7 +16,7 @@ #include "chrome/browser/ui/autofill/autofill_popup_controller.h" #include "components/autofill/core/browser/ui/popup_item_ids.h" #include "components/autofill/core/browser/ui/suggestion.h" -#include "components/password_manager/core/common/password_manager_features.h" +#include "components/autofill/core/common/autofill_util.h" using content::WebContents; @@ -41,8 +41,7 @@ // static bool TouchToFillController::AllowedForWebContents(WebContents* web_contents) { - return base::FeatureList::IsEnabled( - password_manager::features::kTouchToFillAndroid); + return autofill::IsTouchToFillEnabled(); } void TouchToFillController::Show(
diff --git a/chrome/browser/password_manager/touch_to_fill_controller_unittest.cc b/chrome/browser/password_manager/touch_to_fill_controller_unittest.cc index 446d0550..6e0f98e 100644 --- a/chrome/browser/password_manager/touch_to_fill_controller_unittest.cc +++ b/chrome/browser/password_manager/touch_to_fill_controller_unittest.cc
@@ -10,7 +10,7 @@ #include "chrome/browser/autofill/mock_manual_filling_controller.h" #include "components/autofill/core/browser/ui/popup_item_ids.h" #include "components/autofill/core/browser/ui/suggestion.h" -#include "components/password_manager/core/common/password_manager_features.h" +#include "components/autofill/core/common/autofill_features.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -46,8 +46,7 @@ << is_touch_to_fill_enabled); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatureState( - password_manager::features::kTouchToFillAndroid, - is_touch_to_fill_enabled); + autofill::features::kTouchToFillAndroid, is_touch_to_fill_enabled); EXPECT_EQ(is_touch_to_fill_enabled, TouchToFillController::AllowedForWebContents(nullptr)); }
diff --git a/chrome/browser/payments/chrome_payment_request_delegate.cc b/chrome/browser/payments/chrome_payment_request_delegate.cc index 220214e..0ea908a 100644 --- a/chrome/browser/payments/chrome_payment_request_delegate.cc +++ b/chrome/browser/payments/chrome_payment_request_delegate.cc
@@ -144,7 +144,7 @@ // authenticated. Profile* profile = Profile::FromBrowserContext(web_contents_->GetBrowserContext()); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (identity_manager && identity_manager->HasPrimaryAccount()) return identity_manager->GetPrimaryAccountInfo().email;
diff --git a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc index 8febbdf..4125642 100644 --- a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc
@@ -216,7 +216,7 @@ auto* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); ASSERT_TRUE(identity_manager); - identity::SetPrimaryAccount(identity_manager, GetTestUser()); + signin::SetPrimaryAccount(identity_manager, GetTestUser()); UserCloudPolicyManager* policy_manager = browser()->profile()->GetUserCloudPolicyManager();
diff --git a/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc index 22955a53..f6fcbf3 100644 --- a/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc
@@ -175,7 +175,7 @@ // the username to the UserCloudPolicyValidator. auto* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); - identity::SetPrimaryAccount(identity_manager, "user@example.com"); + signin::SetPrimaryAccount(identity_manager, "user@example.com"); ASSERT_TRUE(policy_manager()); policy_manager()->Connect(
diff --git a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc index e2cd466..51f9ba1 100644 --- a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc
@@ -180,7 +180,7 @@ #else // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass // the account id to the UserCloudPolicyValidator. - identity::SetPrimaryAccount( + signin::SetPrimaryAccount( IdentityManagerFactory::GetForProfile(browser()->profile()), PolicyBuilder::kFakeUsername); @@ -219,7 +219,7 @@ IdentityManagerFactory::GetForProfile(browser()->profile()) ->GetPrimaryAccountMutator(); primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC); }
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service.cc b/chrome/browser/policy/cloud/user_policy_signin_service.cc index 78d29c4..455e474 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service.cc
@@ -35,7 +35,7 @@ PrefService* local_state, DeviceManagementService* device_management_service, UserCloudPolicyManager* policy_manager, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> system_url_loader_factory) : UserPolicySigninServiceBase(profile, local_state,
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service.h b/chrome/browser/policy/cloud/user_policy_signin_service.h index bd0383b..cd838c3 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service.h
@@ -36,7 +36,7 @@ PrefService* local_state, DeviceManagementService* device_management_service, UserCloudPolicyManager* policy_manager, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> system_url_loader_factory); ~UserPolicySigninService() override; @@ -49,7 +49,7 @@ const std::string& account_id, const PolicyRegistrationCallback& callback); - // identity::IdentityManager::Observer implementation: + // signin::IdentityManager::Observer implementation: // UserPolicySigninServiceBase is already an observer of IdentityManager. void OnPrimaryAccountSet(const CoreAccountInfo& account_info) override; void OnRefreshTokenUpdatedForAccount(
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 fdf5c8f4..07e41f73 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_base.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_base.cc
@@ -30,7 +30,7 @@ PrefService* local_state, DeviceManagementService* device_management_service, UserCloudPolicyManager* policy_manager, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> system_url_loader_factory) : policy_manager_(policy_manager), identity_manager_(identity_manager),
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 fc6d5e1c..9d60d89 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_base.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service_base.h
@@ -49,7 +49,7 @@ public CloudPolicyClient::Observer, public CloudPolicyService::Observer, public content::NotificationObserver, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // The callback invoked once policy registration is complete. Passed // |dm_token| and |client_id| parameters are empty if policy registration @@ -68,7 +68,7 @@ PrefService* local_state, DeviceManagementService* device_management_service, UserCloudPolicyManager* policy_manager, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> system_url_loader_factory); ~UserPolicySigninServiceBase() override; @@ -84,7 +84,7 @@ scoped_refptr<network::SharedURLLoaderFactory> profile_url_loader_factory, const PolicyFetchCallback& callback); - // identity::IdentityManager::Observer implementation: + // signin::IdentityManager::Observer implementation: void OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) override; @@ -150,7 +150,7 @@ // Convenience helpers to get the associated UserCloudPolicyManager and // IdentityManager. UserCloudPolicyManager* policy_manager() { return policy_manager_; } - identity::IdentityManager* identity_manager() { return identity_manager_; } + signin::IdentityManager* identity_manager() { return identity_manager_; } content::NotificationRegistrar* registrar() { return ®istrar_; } @@ -158,7 +158,7 @@ // Weak pointer to the UserCloudPolicyManager and IdentityManager this service // is associated with. UserCloudPolicyManager* policy_manager_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; content::NotificationRegistrar registrar_;
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 87da8c17..1a7e712 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc
@@ -45,7 +45,7 @@ PrefService* local_state, DeviceManagementService* device_management_service, UserCloudPolicyManager* policy_manager, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> system_url_loader_factory) : UserPolicySigninServiceBase(profile, local_state,
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 7d8cb80..7379492 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h
@@ -18,7 +18,7 @@ class Profile; -namespace identity { +namespace signin { class IdentityManager; } @@ -39,7 +39,7 @@ PrefService* local_state, DeviceManagementService* device_management_service, UserCloudPolicyManager* policy_manager, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> system_url_loader_factory); ~UserPolicySigninService() override;
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 8c4127f..22e809a 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc
@@ -91,7 +91,7 @@ : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), test_account_id_(AccountId::FromUserEmailGaiaId( kTestUser, - identity::GetTestGaiaIdForEmail(kTestUser))), + signin::GetTestGaiaIdForEmail(kTestUser))), register_completed_(false) {} MOCK_METHOD1(OnPolicyRefresh, void(bool)); @@ -265,7 +265,7 @@ EXPECT_EQ(dm_token_, expected_dm_token); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 48b3cf4a..3d4167ff 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -713,6 +713,9 @@ { key::kCrostiniExportImportUIAllowed, crostini::prefs::kUserCrostiniExportImportUIAllowedByPolicy, base::Value::Type::BOOLEAN }, + { key::kCrostiniRootAccessAllowed, + crostini::prefs::kUserCrostiniRootAccessAllowedByPolicy, + base::Value::Type::BOOLEAN }, { key::kReportCrostiniUsageEnabled, crostini::prefs::kReportCrostiniUsageEnabled, base::Value::Type::BOOLEAN },
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 5f8892f..dacda5e 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -537,7 +537,7 @@ ExternalProtocolHandler::RegisterPrefs(registry); flags_ui::PrefServiceFlagsStorage::RegisterPrefs(registry); GpuModeManager::RegisterPrefs(registry); - identity::IdentityManager::RegisterLocalStatePrefs(registry); + signin::IdentityManager::RegisterLocalStatePrefs(registry); IntranetRedirectDetector::RegisterPrefs(registry); language::GeoLanguageProvider::RegisterLocalStatePrefs(registry); language::UlpLanguageCodeLocator::RegisterLocalStatePrefs(registry);
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow.cc b/chrome/browser/printing/cloud_print/gcd_api_flow.cc index fbc83d00..376a654 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow.cc +++ b/chrome/browser/printing/cloud_print/gcd_api_flow.cc
@@ -19,7 +19,7 @@ std::unique_ptr<GCDApiFlow> GCDApiFlow::Create( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - identity::IdentityManager* identity_manager) { + signin::IdentityManager* identity_manager) { return std::make_unique<GCDApiFlowImpl>(url_loader_factory, identity_manager); }
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow.h b/chrome/browser/printing/cloud_print/gcd_api_flow.h index 189e7ef6..e8b6948 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow.h +++ b/chrome/browser/printing/cloud_print/gcd_api_flow.h
@@ -20,7 +20,7 @@ class DictionaryValue; } -namespace identity { +namespace signin { class IdentityManager; } @@ -78,7 +78,7 @@ static std::unique_ptr<GCDApiFlow> Create( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); virtual void Start(std::unique_ptr<Request> request) = 0;
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc b/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc index ff56cc7..4d0de8504 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc +++ b/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc
@@ -91,7 +91,7 @@ GCDApiFlowImpl::GCDApiFlowImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : url_loader_factory_(url_loader_factory), identity_manager_(identity_manager) {} @@ -102,16 +102,16 @@ identity::ScopeSet oauth_scopes; oauth_scopes.insert(request_->GetOAuthScope()); DCHECK(identity_manager_); - token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "cloud_print", identity_manager_, oauth_scopes, base::BindOnce(&GCDApiFlowImpl::OnAccessTokenFetchComplete, base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); } void GCDApiFlowImpl::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) {
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h b/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h index 535ff47..29a97fd7 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h +++ b/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h
@@ -13,7 +13,7 @@ #include "chrome/browser/printing/cloud_print/gcd_api_flow.h" #include "components/signin/public/identity_manager/access_token_info.h" -namespace identity { +namespace signin { class PrimaryAccountAccessTokenFetcher; } namespace network { @@ -29,21 +29,22 @@ // Create an OAuth2-based confirmation. GCDApiFlowImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~GCDApiFlowImpl() override; // GCDApiFlow implementation: void Start(std::unique_ptr<Request> request) override; void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); + private: void OnDownloadedToString(std::unique_ptr<std::string> response_body); std::unique_ptr<network::SimpleURLLoader> url_loader_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; std::unique_ptr<Request> request_; base::WeakPtrFactory<GCDApiFlowImpl> weak_factory_{this};
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc b/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc index 32a4651..f312905 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc +++ b/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc
@@ -83,7 +83,7 @@ private: content::TestBrowserThreadBundle test_browser_thread_bundle_; - identity::IdentityTestEnvironment identity_test_environment_; + signin::IdentityTestEnvironment identity_test_environment_; scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> test_shared_url_loader_factory_; }; @@ -104,7 +104,7 @@ gcd_flow_->OnAccessTokenFetchComplete( GoogleServiceAuthError::AuthErrorNone(), - identity::AccessTokenInfo( + signin::AccessTokenInfo( "SomeToken", base::Time::Now() + base::TimeDelta::FromHours(1), std::string() /* No extra information needed for this test */)); @@ -122,7 +122,7 @@ EXPECT_CALL(*mock_delegate_, OnGCDApiFlowError(GCDApiFlow::ERROR_TOKEN)); gcd_flow_->OnAccessTokenFetchComplete( GoogleServiceAuthError(GoogleServiceAuthError::USER_NOT_SIGNED_UP), - identity::AccessTokenInfo()); + signin::AccessTokenInfo()); } TEST_F(GCDApiFlowTest, BadJson) { @@ -134,7 +134,7 @@ gcd_flow_->OnAccessTokenFetchComplete( GoogleServiceAuthError::AuthErrorNone(), - identity::AccessTokenInfo( + signin::AccessTokenInfo( "SomeToken", base::Time::Now() + base::TimeDelta::FromHours(1), std::string() /* No extra information needed for this test */));
diff --git a/chrome/browser/profiles/gaia_info_update_service.cc b/chrome/browser/profiles/gaia_info_update_service.cc index 7e36982..af78255 100644 --- a/chrome/browser/profiles/gaia_info_update_service.cc +++ b/chrome/browser/profiles/gaia_info_update_service.cc
@@ -39,7 +39,7 @@ GAIAInfoUpdateService::GAIAInfoUpdateService(Profile* profile) : profile_(profile) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); identity_manager->AddObserver(this); @@ -61,7 +61,7 @@ void GAIAInfoUpdateService::Update() { // The user must be logged in. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); if (!identity_manager->HasPrimaryAccount()) return; @@ -88,7 +88,7 @@ return 256; } -identity::IdentityManager* GAIAInfoUpdateService::GetIdentityManager() { +signin::IdentityManager* GAIAInfoUpdateService::GetIdentityManager() { return IdentityManagerFactory::GetForProfile(profile_); } @@ -185,7 +185,7 @@ void GAIAInfoUpdateService::Shutdown() { timer_.Stop(); profile_image_downloader_.reset(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); identity_manager->RemoveObserver(this);
diff --git a/chrome/browser/profiles/gaia_info_update_service.h b/chrome/browser/profiles/gaia_info_update_service.h index a6abf69..1b97069 100644 --- a/chrome/browser/profiles/gaia_info_update_service.h +++ b/chrome/browser/profiles/gaia_info_update_service.h
@@ -23,7 +23,7 @@ // The results are saved in the profile info cache. class GAIAInfoUpdateService : public KeyedService, public ProfileDownloaderDelegate, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: explicit GAIAInfoUpdateService(Profile* profile); ~GAIAInfoUpdateService() override; @@ -37,7 +37,7 @@ // ProfileDownloaderDelegate: bool NeedsProfilePicture() const override; int GetDesiredImageSideLength() const override; - identity::IdentityManager* GetIdentityManager() override; + signin::IdentityManager* GetIdentityManager() override; network::mojom::URLLoaderFactory* GetURLLoaderFactory() override; std::string GetCachedPictureURL() const override; bool IsPreSignin() const override; @@ -55,7 +55,7 @@ void OnUsernameChanged(const std::string& username); void ScheduleNextUpdate(); - // Overridden from identity::IdentityManager::Observer: + // Overridden from signin::IdentityManager::Observer: void OnPrimaryAccountSet( const CoreAccountInfo& primary_account_info) override; void OnPrimaryAccountCleared(
diff --git a/chrome/browser/profiles/gaia_info_update_service_unittest.cc b/chrome/browser/profiles/gaia_info_update_service_unittest.cc index eb81891..c24fd78 100644 --- a/chrome/browser/profiles/gaia_info_update_service_unittest.cc +++ b/chrome/browser/profiles/gaia_info_update_service_unittest.cc
@@ -100,7 +100,7 @@ return profile_; } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/profiles/profile_activity_metrics_recorder.cc b/chrome/browser/profiles/profile_activity_metrics_recorder.cc index 53d27e8..971ed0a 100644 --- a/chrome/browser/profiles/profile_activity_metrics_recorder.cc +++ b/chrome/browser/profiles/profile_activity_metrics_recorder.cc
@@ -5,8 +5,8 @@ #include "chrome/browser/profiles/profile_activity_metrics_recorder.h" #include "base/logging.h" +#include "base/metrics/histogram.h" #include "base/metrics/histogram_macros.h" -#include "base/no_destructor.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_entry.h" @@ -17,6 +17,8 @@ namespace { +ProfileActivityMetricsRecorder* g_profile_activity_metrics_recorder = nullptr; + // The maximum number of profiles that are recorded. This means that all // profiles with bucket index greater than |kMaxProfileBucket| won't be included // in the metrics. @@ -38,24 +40,75 @@ return entry->GetMetricsBucketIndex(); } -} // namespace +void RecordProfileSessionDuration(Profile* profile, + base::TimeDelta session_length) { + if (!profile || session_length.InMinutes() <= 0) + return; -// static -void ProfileActivityMetricsRecorder::Initialize() { - static base::NoDestructor<ProfileActivityMetricsRecorder> - s_profile_activity_metrics_recorder; + int profile_bucket = GetMetricsBucketIndex(profile); + + if (0 <= profile_bucket && profile_bucket <= kMaxProfileBucket) { + base::Histogram::FactoryGet("Profile.SessionDuration.PerProfile", 0, + kMaxProfileBucket, kMaxProfileBucket + 1, + base::HistogramBase::kUmaTargetedHistogramFlag) + ->AddCount(profile_bucket, session_length.InMinutes()); + } } -ProfileActivityMetricsRecorder::ProfileActivityMetricsRecorder() { - BrowserList::AddObserver(this); -} - -void ProfileActivityMetricsRecorder::OnBrowserSetLastActive(Browser* browser) { - int profile_bucket = - GetMetricsBucketIndex(browser->profile()->GetOriginalProfile()); +void RecordBrowserActivation(Profile* profile) { + DCHECK(profile); + int profile_bucket = GetMetricsBucketIndex(profile); if (0 <= profile_bucket && profile_bucket <= kMaxProfileBucket) { UMA_HISTOGRAM_EXACT_LINEAR("Profile.BrowserActive.PerProfile", profile_bucket, kMaxProfileBucket); } } + +} // namespace + +// static +void ProfileActivityMetricsRecorder::Initialize() { + DCHECK(!g_profile_activity_metrics_recorder); + g_profile_activity_metrics_recorder = new ProfileActivityMetricsRecorder(); +} + +// static +void ProfileActivityMetricsRecorder::CleanupForTesting() { + DCHECK(g_profile_activity_metrics_recorder); + delete g_profile_activity_metrics_recorder; + g_profile_activity_metrics_recorder = nullptr; +} + +ProfileActivityMetricsRecorder::ProfileActivityMetricsRecorder() { + BrowserList::AddObserver(this); + metrics::DesktopSessionDurationTracker::Get()->AddObserver(this); +} + +ProfileActivityMetricsRecorder::~ProfileActivityMetricsRecorder() { + BrowserList::RemoveObserver(this); + metrics::DesktopSessionDurationTracker::Get()->RemoveObserver(this); +} + +void ProfileActivityMetricsRecorder::OnBrowserSetLastActive(Browser* browser) { + Profile* active_profile = browser->profile()->GetOriginalProfile(); + + RecordBrowserActivation(active_profile); + + if (last_active_profile_ != active_profile) { + RecordProfileSessionDuration( + last_active_profile_, base::TimeTicks::Now() - profile_session_start_); + last_active_profile_ = active_profile; + profile_session_start_ = base::TimeTicks::Now(); + } +} + +void ProfileActivityMetricsRecorder::OnSessionEnded( + base::TimeDelta session_length, + base::TimeTicks session_end) { + // |session_length| can't be used here because it was measured across all + // profiles. + RecordProfileSessionDuration(last_active_profile_, + session_end - profile_session_start_); + last_active_profile_ = nullptr; +}
diff --git a/chrome/browser/profiles/profile_activity_metrics_recorder.h b/chrome/browser/profiles/profile_activity_metrics_recorder.h index 9de532e..ac61f06 100644 --- a/chrome/browser/profiles/profile_activity_metrics_recorder.h +++ b/chrome/browser/profiles/profile_activity_metrics_recorder.h
@@ -8,27 +8,37 @@ #include <stddef.h> #include "base/macros.h" +#include "base/time/time.h" +#include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h" #include "chrome/browser/ui/browser_list_observer.h" class Browser; +class Profile; -namespace base { -template <typename T> -class NoDestructor; -} - -class ProfileActivityMetricsRecorder : public BrowserListObserver { +class ProfileActivityMetricsRecorder + : public BrowserListObserver, + public metrics::DesktopSessionDurationTracker::Observer { public: // Initializes a |ProfileActivityMetricsRecorder| object and starts // tracking/recording. static void Initialize(); + // Cleans up any global state for testing. + static void CleanupForTesting(); + // BrowserListObserver overrides: void OnBrowserSetLastActive(Browser* browser) override; + // metrics::DesktopSessionDurationTracker::Observer overrides: + void OnSessionEnded(base::TimeDelta session_length, + base::TimeTicks session_end) override; + private: - friend class base::NoDestructor<ProfileActivityMetricsRecorder>; ProfileActivityMetricsRecorder(); + ~ProfileActivityMetricsRecorder() override; + + Profile* last_active_profile_ = nullptr; + base::TimeTicks profile_session_start_; DISALLOW_COPY_AND_ASSIGN(ProfileActivityMetricsRecorder); };
diff --git a/chrome/browser/profiles/profile_activity_metrics_recorder_unittest.cc b/chrome/browser/profiles/profile_activity_metrics_recorder_unittest.cc index ecbcd7d..70e5721 100644 --- a/chrome/browser/profiles/profile_activity_metrics_recorder_unittest.cc +++ b/chrome/browser/profiles/profile_activity_metrics_recorder_unittest.cc
@@ -6,6 +6,9 @@ #include <vector> #include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_task_environment.h" +#include "base/time/time.h" +#include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h" #include "chrome/browser/profiles/profile_activity_metrics_recorder.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" @@ -17,33 +20,54 @@ #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" +namespace { + +constexpr base::TimeDelta kInactivityTimeout = base::TimeDelta::FromMinutes(5); + +} // namespace + class ProfileActivityMetricsRecorderTest : public testing::Test { public: ProfileActivityMetricsRecorderTest() - : profile_manager_(TestingBrowserProcess::GetGlobal()) {} + : thread_bundle_( + base::test::ScopedTaskEnvironment::TimeSource::MOCK_TIME_AND_NOW), + profile_manager_(TestingBrowserProcess::GetGlobal()) {} void SetUp() override { Test::SetUp(); ASSERT_TRUE(profile_manager_.SetUp()); + metrics::DesktopSessionDurationTracker::Initialize(); + metrics::DesktopSessionDurationTracker::Get() + ->SetInactivityTimeoutForTesting(kInactivityTimeout); ProfileActivityMetricsRecorder::Initialize(); } + void TearDown() override { + // Clean up the global state, so it can be correctly initialized for the + // next test case. + ProfileActivityMetricsRecorder::CleanupForTesting(); + metrics::DesktopSessionDurationTracker::CleanupForTesting(); + } + void ActivateBrowser(Profile* profile) { Browser::CreateParams browser_params(profile, false); - TestBrowserWindow browser_window; - browser_params.window = &browser_window; - std::unique_ptr<Browser> browser(Browser::Create(browser_params)); + browsers_.push_back(CreateBrowserWithTestWindowForParams(&browser_params)); - BrowserList::SetLastActive(browser.get()); + BrowserList::SetLastActive(browsers_.back().get()); } void ActivateIncognitoBrowser(Profile* profile) { ActivateBrowser(profile->GetOffTheRecordProfile()); } + void SimulateUserEvent() { + metrics::DesktopSessionDurationTracker::Get()->OnUserEvent(); + } + TestingProfileManager* profile_manager() { return &profile_manager_; } base::HistogramTester* histograms() { return &histogram_tester_; } + content::TestBrowserThreadBundle* thread_bundle() { return &thread_bundle_; } private: content::TestBrowserThreadBundle thread_bundle_; @@ -51,6 +75,8 @@ TestingProfileManager profile_manager_; base::HistogramTester histogram_tester_; + std::vector<std::unique_ptr<Browser>> browsers_; + DISALLOW_COPY_AND_ASSIGN(ProfileActivityMetricsRecorderTest); }; @@ -90,35 +116,69 @@ } TEST_F(ProfileActivityMetricsRecorderTest, MultipleProfiles) { + // Profile 1: Profile is created. This does not affect the histogram. Profile* profile1 = profile_manager()->CreateTestingProfile("p1"); + // Profile 2: Profile is created. This does not affect the histogram. Profile* profile2 = profile_manager()->CreateTestingProfile("p2"); histograms()->ExpectTotalCount("Profile.BrowserActive.PerProfile", 0); - // The browser of profile 1 is activated for the first time. It is assigned + // Profile 1: Browser is activated for the first time. The profile is assigned // bucket 1. ActivateBrowser(profile1); histograms()->ExpectBucketCount("Profile.BrowserActive.PerProfile", /*bucket=*/1, /*count=*/1); - // Profile creation doesn't influence the histogram. + // Profile 3: Profile is created. This does not affect the histogram. Profile* profile3 = profile_manager()->CreateTestingProfile("p3"); histograms()->ExpectTotalCount("Profile.BrowserActive.PerProfile", 1); + // Profile 1: Another browser is activated. ActivateBrowser(profile1); histograms()->ExpectBucketCount("Profile.BrowserActive.PerProfile", /*bucket=*/1, /*count=*/2); - // The browser of profile 3 is activated for the first time. It is assigned + // Profile 1: Session lasts 2 minutes. + thread_bundle()->FastForwardBy(base::TimeDelta::FromMinutes(2)); + + // Profile 3: Browser is activated for the first time. The profile is assigned // bucket 2. ActivateBrowser(profile3); histograms()->ExpectBucketCount("Profile.BrowserActive.PerProfile", /*bucket=*/2, /*count=*/1); + // Profile 1: Session ended. The duration(2 minutes) is recorded. + histograms()->ExpectBucketCount("Profile.SessionDuration.PerProfile", + /*bucket=*/1, /*count=*/2); - // The browser of profile 2 is activated for the first time. It is assigned + // Profile 3: Session lasts 2 minutes. + thread_bundle()->FastForwardBy(base::TimeDelta::FromMinutes(2)); + + // Profile 2: Browser is activated for the first time. The profile is assigned // bucket 3. ActivateBrowser(profile2); histograms()->ExpectBucketCount("Profile.BrowserActive.PerProfile", /*bucket=*/3, /*count=*/1); + // Profile 3: Session ended. The duration(2 minutes) is recorded. + histograms()->ExpectBucketCount("Profile.SessionDuration.PerProfile", + /*bucket=*/2, /*count=*/2); histograms()->ExpectTotalCount("Profile.BrowserActive.PerProfile", 4); } + +TEST_F(ProfileActivityMetricsRecorderTest, SessionInactivityNotRecorded) { + Profile* profile = profile_manager()->CreateTestingProfile("p1"); + + ActivateBrowser(profile); + histograms()->ExpectBucketCount("Profile.BrowserActive.PerProfile", + /*bucket=*/1, /*count=*/1); + + // Wait 2 minutes before doing another user interaction. + thread_bundle()->FastForwardBy(base::TimeDelta::FromMinutes(2)); + SimulateUserEvent(); + + // Stay inactive so the session ends. + thread_bundle()->FastForwardBy(kInactivityTimeout * 2); + + // The inactive time is not recorded. + histograms()->ExpectBucketCount("Profile.SessionDuration.PerProfile", + /*bucket=*/1, /*count=*/2); +}
diff --git a/chrome/browser/profiles/profile_downloader.cc b/chrome/browser/profiles/profile_downloader.cc index 408fab22..6ec7efa 100644 --- a/chrome/browser/profiles/profile_downloader.cc +++ b/chrome/browser/profiles/profile_downloader.cc
@@ -141,7 +141,7 @@ account_id_, "profile_downloader", scopes, base::BindOnce(&ProfileDownloader::OnAccessTokenFetchComplete, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kWaitUntilRefreshTokenAvailable); + signin::AccessTokenFetcher::Mode::kWaitUntilRefreshTokenAvailable); } ProfileDownloader::~ProfileDownloader() { @@ -282,7 +282,7 @@ void ProfileDownloader::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { oauth2_access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) { LOG(WARNING)
diff --git a/chrome/browser/profiles/profile_downloader.h b/chrome/browser/profiles/profile_downloader.h index f75acd85..8f99d89 100644 --- a/chrome/browser/profiles/profile_downloader.h +++ b/chrome/browser/profiles/profile_downloader.h
@@ -20,17 +20,17 @@ #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "third_party/skia/include/core/SkBitmap.h" -namespace identity { +namespace signin { class AccessTokenFetcher; struct AccessTokenInfo; -} +} // namespace signin class ProfileDownloaderDelegate; // Downloads user profile information. The profile picture is decoded in a // sandboxed process. class ProfileDownloader : public ImageDecoder::ImageRequest, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: enum PictureStatus { PICTURE_SUCCESS, @@ -92,16 +92,16 @@ void OnURLLoaderComplete(std::unique_ptr<std::string> response_body); - // Overriden from ImageDecoder::ImageRequest: + // Overridden from ImageDecoder::ImageRequest: void OnImageDecoded(const SkBitmap& decoded_image) override; void OnDecodeImageFailed() override; - // Overriden from identity::IdentityManager::Observer: + // Overridden from signin::IdentityManager::Observer: void OnExtendedAccountInfoUpdated(const AccountInfo& info) override; // Callback for AccessTokenFetcher. void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // Issues the first request to get user profile image. void StartFetchingImage(); @@ -119,12 +119,12 @@ std::string account_id_; std::string auth_token_; std::unique_ptr<network::SimpleURLLoader> simple_loader_; - std::unique_ptr<identity::AccessTokenFetcher> oauth2_access_token_fetcher_; + std::unique_ptr<signin::AccessTokenFetcher> oauth2_access_token_fetcher_; AccountInfo account_info_; SkBitmap profile_picture_; PictureStatus picture_status_; - identity::IdentityManager* identity_manager_; - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + signin::IdentityManager* identity_manager_; + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; bool waiting_for_account_info_;
diff --git a/chrome/browser/profiles/profile_downloader_delegate.h b/chrome/browser/profiles/profile_downloader_delegate.h index a7aec77..893ac74 100644 --- a/chrome/browser/profiles/profile_downloader_delegate.h +++ b/chrome/browser/profiles/profile_downloader_delegate.h
@@ -11,9 +11,9 @@ class ProfileDownloader; -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin namespace network { namespace mojom { @@ -49,7 +49,7 @@ virtual std::string GetCachedPictureURL() const = 0; // Returns the IdentityManager associated with this download request. - virtual identity::IdentityManager* GetIdentityManager() = 0; + virtual signin::IdentityManager* GetIdentityManager() = 0; // Returns the URLLoaderFactory to use for this download request. virtual network::mojom::URLLoaderFactory* GetURLLoaderFactory() = 0;
diff --git a/chrome/browser/profiles/profile_downloader_unittest.cc b/chrome/browser/profiles/profile_downloader_unittest.cc index 437c11ad..14205d3 100644 --- a/chrome/browser/profiles/profile_downloader_unittest.cc +++ b/chrome/browser/profiles/profile_downloader_unittest.cc
@@ -36,7 +36,7 @@ class ProfileDownloaderTest : public testing::Test, public ProfileDownloaderDelegate, - public identity::IdentityManager::DiagnosticsObserver { + public signin::IdentityManager::DiagnosticsObserver { protected: ProfileDownloaderTest() : profile_downloader_(this) { identity_test_env_.identity_manager()->AddDiagnosticsObserver(this); @@ -48,7 +48,7 @@ bool NeedsProfilePicture() const override { return true; } int GetDesiredImageSideLength() const override { return 128; } std::string GetCachedPictureURL() const override { return std::string(); } - identity::IdentityManager* GetIdentityManager() override { + signin::IdentityManager* GetIdentityManager() override { return identity_test_env_.identity_manager(); } network::mojom::URLLoaderFactory* GetURLLoaderFactory() override { @@ -89,7 +89,7 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; ProfileDownloader profile_downloader_; base::OnceClosure on_access_token_request_callback_;
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index 37b90f5..17a23f7 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc
@@ -826,7 +826,7 @@ } std::string ProfileImpl::GetProfileUserName() const { - const identity::IdentityManager* identity_manager = + const signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfileIfExists(this); if (identity_manager) return identity_manager->GetPrimaryAccountInfo().email;
diff --git a/chrome/browser/profiles/profile_manager.cc b/chrome/browser/profiles/profile_manager.cc index 8d1ed7b..c6028f0 100644 --- a/chrome/browser/profiles/profile_manager.cc +++ b/chrome/browser/profiles/profile_manager.cc
@@ -1587,7 +1587,7 @@ return; } - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); CoreAccountInfo account_info = identity_manager->GetPrimaryAccountInfo(); base::string16 username = base::UTF8ToUTF16(account_info.email); @@ -1621,10 +1621,9 @@ FROM_HERE, {BrowserThread::UI}, base::BindOnce( base::IgnoreResult( - &identity::PrimaryAccountMutator::ClearPrimaryAccount), + &signin::PrimaryAccountMutator::ClearPrimaryAccount), base::Unretained(account_mutator), - identity::PrimaryAccountMutator::ClearAccountsAction:: - kRemoveAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, signin_metrics::AUTHENTICATION_FAILED_WITH_FORCE_SIGNIN, signin_metrics::SignoutDelete::IGNORE_METRIC)); }
diff --git a/chrome/browser/profiles/profile_window.cc b/chrome/browser/profiles/profile_window.cc index 1a5eda6..ae12e72 100644 --- a/chrome/browser/profiles/profile_window.cc +++ b/chrome/browser/profiles/profile_window.cc
@@ -368,7 +368,7 @@ // TODO(mlerman): After one release remove any hosted_domain reference to the // pref, since all users will have this in the AccountTrackerService. if (hosted_domain.empty()) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); base::Optional<AccountInfo> primary_account_info =
diff --git a/chrome/browser/profiles/profile_window_browsertest.cc b/chrome/browser/profiles/profile_window_browsertest.cc index 9d028972..8a5f847 100644 --- a/chrome/browser/profiles/profile_window_browsertest.cc +++ b/chrome/browser/profiles/profile_window_browsertest.cc
@@ -202,7 +202,7 @@ IN_PROC_BROWSER_TEST_F(ProfileWindowBrowserTest, GuestCannotSignin) { Browser* guest_browser = OpenGuestBrowser(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(guest_browser->profile()); // Guest profiles can't sign in without a IdentityManager.
diff --git a/chrome/browser/profiles/renderer_updater.h b/chrome/browser/profiles/renderer_updater.h index 2ead3d0..9c92a09 100644 --- a/chrome/browser/profiles/renderer_updater.h +++ b/chrome/browser/profiles/renderer_updater.h
@@ -30,7 +30,7 @@ // The RendererUpdater is responsible for updating renderers about state change. class RendererUpdater : public KeyedService, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, #if defined(OS_CHROMEOS) public chromeos::OAuth2LoginManager::Observer, #endif @@ -92,9 +92,9 @@ std::string cached_variation_ids_header_; std::string cached_variation_ids_header_signed_in_; - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; DISALLOW_COPY_AND_ASSIGN(RendererUpdater); };
diff --git a/chrome/browser/resource_coordinator/usage_clock.cc b/chrome/browser/resource_coordinator/usage_clock.cc index 3ff310a..3616a2f 100644 --- a/chrome/browser/resource_coordinator/usage_clock.cc +++ b/chrome/browser/resource_coordinator/usage_clock.cc
@@ -40,7 +40,8 @@ current_usage_session_start_time_ = NowTicks(); } -void UsageClock::OnSessionEnded(base::TimeDelta session_length) { +void UsageClock::OnSessionEnded(base::TimeDelta session_length, + base::TimeTicks session_end) { // Ignore |session_length| because it wasn't measured using the resource // coordinator clock. DCHECK(IsInUse());
diff --git a/chrome/browser/resource_coordinator/usage_clock.h b/chrome/browser/resource_coordinator/usage_clock.h index 6b7bbd9..064e3bed 100644 --- a/chrome/browser/resource_coordinator/usage_clock.h +++ b/chrome/browser/resource_coordinator/usage_clock.h
@@ -33,7 +33,8 @@ private: void OnSessionStarted(base::TimeTicks session_start) override; - void OnSessionEnded(base::TimeDelta session_length) override; + void OnSessionEnded(base::TimeDelta session_length, + base::TimeTicks session_end) override; // The total time elapsed in completed usage sessions. The duration of the // current usage session, if any, must be added to this to get the total usage
diff --git a/chrome/browser/safe_browsing/advanced_protection_status_manager.cc b/chrome/browser/safe_browsing/advanced_protection_status_manager.cc index 313d64e6..24095fe 100644 --- a/chrome/browser/safe_browsing/advanced_protection_status_manager.cc +++ b/chrome/browser/safe_browsing/advanced_protection_status_manager.cc
@@ -155,7 +155,7 @@ void AdvancedProtectionStatusManager::OnAccessTokenFetchComplete( std::string account_id, GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { DCHECK(access_token_fetcher_); if (is_under_advanced_protection_) { @@ -197,12 +197,12 @@ scopes.insert(GaiaConstants::kOAuth1LoginScope); access_token_fetcher_ = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "advanced_protection_status_manager", identity_manager_, scopes, base::BindOnce( &AdvancedProtectionStatusManager::OnAccessTokenFetchComplete, base::Unretained(this), primary_account_id), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); } void AdvancedProtectionStatusManager::ScheduleNextRefresh() {
diff --git a/chrome/browser/safe_browsing/advanced_protection_status_manager.h b/chrome/browser/safe_browsing/advanced_protection_status_manager.h index a450ec1..08279280 100644 --- a/chrome/browser/safe_browsing/advanced_protection_status_manager.h +++ b/chrome/browser/safe_browsing/advanced_protection_status_manager.h
@@ -11,7 +11,7 @@ #include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" -namespace identity { +namespace signin { class PrimaryAccountAccessTokenFetcher; } @@ -27,7 +27,7 @@ // of its original profile. class AdvancedProtectionStatusManager : public KeyedService, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: explicit AdvancedProtectionStatusManager(Profile* profile); ~AdvancedProtectionStatusManager() override; @@ -101,7 +101,7 @@ void OnAccessTokenFetchComplete(std::string account_id, GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); // Requests Gaia refresh token to obtain advanced protection status. void RefreshAdvancedProtectionStatus(); @@ -133,8 +133,8 @@ Profile* const profile_; - identity::IdentityManager* identity_manager_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + signin::IdentityManager* identity_manager_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; AccountTrackerService* account_tracker_service_;
diff --git a/chrome/browser/safe_browsing/advanced_protection_status_manager_unittest.cc b/chrome/browser/safe_browsing/advanced_protection_status_manager_unittest.cc index 31a75d5..07bcf6f 100644 --- a/chrome/browser/safe_browsing/advanced_protection_status_manager_unittest.cc +++ b/chrome/browser/safe_browsing/advanced_protection_status_manager_unittest.cc
@@ -80,7 +80,7 @@ : GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc b/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc index f7e0197..3662de8 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc +++ b/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc
@@ -141,7 +141,7 @@ embedded_test_server()->GetURL(kChangePasswordUrl).spec()); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc b/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc index 489fdef..9eaf553 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc +++ b/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc
@@ -281,7 +281,7 @@ return request_ ? request_->throttles_.size() : 0u; } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_profile_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_service.cc b/chrome/browser/search/one_google_bar/one_google_bar_service.cc index a25911e0..a176251 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_service.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_service.cc
@@ -12,11 +12,11 @@ #include "components/signin/public/identity_manager/identity_manager.h" class OneGoogleBarService::SigninObserver - : public identity::IdentityManager::Observer { + : public signin::IdentityManager::Observer { public: using SigninStatusChangedCallback = base::Closure; - SigninObserver(identity::IdentityManager* identity_manager, + SigninObserver(signin::IdentityManager* identity_manager, const SigninStatusChangedCallback& callback) : identity_manager_(identity_manager), callback_(callback) { identity_manager_->AddObserver(this); @@ -27,17 +27,17 @@ private: // IdentityManager::Observer implementation. void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override { callback_.Run(); } - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; SigninStatusChangedCallback callback_; }; OneGoogleBarService::OneGoogleBarService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<OneGoogleBarLoader> loader) : loader_(std::move(loader)), signin_observer_(std::make_unique<SigninObserver>(
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_service.h b/chrome/browser/search/one_google_bar/one_google_bar_service.h index 377422a..b30239d1 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_service.h +++ b/chrome/browser/search/one_google_bar/one_google_bar_service.h
@@ -14,16 +14,16 @@ #include "chrome/browser/search/one_google_bar/one_google_bar_service_observer.h" #include "components/keyed_service/core/keyed_service.h" -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin // A service that downloads, caches, and hands out OneGoogleBarData. It never // initiates a download automatically, only when Refresh is called. When the // user signs in or out, the cached value is cleared. class OneGoogleBarService : public KeyedService { public: - OneGoogleBarService(identity::IdentityManager* identity_manager, + OneGoogleBarService(signin::IdentityManager* identity_manager, std::unique_ptr<OneGoogleBarLoader> loader); ~OneGoogleBarService() override;
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_service_factory.cc b/chrome/browser/search/one_google_bar/one_google_bar_service_factory.cc index 906b1c6..ba808e1 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_service_factory.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_service_factory.cc
@@ -51,7 +51,7 @@ content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); GoogleURLTracker* google_url_tracker = GoogleURLTrackerFactory::GetForProfile(profile);
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_service_unittest.cc b/chrome/browser/search/one_google_bar/one_google_bar_service_unittest.cc index ed5d793..883ed27 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_service_unittest.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_service_unittest.cc
@@ -73,7 +73,7 @@ base::test::ScopedTaskEnvironment task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_env_; + signin::IdentityTestEnvironment identity_env_; // Owned by the service. FakeOneGoogleBarLoader* loader_;
diff --git a/chrome/browser/search/search_suggest/search_suggest_service.cc b/chrome/browser/search/search_suggest/search_suggest_service.cc index d3f256b..4891190f 100644 --- a/chrome/browser/search/search_suggest/search_suggest_service.cc +++ b/chrome/browser/search/search_suggest/search_suggest_service.cc
@@ -56,11 +56,11 @@ } // namespace class SearchSuggestService::SigninObserver - : public identity::IdentityManager::Observer { + : public signin::IdentityManager::Observer { public: using SigninStatusChangedCallback = base::RepeatingClosure; - SigninObserver(identity::IdentityManager* identity_manager, + SigninObserver(signin::IdentityManager* identity_manager, const SigninStatusChangedCallback& callback) : identity_manager_(identity_manager), callback_(callback) { if (identity_manager_) @@ -80,19 +80,19 @@ private: // IdentityManager::Observer implementation. void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override { callback_.Run(); } // May be nullptr in tests. - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; SigninStatusChangedCallback callback_; }; SearchSuggestService::SearchSuggestService( Profile* profile, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<SearchSuggestLoader> loader) : loader_(std::move(loader)), signin_observer_(std::make_unique<SigninObserver>(
diff --git a/chrome/browser/search/search_suggest/search_suggest_service.h b/chrome/browser/search/search_suggest/search_suggest_service.h index 813dda7..6413d96 100644 --- a/chrome/browser/search/search_suggest/search_suggest_service.h +++ b/chrome/browser/search/search_suggest/search_suggest_service.h
@@ -19,9 +19,9 @@ class Profile; -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin // A service that downloads, caches, and hands out SearchSuggestData. It never // initiates a download automatically, only when Refresh is called. When the @@ -29,7 +29,7 @@ class SearchSuggestService : public KeyedService { public: SearchSuggestService(Profile* profile, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<SearchSuggestLoader> loader); ~SearchSuggestService() override;
diff --git a/chrome/browser/search/search_suggest/search_suggest_service_factory.cc b/chrome/browser/search/search_suggest/search_suggest_service_factory.cc index 2d5239d..62fbcf2 100644 --- a/chrome/browser/search/search_suggest/search_suggest_service_factory.cc +++ b/chrome/browser/search/search_suggest/search_suggest_service_factory.cc
@@ -51,7 +51,7 @@ KeyedService* SearchSuggestServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); GoogleURLTracker* google_url_tracker = GoogleURLTrackerFactory::GetForProfile(profile);
diff --git a/chrome/browser/search/search_suggest/search_suggest_service_unittest.cc b/chrome/browser/search/search_suggest/search_suggest_service_unittest.cc index 071d1bb..e1b13dca 100644 --- a/chrome/browser/search/search_suggest/search_suggest_service_unittest.cc +++ b/chrome/browser/search/search_suggest/search_suggest_service_unittest.cc
@@ -64,7 +64,7 @@ template_url_service_ = TemplateURLServiceFactory::GetForProfile(profile()); search_test_utils::WaitForTemplateURLServiceToLoad(template_url_service_); - identity_env_ = std::make_unique<identity::IdentityTestEnvironment>( + identity_env_ = std::make_unique<signin::IdentityTestEnvironment>( &test_url_loader_factory_); auto loader = std::make_unique<FakeSearchSuggestLoader>(); loader_ = loader.get(); @@ -132,7 +132,7 @@ private: TemplateURLService* template_url_service_; network::TestURLLoaderFactory test_url_loader_factory_; - std::unique_ptr<identity::IdentityTestEnvironment> identity_env_; + std::unique_ptr<signin::IdentityTestEnvironment> identity_env_; // Owned by the service. FakeSearchSuggestLoader* loader_;
diff --git a/chrome/browser/search/suggestions/suggestions_service_factory.cc b/chrome/browser/search/suggestions/suggestions_service_factory.cc index f61a8b8c4..f361997e 100644 --- a/chrome/browser/search/suggestions/suggestions_service_factory.cc +++ b/chrome/browser/search/suggestions/suggestions_service_factory.cc
@@ -54,7 +54,7 @@ content::BrowserContext* context) const { Profile* profile = static_cast<Profile*>(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); syncer::SyncService* sync_service = ProfileSyncServiceFactory::GetForProfile(profile);
diff --git a/chrome/browser/sharing/click_to_call/click_to_call_utils_unittest.cc b/chrome/browser/sharing/click_to_call/click_to_call_utils_unittest.cc index dd521c6..0467d39 100644 --- a/chrome/browser/sharing/click_to_call/click_to_call_utils_unittest.cc +++ b/chrome/browser/sharing/click_to_call/click_to_call_utils_unittest.cc
@@ -102,6 +102,14 @@ EXPECT_FALSE(ShouldOfferClickToCall(&profile_, GURL(kTelUrl))); } +TEST_F(ClickToCallUtilsTest, IncognitoProfile_DoNotShowMenu) { + scoped_feature_list_.InitAndEnableFeature(kClickToCallUI); + EXPECT_CALL(*service(), GetState()).Times(0); + + EXPECT_FALSE( + ShouldOfferClickToCall(profile_.GetOffTheRecordProfile(), GURL(kTelUrl))); +} + TEST_F(ClickToCallUtilsTest, EmptyTelProtocol_DoNotShowMenu) { scoped_feature_list_.InitAndEnableFeature(kClickToCallUI); EXPECT_CALL(*service(), GetState())
diff --git a/chrome/browser/sharing/sharing_fcm_handler.cc b/chrome/browser/sharing/sharing_fcm_handler.cc index 7bcd886..7ee5696 100644 --- a/chrome/browser/sharing/sharing_fcm_handler.cc +++ b/chrome/browser/sharing/sharing_fcm_handler.cc
@@ -4,12 +4,45 @@ #include "chrome/browser/sharing/sharing_fcm_handler.h" +#include "base/no_destructor.h" +#include "base/strings/strcat.h" #include "chrome/browser/sharing/sharing_constants.h" #include "chrome/browser/sharing/sharing_fcm_sender.h" #include "chrome/browser/sharing/sharing_message_handler.h" #include "chrome/browser/sharing/sharing_metrics.h" #include "chrome/browser/sharing/sharing_service_factory.h" #include "components/gcm_driver/gcm_driver.h" +#include "third_party/re2/src/re2/re2.h" + +namespace { + +// The regex captures +// Group 1: type:timesmap +// Group 2: userId# +// Group 3: hashcode +const char kMessageIdRegexPattern[] = "(0:[0-9]+%)([0-9]+#)?([a-f0-9]+)"; + +// Returns message_id with userId stripped. +// FCM message_id is a persistent id in format of: +// 0:1416811810537717%0#e7a71353318775c7 +// ^ ^ ^ ^ +// type : timestamp % userId # hashcode +// As per go/persistent-id, userId# is optional, and should be stripped +// comparing persistent ids. +// Retrns |message_id| with userId stripped, or |message_id| if it is not +// confined to the format. +std::string GetStrippedMessageId(const std::string& message_id) { + std::string stripped_message_id, type_timestamp, hashcode; + static const base::NoDestructor<re2::RE2> kMessageIdRegex( + kMessageIdRegexPattern); + if (!re2::RE2::FullMatch(message_id, *kMessageIdRegex, &type_timestamp, + nullptr, &hashcode)) { + return message_id; + } + return base::StrCat({type_timestamp, hashcode}); +} + +} // namespace SharingFCMHandler::SharingFCMHandler(gcm::GCMDriver* gcm_driver, SharingFCMSender* sharing_fcm_sender) @@ -59,10 +92,10 @@ void SharingFCMHandler::OnMessage(const std::string& app_id, const gcm::IncomingMessage& message) { + std::string message_id = GetStrippedMessageId(message.message_id); SharingMessage sharing_message; if (!sharing_message.ParseFromString(message.raw_data)) { - LOG(ERROR) << "Failed to parse incoming message with id : " - << message.message_id; + LOG(ERROR) << "Failed to parse incoming message with id : " << message_id; return; } DCHECK(sharing_message.payload_case() != SharingMessage::PAYLOAD_NOT_SET) @@ -78,7 +111,7 @@ it->second->OnMessage(sharing_message); if (sharing_message.payload_case() != SharingMessage::kAckMessage) - SendAckMessage(sharing_message.sender_guid(), message.message_id); + SendAckMessage(sharing_message.sender_guid(), message_id); } }
diff --git a/chrome/browser/sharing/sharing_fcm_handler_unittest.cc b/chrome/browser/sharing/sharing_fcm_handler_unittest.cc index 759a770f..b43cde4 100644 --- a/chrome/browser/sharing/sharing_fcm_handler_unittest.cc +++ b/chrome/browser/sharing/sharing_fcm_handler_unittest.cc
@@ -19,7 +19,9 @@ namespace { const char kTestAppId[] = "test_app_id"; -const char kTestMessageId[] = "test_message_id"; +const char kTestMessageId[] = "0:1563805165426489%0bb84dcff9fd7ecd"; +const char kTestMessageIdSecondaryUser[] = + "0:1563805165426489%20#0bb84dcff9fd7ecd"; const char kOriginalMessageId[] = "test_original_message_id"; const char kSenderGuid[] = "test_sender_guid"; @@ -54,9 +56,10 @@ // Creates a gcm::IncomingMessage with SharingMessage and defaults. gcm::IncomingMessage CreateGCMIncomingMessage( + const std::string& message_id, const SharingMessage& sharing_message) { gcm::IncomingMessage incoming_message; - incoming_message.message_id = kTestMessageId; + incoming_message.message_id = message_id; sharing_message.SerializeToString(&incoming_message.raw_data); return incoming_message; } @@ -85,7 +88,7 @@ sharing_message.mutable_ack_message()->set_original_message_id( kOriginalMessageId); gcm::IncomingMessage incoming_message = - CreateGCMIncomingMessage(sharing_message); + CreateGCMIncomingMessage(kTestMessageId, sharing_message); EXPECT_CALL(mock_sharing_message_handler_, OnMessage(ProtoEquals(sharing_message))); @@ -102,7 +105,7 @@ sharing_message.set_sender_guid(kSenderGuid); sharing_message.mutable_ping_message(); gcm::IncomingMessage incoming_message = - CreateGCMIncomingMessage(sharing_message); + CreateGCMIncomingMessage(kTestMessageId, sharing_message); SharingMessage sharing_ack_message; sharing_ack_message.mutable_ack_message()->set_original_message_id( @@ -132,3 +135,27 @@ sharing_fcm_handler_->RemoveSharingHandler(SharingMessage::kPingMessage); sharing_fcm_handler_->OnMessage(kTestAppId, incoming_message); } + +// Test for handling of SharingMessage payload other than AckMessage for +// secondary users in Android. +TEST_F(SharingFCMHandlerTest, PingMessageHandlerSecondaryUser) { + SharingMessage sharing_message; + sharing_message.set_sender_guid(kSenderGuid); + sharing_message.mutable_ping_message(); + gcm::IncomingMessage incoming_message = + CreateGCMIncomingMessage(kTestMessageIdSecondaryUser, sharing_message); + + SharingMessage sharing_ack_message; + sharing_ack_message.mutable_ack_message()->set_original_message_id( + kTestMessageId); + + // Tests OnMessage flow in SharingFCMHandler after handler is added. + EXPECT_CALL(mock_sharing_message_handler_, + OnMessage(ProtoEquals(sharing_message))); + EXPECT_CALL(mock_sharing_fcm_sender_, + SendMessageToDevice(Eq(kSenderGuid), Eq(kAckTimeToLive), + ProtoEquals(sharing_ack_message), _)); + sharing_fcm_handler_->AddSharingHandler(SharingMessage::kPingMessage, + &mock_sharing_message_handler_); + sharing_fcm_handler_->OnMessage(kTestAppId, incoming_message); +}
diff --git a/chrome/browser/sharing/sharing_metrics.cc b/chrome/browser/sharing/sharing_metrics.cc index 674b79d..c1657e2 100644 --- a/chrome/browser/sharing/sharing_metrics.cc +++ b/chrome/browser/sharing/sharing_metrics.cc
@@ -79,3 +79,7 @@ index, /*value_max=*/20); } + +void LogSharingMessageAckTime(base::TimeDelta time) { + base::UmaHistogramMediumTimes("Sharing.MessageAckTime", time); +}
diff --git a/chrome/browser/sharing/sharing_metrics.h b/chrome/browser/sharing/sharing_metrics.h index 33fbada..208ced2 100644 --- a/chrome/browser/sharing/sharing_metrics.h +++ b/chrome/browser/sharing/sharing_metrics.h
@@ -7,6 +7,8 @@ #include "chrome/browser/sharing/proto/sharing_message.pb.h" +#include "base/time/time.h" + enum class SharingDeviceRegistrationResult; // Result of VAPID key creation during Sharing registration. @@ -60,4 +62,8 @@ // one from SharingClickToCallUi defined in histograms.xml. void LogClickToCallSelectedAppIndex(const char* histogram_suffix, int index); +// Logs to UMA the time from sending a FCM message from the Sharing service +// until an ack message is received for it. +void LogSharingMessageAckTime(base::TimeDelta time); + #endif // CHROME_BROWSER_SHARING_SHARING_METRICS_H_
diff --git a/chrome/browser/sharing/sharing_service.cc b/chrome/browser/sharing/sharing_service.cc index 668a7d2..ea710dca 100644 --- a/chrome/browser/sharing/sharing_service.cc +++ b/chrome/browser/sharing/sharing_service.cc
@@ -24,6 +24,7 @@ #include "chrome/browser/sharing/sharing_fcm_handler.h" #include "chrome/browser/sharing/sharing_fcm_sender.h" #include "chrome/browser/sharing/sharing_message_handler.h" +#include "chrome/browser/sharing/sharing_metrics.h" #include "chrome/browser/sharing/sharing_sync_preference.h" #include "chrome/browser/sharing/vapid_key_manager.h" #include "components/sync/driver/sync_service.h" @@ -164,20 +165,29 @@ fcm_sender_->SendMessageToDevice( device_guid, time_to_live, std::move(message), base::BindOnce(&SharingService::OnMessageSent, - weak_ptr_factory_.GetWeakPtr(), message_guid)); + weak_ptr_factory_.GetWeakPtr(), base::TimeTicks::Now(), + message_guid)); } -void SharingService::OnMessageSent(const std::string& message_guid, +void SharingService::OnMessageSent(base::TimeTicks start_time, + const std::string& message_guid, base::Optional<std::string> message_id) { if (!message_id) { InvokeSendMessageCallback(message_guid, /*success=*/false); return; } + send_message_times_.emplace(*message_id, start_time); message_guids_.emplace(*message_id, message_guid); } void SharingService::OnAckReceived(const std::string& message_id) { + auto times_iter = send_message_times_.find(message_id); + if (times_iter != send_message_times_.end()) { + LogSharingMessageAckTime(base::TimeTicks::Now() - times_iter->second); + send_message_times_.erase(times_iter); + } + auto iter = message_guids_.find(message_id); if (iter == message_guids_.end()) return;
diff --git a/chrome/browser/sharing/sharing_service.h b/chrome/browser/sharing/sharing_service.h index 076fc59..5cc47ab7 100644 --- a/chrome/browser/sharing/sharing_service.h +++ b/chrome/browser/sharing/sharing_service.h
@@ -105,7 +105,8 @@ void UnregisterDevice(); void OnDeviceRegistered(SharingDeviceRegistrationResult result); void OnDeviceUnregistered(SharingDeviceRegistrationResult result); - void OnMessageSent(const std::string& message_guid, + void OnMessageSent(base::TimeTicks start_time, + const std::string& message_guid, base::Optional<std::string> message_id); void InvokeSendMessageCallback(const std::string& message_guid, bool result); @@ -128,6 +129,9 @@ // Map of random GUID to SendMessageCallback. std::map<std::string, SendMessageCallback> send_message_callbacks_; + // Map of FCM message_id to time at start of send message request to FCM. + std::map<std::string, base::TimeTicks> send_message_times_; + // Map of FCM message_id to random GUID. std::map<std::string, std::string> message_guids_;
diff --git a/chrome/browser/sharing/sharing_service_factory.cc b/chrome/browser/sharing/sharing_service_factory.cc index 85cd8e56..d3b9e0e 100644 --- a/chrome/browser/sharing/sharing_service_factory.cc +++ b/chrome/browser/sharing/sharing_service_factory.cc
@@ -9,7 +9,6 @@ #include "base/memory/singleton.h" #include "chrome/browser/gcm/gcm_profile_service_factory.h" #include "chrome/browser/gcm/instance_id/instance_id_profile_service_factory.h" -#include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sharing/sharing_device_registration.h" #include "chrome/browser/sharing/sharing_fcm_handler.h" @@ -101,7 +100,11 @@ content::BrowserContext* SharingServiceFactory::GetBrowserContextToUse( content::BrowserContext* context) const { - return chrome::GetBrowserContextRedirectedInIncognito(context); + // Sharing features are disabled in incognito. + if (context->IsOffTheRecord()) + return nullptr; + + return context; } // Due to the dependency on SyncService, this cannot be instantiated before
diff --git a/chrome/browser/signin/account_reconcilor_factory.cc b/chrome/browser/signin/account_reconcilor_factory.cc index 55e9eb3..d4c8c65f 100644 --- a/chrome/browser/signin/account_reconcilor_factory.cc +++ b/chrome/browser/signin/account_reconcilor_factory.cc
@@ -49,7 +49,7 @@ : public signin::MirrorAccountReconcilorDelegate { public: explicit ChromeOSChildAccountReconcilorDelegate( - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : signin::MirrorAccountReconcilorDelegate(identity_manager) {} base::TimeDelta GetReconcileTimeout() const override { @@ -88,7 +88,7 @@ : public signin::MirrorAccountReconcilorDelegate { public: ChromeOSAccountReconcilorDelegate( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, chromeos::AccountManagerMigrator* account_migrator) : signin::MirrorAccountReconcilorDelegate(identity_manager), account_migrator_(account_migrator) {} @@ -140,7 +140,7 @@ KeyedService* AccountReconcilorFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); SigninClient* signin_client = ChromeSigninClientFactory::GetForProfile(profile); @@ -205,7 +205,7 @@ std::unique_ptr<signin::ConsistencyCookieManagerBase> AccountReconcilorFactory::CreateConsistencyCookieManager( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* signin_client, AccountReconcilor* account_reconcilor) const { #if defined(OS_ANDROID)
diff --git a/chrome/browser/signin/account_reconcilor_factory.h b/chrome/browser/signin/account_reconcilor_factory.h index 90cae3cd..2ad657b9 100644 --- a/chrome/browser/signin/account_reconcilor_factory.h +++ b/chrome/browser/signin/account_reconcilor_factory.h
@@ -10,7 +10,7 @@ #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -51,7 +51,7 @@ content::BrowserContext* profile) const override; std::unique_ptr<signin::ConsistencyCookieManagerBase> - CreateConsistencyCookieManager(identity::IdentityManager* identity_manager, + CreateConsistencyCookieManager(signin::IdentityManager* identity_manager, SigninClient* signin_client, AccountReconcilor* account_reconcilor) const; };
diff --git a/chrome/browser/signin/chrome_signin_client.cc b/chrome/browser/signin/chrome_signin_client.cc index 14368b1..e095050 100644 --- a/chrome/browser/signin/chrome_signin_client.cc +++ b/chrome/browser/signin/chrome_signin_client.cc
@@ -234,7 +234,7 @@ void ChromeSigninClient::OnAccessTokenAvailable( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { access_token_fetcher_.reset(); // Exchange the access token for a handle that can be used for later @@ -315,11 +315,11 @@ if (identity_manager->HasPrimaryAccount()) { const identity::ScopeSet scopes{GaiaConstants::kGoogleUserInfoEmail}; access_token_fetcher_ = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "chrome_signin_client", identity_manager, scopes, base::BindOnce(&ChromeSigninClient::OnAccessTokenAvailable, base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); } } }
diff --git a/chrome/browser/signin/chrome_signin_client.h b/chrome/browser/signin/chrome_signin_client.h index df241f53..27dd0124 100644 --- a/chrome/browser/signin/chrome_signin_client.h +++ b/chrome/browser/signin/chrome_signin_client.h
@@ -98,9 +98,9 @@ const base::FilePath& profile_path); void OnCloseBrowsersAborted(const base::FilePath& profile_path); - // identity::PrimaryAccountAccessTokenFetcher callback + // signin::PrimaryAccountAccessTokenFetcher callback void OnAccessTokenAvailable(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); Profile* profile_; @@ -117,7 +117,7 @@ #endif std::unique_ptr<gaia::GaiaOAuthClient> oauth_client_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; scoped_refptr<network::SharedURLLoaderFactory>
diff --git a/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.cc b/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.cc index cbd80b4..7c600c3 100644 --- a/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.cc +++ b/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.cc
@@ -64,7 +64,7 @@ #endif accounts_status.num_opened_accounts++; - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile->GetOriginalProfile()); if (identity_manager && identity_manager->HasPrimaryAccount()) accounts_status.num_signed_in_accounts++; @@ -73,12 +73,12 @@ return accounts_status; } -std::vector<identity::IdentityManager*> +std::vector<signin::IdentityManager*> ChromeSigninStatusMetricsProviderDelegate::GetIdentityManagersForAllAccounts() { ProfileManager* profile_manager = g_browser_process->profile_manager(); std::vector<Profile*> profiles = profile_manager->GetLoadedProfiles(); - std::vector<identity::IdentityManager*> managers; + std::vector<signin::IdentityManager*> managers; for (Profile* profile : profiles) { auto* identity_manager = IdentityManagerFactory::GetForProfileIfExists(profile); @@ -92,7 +92,7 @@ #if !defined(OS_ANDROID) void ChromeSigninStatusMetricsProviderDelegate::OnBrowserAdded( Browser* browser) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(browser->profile()); // Nothing will change if the opened browser is in incognito mode. @@ -105,12 +105,12 @@ #endif void ChromeSigninStatusMetricsProviderDelegate::IdentityManagerCreated( - identity::IdentityManager* identity_manager) { + signin::IdentityManager* identity_manager) { owner()->OnIdentityManagerCreated(identity_manager); } void ChromeSigninStatusMetricsProviderDelegate::IdentityManagerShutdown( - identity::IdentityManager* identity_manager) { + signin::IdentityManager* identity_manager) { owner()->OnIdentityManagerShutdown(identity_manager); }
diff --git a/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.h b/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.h index c41591b..18b8e76 100644 --- a/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.h +++ b/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.h
@@ -31,7 +31,7 @@ // SigninStatusMetricsProviderDelegate: void Initialize() override; AccountsStatus GetStatusOfAllAccounts() override; - std::vector<identity::IdentityManager*> GetIdentityManagersForAllAccounts() + std::vector<signin::IdentityManager*> GetIdentityManagersForAllAccounts() override; #if !defined(OS_ANDROID) @@ -41,9 +41,9 @@ // IdentityManagerFactoryObserver: void IdentityManagerCreated( - identity::IdentityManager* identity_manager) override; + signin::IdentityManager* identity_manager) override; void IdentityManagerShutdown( - identity::IdentityManager* identity_manager) override; + signin::IdentityManager* identity_manager) override; // Updates the sign-in status right after a new browser is opened. void UpdateStatusWhenBrowserAdded(bool signed_in);
diff --git a/chrome/browser/signin/dice_browsertest.cc b/chrome/browser/signin/dice_browsertest.cc index 2c6c811..804e7f2 100644 --- a/chrome/browser/signin/dice_browsertest.cc +++ b/chrome/browser/signin/dice_browsertest.cc
@@ -169,7 +169,7 @@ kDiceResponseHeader, base::StringPrintf( "action=SIGNIN,authuser=1,id=%s,email=%s,authorization_code=%s", - identity::GetTestGaiaIdForEmail(main_email).c_str(), + signin::GetTestGaiaIdForEmail(main_email).c_str(), main_email.c_str(), kAuthorizationCode)); } @@ -197,7 +197,7 @@ http_response->AddCustomHeader( kDiceResponseHeader, base::StringPrintf("action=ENABLE_SYNC,authuser=1,id=%s,email=%s", - identity::GetTestGaiaIdForEmail(main_email).c_str(), + signin::GetTestGaiaIdForEmail(main_email).c_str(), main_email.c_str())); http_response->AddCustomHeader("Cache-Control", "no-store"); return std::move(http_response); @@ -220,7 +220,7 @@ EXPECT_LT(signout_type, kSignoutTypeLast); std::string signout_header_value; if (signout_type == kAllAccounts || signout_type == kMainAccount) { - std::string main_gaia_id = identity::GetTestGaiaIdForEmail(main_email); + std::string main_gaia_id = signin::GetTestGaiaIdForEmail(main_email); signout_header_value = base::StringPrintf("email=\"%s\", obfuscatedid=\"%s\", sessionindex=1", main_email.c_str(), main_gaia_id.c_str()); @@ -229,7 +229,7 @@ if (!signout_header_value.empty()) signout_header_value += ", "; std::string secondary_gaia_id = - identity::GetTestGaiaIdForEmail(kSecondaryEmail); + signin::GetTestGaiaIdForEmail(kSecondaryEmail); signout_header_value += base::StringPrintf("email=\"%s\", obfuscatedid=\"%s\", sessionindex=2", kSecondaryEmail, secondary_gaia_id.c_str()); @@ -313,7 +313,7 @@ class DiceBrowserTest : public InProcessBrowserTest, public AccountReconcilor::Observer, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { protected: ~DiceBrowserTest() override {} @@ -360,7 +360,7 @@ } // Returns the identity manager. - identity::IdentityManager* GetIdentityManager() { + signin::IdentityManager* GetIdentityManager() { return IdentityManagerFactory::GetForProfile(browser()->profile()); } @@ -368,14 +368,14 @@ // gaia ID. std::string GetMainAccountID() { return GetIdentityManager()->PickAccountIdForAccount( - identity::GetTestGaiaIdForEmail(main_email_), main_email_); + signin::GetTestGaiaIdForEmail(main_email_), main_email_); } // Returns the account ID associated with kSecondaryEmail and its associated // gaia ID. std::string GetSecondaryAccountID() { return GetIdentityManager()->PickAccountIdForAccount( - identity::GetTestGaiaIdForEmail(kSecondaryEmail), kSecondaryEmail); + signin::GetTestGaiaIdForEmail(kSecondaryEmail), kSecondaryEmail); } std::string GetDeviceId() { @@ -385,8 +385,8 @@ // Signin with a main account and add token for a secondary account. void SetupSignedInAccounts() { // Signin main account. - AccountInfo primary_account_info = identity::MakePrimaryAccountAvailable( - GetIdentityManager(), main_email_); + AccountInfo primary_account_info = + signin::MakePrimaryAccountAvailable(GetIdentityManager(), main_email_); ASSERT_TRUE( GetIdentityManager()->HasAccountWithRefreshToken(GetMainAccountID())); ASSERT_FALSE( @@ -396,7 +396,7 @@ // Add a token for a secondary account. AccountInfo secondary_account_info = - identity::MakeAccountAvailable(GetIdentityManager(), kSecondaryEmail); + signin::MakeAccountAvailable(GetIdentityManager(), kSecondaryEmail); ASSERT_TRUE(GetIdentityManager()->HasAccountWithRefreshToken( secondary_account_info.account_id)); ASSERT_FALSE( @@ -515,7 +515,7 @@ } } - // identity::IdentityManager::Observer + // signin::IdentityManager::Observer void OnPrimaryAccountSet( const CoreAccountInfo& primary_account_info) override { RunClosureIfValid(std::move(on_primary_account_set_quit_closure_));
diff --git a/chrome/browser/signin/dice_response_handler.cc b/chrome/browser/signin/dice_response_handler.cc index 810cd96..df82660 100644 --- a/chrome/browser/signin/dice_response_handler.cc +++ b/chrome/browser/signin/dice_response_handler.cc
@@ -226,7 +226,7 @@ DiceResponseHandler::DiceResponseHandler( SigninClient* signin_client, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, AccountReconcilor* account_reconcilor, AboutSigninInternals* about_signin_internals, signin::AccountConsistencyMethod account_consistency,
diff --git a/chrome/browser/signin/dice_response_handler.h b/chrome/browser/signin/dice_response_handler.h index a789d38..bc55f76e 100644 --- a/chrome/browser/signin/dice_response_handler.h +++ b/chrome/browser/signin/dice_response_handler.h
@@ -24,7 +24,7 @@ class SigninClient; class Profile; -namespace identity { +namespace signin { class IdentityManager; } @@ -55,7 +55,7 @@ static DiceResponseHandler* GetForProfile(Profile* profile); DiceResponseHandler(SigninClient* signin_client, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, AccountReconcilor* account_reconcilor, AboutSigninInternals* about_signin_internals, signin::AccountConsistencyMethod account_consistency, @@ -152,7 +152,7 @@ const GoogleServiceAuthError& error); SigninClient* signin_client_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; AccountReconcilor* account_reconcilor_; AboutSigninInternals* about_signin_internals_; signin::AccountConsistencyMethod account_consistency_;
diff --git a/chrome/browser/signin/dice_response_handler_unittest.cc b/chrome/browser/signin/dice_response_handler_unittest.cc index aa04a57..8d93791 100644 --- a/chrome/browser/signin/dice_response_handler_unittest.cc +++ b/chrome/browser/signin/dice_response_handler_unittest.cc
@@ -143,7 +143,7 @@ DiceResponseParams dice_params; dice_params.user_intention = action; DiceResponseParams::AccountInfo account_info; - account_info.gaia_id = identity::GetTestGaiaIdForEmail(kEmail); + account_info.gaia_id = signin::GetTestGaiaIdForEmail(kEmail); account_info.email = kEmail; account_info.session_index = kSessionIndex; switch (action) { @@ -174,7 +174,7 @@ void OnBlockReconcile() override { ++reconcilor_blocked_count_; } void OnUnblockReconcile() override { ++reconcilor_unblocked_count_; } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return identity_test_env_.identity_manager(); } @@ -182,7 +182,7 @@ base::ScopedTempDir temp_dir_; sync_preferences::TestingPrefServiceSyncable pref_service_; DiceTestSigninClient signin_client_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; SigninErrorController signin_error_controller_; AboutSigninInternals about_signin_internals_; std::unique_ptr<AccountReconcilor> account_reconcilor_; @@ -507,7 +507,7 @@ const char kSecondaryEmail[] = "other@gmail.com"; DiceResponseParams dice_params = MakeDiceParams(DiceAction::SIGNOUT); dice_params.signout_info->account_infos.emplace_back( - identity::GetTestGaiaIdForEmail(kSecondaryEmail), kSecondaryEmail, 1); + signin::GetTestGaiaIdForEmail(kSecondaryEmail), kSecondaryEmail, 1); const auto& main_account_info = dice_params.signout_info->account_infos[0]; // User is signed in to Chrome, and has some refresh token for a secondary
diff --git a/chrome/browser/signin/force_signin_verifier.cc b/chrome/browser/signin/force_signin_verifier.cc index b54d674..b53470e 100644 --- a/chrome/browser/signin/force_signin_verifier.cc +++ b/chrome/browser/signin/force_signin_verifier.cc
@@ -38,7 +38,7 @@ "Signin.ForceSigninVerificationTime.Failure"; ForceSigninVerifier::ForceSigninVerifier( - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : has_token_verified_(false), backoff_entry_(&kForceSigninVerifierBackoffPolicy), creation_time_(base::TimeTicks::Now()), @@ -55,7 +55,7 @@ void ForceSigninVerifier::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { if (error.state() != GoogleServiceAuthError::NONE) { if (error.IsPersistentError()) { UMA_HISTOGRAM_MEDIUM_TIMES(kForceSigninVerificationFailureTimeMetricsName, @@ -127,11 +127,11 @@ // It is safe to use Unretained(this) here given that the callback // will not be invoked if this object is deleted. access_token_fetcher_ = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "force_signin_verifier", identity_manager_, oauth2_scopes, base::BindOnce(&ForceSigninVerifier::OnAccessTokenFetchComplete, base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); } bool ForceSigninVerifier::ShouldSendRequest() { @@ -146,12 +146,12 @@ if (!primary_account_mutator) return; primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, signin_metrics::AUTHENTICATION_FAILED_WITH_FORCE_SIGNIN, signin_metrics::SignoutDelete::IGNORE_METRIC); } -identity::PrimaryAccountAccessTokenFetcher* +signin::PrimaryAccountAccessTokenFetcher* ForceSigninVerifier::GetAccessTokenFetcherForTesting() { return access_token_fetcher_.get(); }
diff --git a/chrome/browser/signin/force_signin_verifier.h b/chrome/browser/signin/force_signin_verifier.h index eb2820cc..08676fa7 100644 --- a/chrome/browser/signin/force_signin_verifier.h +++ b/chrome/browser/signin/force_signin_verifier.h
@@ -15,11 +15,11 @@ #include "net/base/backoff_entry.h" #include "services/network/public/cpp/network_connection_tracker.h" -namespace identity { +namespace signin { class IdentityManager; class PrimaryAccountAccessTokenFetcher; struct AccessTokenInfo; -} // namespace identity +} // namespace signin extern const char kForceSigninVerificationMetricsName[]; extern const char kForceSigninVerificationSuccessTimeMetricsName[]; @@ -31,11 +31,11 @@ class ForceSigninVerifier : public network::NetworkConnectionTracker::NetworkConnectionObserver { public: - explicit ForceSigninVerifier(identity::IdentityManager* identity_manager); + explicit ForceSigninVerifier(signin::IdentityManager* identity_manager); ~ForceSigninVerifier() override; void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); // override network::NetworkConnectionTracker::NetworkConnectionObserver void OnConnectionChanged(network::mojom::ConnectionType type) override; @@ -64,12 +64,12 @@ virtual void CloseAllBrowserWindows(); - identity::PrimaryAccountAccessTokenFetcher* GetAccessTokenFetcherForTesting(); + signin::PrimaryAccountAccessTokenFetcher* GetAccessTokenFetcherForTesting(); net::BackoffEntry* GetBackoffEntryForTesting(); base::OneShotTimer* GetOneShotTimerForTesting(); private: - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; // Indicates whether the verification is finished successfully or with a @@ -79,7 +79,7 @@ base::OneShotTimer backoff_request_timer_; base::TimeTicks creation_time_; - identity::IdentityManager* identity_manager_ = nullptr; + signin::IdentityManager* identity_manager_ = nullptr; DISALLOW_COPY_AND_ASSIGN(ForceSigninVerifier); };
diff --git a/chrome/browser/signin/force_signin_verifier_unittest.cc b/chrome/browser/signin/force_signin_verifier_unittest.cc index 1238177..c1b28513 100644 --- a/chrome/browser/signin/force_signin_verifier_unittest.cc +++ b/chrome/browser/signin/force_signin_verifier_unittest.cc
@@ -20,14 +20,14 @@ : public ForceSigninVerifier { public: explicit ForceSigninVerifierWithAccessToInternalsForTesting( - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : ForceSigninVerifier(identity_manager) {} bool IsDelayTaskPosted() { return GetOneShotTimerForTesting()->IsRunning(); } int FailureCount() { return GetBackoffEntryForTesting()->failure_count(); } - identity::PrimaryAccountAccessTokenFetcher* access_token_fetcher() { + signin::PrimaryAccountAccessTokenFetcher* access_token_fetcher() { return GetAccessTokenFetcherForTesting(); } @@ -147,7 +147,7 @@ TEST(ForceSigninVerifierTest, OnGetTokenSuccess) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com"); @@ -176,7 +176,7 @@ TEST(ForceSigninVerifierTest, OnGetTokenPersistentFailure) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com"); @@ -206,7 +206,7 @@ TEST(ForceSigninVerifierTest, OnGetTokenTransientFailure) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com"); @@ -235,7 +235,7 @@ TEST(ForceSigninVerifierTest, OnLostConnection) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com"); @@ -259,7 +259,7 @@ TEST(ForceSigninVerifierTest, OnReconnected) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com"); @@ -283,7 +283,7 @@ TEST(ForceSigninVerifierTest, GetNetworkStatusAsync) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com"); @@ -305,7 +305,7 @@ TEST(ForceSigninVerifierTest, LaunchVerifierWithoutNetwork) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com"); @@ -334,7 +334,7 @@ TEST(ForceSigninVerifierTest, ChangeNetworkFromWIFITo4GWithOnGoingRequest) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com"); @@ -365,7 +365,7 @@ TEST(ForceSigninVerifierTest, ChangeNetworkFromWIFITo4GWithFinishedRequest) { base::test::ScopedTaskEnvironment scoped_task_env; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; const AccountInfo account_info = identity_test_env.MakePrimaryAccountAvailable("email@test.com");
diff --git a/chrome/browser/signin/identity_manager_factory.cc b/chrome/browser/signin/identity_manager_factory.cc index 935117b..25aaf8e 100644 --- a/chrome/browser/signin/identity_manager_factory.cc +++ b/chrome/browser/signin/identity_manager_factory.cc
@@ -43,7 +43,7 @@ void IdentityManagerFactory::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { - identity::IdentityManager::RegisterProfilePrefs(registry); + signin::IdentityManager::RegisterProfilePrefs(registry); } IdentityManagerFactory::IdentityManagerFactory() @@ -59,16 +59,16 @@ IdentityManagerFactory::~IdentityManagerFactory() {} // static -identity::IdentityManager* IdentityManagerFactory::GetForProfile( +signin::IdentityManager* IdentityManagerFactory::GetForProfile( Profile* profile) { - return static_cast<identity::IdentityManager*>( + return static_cast<signin::IdentityManager*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } // static -identity::IdentityManager* IdentityManagerFactory::GetForProfileIfExists( +signin::IdentityManager* IdentityManagerFactory::GetForProfileIfExists( const Profile* profile) { - return static_cast<identity::IdentityManager*>( + return static_cast<signin::IdentityManager*>( GetInstance()->GetServiceForBrowserContext(const_cast<Profile*>(profile), false)); } @@ -96,7 +96,7 @@ content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - identity::IdentityManagerBuildParams params; + signin::IdentityManagerBuildParams params; params.account_consistency = AccountConsistencyModeManager::GetMethodForProfile(profile), params.image_decoder = std::make_unique<ImageDecoderImpl>(); @@ -131,8 +131,8 @@ base::Unretained(profile)); #endif - std::unique_ptr<identity::IdentityManager> identity_manager = - identity::BuildIdentityManager(¶ms); + std::unique_ptr<signin::IdentityManager> identity_manager = + signin::BuildIdentityManager(¶ms); for (Observer& observer : observer_list_) observer.IdentityManagerCreated(identity_manager.get()); @@ -142,7 +142,7 @@ void IdentityManagerFactory::BrowserContextShutdown( content::BrowserContext* context) { - auto* identity_manager = static_cast<identity::IdentityManager*>( + auto* identity_manager = static_cast<signin::IdentityManager*>( GetServiceForBrowserContext(context, false)); if (identity_manager) { for (Observer& observer : observer_list_)
diff --git a/chrome/browser/signin/identity_manager_factory.h b/chrome/browser/signin/identity_manager_factory.h index 0b7814b..57d8f7ca 100644 --- a/chrome/browser/signin/identity_manager_factory.h +++ b/chrome/browser/signin/identity_manager_factory.h
@@ -12,7 +12,7 @@ #include "base/observer_list.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -26,20 +26,19 @@ public: // Called when a IdentityManager instance is created. virtual void IdentityManagerCreated( - identity::IdentityManager* identity_manager) {} + signin::IdentityManager* identity_manager) {} // Called when a IdentityManager instance is being shut down. Observers // of |identity_manager| should remove themselves at this point. virtual void IdentityManagerShutdown( - identity::IdentityManager* identity_manager) {} + signin::IdentityManager* identity_manager) {} protected: ~Observer() override {} }; - static identity::IdentityManager* GetForProfile(Profile* profile); - static identity::IdentityManager* GetForProfileIfExists( - const Profile* profile); + static signin::IdentityManager* GetForProfile(Profile* profile); + static signin::IdentityManager* GetForProfileIfExists(const Profile* profile); // Returns an instance of the IdentityManagerFactory singleton. static IdentityManagerFactory* GetInstance();
diff --git a/chrome/browser/signin/identity_services_provider_android.cc b/chrome/browser/signin/identity_services_provider_android.cc index e8fa0e01..2e6c3ed 100644 --- a/chrome/browser/signin/identity_services_provider_android.cc +++ b/chrome/browser/signin/identity_services_provider_android.cc
@@ -17,7 +17,7 @@ JNIEnv* env, const JavaParamRef<jobject>& j_profile_android) { Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile_android); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); return identity_manager->LegacyGetAccountTrackerServiceJavaObject(); } @@ -27,7 +27,7 @@ JNIEnv* env, const JavaParamRef<jobject>& j_profile_android) { Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile_android); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); return identity_manager->LegacyGetOAuth2TokenServiceJavaObject(); }
diff --git a/chrome/browser/signin/identity_test_environment_profile_adaptor.cc b/chrome/browser/signin/identity_test_environment_profile_adaptor.cc index e3dc5fd..9a61ea9 100644 --- a/chrome/browser/signin/identity_test_environment_profile_adaptor.cc +++ b/chrome/browser/signin/identity_test_environment_profile_adaptor.cc
@@ -72,7 +72,7 @@ content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); - return identity::IdentityTestEnvironment::BuildIdentityManagerForTests( + return signin::IdentityTestEnvironment::BuildIdentityManagerForTests( ChromeSigninClientFactory::GetForProfile(profile), profile->GetPrefs(), profile->GetPath()); }
diff --git a/chrome/browser/signin/identity_test_environment_profile_adaptor.h b/chrome/browser/signin/identity_test_environment_profile_adaptor.h index 8149f163..abc283ad 100644 --- a/chrome/browser/signin/identity_test_environment_profile_adaptor.h +++ b/chrome/browser/signin/identity_test_environment_profile_adaptor.h
@@ -11,14 +11,14 @@ #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/sync_preferences/testing_pref_service_syncable.h" -// Adaptor that supports identity::IdentityTestEnvironment's usage in testing +// Adaptor that supports signin::IdentityTestEnvironment's usage in testing // contexts where the relevant fake objects must be injected via the // BrowserContextKeyedServiceFactory infrastructure as the production code // accesses IdentityManager via that infrastructure. Before using this // class, please consider whether you can change the production code in question // to take in the relevant dependencies directly rather than obtaining them from // the Profile; this is both cleaner in general and allows for direct usage of -// identity::IdentityTestEnvironment in the test. +// signin::IdentityTestEnvironment in the test. class IdentityTestEnvironmentProfileAdaptor { public: // Creates and returns a TestingProfile that has been configured with the set @@ -39,13 +39,13 @@ static std::unique_ptr<TestingProfile> CreateProfileForIdentityTestEnvironment(TestingProfile::Builder& builder); - // Sets the testing factories that identity::IdentityTestEnvironment + // Sets the testing factories that signin::IdentityTestEnvironment // requires explicitly on a Profile that is passed to it. // See the above variant for comments on common parameters. static void SetIdentityTestEnvironmentFactoriesOnBrowserContext( content::BrowserContext* browser_context); - // Appends the set of testing factories that identity::IdentityTestEnvironment + // Appends the set of testing factories that signin::IdentityTestEnvironment // requires to |factories_to_append_to|, which should be the set of testing // factories supplied to TestingProfile (via one of the various mechanisms for // doing so). Prefer the above API if possible, as it is less fragile. This @@ -57,7 +57,7 @@ static void AppendIdentityTestEnvironmentFactories( TestingProfile::TestingFactories* factories_to_append_to); - // Returns the set of testing factories that identity::IdentityTestEnvironment + // Returns the set of testing factories that signin::IdentityTestEnvironment // requires, which can be useful to configure profiles for services that do // not require any other testing factory than the ones specified in here. static TestingProfile::TestingFactories GetIdentityTestEnvironmentFactories(); @@ -75,7 +75,7 @@ // Returns the IdentityTestEnvironment associated with this object (and // implicitly with the Profile passed to this object's constructor). - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } @@ -85,7 +85,7 @@ static std::unique_ptr<KeyedService> BuildIdentityManagerForTests( content::BrowserContext* context); - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; DISALLOW_COPY_AND_ASSIGN(IdentityTestEnvironmentProfileAdaptor); };
diff --git a/chrome/browser/signin/process_dice_header_delegate_impl.cc b/chrome/browser/signin/process_dice_header_delegate_impl.cc index da7b1f5..01203537 100644 --- a/chrome/browser/signin/process_dice_header_delegate_impl.cc +++ b/chrome/browser/signin/process_dice_header_delegate_impl.cc
@@ -28,7 +28,7 @@ ProcessDiceHeaderDelegateImpl::ProcessDiceHeaderDelegateImpl( content::WebContents* web_contents, signin::AccountConsistencyMethod account_consistency, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, bool is_sync_signin_tab, EnableSyncCallback enable_sync_callback, ShowSigninErrorCallback show_signin_error_callback,
diff --git a/chrome/browser/signin/process_dice_header_delegate_impl.h b/chrome/browser/signin/process_dice_header_delegate_impl.h index a7e487be..2ecdc49 100644 --- a/chrome/browser/signin/process_dice_header_delegate_impl.h +++ b/chrome/browser/signin/process_dice_header_delegate_impl.h
@@ -19,7 +19,7 @@ class WebContents; } -namespace identity { +namespace signin { class IdentityManager; } @@ -42,7 +42,7 @@ ProcessDiceHeaderDelegateImpl( content::WebContents* web_contents, signin::AccountConsistencyMethod account_consistency, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, bool is_sync_signin_tab, EnableSyncCallback enable_sync_callback, ShowSigninErrorCallback show_signin_error_callback, @@ -59,7 +59,7 @@ bool ShouldEnableSync(); signin::AccountConsistencyMethod account_consistency_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; EnableSyncCallback enable_sync_callback_; ShowSigninErrorCallback show_signin_error_callback_; bool is_sync_signin_tab_;
diff --git a/chrome/browser/signin/process_dice_header_delegate_impl_unittest.cc b/chrome/browser/signin/process_dice_header_delegate_impl_unittest.cc index f3466bb..5eaf96f4 100644 --- a/chrome/browser/signin/process_dice_header_delegate_impl_unittest.cc +++ b/chrome/browser/signin/process_dice_header_delegate_impl_unittest.cc
@@ -70,7 +70,7 @@ show_error_called_ = true; } - identity::IdentityTestEnvironment identity_test_environment_; + signin::IdentityTestEnvironment identity_test_environment_; bool enable_sync_called_; bool show_error_called_;
diff --git a/chrome/browser/signin/signin_error_notifier_ash.h b/chrome/browser/signin/signin_error_notifier_ash.h index 1884668..558fdc7 100644 --- a/chrome/browser/signin/signin_error_notifier_ash.h +++ b/chrome/browser/signin/signin_error_notifier_ash.h
@@ -18,9 +18,9 @@ class Profile; -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity. +} // namespace signin. // Shows signin-related errors as notifications in Ash. class SigninErrorNotifier : public SigninErrorController::Observer, @@ -64,7 +64,7 @@ Profile* const profile_; // A non-owning pointer to IdentityManager. - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; // A non-owning pointer. chromeos::AccountManager* const account_manager_;
diff --git a/chrome/browser/signin/signin_error_notifier_ash_unittest.cc b/chrome/browser/signin/signin_error_notifier_ash_unittest.cc index c5cc159..f44f750b 100644 --- a/chrome/browser/signin/signin_error_notifier_ash_unittest.cc +++ b/chrome/browser/signin/signin_error_notifier_ash_unittest.cc
@@ -67,11 +67,11 @@ void SetAuthError(const std::string& account_id, const GoogleServiceAuthError& error) { - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_test_env()->identity_manager(), account_id, error); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_profile_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/signin/signin_global_error_unittest.cc b/chrome/browser/signin/signin_global_error_unittest.cc index 435a794..199e351 100644 --- a/chrome/browser/signin/signin_global_error_unittest.cc +++ b/chrome/browser/signin/signin_global_error_unittest.cc
@@ -79,12 +79,12 @@ SigninErrorController* error_controller() { return error_controller_; } void SetAuthError(GoogleServiceAuthError::State state) { - identity::IdentityTestEnvironment* identity_test_env = + signin::IdentityTestEnvironment* identity_test_env = identity_test_env_profile_adaptor_->identity_test_env(); std::string primary_account_id = identity_test_env->identity_manager()->GetPrimaryAccountId(); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_test_env->identity_manager(), primary_account_id, GoogleServiceAuthError(state)); }
diff --git a/chrome/browser/signin/signin_manager_android_wrapper.cc b/chrome/browser/signin/signin_manager_android_wrapper.cc index 6d200f94..8d2bdf39 100644 --- a/chrome/browser/signin/signin_manager_android_wrapper.cc +++ b/chrome/browser/signin/signin_manager_android_wrapper.cc
@@ -7,7 +7,7 @@ SigninManagerAndroidWrapper::SigninManagerAndroidWrapper( SigninClient* signin_client, PrefService* local_state_prefs_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<SigninManagerDelegate> signin_manager_delegate) : signin_manager_android_(signin_client, local_state_prefs_service,
diff --git a/chrome/browser/signin/signin_manager_android_wrapper.h b/chrome/browser/signin/signin_manager_android_wrapper.h index c482505..285ce56 100644 --- a/chrome/browser/signin/signin_manager_android_wrapper.h +++ b/chrome/browser/signin/signin_manager_android_wrapper.h
@@ -16,7 +16,7 @@ SigninManagerAndroidWrapper( SigninClient* signin_client, PrefService* local_state_prefs_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<SigninManagerDelegate> signin_manager_delegate); ~SigninManagerAndroidWrapper() override;
diff --git a/chrome/browser/signin/signin_profile_attributes_updater.cc b/chrome/browser/signin/signin_profile_attributes_updater.cc index 3078514..cbe1958 100644 --- a/chrome/browser/signin/signin_profile_attributes_updater.cc +++ b/chrome/browser/signin/signin_profile_attributes_updater.cc
@@ -13,7 +13,7 @@ #include "components/signin/public/identity_manager/account_info.h" SigninProfileAttributesUpdater::SigninProfileAttributesUpdater( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninErrorController* signin_error_controller, ProfileAttributesStorage* profile_attributes_storage, const base::FilePath& profile_path)
diff --git a/chrome/browser/signin/signin_profile_attributes_updater.h b/chrome/browser/signin/signin_profile_attributes_updater.h index a95fb55..29a2067 100644 --- a/chrome/browser/signin/signin_profile_attributes_updater.h +++ b/chrome/browser/signin/signin_profile_attributes_updater.h
@@ -19,10 +19,10 @@ class SigninProfileAttributesUpdater : public KeyedService, public SigninErrorController::Observer, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: SigninProfileAttributesUpdater( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninErrorController* signin_error_controller, ProfileAttributesStorage* profile_attributes_storage, const base::FilePath& profile_path); @@ -45,11 +45,11 @@ void OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) override; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; SigninErrorController* signin_error_controller_; ProfileAttributesStorage* profile_attributes_storage_; const base::FilePath profile_path_; - ScopedObserver<identity::IdentityManager, SigninProfileAttributesUpdater> + ScopedObserver<signin::IdentityManager, SigninProfileAttributesUpdater> identity_manager_observer_; ScopedObserver<SigninErrorController, SigninProfileAttributesUpdater> signin_error_controller_observer_;
diff --git a/chrome/browser/signin/signin_profile_attributes_updater_unittest.cc b/chrome/browser/signin/signin_profile_attributes_updater_unittest.cc index 0e7c2a88..12a7743 100644 --- a/chrome/browser/signin/signin_profile_attributes_updater_unittest.cc +++ b/chrome/browser/signin/signin_profile_attributes_updater_unittest.cc
@@ -61,7 +61,7 @@ content::TestBrowserThreadBundle thread_bundle_; TestingProfileManager profile_manager_; base::FilePath profile_path_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; SigninErrorController signin_error_controller_; std::unique_ptr<SigninProfileAttributesUpdater> signin_profile_attributes_updater_; @@ -80,7 +80,7 @@ // Signin. identity_test_env_.MakePrimaryAccountAvailable(kEmail); EXPECT_TRUE(entry->IsAuthenticated()); - EXPECT_EQ(identity::GetTestGaiaIdForEmail(kEmail), entry->GetGAIAId()); + EXPECT_EQ(signin::GetTestGaiaIdForEmail(kEmail), entry->GetGAIAId()); EXPECT_EQ(kEmail, base::UTF16ToUTF8(entry->GetUserName())); // Signout. @@ -145,7 +145,7 @@ identity_test_env_.MakePrimaryAccountAvailable(kEmail); EXPECT_TRUE(entry->IsAuthenticated()); - EXPECT_EQ(identity::GetTestGaiaIdForEmail(kEmail), entry->GetGAIAId()); + EXPECT_EQ(signin::GetTestGaiaIdForEmail(kEmail), entry->GetGAIAId()); EXPECT_EQ(kEmail, base::UTF16ToUTF8(entry->GetUserName())); identity_test_env_.ClearPrimaryAccount();
diff --git a/chrome/browser/signin/signin_promo_util.cc b/chrome/browser/signin/signin_promo_util.cc index 612f981..ad49d90 100644 --- a/chrome/browser/signin/signin_promo_util.cc +++ b/chrome/browser/signin/signin_promo_util.cc
@@ -39,7 +39,7 @@ return false; // Display the signin promo if the user is not signed in. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(original_profile); return !identity_manager->HasPrimaryAccount(); #endif
diff --git a/chrome/browser/signin/signin_ui_util.cc b/chrome/browser/signin/signin_ui_util.cc index 77df17d..0bcb7c5 100644 --- a/chrome/browser/signin/signin_ui_util.cc +++ b/chrome/browser/signin/signin_ui_util.cc
@@ -57,7 +57,7 @@ namespace signin_ui_util { base::string16 GetAuthenticatedUsername( - const identity::IdentityManager* identity_manager) { + const signin::IdentityManager* identity_manager) { std::string user_display_name; if (identity_manager->HasPrimaryAccount()) { @@ -146,7 +146,7 @@ ? signin_metrics::PromoAction::PROMO_ACTION_WITH_DEFAULT : signin_metrics::PromoAction::PROMO_ACTION_NOT_DEFAULT; - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); bool needs_reauth_before_enable_sync = !identity_manager->HasAccountWithRefreshToken(account.account_id) || @@ -170,16 +170,16 @@ } // namespace internal std::string GetDisplayEmail(Profile* profile, const std::string& account_id) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); std::string email = identity_manager ->FindAccountInfoForAccountWithRefreshTokenByAccountId(account_id) ->email; if (email.empty()) { - DCHECK_EQ(identity::IdentityManager::AccountIdMigrationState:: - MIGRATION_NOT_STARTED, - identity_manager->GetAccountIdMigrationState()); + DCHECK_EQ( + signin::IdentityManager::AccountIdMigrationState::MIGRATION_NOT_STARTED, + identity_manager->GetAccountIdMigrationState()); return account_id; } return email; @@ -187,7 +187,7 @@ std::vector<AccountInfo> GetAccountsForDicePromos(Profile* profile) { // Fetch account ids for accounts that have a token. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); std::vector<AccountInfo> accounts_with_tokens = identity_manager->GetExtendedAccountInfoForAccountsWithRefreshToken(); @@ -215,7 +215,7 @@ std::vector<AccountInfo> accounts; for (auto& account_info : accounts_with_tokens) { DCHECK(!account_info.IsEmpty()); - if (!identity::IsUsernameAllowedByPatternFromPrefs( + if (!signin::IsUsernameAllowedByPatternFromPrefs( g_browser_process->local_state(), account_info.email)) { continue; }
diff --git a/chrome/browser/signin/signin_ui_util.h b/chrome/browser/signin/signin_ui_util.h index 0ab7f7f8..b487ba3 100644 --- a/chrome/browser/signin/signin_ui_util.h +++ b/chrome/browser/signin/signin_ui_util.h
@@ -19,7 +19,7 @@ class Profile; class Browser; -namespace identity { +namespace signin { class IdentityManager; } @@ -33,7 +33,7 @@ // Returns the username of the authenticated user or an empty string if there is // no authenticated user. base::string16 GetAuthenticatedUsername( - const identity::IdentityManager* identity_manager); + const signin::IdentityManager* identity_manager); // Initializes signin-related preferences. void InitializePrefsForProfile(Profile* profile);
diff --git a/chrome/browser/signin/signin_ui_util_unittest.cc b/chrome/browser/signin/signin_ui_util_unittest.cc index 9eb0063..7a642eb 100644 --- a/chrome/browser/signin/signin_ui_util_unittest.cc +++ b/chrome/browser/signin/signin_ui_util_unittest.cc
@@ -141,7 +141,7 @@ } // Returns the identity manager. - identity::IdentityManager* GetIdentityManager() { + signin::IdentityManager* GetIdentityManager() { return IdentityManagerFactory::GetForProfile(profile()); } @@ -323,7 +323,7 @@ // Add an account and then put its refresh token into an error state to // require a reauth before enabling sync. - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( GetIdentityManager(), account_id, GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
diff --git a/chrome/browser/signin/signin_util.cc b/chrome/browser/signin/signin_util.cc index cb67058f5..1c0966c 100644 --- a/chrome/browser/signin/signin_util.cc +++ b/chrome/browser/signin/signin_util.cc
@@ -222,7 +222,7 @@ CoreAccountInfo primary_account = identity_manager->GetPrimaryAccountInfo(); if (profile->GetPrefs()->GetBoolean(prefs::kSigninAllowed) && - identity::IsUsernameAllowedByPatternFromPrefs( + signin::IsUsernameAllowedByPatternFromPrefs( g_browser_process->local_state(), primary_account.email)) { return; } @@ -239,7 +239,7 @@ auto* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNIN_NOT_ALLOWED_ON_PROFILE_INIT, signin_metrics::SignoutDelete::IGNORE_METRIC); break;
diff --git a/chrome/browser/signin/signin_util_win_browsertest.cc b/chrome/browser/signin/signin_util_win_browsertest.cc index b9196b1..d367ecda 100644 --- a/chrome/browser/signin/signin_util_win_browsertest.cc +++ b/chrome/browser/signin/signin_util_win_browsertest.cc
@@ -213,7 +213,7 @@ IdentityManagerFactory::GetForProfile(profile) ->GetPrimaryAccountMutator(); primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::FORCE_SIGNOUT_ALWAYS_ALLOWED_FOR_TEST, signin_metrics::SignoutDelete::DELETED); @@ -239,7 +239,7 @@ // Make sure the profile stays signed in, but in an auth error state. auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager, identity_manager->GetPrimaryAccountId(), GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason::
diff --git a/chrome/browser/supervised_user/child_accounts/child_account_service.cc b/chrome/browser/supervised_user/child_accounts/child_account_service.cc index 691ba85..31da29f 100644 --- a/chrome/browser/supervised_user/child_accounts/child_account_service.cc +++ b/chrome/browser/supervised_user/child_accounts/child_account_service.cc
@@ -126,7 +126,7 @@ } ChildAccountService::AuthState ChildAccountService::GetGoogleAuthState() { - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = identity_manager_->GetAccountsInCookieJar(); if (!accounts_in_cookie_jar_info.accounts_are_fresh) return AuthState::PENDING; @@ -305,7 +305,7 @@ } void ChildAccountService::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { google_auth_state_observers_.Notify(); }
diff --git a/chrome/browser/supervised_user/child_accounts/child_account_service.h b/chrome/browser/supervised_user/child_accounts/child_account_service.h index 8e74357e6..aaa13cc 100644 --- a/chrome/browser/supervised_user/child_accounts/child_account_service.h +++ b/chrome/browser/supervised_user/child_accounts/child_account_service.h
@@ -33,7 +33,7 @@ // supervised user experience, fetch information about the parent(s)). class ChildAccountService : public KeyedService, public FamilyInfoFetcher::Consumer, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public SupervisedUserService::Delegate { public: enum class AuthState { AUTHENTICATED, NOT_AUTHENTICATED, PENDING }; @@ -78,7 +78,7 @@ // Sets whether the signed-in account is a child account. void SetIsChildAccount(bool is_child_account); - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnExtendedAccountInfoUpdated(const AccountInfo& info) override; void OnExtendedAccountInfoRemoved(const AccountInfo& info) override; @@ -89,7 +89,7 @@ // IdentityManager::Observer implementation. void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; void StartFetchingFamilyInfo(); @@ -114,7 +114,7 @@ base::OneShotTimer family_fetch_timer_; net::BackoffEntry family_fetch_backoff_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; base::CallbackList<void()> google_auth_state_observers_;
diff --git a/chrome/browser/supervised_user/child_accounts/child_account_service_unittest.cc b/chrome/browser/supervised_user/child_accounts/child_account_service_unittest.cc index ed90452..ba5ce09f 100644 --- a/chrome/browser/supervised_user/child_accounts/child_account_service_unittest.cc +++ b/chrome/browser/supervised_user/child_accounts/child_account_service_unittest.cc
@@ -46,7 +46,7 @@ ->GetTestURLLoaderFactory(); } - identity::AccountsCookieMutator* GetAccountsCookieMutator() { + signin::AccountsCookieMutator* GetAccountsCookieMutator() { IdentityTestEnvironmentProfileAdaptor identity_test_env_profile_adaptor( profile_.get()); return identity_test_env_profile_adaptor.identity_test_env()
diff --git a/chrome/browser/supervised_user/child_accounts/family_info_fetcher.cc b/chrome/browser/supervised_user/child_accounts/family_info_fetcher.cc index 90fc3936..5b87559 100644 --- a/chrome/browser/supervised_user/child_accounts/family_info_fetcher.cc +++ b/chrome/browser/supervised_user/child_accounts/family_info_fetcher.cc
@@ -83,7 +83,7 @@ FamilyInfoFetcher::FamilyInfoFetcher( Consumer* consumer, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : consumer_(consumer), primary_account_id_(identity_manager->GetPrimaryAccountId()), @@ -123,17 +123,17 @@ void FamilyInfoFetcher::StartFetchingAccessToken() { OAuth2AccessTokenManager::ScopeSet scopes{kScope}; - access_token_fetcher_ = std::make_unique< - identity::PrimaryAccountAccessTokenFetcher>( - "family_info_fetcher", identity_manager_, scopes, - base::BindOnce(&FamilyInfoFetcher::OnAccessTokenFetchComplete, - base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + access_token_fetcher_ = + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( + "family_info_fetcher", identity_manager_, scopes, + base::BindOnce(&FamilyInfoFetcher::OnAccessTokenFetchComplete, + base::Unretained(this)), + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void FamilyInfoFetcher::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) { DLOG(WARNING) << "Failed to get an access token: " << error.ToString();
diff --git a/chrome/browser/supervised_user/child_accounts/family_info_fetcher.h b/chrome/browser/supervised_user/child_accounts/family_info_fetcher.h index 2dafc96..76864fb 100644 --- a/chrome/browser/supervised_user/child_accounts/family_info_fetcher.h +++ b/chrome/browser/supervised_user/child_accounts/family_info_fetcher.h
@@ -19,10 +19,10 @@ class ListValue; } -namespace identity { +namespace signin { struct AccessTokenInfo; class PrimaryAccountAccessTokenFetcher; -} +} // namespace signin namespace network { class SimpleURLLoader; @@ -85,7 +85,7 @@ // methods below. |consumer| must outlive us. FamilyInfoFetcher( Consumer* consumer, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~FamilyInfoFetcher(); @@ -105,7 +105,7 @@ private: void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); void OnSimpleLoaderComplete(std::unique_ptr<std::string> response_body); @@ -123,11 +123,11 @@ Consumer* consumer_; const std::string primary_account_id_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; std::string request_path_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; std::string access_token_; bool access_token_expired_;
diff --git a/chrome/browser/supervised_user/child_accounts/family_info_fetcher_unittest.cc b/chrome/browser/supervised_user/child_accounts/family_info_fetcher_unittest.cc index 7155878d..0b3831a 100644 --- a/chrome/browser/supervised_user/child_accounts/family_info_fetcher_unittest.cc +++ b/chrome/browser/supervised_user/child_accounts/family_info_fetcher_unittest.cc
@@ -177,7 +177,7 @@ } base::test::ScopedTaskEnvironment scoped_task_environment_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; network::TestURLLoaderFactory test_url_loader_factory_; std::unique_ptr<FamilyInfoFetcher> fetcher_; };
diff --git a/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.cc b/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.cc index a7db9db..059264d 100644 --- a/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.cc +++ b/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.cc
@@ -63,7 +63,7 @@ std::string request_type; std::string object_ref; SuccessCallback callback; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher; std::string access_token; bool access_token_expired; @@ -82,7 +82,7 @@ PermissionRequestCreatorApiary::Request::~Request() {} PermissionRequestCreatorApiary::PermissionRequestCreatorApiary( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : identity_manager_(identity_manager), url_loader_factory_(std::move(url_loader_factory)), @@ -162,18 +162,18 @@ // will not be invoked if this object is deleted. Likewise, |request| // only comes from |requests_|, which are owned by this object too. request->access_token_fetcher = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "permissions_creator", identity_manager_, scopes, base::BindOnce( &PermissionRequestCreatorApiary::OnAccessTokenFetchComplete, base::Unretained(this), request), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); } void PermissionRequestCreatorApiary::OnAccessTokenFetchComplete( Request* request, GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { auto it = requests_.begin(); while (it != requests_.end()) { if (request->access_token_fetcher.get() ==
diff --git a/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.h b/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.h index 2a1831c..a89ce65 100644 --- a/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.h +++ b/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.h
@@ -17,10 +17,10 @@ class GURL; class Profile; -namespace identity { +namespace signin { class IdentityManager; struct AccessTokenInfo; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -29,7 +29,7 @@ class PermissionRequestCreatorApiary : public PermissionRequestCreator { public: PermissionRequestCreatorApiary( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~PermissionRequestCreatorApiary() override; @@ -53,7 +53,7 @@ void OnAccessTokenFetchComplete(Request* request, GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); void OnSimpleLoaderComplete(RequestList::iterator it, std::unique_ptr<std::string> response_body); @@ -71,7 +71,7 @@ void DispatchResult(RequestList::iterator it, bool success); - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; bool retry_on_network_change_;
diff --git a/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary_unittest.cc b/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary_unittest.cc index b566109..2a385d8 100644 --- a/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary_unittest.cc +++ b/chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary_unittest.cc
@@ -87,7 +87,7 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; std::string account_id_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; std::unique_ptr<PermissionRequestCreatorApiary> permission_creator_;
diff --git a/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.cc b/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.cc index 16a7a43df..e71db1f3 100644 --- a/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.cc +++ b/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.cc
@@ -145,7 +145,7 @@ KidsChromeManagementCallback callback; std::unique_ptr<network::ResourceRequest> resource_request; const net::NetworkTrafficAnnotationTag traffic_annotation; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher; bool access_token_expired; const char* oauth_consumer_name; @@ -227,18 +227,18 @@ identity::ScopeSet scopes{req->scope}; req->access_token_fetcher = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( req->oauth_consumer_name, identity_manager_, scopes, base::BindOnce( &KidsChromeManagementClient::OnAccessTokenFetchComplete, base::Unretained(this), it), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); } void KidsChromeManagementClient::OnAccessTokenFetchComplete( KidsChromeRequestList::iterator it, GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { if (error.state() != GoogleServiceAuthError::NONE) { DLOG(WARNING) << "Token error: " << error.ToString(); @@ -287,7 +287,7 @@ void KidsChromeManagementClient::OnSimpleLoaderComplete( KidsChromeRequestList::iterator it, std::unique_ptr<network::SimpleURLLoader> simple_url_loader, - identity::AccessTokenInfo token_info, + signin::AccessTokenInfo token_info, std::unique_ptr<std::string> response_body) { int response_code = -1;
diff --git a/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.h b/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.h index 10a5a1a..b0baa420 100644 --- a/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.h +++ b/chrome/browser/supervised_user/kids_chrome_management/kids_chrome_management_client.h
@@ -16,10 +16,10 @@ #include "components/keyed_service/core/keyed_service.h" #include "third_party/protobuf/src/google/protobuf/message_lite.h" -namespace identity { +namespace signin { struct AccessTokenInfo; class IdentityManager; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -87,12 +87,12 @@ void OnAccessTokenFetchComplete( KidsChromeRequestList::iterator kids_chrome_request, GoogleServiceAuthError auth_error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); void OnSimpleLoaderComplete( KidsChromeRequestList::iterator kids_chrome_request, std::unique_ptr<network::SimpleURLLoader> simple_url_loader, - identity::AccessTokenInfo token_info, + signin::AccessTokenInfo token_info, std::unique_ptr<std::string> response_body); // Calls the callback provided by the existing RPC client with the response @@ -103,7 +103,7 @@ ErrorCode error); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // List of requests in execution. KidsChromeRequestList requests_in_progress_;
diff --git a/chrome/browser/supervised_user/kids_management_url_checker_client.cc b/chrome/browser/supervised_user/kids_management_url_checker_client.cc index df84b7f..9046b4e 100644 --- a/chrome/browser/supervised_user/kids_management_url_checker_client.cc +++ b/chrome/browser/supervised_user/kids_management_url_checker_client.cc
@@ -142,7 +142,7 @@ Check(Check&&) = default; GURL url; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher; bool access_token_expired; std::unique_ptr<network::SimpleURLLoader> simple_url_loader; @@ -164,7 +164,7 @@ KidsManagementURLCheckerClient::KidsManagementURLCheckerClient( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::string& country, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : url_loader_factory_(std::move(url_loader_factory)), traffic_annotation_( net::DefineNetworkTrafficAnnotation("kids_management_url_checker", R"( @@ -214,18 +214,18 @@ // only comes from |checks_in_progress_|, which are owned by this object // too. it->get()->access_token_fetcher = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "kids_url_classifier", identity_manager_, scopes, base::BindOnce( &KidsManagementURLCheckerClient::OnAccessTokenFetchComplete, base::Unretained(this), it), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); } void KidsManagementURLCheckerClient::OnAccessTokenFetchComplete( CheckList::iterator it, GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { if (error.state() != GoogleServiceAuthError::NONE) { DLOG(WARNING) << "Token error: " << error.ToString(); @@ -259,7 +259,7 @@ void KidsManagementURLCheckerClient::OnSimpleLoaderComplete( CheckList::iterator it, - identity::AccessTokenInfo token_info, + signin::AccessTokenInfo token_info, std::unique_ptr<std::string> response_body) { Check* check = it->get(); std::unique_ptr<network::SimpleURLLoader> simple_url_loader =
diff --git a/chrome/browser/supervised_user/kids_management_url_checker_client.h b/chrome/browser/supervised_user/kids_management_url_checker_client.h index 3c7bb1a..bbcd129 100644 --- a/chrome/browser/supervised_user/kids_management_url_checker_client.h +++ b/chrome/browser/supervised_user/kids_management_url_checker_client.h
@@ -20,10 +20,10 @@ class SharedURLLoaderFactory; } // namespace network -namespace identity { +namespace signin { class IdentityManager; struct AccessTokenInfo; -} // namespace identity +} // namespace signin struct KidsManagementURLCheckerResponse; @@ -38,7 +38,7 @@ KidsManagementURLCheckerClient( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::string& country, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~KidsManagementURLCheckerClient() override; // Checks whether an |url| is restricted according to KidsManagement @@ -58,10 +58,10 @@ void OnAccessTokenFetchComplete(CheckList::iterator it, GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); void OnSimpleLoaderComplete(CheckList::iterator it, - identity::AccessTokenInfo token_info, + signin::AccessTokenInfo token_info, std::unique_ptr<std::string> response_body); void DispatchResult(CheckList::iterator it, @@ -70,7 +70,7 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; const net::NetworkTrafficAnnotationTag traffic_annotation_; const std::string country_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; CheckList checks_in_progress_;
diff --git a/chrome/browser/supervised_user/kids_management_url_checker_client_unittest.cc b/chrome/browser/supervised_user/kids_management_url_checker_client_unittest.cc index 632ff0e8..5757cc4a 100644 --- a/chrome/browser/supervised_user/kids_management_url_checker_client_unittest.cc +++ b/chrome/browser/supervised_user/kids_management_url_checker_client_unittest.cc
@@ -110,7 +110,7 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; std::string account_id_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; std::unique_ptr<KidsManagementURLCheckerClient> url_classifier_;
diff --git a/chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.cc b/chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.cc index f5efd3a..54e9064 100644 --- a/chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.cc +++ b/chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.cc
@@ -59,7 +59,7 @@ return std::string(); } -identity::IdentityManager* +signin::IdentityManager* CustodianProfileDownloaderService::GetIdentityManager() { DCHECK(custodian_profile_); return IdentityManagerFactory::GetForProfile(custodian_profile_);
diff --git a/chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.h b/chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.h index 26f473e..5a1fc1c 100644 --- a/chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.h +++ b/chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.h
@@ -36,7 +36,7 @@ bool NeedsProfilePicture() const override; int GetDesiredImageSideLength() const override; std::string GetCachedPictureURL() const override; - identity::IdentityManager* GetIdentityManager() override; + signin::IdentityManager* GetIdentityManager() override; network::mojom::URLLoaderFactory* GetURLLoaderFactory() override; bool IsPreSignin() const override; void OnProfileDownloadSuccess(ProfileDownloader* downloader) override;
diff --git a/chrome/browser/supervised_user/supervised_user_service_unittest.cc b/chrome/browser/supervised_user/supervised_user_service_unittest.cc index 929b8e9f..67dcbd1 100644 --- a/chrome/browser/supervised_user/supervised_user_service_unittest.cc +++ b/chrome/browser/supervised_user/supervised_user_service_unittest.cc
@@ -206,7 +206,7 @@ base::Unretained(result_holder))); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_environment_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/supervised_user/supervised_user_url_filter.cc b/chrome/browser/supervised_user/supervised_user_url_filter.cc index c8a298d2..8bc7bb3 100644 --- a/chrome/browser/supervised_user/supervised_user_url_filter.cc +++ b/chrome/browser/supervised_user/supervised_user_url_filter.cc
@@ -535,7 +535,7 @@ void SupervisedUserURLFilter::InitAsyncURLChecker( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - identity::IdentityManager* identity_manager) { + signin::IdentityManager* identity_manager) { std::string country; variations::VariationsService* variations_service = g_browser_process->variations_service();
diff --git a/chrome/browser/supervised_user/supervised_user_url_filter.h b/chrome/browser/supervised_user/supervised_user_url_filter.h index 7de081a..1f7face9 100644 --- a/chrome/browser/supervised_user/supervised_user_url_filter.h +++ b/chrome/browser/supervised_user/supervised_user_url_filter.h
@@ -23,7 +23,7 @@ class GURL; class SupervisedUserBlacklist; -namespace identity { +namespace signin { class IdentityManager; } @@ -157,7 +157,7 @@ // Initializes the experimental asynchronous checker. void InitAsyncURLChecker( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); // Clears any asynchronous checker. void ClearAsyncURLChecker();
diff --git a/chrome/browser/sync/profile_sync_service_android.cc b/chrome/browser/sync/profile_sync_service_android.cc index 46e0273..ed69b099 100644 --- a/chrome/browser/sync/profile_sync_service_android.cc +++ b/chrome/browser/sync/profile_sync_service_android.cc
@@ -169,6 +169,14 @@ return sync_service_->IsSyncFeatureActive(); } +jboolean ProfileSyncServiceAndroid::IsSyncDisabledByEnterprisePolicy( + JNIEnv* env, + const JavaParamRef<jobject>& obj) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + return sync_service_->HasDisableReason( + syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); +} + jboolean ProfileSyncServiceAndroid::IsEngineInitialized( JNIEnv* env, const JavaParamRef<jobject>&) {
diff --git a/chrome/browser/sync/profile_sync_service_android.h b/chrome/browser/sync/profile_sync_service_android.h index e8699b63..d3a70fff 100644 --- a/chrome/browser/sync/profile_sync_service_android.h +++ b/chrome/browser/sync/profile_sync_service_android.h
@@ -49,6 +49,9 @@ jboolean allowed); jboolean IsSyncActive(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); + jboolean IsSyncDisabledByEnterprisePolicy( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj); jboolean IsEngineInitialized(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); void SetSetupInProgress(JNIEnv* env,
diff --git a/chrome/browser/sync/sync_ui_util_unittest.cc b/chrome/browser/sync/sync_ui_util_unittest.cc index 495627f..51cb8ea 100644 --- a/chrome/browser/sync/sync_ui_util_unittest.cc +++ b/chrome/browser/sync/sync_ui_util_unittest.cc
@@ -59,7 +59,7 @@ // return. std::pair<sync_ui_util::MessageType, sync_ui_util::ActionType> SetUpDistinctCase(TestSyncService* service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, int case_number) { switch (case_number) { case STATUS_CASE_SETUP_IN_PROGRESS: { @@ -85,10 +85,10 @@ // Make sure to fail authentication with an error in this case. std::string account_id = identity_manager->GetPrimaryAccountId(); - identity::SetRefreshTokenForPrimaryAccount(identity_manager); + signin::SetRefreshTokenForPrimaryAccount(identity_manager); service->SetAuthenticatedAccountInfo( identity_manager->GetPrimaryAccountInfo()); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager, account_id, GoogleServiceAuthError(GoogleServiceAuthError::State::SERVICE_ERROR)); service->SetDisableReasons(syncer::SyncService::DISABLE_REASON_NONE); @@ -193,10 +193,9 @@ std::unique_ptr<Profile> profile = BuildTestingProfile(); IdentityTestEnvironmentProfileAdaptor env_adaptor(profile.get()); - identity::IdentityTestEnvironment* environment = + signin::IdentityTestEnvironment* environment = env_adaptor.identity_test_env(); - identity::IdentityManager* identity_manager = - environment->identity_manager(); + signin::IdentityManager* identity_manager = environment->identity_manager(); // Need a primary account signed in before calling SetUpDistinctCase(). environment->MakePrimaryAccountAvailable(kTestUser); @@ -318,9 +317,9 @@ std::unique_ptr<Profile> profile = BuildTestingProfile(); IdentityTestEnvironmentProfileAdaptor env_adaptor(profile.get()); - identity::IdentityTestEnvironment* environment = + signin::IdentityTestEnvironment* environment = env_adaptor.identity_test_env(); - identity::IdentityManager* identity_manager = environment->identity_manager(); + signin::IdentityManager* identity_manager = environment->identity_manager(); AccountInfo primary_account_info = environment->MakePrimaryAccountAvailable(kTestUser); @@ -345,7 +344,7 @@ EXPECT_EQ(message, sync_ui_util::MessageType::SYNCED); // Add an error to the secondary account. - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager, secondary_account_info.account_id, GoogleServiceAuthError( GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS));
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 893a03d..4d8d9ce 100644 --- a/chrome/browser/sync/test/integration/profile_sync_service_harness.cc +++ b/chrome/browser/sync/test/integration/profile_sync_service_harness.cc
@@ -144,7 +144,7 @@ } case SigninType::FAKE_SIGNIN: { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); // Verify HasPrimaryAccount() separately because @@ -158,12 +158,11 @@ // always hand out the same access token string, any new access token // acquired later would also be considered invalid. if (!identity_manager->HasPrimaryAccountWithRefreshToken()) { - identity::SetRefreshTokenForPrimaryAccount(identity_manager); + signin::SetRefreshTokenForPrimaryAccount(identity_manager); } } else { // Authenticate sync client using GAIA credentials. - identity::MakePrimaryAccountAvailable( - identity_manager, username_); + signin::MakePrimaryAccountAvailable(identity_manager, username_); } return true; } @@ -176,20 +175,20 @@ #if !defined(OS_CHROMEOS) void ProfileSyncServiceHarness::SignOutPrimaryAccount() { DCHECK(!username_.empty()); - identity::ClearPrimaryAccount( + signin::ClearPrimaryAccount( IdentityManagerFactory::GetForProfile(profile_), - identity::ClearPrimaryAccountPolicy::REMOVE_ALL_ACCOUNTS); + signin::ClearPrimaryAccountPolicy::REMOVE_ALL_ACCOUNTS); } #endif // !OS_CHROMEOS void ProfileSyncServiceHarness::EnterSyncPausedStateForPrimaryAccount() { DCHECK(service_->IsSyncFeatureActive()); - identity::SetInvalidRefreshTokenForPrimaryAccount( + signin::SetInvalidRefreshTokenForPrimaryAccount( IdentityManagerFactory::GetForProfile(profile_)); } void ProfileSyncServiceHarness::ExitSyncPausedStateForPrimaryAccount() { - identity::SetRefreshTokenForPrimaryAccount( + signin::SetRefreshTokenForPrimaryAccount( IdentityManagerFactory::GetForProfile(profile_)); }
diff --git a/chrome/browser/sync/test/integration/secondary_account_helper.cc b/chrome/browser/sync/test/integration/secondary_account_helper.cc index 9493669e..048383f 100644 --- a/chrome/browser/sync/test/integration/secondary_account_helper.cc +++ b/chrome/browser/sync/test/integration/secondary_account_helper.cc
@@ -71,17 +71,17 @@ Profile* profile, network::TestURLLoaderFactory* test_url_loader_factory, const std::string& email) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); AccountInfo account_info = - identity::MakeAccountAvailable(identity_manager, email); - identity::SetCookieAccounts(identity_manager, test_url_loader_factory, - {{account_info.email, account_info.gaia}}); + signin::MakeAccountAvailable(identity_manager, email); + signin::SetCookieAccounts(identity_manager, test_url_loader_factory, + {{account_info.email, account_info.gaia}}); } #if !defined(OS_CHROMEOS) void MakeAccountPrimary(Profile* profile, const std::string& email) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); base::Optional<AccountInfo> maybe_account = identity_manager->FindAccountInfoForAccountWithRefreshTokenByEmailAddress(
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 b0775c1..183995a 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
@@ -759,7 +759,7 @@ ASSERT_EQ(1u, GetBookmarkBarNode(kSingleProfileIndex)->children().size()); #if defined(CHROMEOS) - // identity::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order + // signin::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order // to get a non-empty refresh token on startup. GetClient(0)->SignInPrimaryAccount(); #endif // defined(CHROMEOS)
diff --git a/chrome/browser/sync/test/integration/single_client_passwords_sync_test.cc b/chrome/browser/sync/test/integration/single_client_passwords_sync_test.cc index 694a0972..ade1290 100644 --- a/chrome/browser/sync/test/integration/single_client_passwords_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_passwords_sync_test.cc
@@ -179,7 +179,7 @@ ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; ASSERT_EQ(1, GetPasswordCount(0)); #if defined(CHROMEOS) - // identity::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order + // signin::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order // to get a non-empty refresh token on startup. GetClient(0)->SignInPrimaryAccount(); #endif // defined(CHROMEOS) @@ -245,7 +245,7 @@ ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; ASSERT_EQ(2, GetPasswordCount(0)); #if defined(CHROMEOS) - // identity::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order + // signin::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order // to get a non-empty refresh token on startup. GetClient(0)->SignInPrimaryAccount(); #endif // defined(CHROMEOS)
diff --git a/chrome/browser/sync/test/integration/single_client_polling_sync_test.cc b/chrome/browser/sync/test/integration/single_client_polling_sync_test.cc index 8a54a1d..1b837a1 100644 --- a/chrome/browser/sync/test/integration/single_client_polling_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_polling_sync_test.cc
@@ -131,7 +131,7 @@ ShouldPollWhenIntervalExpiredAcrossRestarts) { ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; #if defined(CHROMEOS) - // identity::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order + // signin::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order // to get a non-empty refresh token on startup. GetClient(0)->SignInPrimaryAccount(); #endif // defined(CHROMEOS)
diff --git a/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc b/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc index 9271959..9dc97528 100644 --- a/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc
@@ -161,7 +161,7 @@ base::HistogramTester histogram_tester; ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; #if defined(CHROMEOS) - // identity::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order + // signin::SetRefreshTokenForPrimaryAccount() is needed on ChromeOS in order // to get a non-empty refresh token on startup. GetClient(0)->SignInPrimaryAccount(); #endif // defined(CHROMEOS)
diff --git a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc index 4f7fff99..345aaa8 100644 --- a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc
@@ -756,7 +756,7 @@ // Avoid interferences from actual IdentityManager trying to fetch gaia // account information, which would exercise // ProfileSyncService::OnAccountsInCookieUpdated(). - identity::CancelAllOngoingGaiaCookieOperations( + signin::CancelAllOngoingGaiaCookieOperations( IdentityManagerFactory::GetForProfile(GetProfile(0))); // Trigger a cookie jar change (user signing in to content area).
diff --git a/chrome/browser/sync/test/integration/sync_auth_test.cc b/chrome/browser/sync/test/integration/sync_auth_test.cc index 8317559..e71f7d34 100644 --- a/chrome/browser/sync/test/integration/sync_auth_test.cc +++ b/chrome/browser/sync/test/integration/sync_auth_test.cc
@@ -127,7 +127,7 @@ // Disable retries so that we instantly trigger the case where // ProfileSyncService must pick up where OAuth2TokenService left off (in // terms of retries). - identity::DisableAccessTokenFetchRetries( + signin::DisableAccessTokenFetchRetries( IdentityManagerFactory::GetForProfile(GetProfile(0))); }
diff --git a/chrome/browser/sync_file_system/drive_backend/sync_engine.cc b/chrome/browser/sync_file_system/drive_backend/sync_engine.cc index 121330b..6cf5e759 100644 --- a/chrome/browser/sync_file_system/drive_backend/sync_engine.cc +++ b/chrome/browser/sync_file_system/drive_backend/sync_engine.cc
@@ -94,7 +94,7 @@ std::unique_ptr<drive::DriveServiceInterface> SyncEngine::DriveServiceFactory::CreateDriveService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, base::SequencedTaskRunner* blocking_task_runner) { return std::unique_ptr< @@ -209,7 +209,7 @@ drive::DriveNotificationManagerFactory::GetForBrowserContext(context); extensions::ExtensionService* extension_service = extensions::ExtensionSystem::Get(context)->extension_service(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory = content::BrowserContext::GetDefaultStoragePartition(context) @@ -720,7 +720,7 @@ TaskLogger* task_logger, drive::DriveNotificationManager* notification_manager, extensions::ExtensionServiceInterface* extension_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, std::unique_ptr<DriveServiceFactory> drive_service_factory, leveldb::Env* env_override)
diff --git a/chrome/browser/sync_file_system/drive_backend/sync_engine.h b/chrome/browser/sync_file_system/drive_backend/sync_engine.h index a2bc036b..f0e655c 100644 --- a/chrome/browser/sync_file_system/drive_backend/sync_engine.h +++ b/chrome/browser/sync_file_system/drive_backend/sync_engine.h
@@ -65,7 +65,7 @@ public LocalChangeProcessor, public drive::DriveNotificationObserver, public drive::DriveServiceObserver, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public network::NetworkConnectionTracker::NetworkConnectionObserver { public: typedef RemoteFileSyncService::Observer SyncServiceObserver; @@ -75,7 +75,7 @@ DriveServiceFactory() {} virtual ~DriveServiceFactory() {} virtual std::unique_ptr<drive::DriveServiceInterface> CreateDriveService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, base::SequencedTaskRunner* blocking_task_runner); @@ -166,7 +166,7 @@ TaskLogger* task_logger, drive::DriveNotificationManager* notification_manager, extensions::ExtensionServiceInterface* extension_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, std::unique_ptr<DriveServiceFactory> drive_service_factory, leveldb::Env* env_override); @@ -196,7 +196,7 @@ // KeyedService::DependsOn(). drive::DriveNotificationManager* notification_manager_; extensions::ExtensionServiceInterface* extension_service_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
diff --git a/chrome/browser/ui/app_list/internal_app/internal_app_metadata.cc b/chrome/browser/ui/app_list/internal_app/internal_app_metadata.cc index d49cc76..fe4ca725 100644 --- a/chrome/browser/ui/app_list/internal_app/internal_app_metadata.cc +++ b/chrome/browser/ui/app_list/internal_app/internal_app_metadata.cc
@@ -104,6 +104,9 @@ /*searchable_string_resource_id=*/IDS_INTERNAL_APP_DISCOVER}); } + // TODO(calamity/nigeltao): when removing the + // web_app::SystemWebAppManager::IsEnabled condition, we can probably also + // remove the apps::BuiltInChromeOsApps::SetHideSettingsAppForTesting hack. if (!web_app::SystemWebAppManager::IsEnabled()) { internal_app_list->push_back( {kInternalAppIdSettings, IDS_INTERNAL_APP_SETTINGS,
diff --git a/chrome/browser/ui/ash/assistant/assistant_client.h b/chrome/browser/ui/ash/assistant/assistant_client.h index 6694805..dff30e7 100644 --- a/chrome/browser/ui/ash/assistant/assistant_client.h +++ b/chrome/browser/ui/ash/assistant/assistant_client.h
@@ -20,7 +20,7 @@ // Class to handle all assistant in-browser-process functionalities. class AssistantClient : chromeos::assistant::mojom::Client, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public session_manager::SessionManagerObserver { public: static AssistantClient* Get(); @@ -37,7 +37,7 @@ RequestAssistantStructureCallback callback) override; private: - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: // Retry to initiate Assistant service when account info has been updated. // This is necessary if previous calls of MaybeInit() failed due to Assistant // disallowed by account type. This can happen when the chromeos sign-in @@ -61,7 +61,7 @@ // Non-owning pointers. Profile* profile_ = nullptr; - identity::IdentityManager* identity_manager_ = nullptr; + signin::IdentityManager* identity_manager_ = nullptr; DISALLOW_COPY_AND_ASSIGN(AssistantClient); };
diff --git a/chrome/browser/ui/ash/multi_user/multi_user_util_chromeos_unittest.cc b/chrome/browser/ui/ash/multi_user/multi_user_util_chromeos_unittest.cc index 87abe02..d94da5d 100644 --- a/chrome/browser/ui/ash/multi_user/multi_user_util_chromeos_unittest.cc +++ b/chrome/browser/ui/ash/multi_user/multi_user_util_chromeos_unittest.cc
@@ -73,7 +73,7 @@ TestingProfile* profile() { return profile_.get(); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_adaptor_->identity_test_env(); } @@ -93,7 +93,7 @@ // revoked. (On Chrome OS we don't force to end the session in this case.) TEST_F(MultiUserUtilTest, ReturnValidAccountIdIfTokenRevoked) { std::string account_id = AddUserAndSignIn(kTestAccountEmail); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = identity_test_env()->identity_manager(); EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken(account_id));
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.cc b/chrome/browser/ui/autofill/chrome_autofill_client.cc index 885c27b..a407f6a2 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.cc +++ b/chrome/browser/ui/autofill/chrome_autofill_client.cc
@@ -128,7 +128,7 @@ return ProfileSyncServiceFactory::GetForProfile(profile); } -identity::IdentityManager* ChromeAutofillClient::GetIdentityManager() { +signin::IdentityManager* ChromeAutofillClient::GetIdentityManager() { Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); return IdentityManagerFactory::GetForProfile(profile->GetOriginalProfile()); @@ -598,7 +598,7 @@ Profile* profile = GetProfile(); if (!profile) return base::string16(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (!identity_manager) return base::string16();
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.h b/chrome/browser/ui/autofill/chrome_autofill_client.h index 706f894e..af4b043 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.h +++ b/chrome/browser/ui/autofill/chrome_autofill_client.h
@@ -55,7 +55,7 @@ AutocompleteHistoryManager* GetAutocompleteHistoryManager() override; PrefService* GetPrefs() override; syncer::SyncService* GetSyncService() override; - identity::IdentityManager* GetIdentityManager() override; + signin::IdentityManager* GetIdentityManager() override; FormDataImporter* GetFormDataImporter() override; payments::PaymentsClient* GetPaymentsClient() override; StrikeDatabase* GetStrikeDatabase() override;
diff --git a/chrome/browser/ui/extensions/extension_installed_bubble_browsertest.cc b/chrome/browser/ui/extensions/extension_installed_bubble_browsertest.cc index 2448b82..f5c453c 100644 --- a/chrome/browser/ui/extensions/extension_installed_bubble_browsertest.cc +++ b/chrome/browser/ui/extensions/extension_installed_bubble_browsertest.cc
@@ -138,7 +138,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionInstalledBubbleBrowserTest, DISABLED_InvokeUi_NoAction) { // Sign in to supppress the signin promo. - identity::MakePrimaryAccountAvailable( + signin::MakePrimaryAccountAvailable( IdentityManagerFactory::GetForProfile(profile()), "test@example.com"); ShowAndVerifyUi(); }
diff --git a/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc b/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc index a20b14b..b2a9141 100644 --- a/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc +++ b/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc
@@ -71,7 +71,7 @@ static std::unique_ptr<KeyedService> CreateOneGoogleBarService( content::BrowserContext* context) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile( Profile::FromBrowserContext(context)); return std::make_unique<OneGoogleBarService>(
diff --git a/chrome/browser/ui/search/search_tab_helper_unittest.cc b/chrome/browser/ui/search/search_tab_helper_unittest.cc index 3eed020..0d62a665 100644 --- a/chrome/browser/ui/search/search_tab_helper_unittest.cc +++ b/chrome/browser/ui/search/search_tab_helper_unittest.cc
@@ -105,7 +105,7 @@ sync_service->SetPreferredDataTypes(types); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { DCHECK(identity_test_env_adaptor_); return identity_test_env_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/ui/signin_view_controller.cc b/chrome/browser/ui/signin_view_controller.cc index 543518ed..cf92cdc 100644 --- a/chrome/browser/ui/signin_view_controller.cc +++ b/chrome/browser/ui/signin_view_controller.cc
@@ -84,7 +84,7 @@ // Returns the promo action to be used when signing with a new account. signin_metrics::PromoAction GetPromoActionForNewAccount( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, signin::AccountConsistencyMethod account_consistency) { if (account_consistency != signin::AccountConsistencyMethod::kDice) return signin_metrics::PromoAction::PROMO_ACTION_NEW_ACCOUNT_PRE_DICE; @@ -268,7 +268,7 @@ signin_metrics::Reason reason = signin_metrics::Reason::REASON_SIGNIN_PRIMARY_ACCOUNT; std::string email_to_use = email_hint; - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(browser->profile()); if (identity_manager->HasPrimaryAccount()) { reason = signin_metrics::Reason::REASON_REAUTHENTICATION;
diff --git a/chrome/browser/ui/toolbar/media_router_contextual_menu.cc b/chrome/browser/ui/toolbar/media_router_contextual_menu.cc index 3ba07198..b9d4ac81 100644 --- a/chrome/browser/ui/toolbar/media_router_contextual_menu.cc +++ b/chrome/browser/ui/toolbar/media_router_contextual_menu.cc
@@ -124,7 +124,7 @@ if (command_id == IDC_MEDIA_ROUTER_CLOUD_SERVICES_TOGGLE) { // Cloud services preference is not set or used if the user is not signed // in. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(browser_->profile()); return identity_manager && identity_manager->HasPrimaryAccount(); }
diff --git a/chrome/browser/ui/toolbar/media_router_contextual_menu_unittest.cc b/chrome/browser/ui/toolbar/media_router_contextual_menu_unittest.cc index 6eaf1623..b61aa52 100644 --- a/chrome/browser/ui/toolbar/media_router_contextual_menu_unittest.cc +++ b/chrome/browser/ui/toolbar/media_router_contextual_menu_unittest.cc
@@ -102,7 +102,7 @@ } protected: - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { DCHECK(identity_test_env_adaptor_); return identity_test_env_adaptor_->identity_test_env(); }
diff --git a/chrome/browser/ui/views/autofill/payments/save_card_bubble_views_browsertest.cc b/chrome/browser/ui/views/autofill/payments/save_card_bubble_views_browsertest.cc index f5af480..d50bb45b 100644 --- a/chrome/browser/ui/views/autofill/payments/save_card_bubble_views_browsertest.cc +++ b/chrome/browser/ui/views/autofill/payments/save_card_bubble_views_browsertest.cc
@@ -314,7 +314,7 @@ } void SetAccountFullName(const std::string& full_name) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); PersonalDataManager* personal_data_manager = PersonalDataManagerFactory::GetForProfile(browser()->profile()); @@ -328,7 +328,7 @@ account_info.is_under_advanced_protection = core_info.is_under_advanced_protection; account_info.full_name = full_name; - identity::UpdateAccountInfoForAccount(identity_manager, account_info); + signin::UpdateAccountInfoForAccount(identity_manager, account_info); } void SubmitFormAndWaitForCardLocalSaveBubble() {
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_browsertest.cc b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_browsertest.cc index 5ef7d1e..9c5a88a6 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_browsertest.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_browsertest.cc
@@ -26,14 +26,14 @@ // DialogBrowserTest: void ShowUi(const std::string& name) override { #if !defined(OS_CHROMEOS) - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); if (name == "bookmark_details") { - identity::ClearPrimaryAccount( - identity_manager, identity::ClearPrimaryAccountPolicy::DEFAULT); + signin::ClearPrimaryAccount(identity_manager, + signin::ClearPrimaryAccountPolicy::DEFAULT); } else { constexpr char kTestUserEmail[] = "testuser@gtest.com"; - identity::MakePrimaryAccountAvailable(identity_manager, kTestUserEmail); + signin::MakePrimaryAccountAvailable(identity_manager, kTestUserEmail); } #endif
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_unittest.cc b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_unittest.cc index aaf93c2..3b104c035 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view_unittest.cc
@@ -77,7 +77,7 @@ // Verifies that the sync promo is not displayed for a signed in user. TEST_F(BookmarkBubbleViewTest, SyncPromoSignedIn) { - identity::MakePrimaryAccountAvailable( + signin::MakePrimaryAccountAvailable( IdentityManagerFactory::GetForProfile(profile()), "fake_username"); CreateBubbleView(); std::unique_ptr<views::View> footnote = CreateFootnoteView();
diff --git a/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc b/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc index cceeec6..9b1d91f6 100644 --- a/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc +++ b/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc
@@ -239,7 +239,7 @@ } void AvatarToolbarButton::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { UpdateIcon(); } @@ -384,7 +384,7 @@ AvatarToolbarButton::SyncState AvatarToolbarButton::GetSyncState() const { #if !defined(OS_CHROMEOS) - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); if (identity_manager && identity_manager->HasPrimaryAccount() && profile_->IsSyncAllowed() && error_controller_.HasAvatarError()) {
diff --git a/chrome/browser/ui/views/profiles/avatar_toolbar_button.h b/chrome/browser/ui/views/profiles/avatar_toolbar_button.h index 36922dff..16b9f20 100644 --- a/chrome/browser/ui/views/profiles/avatar_toolbar_button.h +++ b/chrome/browser/ui/views/profiles/avatar_toolbar_button.h
@@ -24,7 +24,7 @@ public AvatarButtonErrorControllerDelegate, public BrowserListObserver, public ProfileAttributesStorage::Observer, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public ui::MaterialDesignControllerObserver { public: explicit AvatarToolbarButton(Browser* browser); @@ -64,7 +64,7 @@ // IdentityManager::Observer: // Needed if the first sync promo account should be displayed. void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; void OnExtendedAccountInfoUpdated(const AccountInfo& info) override; void OnExtendedAccountInfoRemoved(const AccountInfo& info) override; @@ -95,7 +95,7 @@ ScopedObserver<BrowserList, BrowserListObserver> browser_list_observer_; ScopedObserver<ProfileAttributesStorage, AvatarToolbarButton> profile_observer_; - ScopedObserver<identity::IdentityManager, AvatarToolbarButton> + ScopedObserver<signin::IdentityManager, AvatarToolbarButton> identity_manager_observer_; ScopedObserver<ui::MaterialDesignController, AvatarToolbarButton> md_observer_{this};
diff --git a/chrome/browser/ui/views/profiles/profile_chooser_view.cc b/chrome/browser/ui/views/profiles/profile_chooser_view.cc index 1f3de0e..853ce00 100644 --- a/chrome/browser/ui/views/profiles/profile_chooser_view.cc +++ b/chrome/browser/ui/views/profiles/profile_chooser_view.cc
@@ -182,7 +182,7 @@ avatar_menu_->RebuildMenu(); Profile* profile = browser()->profile(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (identity_manager) @@ -266,7 +266,7 @@ // Unsubscribe from everything early so that the updates do not reach the // bubble and change its state. avatar_menu_.reset(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); if (identity_manager) identity_manager->RemoveObserver(this); @@ -343,7 +343,7 @@ IdentityManagerFactory::GetForProfile(browser()->profile()) ->GetPrimaryAccountMutator()) { account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, signin_metrics::SignoutDelete::IGNORE_METRIC); ShowViewOrOpenTab(profiles::BUBBLE_VIEW_MODE_GAIA_SIGNIN);
diff --git a/chrome/browser/ui/views/profiles/profile_chooser_view.h b/chrome/browser/ui/views/profiles/profile_chooser_view.h index 63470c1..99ce6f5 100644 --- a/chrome/browser/ui/views/profiles/profile_chooser_view.h +++ b/chrome/browser/ui/views/profiles/profile_chooser_view.h
@@ -36,7 +36,7 @@ // It displays a list of profiles and allows users to switch between profiles. class ProfileChooserView : public ProfileMenuViewBase, public AvatarMenuObserver, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: ProfileChooserView(views::Button* anchor_button, Browser* browser, @@ -71,7 +71,7 @@ // AvatarMenuObserver: void OnAvatarMenuChanged(AvatarMenu* avatar_menu) override; - // identity::IdentityManager::Observer overrides. + // signin::IdentityManager::Observer overrides. void OnRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info) override;
diff --git a/chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view.cc b/chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view.cc index 25f57db..d8777ab 100644 --- a/chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view.cc +++ b/chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view.cc
@@ -25,7 +25,7 @@ namespace { // Icon sizes in DIP. -constexpr int kPrimaryIconSize = 16; +constexpr int kPrimaryIconSize = 20; constexpr int kPrimaryIconBorderWidth = 8; SkColor GetColorfromTheme() {
diff --git a/chrome/browser/ui/views/sharing/click_to_call/click_to_call_icon_view.cc b/chrome/browser/ui/views/sharing/click_to_call/click_to_call_icon_view.cc index 6d6044857..bc47299 100644 --- a/chrome/browser/ui/views/sharing/click_to_call/click_to_call_icon_view.cc +++ b/chrome/browser/ui/views/sharing/click_to_call/click_to_call_icon_view.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view.h" #include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/base/material_design/material_design_controller.h" #include "ui/gfx/animation/throb_animation.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/paint_vector_icon.h" @@ -26,6 +27,10 @@ // Width of the loader bar in percent of its range. constexpr float kLoaderWidth = 0.2f; +// TODO(knollr): move these into IconLabelBubbleView. +constexpr int kIconTextSpacing = 8; +constexpr int kIconTextSpacingTouch = 10; + ClickToCallSharingDialogController* GetControllerFromWebContents( content::WebContents* web_contents) { if (!web_contents) @@ -57,26 +62,30 @@ bool ClickToCallIconView::Update() { auto* controller = GetControllerFromWebContents(GetWebContents()); - if (controller) { - if (show_error_ != controller->send_failed()) { - show_error_ = controller->send_failed(); - UpdateIconImage(); - } + if (!controller) + return false; - if (controller->is_loading()) - StartLoadingAnimation(); - else - StopLoadingAnimation(); + if (show_error_ != controller->send_failed()) { + show_error_ = controller->send_failed(); + UpdateIconImage(); } + if (controller->is_loading()) + StartLoadingAnimation(); + else + StopLoadingAnimation(); + const bool is_bubble_showing = IsBubbleShowing(); + + if (is_bubble_showing || loading_animation_ || last_controller_ != controller) + ResetSlideAnimation(/*show=*/false); + + last_controller_ = controller; + const bool is_visible = is_bubble_showing || loading_animation_ || label()->GetVisible(); const bool visibility_changed = GetVisible() != is_visible; - if (is_bubble_showing || loading_animation_) - ResetSlideAnimation(/*show=*/false); - SetVisible(is_visible); UpdateInkDrop(is_bubble_showing); return visibility_changed; @@ -123,11 +132,12 @@ float start = std::max(0.0f, (progress - kLoaderWidth) / (1 - kLoaderWidth)); float end = std::min(1.0f, progress / (1 - kLoaderWidth)); // Convert percentages to actual location. - start = start * (range - kLoaderHeight); - end = end * (range - kLoaderHeight) + kLoaderHeight; + const float size = kLoaderHeight * scale; + start = start * (range - size); + end = end * (range - size) + size; - gfx::RectF bounds(start + offset, icon_bounds.bottom() - kLoaderHeight, - end - start, kLoaderHeight); + gfx::RectF bounds(start + offset, icon_bounds.bottom() - size, end - start, + size); cc::PaintFlags flags; flags.setAntiAlias(true); @@ -136,14 +146,33 @@ canvas->DrawRoundRect(bounds, bounds.height() / 2, flags); } +double ClickToCallIconView::WidthMultiplier() const { + double multiplier = PageActionIconView::WidthMultiplier(); + + double min_width = image()->GetPreferredSize().width() + GetInsets().width(); + double spacing = ui::MaterialDesignController::touch_ui() + ? kIconTextSpacingTouch + : kIconTextSpacing; + double label_width = label()->GetPreferredSize().width(); + double max_width = min_width + spacing + label_width; + + // We offset the width multiplier to start expanding the label straight away + // instead of completely hide the icon and expanding it from zero width. + double offset = min_width / max_width; + return multiplier * (1 - offset) + offset; +} + void ClickToCallIconView::AnimationProgressed(const gfx::Animation* animation) { - if (animation != loading_animation_.get()) + if (animation != loading_animation_.get()) { + UpdateOpacity(); return PageActionIconView::AnimationProgressed(animation); + } SchedulePaint(); } void ClickToCallIconView::AnimationEnded(const gfx::Animation* animation) { PageActionIconView::AnimationEnded(animation); + UpdateOpacity(); Update(); } @@ -152,6 +181,22 @@ UpdateLoaderColor(); } +void ClickToCallIconView::UpdateOpacity() { + if (!IsShrinking()) { + DestroyLayer(); + SetTextSubpixelRenderingEnabled(true); + return; + } + + if (!layer()) { + SetPaintToLayer(); + SetTextSubpixelRenderingEnabled(false); + layer()->SetFillsBoundsOpaquely(false); + } + + layer()->SetOpacity(PageActionIconView::WidthMultiplier()); +} + void ClickToCallIconView::UpdateInkDrop(bool activate) { auto target_state = activate ? views::InkDropState::ACTIVATED : views::InkDropState::HIDDEN;
diff --git a/chrome/browser/ui/views/sharing/click_to_call/click_to_call_icon_view.h b/chrome/browser/ui/views/sharing/click_to_call/click_to_call_icon_view.h index 14eef2d..26615a9 100644 --- a/chrome/browser/ui/views/sharing/click_to_call/click_to_call_icon_view.h +++ b/chrome/browser/ui/views/sharing/click_to_call/click_to_call_icon_view.h
@@ -22,6 +22,8 @@ class Event; } // namespace ui +class ClickToCallSharingDialogController; + // The location bar icon to show the click to call bubble where the user can // choose to send a phone number to a target device or use an OS handler app. class ClickToCallIconView : public PageActionIconView { @@ -49,6 +51,7 @@ const gfx::VectorIcon& GetVectorIcon() const override; const gfx::VectorIcon& GetVectorIconBadge() const override; bool IsTriggerableEvent(const ui::Event& event) override; + double WidthMultiplier() const override; // gfx::AnimationDelegate: void AnimationProgressed(const gfx::Animation* animation) override; @@ -57,10 +60,12 @@ private: void UpdateInkDrop(bool activate); void UpdateLoaderColor(); + void UpdateOpacity(); SkColor loader_color_; std::unique_ptr<gfx::ThrobAnimation> loading_animation_; bool show_error_ = false; + ClickToCallSharingDialogController* last_controller_; DISALLOW_COPY_AND_ASSIGN(ClickToCallIconView); };
diff --git a/chrome/browser/ui/views/sync/inline_login_ui_browsertest.cc b/chrome/browser/ui/views/sync/inline_login_ui_browsertest.cc index 5e127f9..3a76b85 100644 --- a/chrome/browser/ui/views/sync/inline_login_ui_browsertest.cc +++ b/chrome/browser/ui/views/sync/inline_login_ui_browsertest.cc
@@ -359,7 +359,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginUIBrowserTest, CanOfferProfileConnected) { auto* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); - identity::MakePrimaryAccountAvailable(identity_manager, "foo@gmail.com"); + signin::MakePrimaryAccountAvailable(identity_manager, "foo@gmail.com"); EnableSigninAllowed(true); std::string error_message; @@ -505,7 +505,7 @@ } protected: - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return identity_test_env_profile_adaptor_->identity_test_env() ->identity_manager(); }
diff --git a/chrome/browser/ui/web_applications/web_app_ui_manager_impl_browsertest.cc b/chrome/browser/ui/web_applications/web_app_ui_manager_impl_browsertest.cc index c4cc9b3..820204f 100644 --- a/chrome/browser/ui/web_applications/web_app_ui_manager_impl_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_ui_manager_impl_browsertest.cc
@@ -7,6 +7,7 @@ #include "base/barrier_closure.h" #include "base/test/bind_test_util.h" #include "base/threading/thread_task_runner_handle.h" +#include "chrome/browser/apps/app_service/built_in_chromeos_apps.h" #include "chrome/browser/extensions/browsertest_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" @@ -183,13 +184,22 @@ : public WebAppUiManagerImplBrowserTest { public: void SetUp() override { + hide_settings_app_for_testing_ = + apps::BuiltInChromeOsApps::SetHideSettingsAppForTesting(true); // Disable System Web Apps so that the Internal Apps are installed. scoped_feature_list_.InitAndDisableFeature(features::kSystemWebApps); WebAppUiManagerImplBrowserTest::SetUp(); } + void TearDown() override { + WebAppUiManagerImplBrowserTest::TearDown(); + apps::BuiltInChromeOsApps::SetHideSettingsAppForTesting( + hide_settings_app_for_testing_); + } + private: base::test::ScopedFeatureList scoped_feature_list_; + bool hide_settings_app_for_testing_ = false; }; // Tests that the Settings app migrates the launcher and app list details from
diff --git a/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc b/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc index ef1b002..450ea8da 100644 --- a/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc +++ b/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc
@@ -81,7 +81,7 @@ identity_manager_->GetPrimaryAccountId(), "add_supervision", scopes, base::BindOnce(&AddSupervisionHandler::OnAccessTokenFetchComplete, weak_ptr_factory_.GetWeakPtr(), std::move(callback)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } void AddSupervisionHandler::LogOut() { @@ -98,7 +98,7 @@ void AddSupervisionHandler::OnAccessTokenFetchComplete( GetOAuthTokenCallback callback, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { oauth2_access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) { DLOG(ERROR) << "AddSupervisionHandler: OAuth2 token request failed. "
diff --git a/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h b/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h index b085b43..63db8d6 100644 --- a/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h +++ b/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h
@@ -15,11 +15,11 @@ class WebUI; } // namespace content -namespace identity { +namespace signin { class AccessTokenFetcher; struct AccessTokenInfo; class IdentityManager; -} // namespace identity +} // namespace signin class GoogleServiceAuthError; @@ -54,14 +54,14 @@ private: void OnAccessTokenFetchComplete(GetOAuthTokenCallback callback, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // The AddSupervisionUI that this AddSupervisionHandler belongs to. content::WebUI* web_ui_; // Used to fetch OAuth2 access tokens. - identity::IdentityManager* identity_manager_; - std::unique_ptr<identity::AccessTokenFetcher> oauth2_access_token_fetcher_; + signin::IdentityManager* identity_manager_; + std::unique_ptr<signin::AccessTokenFetcher> oauth2_access_token_fetcher_; mojo::Binding<add_supervision::mojom::AddSupervisionHandler> binding_;
diff --git a/chrome/browser/ui/webui/history_ui.cc b/chrome/browser/ui/webui/history_ui.cc index 2d1d34df..368b995 100644 --- a/chrome/browser/ui/webui/history_ui.cc +++ b/chrome/browser/ui/webui/history_ui.cc
@@ -42,7 +42,7 @@ constexpr char kShowMenuPromoKey[] = "showMenuPromo"; bool IsUserSignedIn(Profile* profile) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); return identity_manager && identity_manager->HasPrimaryAccount(); }
diff --git a/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc b/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc index 7fcad9d..94f7f790 100644 --- a/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc +++ b/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc
@@ -390,7 +390,7 @@ test_url_loader_factory_.AddResponse(kURLRegisterComplete, kResponseRegisterComplete); - identity::MakePrimaryAccountAvailable( + signin::MakePrimaryAccountAvailable( IdentityManagerFactory::GetForProfile(browser()->profile()), kSampleUser);
diff --git a/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc b/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc index bc4fe32..1a90506 100644 --- a/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc +++ b/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
@@ -119,7 +119,7 @@ LocalDiscoveryUIHandler::~LocalDiscoveryUIHandler() { Profile* profile = Profile::FromWebUI(web_ui()); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (identity_manager) identity_manager->RemoveObserver(this); @@ -193,7 +193,7 @@ cloud_print::PrivetHTTPAsynchronousFactory::CreateInstance( url_loader_factory); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (identity_manager) identity_manager->AddObserver(this); @@ -458,7 +458,7 @@ std::string LocalDiscoveryUIHandler::GetSyncAccount() const { Profile* profile = Profile::FromWebUI(web_ui()); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); std::string email; @@ -515,7 +515,7 @@ if (!profile) return std::unique_ptr<GCDApiFlow>(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); if (!(identity_manager && identity_manager->HasPrimaryAccount())) return std::unique_ptr<GCDApiFlow>();
diff --git a/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h b/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h index 70a4c0e..caf5a5b 100644 --- a/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h +++ b/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h
@@ -45,7 +45,7 @@ public cloud_print::PrivetRegisterOperation::Delegate, public cloud_print::PrivetDeviceLister::Delegate, public cloud_print::CloudPrintPrinterList::Delegate, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // Class used to set a URLLoaderFactory that should be used when making // network requests. Create one instance of this object with the @@ -91,7 +91,7 @@ const cloud_print::CloudPrintPrinterList::DeviceList& devices) override; void OnDeviceListUnavailable() override; - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnPrimaryAccountSet( const CoreAccountInfo& primary_account_info) override; void OnPrimaryAccountCleared(
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc index e827cf24..e3d7c5f1 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc
@@ -71,7 +71,6 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "google_apis/gaia/gaia_auth_util.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "net/base/url_util.h" #include "printing/backend/print_backend.h" #include "printing/backend/print_backend_consts.h" @@ -1090,7 +1089,7 @@ } void PrintPreviewHandler::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { base::Value account_list(base::Value::Type::LIST); const std::vector<gaia::ListedAccount>& accounts =
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.h b/chrome/browser/ui/webui/print_preview/print_preview_handler.h index b4c5aad9..305ba93 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.h +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.h
@@ -50,7 +50,7 @@ // The handler for Javascript messages related to the print preview dialog. class PrintPreviewHandler : public content::WebUIMessageHandler, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: PrintPreviewHandler(); ~PrintPreviewHandler() override; @@ -62,7 +62,7 @@ // IdentityManager::Observer implementation. void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; // Called when print preview failed. |request_id| identifies the request that @@ -337,7 +337,7 @@ // Pointer to the identity manager service so that print preview can listen // for GAIA cookie changes. - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // Handles requests for cloud printers. Created lazily by calling // GetPrinterHandler().
diff --git a/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc b/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc index 5aa315fd..88a2448 100644 --- a/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc +++ b/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc
@@ -249,7 +249,7 @@ privet_local_print_operation_->SetPageSize(page_size); privet_local_print_operation_->SetData(print_data); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfileIfExists(profile_); if (identity_manager) { privet_local_print_operation_->SetUsername(
diff --git a/chrome/browser/ui/webui/profile_info_watcher.cc b/chrome/browser/ui/webui/profile_info_watcher.cc index 3fa52f1..4767226 100644 --- a/chrome/browser/ui/webui/profile_info_watcher.cc +++ b/chrome/browser/ui/webui/profile_info_watcher.cc
@@ -50,7 +50,7 @@ return username; } -identity::IdentityManager* ProfileInfoWatcher::GetIdentityManager() const { +signin::IdentityManager* ProfileInfoWatcher::GetIdentityManager() const { return IdentityManagerFactory::GetForProfile(profile_); }
diff --git a/chrome/browser/ui/webui/profile_info_watcher.h b/chrome/browser/ui/webui/profile_info_watcher.h index 9849315..315c682 100644 --- a/chrome/browser/ui/webui/profile_info_watcher.h +++ b/chrome/browser/ui/webui/profile_info_watcher.h
@@ -14,7 +14,7 @@ class Profile; -namespace identity { +namespace signin { class IdentityManager; } @@ -33,7 +33,7 @@ void OnProfileAuthInfoChanged(const base::FilePath& profile_path) override; // Gets the IdentityManager for |profile_|. - identity::IdentityManager* GetIdentityManager() const; + signin::IdentityManager* GetIdentityManager() const; // Runs |callback_| when a profile changes. No-ops if |GetIdentityManager()| // returns nullptr.
diff --git a/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc b/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc index 5da9501..e06d720 100644 --- a/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc +++ b/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc
@@ -97,7 +97,7 @@ AccountManagerUIHandler::AccountManagerUIHandler( AccountManager* account_manager, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : account_manager_(account_manager), identity_manager_(identity_manager), account_manager_observer_(this), @@ -322,11 +322,11 @@ RefreshUI(); } -// |identity::IdentityManager::Observer| overrides. For newly added accounts, -// |identity::IdentityManager| may take some time to fetch user's full name and +// |signin::IdentityManager::Observer| overrides. For newly added accounts, +// |signin::IdentityManager| may take some time to fetch user's full name and // account image. Whenever that is completed, we may need to update the UI with // this new set of information. Note that we may be listening to -// |identity::IdentityManager| but we still consider |AccountManager| to be the +// |signin::IdentityManager| but we still consider |AccountManager| to be the // source of truth for account list. void AccountManagerUIHandler::OnExtendedAccountInfoUpdated( const AccountInfo& info) {
diff --git a/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h b/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h index 2e9a051..071c7cf 100644 --- a/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h +++ b/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h
@@ -20,12 +20,12 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, public AccountManager::Observer, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // Accepts non-owning pointers to |AccountManager|, |AccountTrackerService| // and |IdentityManager|. Both of these must outlive |this| instance. AccountManagerUIHandler(AccountManager* account_manager, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~AccountManagerUIHandler() override; // WebUIMessageHandler implementation. @@ -39,7 +39,7 @@ void OnTokenUpserted(const AccountManager::Account& account) override; void OnAccountRemoved(const AccountManager::Account& account) override; - // |identity::IdentityManager::Observer| overrides. + // |signin::IdentityManager::Observer| overrides. void OnExtendedAccountInfoUpdated(const AccountInfo& info) override; private: @@ -74,16 +74,16 @@ AccountManager* const account_manager_; // A non-owning pointer to |IdentityManager|. - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; // An observer for |AccountManager|. Automatically deregisters when |this| is // destructed. ScopedObserver<AccountManager, AccountManager::Observer> account_manager_observer_; - // An observer for |identity::IdentityManager|. Automatically deregisters when + // An observer for |signin::IdentityManager|. Automatically deregisters when // |this| is destructed. - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; base::WeakPtrFactory<AccountManagerUIHandler> weak_factory_;
diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index 8c9f865..3ea106d0 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc
@@ -343,7 +343,7 @@ prefs::kSigninAllowed, base::Bind(&PeopleHandler::UpdateSyncStatus, base::Unretained(this))); - identity::IdentityManager* identity_manager( + signin::IdentityManager* identity_manager( IdentityManagerFactory::GetInstance()->GetForProfile(profile_)); if (identity_manager) identity_manager_observer_.Add(identity_manager); @@ -388,7 +388,7 @@ // then sign in again. identity_manager->GetPrimaryAccountMutator()->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, signin_metrics::SignoutDelete::IGNORE_METRIC); } @@ -812,7 +812,7 @@ : signin_metrics::SignoutDelete::KEEPING; identity_manager->GetPrimaryAccountMutator()->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric); } else { DCHECK(!delete_profile) @@ -889,7 +889,7 @@ IdentityManagerFactory::GetForProfile(profile_) ->GetPrimaryAccountMutator() ->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction:: + signin::PrimaryAccountMutator::ClearAccountsAction:: kDefault, signin_metrics::ABORT_SIGNIN, signin_metrics::SignoutDelete::IGNORE_METRIC);
diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h index a89e03e..83cd891 100644 --- a/chrome/browser/ui/webui/settings/people_handler.h +++ b/chrome/browser/ui/webui/settings/people_handler.h
@@ -43,7 +43,7 @@ namespace settings { class PeopleHandler : public SettingsPageUIHandler, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public SyncStartupTracker::Observer, public LoginUIService::LoginUI, public syncer::SyncServiceObserver, @@ -261,7 +261,7 @@ PrefChangeRegistrar profile_pref_registrar_; // Manages observer lifetimes. - ScopedObserver<identity::IdentityManager, PeopleHandler> + ScopedObserver<signin::IdentityManager, PeopleHandler> identity_manager_observer_; ScopedObserver<syncer::SyncService, PeopleHandler> sync_service_observer_;
diff --git a/chrome/browser/ui/webui/settings/people_handler_unittest.cc b/chrome/browser/ui/webui/settings/people_handler_unittest.cc index 8a947cd..87b349ec 100644 --- a/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/people_handler_unittest.cc
@@ -363,7 +363,7 @@ return std::string(kTestUser); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_adaptor_->identity_test_env(); } @@ -1049,7 +1049,7 @@ primary_account_info.is_under_advanced_protection, signin_metrics::SourceForRefreshTokenOperation::kUnknown); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager, primary_account_info.account_id, GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
diff --git a/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc b/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc index de71dd6..ed1e4d58 100644 --- a/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc +++ b/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc
@@ -339,7 +339,7 @@ } void ClearBrowsingDataHandler::UpdateSyncState() { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); FireWebUIListener( "update-sync-state",
diff --git a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc index fe0167c..dd5f7fb49 100644 --- a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc +++ b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc
@@ -71,7 +71,7 @@ DISALLOW_COPY_AND_ASSIGN(DiceTurnSyncOnHelperShutdownNotifierFactory); }; -AccountInfo GetAccountInfo(identity::IdentityManager* identity_manager, +AccountInfo GetAccountInfo(signin::IdentityManager* identity_manager, const std::string& account_id) { auto maybe_account_info = identity_manager->FindAccountInfoForAccountWithRefreshTokenByAccountId( @@ -80,7 +80,7 @@ : AccountInfo(); } -class TokensLoadedCallbackRunner : public identity::IdentityManager::Observer { +class TokensLoadedCallbackRunner : public signin::IdentityManager::Observer { public: // Calls |callback| when tokens are loaded. static void RunWhenLoaded(Profile* profile, @@ -99,7 +99,7 @@ } private: - TokensLoadedCallbackRunner(identity::IdentityManager* identity_manager, + TokensLoadedCallbackRunner(signin::IdentityManager* identity_manager, KeyedServiceShutdownNotifier* shutdown_notifier, base::OnceClosure callback) : identity_manager_(identity_manager), @@ -112,7 +112,7 @@ scoped_identity_manager_observer_.Add(identity_manager_); } - // identity::IdentityManager::Observer implementation: + // signin::IdentityManager::Observer implementation: void OnRefreshTokensLoaded() override { std::move(callback_).Run(); delete this; @@ -120,8 +120,8 @@ void OnShutdown() { delete this; } - identity::IdentityManager* identity_manager_; - ScopedObserver<identity::IdentityManager, TokensLoadedCallbackRunner> + signin::IdentityManager* identity_manager_; + ScopedObserver<signin::IdentityManager, TokensLoadedCallbackRunner> scoped_identity_manager_observer_; base::OnceClosure callback_; std::unique_ptr<KeyedServiceShutdownNotifier::Subscription> @@ -499,7 +499,7 @@ identity_manager_->GetPrimaryAccountMutator(); DCHECK(primary_account_mutator); primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, signin_metrics::ABORT_SIGNIN, signin_metrics::SignoutDelete::IGNORE_METRIC); AbortAndDelete();
diff --git a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h index 6f1a148..59e334d 100644 --- a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h +++ b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h
@@ -21,7 +21,7 @@ class Browser; -namespace identity { +namespace signin { class IdentityManager; } @@ -196,7 +196,7 @@ std::unique_ptr<Delegate> delegate_; Profile* profile_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; const signin_metrics::AccessPoint signin_access_point_; const signin_metrics::PromoAction signin_promo_action_; const signin_metrics::Reason signin_reason_;
diff --git a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc index 9c686bb4..bcc7150 100644 --- a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc +++ b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc
@@ -130,7 +130,7 @@ } FakeUserPolicySigninService(Profile* profile, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : UserPolicySigninService(profile, nullptr, nullptr, @@ -231,10 +231,10 @@ // Basic accessors. Profile* profile() { return profile_.get(); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_profile_adaptor_->identity_test_env(); } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return identity_test_env()->identity_manager(); } const std::string& account_id() { return account_id_; }
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc b/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc index dd4df45..023d1b5e 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc
@@ -251,7 +251,7 @@ const std::string& username, const std::string& password) { DCHECK(signin_util::IsForceSigninEnabled()); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); bool has_primary_account = identity_manager->HasPrimaryAccount(); if (has_primary_account && !password.empty()) { @@ -358,7 +358,7 @@ AboutSigninInternalsFactory::GetForProfile(profile_); about_signin_internals->OnRefreshTokenReceived("Successful"); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); std::string primary_email = identity_manager->GetPrimaryAccountInfo().email; @@ -442,7 +442,7 @@ void InlineSigninHelper::CreateSyncStarter(const std::string& refresh_token) { DCHECK(signin_util::IsForceSigninEnabled()); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); if (identity_manager->HasPrimaryAccount()) { // Already signed in, nothing to do.
diff --git a/chrome/browser/ui/webui/signin/login_ui_test_utils.cc b/chrome/browser/ui/webui/signin/login_ui_test_utils.cc index 6e79e75..a32321ef 100644 --- a/chrome/browser/ui/webui/signin/login_ui_test_utils.cc +++ b/chrome/browser/ui/webui/signin/login_ui_test_utils.cc
@@ -44,7 +44,7 @@ // The SignInObserver observes the identity manager and blocks until a signin // success or failure notification is fired. -class SignInObserver : public identity::IdentityManager::Observer { +class SignInObserver : public signin::IdentityManager::Observer { public: SignInObserver() : seen_(false), running_(false), signed_in_(false) {} @@ -298,7 +298,7 @@ return false; #else SignInObserver signin_observer; - ScopedObserver<identity::IdentityManager, SignInObserver> + ScopedObserver<signin::IdentityManager, SignInObserver> scoped_signin_observer(&signin_observer); scoped_signin_observer.Add( IdentityManagerFactory::GetForProfile(browser->profile()));
diff --git a/chrome/browser/ui/webui/signin/signin_utils_desktop.cc b/chrome/browser/ui/webui/signin/signin_utils_desktop.cc index 96a507e..80d414c 100644 --- a/chrome/browser/ui/webui/signin/signin_utils_desktop.cc +++ b/chrome/browser/ui/webui/signin/signin_utils_desktop.cc
@@ -47,7 +47,7 @@ return false; // Make sure this username is not prohibited by policy. - if (!identity::IsUsernameAllowedByPatternFromPrefs( + if (!signin::IsUsernameAllowedByPatternFromPrefs( g_browser_process->local_state(), email)) { if (error_message) { error_message->assign(
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_handler.h b/chrome/browser/ui/webui/signin/sync_confirmation_handler.h index aae31f3..c1e1ab9 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_handler.h +++ b/chrome/browser/ui/webui/signin/sync_confirmation_handler.h
@@ -19,12 +19,12 @@ class ListValue; } -namespace identity { +namespace signin { class IdentityManager; } class SyncConfirmationHandler : public content::WebUIMessageHandler, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public BrowserListObserver { public: // Creates a SyncConfirmationHandler for the |browser|. All strings in the @@ -38,7 +38,7 @@ // content::WebUIMessageHandler: void RegisterMessages() override; - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnExtendedAccountInfoUpdated(const AccountInfo& info) override; // BrowserListObserver: @@ -103,7 +103,7 @@ // and their respective GRD IDs. std::unordered_map<std::string, int> string_to_grd_id_map_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; DISALLOW_COPY_AND_ASSIGN(SyncConfirmationHandler); };
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc b/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc index b039d906..3593351 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc
@@ -123,7 +123,7 @@ ConsentAuditorFactory::GetForProfile(profile())); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return identity_test_env_adaptor_->identity_test_env(); } @@ -165,7 +165,7 @@ ASSERT_TRUE(call_data.arg1()->GetAsString(&event)); EXPECT_EQ("account-image-changed", event); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile()); base::Optional<AccountInfo> primary_account = identity_manager->FindExtendedAccountInfoForAccount(
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc index d5457932..5d58676 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
@@ -64,7 +64,7 @@ constexpr int kAccountPictureSize = 68; std::string custom_picture_url = profiles::GetPlaceholderAvatarIconUrl(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); base::Optional<AccountInfo> primary_account_info = identity_manager->FindExtendedAccountInfoForAccount(
diff --git a/chrome/browser/ui/webui/signin_internals_ui.cc b/chrome/browser/ui/webui/signin_internals_ui.cc index 473cd75d..45574c4 100644 --- a/chrome/browser/ui/webui/signin_internals_ui.cc +++ b/chrome/browser/ui/webui/signin_internals_ui.cc
@@ -79,9 +79,9 @@ "chrome.signin.getSigninInfo.handleReply", *about_signin_internals->GetSigninStatus()); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); - identity::AccountsInCookieJarInfo accounts_in_cookie_jar = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar = identity_manager->GetAccountsInCookieJar(); if (accounts_in_cookie_jar.accounts_are_fresh) { about_signin_internals->OnAccountsInCookieUpdated(
diff --git a/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc b/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc index d9fab3fb..28d6c59 100644 --- a/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc +++ b/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc
@@ -216,7 +216,7 @@ FilteringBehaviorToString( filter->GetDefaultFilteringBehavior())); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); // |identity_manager| is null in incognito and guest profiles. if (identity_manager) {
diff --git a/chrome/browser/web_applications/bookmark_apps/policy/web_app_policy_manager_unittest.cc b/chrome/browser/web_applications/bookmark_apps/policy/web_app_policy_manager_unittest.cc index 302d3bb..24ab59ec 100644 --- a/chrome/browser/web_applications/bookmark_apps/policy/web_app_policy_manager_unittest.cc +++ b/chrome/browser/web_applications/bookmark_apps/policy/web_app_policy_manager_unittest.cc
@@ -166,9 +166,7 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - DCHECK(profile()->AsTestingProfile()); - auto* provider = static_cast<web_app::TestWebAppProvider*>( - web_app::WebAppProvider::Get(profile())); + auto* provider = web_app::TestWebAppProvider::Get(profile()); auto test_app_registrar = std::make_unique<TestAppRegistrar>(); test_app_registrar_ = test_app_registrar.get(); @@ -183,6 +181,8 @@ std::make_unique<WebAppPolicyManager>(profile()); web_app_policy_manager_ = web_app_policy_manager.get(); provider->SetWebAppPolicyManager(std::move(web_app_policy_manager)); + + provider->Start(); } void SimulatePreviouslyInstalledApp(GURL url,
diff --git a/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_browsertest.cc b/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_browsertest.cc index a7f70fe..1e44978 100644 --- a/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_browsertest.cc +++ b/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_browsertest.cc
@@ -159,7 +159,7 @@ test_system_web_app_manager_->SetSystemApps(std::move(system_apps)); // Start registry and all dependent subsystems: - provider->StartRegistry(); + provider->Start(); return provider; }
diff --git a/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_unittest.cc b/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_unittest.cc index bc4a3de..f093c8d 100644 --- a/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_unittest.cc +++ b/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_unittest.cc
@@ -66,9 +66,7 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - DCHECK(profile()->AsTestingProfile()); - auto* provider = static_cast<web_app::TestWebAppProvider*>( - web_app::WebAppProvider::Get(profile())); + auto* provider = web_app::TestWebAppProvider::Get(profile()); auto test_app_registrar = std::make_unique<TestAppRegistrar>(); test_app_registrar_ = test_app_registrar.get(); @@ -87,6 +85,8 @@ auto ui_manager = std::make_unique<TestWebAppUiManager>(); ui_manager_ = ui_manager.get(); provider->SetWebAppUiManager(std::move(ui_manager)); + + provider->Start(); } void SimulatePreviouslyInstalledApp(GURL url,
diff --git a/chrome/browser/web_applications/bookmark_apps/test_web_app_provider.cc b/chrome/browser/web_applications/bookmark_apps/test_web_app_provider.cc index 431f3cd2..c09333e 100644 --- a/chrome/browser/web_applications/bookmark_apps/test_web_app_provider.cc +++ b/chrome/browser/web_applications/bookmark_apps/test_web_app_provider.cc
@@ -22,57 +22,86 @@ namespace web_app { +#define CHECK_NOT_STARTED() \ + CHECK(!started_) << "Attempted to set a WebAppProvider subsystem after " \ + "Start() was called."; + // static std::unique_ptr<KeyedService> TestWebAppProvider::BuildDefault( content::BrowserContext* context) { - return std::make_unique<TestWebAppProvider>( - Profile::FromBrowserContext(context)); + auto provider = std::make_unique<TestWebAppProvider>( + Profile::FromBrowserContext(context), + /*run_subsystem_startup_tasks=*/false); + // TODO(crbug.com/973324): Replace core subsystems with fakes by default. + provider->ConnectSubsystems(); + return provider; } -TestWebAppProvider::TestWebAppProvider(Profile* profile) - : WebAppProvider(profile) {} +// static +TestWebAppProvider* TestWebAppProvider::Get(Profile* profile) { + CHECK(profile->AsTestingProfile()); + auto* test_provider = static_cast<web_app::TestWebAppProvider*>( + web_app::WebAppProvider::Get(profile)); + CHECK(!test_provider->started_); + + // Disconnect so that clients are forced to call Start() before accessing any + // subsystems. + test_provider->connected_ = false; + + return test_provider; +} + +TestWebAppProvider::TestWebAppProvider(Profile* profile, + bool run_subsystem_startup_tasks) + : WebAppProvider(profile), + run_subsystem_startup_tasks_(run_subsystem_startup_tasks) {} TestWebAppProvider::~TestWebAppProvider() = default; +void TestWebAppProvider::StartImpl() { + if (run_subsystem_startup_tasks_) + WebAppProvider::StartImpl(); +} + void TestWebAppProvider::SetRegistrar(std::unique_ptr<AppRegistrar> registrar) { + CHECK_NOT_STARTED(); registrar_ = std::move(registrar); - ConnectSubsystems(); } void TestWebAppProvider::SetInstallManager( std::unique_ptr<InstallManager> install_manager) { + CHECK_NOT_STARTED(); install_manager_ = std::move(install_manager); - ConnectSubsystems(); } void TestWebAppProvider::SetInstallFinalizer( std::unique_ptr<InstallFinalizer> install_finalizer) { + CHECK_NOT_STARTED(); install_finalizer_ = std::move(install_finalizer); - ConnectSubsystems(); } void TestWebAppProvider::SetPendingAppManager( std::unique_ptr<PendingAppManager> pending_app_manager) { + CHECK_NOT_STARTED(); pending_app_manager_ = std::move(pending_app_manager); - ConnectSubsystems(); } void TestWebAppProvider::SetWebAppUiManager( std::unique_ptr<WebAppUiManager> ui_manager) { + CHECK_NOT_STARTED(); ui_manager_ = std::move(ui_manager); - ConnectSubsystems(); } void TestWebAppProvider::SetSystemWebAppManager( std::unique_ptr<SystemWebAppManager> system_web_app_manager) { + CHECK_NOT_STARTED(); system_web_app_manager_ = std::move(system_web_app_manager); - ConnectSubsystems(); } void TestWebAppProvider::SetWebAppPolicyManager( std::unique_ptr<WebAppPolicyManager> web_app_policy_manager) { + CHECK_NOT_STARTED(); web_app_policy_manager_ = std::move(web_app_policy_manager); - ConnectSubsystems(); } TestWebAppProviderCreator::TestWebAppProviderCreator(
diff --git a/chrome/browser/web_applications/bookmark_apps/test_web_app_provider.h b/chrome/browser/web_applications/bookmark_apps/test_web_app_provider.h index 6e9191a..6676739 100644 --- a/chrome/browser/web_applications/bookmark_apps/test_web_app_provider.h +++ b/chrome/browser/web_applications/bookmark_apps/test_web_app_provider.h
@@ -28,12 +28,22 @@ class TestWebAppProvider : public WebAppProvider { public: - // Builds a default WebAppProvider that won't be started. To activate this - // default instance, call WebAppProvider::StartRegistry(). + // Used by the TestingProfile in unit tests. + // Builds a stub WebAppProvider which will not fire subsystem startup tasks. + // Use TestWebAppProvider::Get() to replace subsystems. static std::unique_ptr<KeyedService> BuildDefault( content::BrowserContext* context); - explicit TestWebAppProvider(Profile* profile); + // Gets a TestWebAppProvider that can have its subsystems set. This should + // only be called once during SetUp(), and clients must call Start() before + // using the subsystems. + static TestWebAppProvider* Get(Profile* profile); + + // |run_subsystem_startup_tasks| is true by default as browser test clients + // will generally want to construct their TestWebAppProvider to behave as it + // would in a production browser. + explicit TestWebAppProvider(Profile* profile, + bool run_subsystem_startup_tasks = true); ~TestWebAppProvider() override; void SetRegistrar(std::unique_ptr<AppRegistrar> registrar); @@ -46,8 +56,20 @@ std::unique_ptr<SystemWebAppManager> system_web_app_manager); void SetWebAppPolicyManager( std::unique_ptr<WebAppPolicyManager> web_app_policy_manager); + + private: + // WebAppProvider: + void StartImpl() override; + + // If true, when Start()ed the TestWebAppProvider will call + // WebAppProvider::StartImpl() and fire startup tasks like a real + // WebAppProvider. + bool run_subsystem_startup_tasks_; }; +// Used in BrowserTests to ensure that the WebAppProvider that is create on +// profile startup is the TestWebAppProvider. Hooks into the +// BrowserContextKeyedService initialization pipeline. class TestWebAppProviderCreator { public: using CreateWebAppProviderCallback =
diff --git a/chrome/browser/web_applications/extensions/bookmark_app_helper_installation_task_unittest.cc b/chrome/browser/web_applications/extensions/bookmark_app_helper_installation_task_unittest.cc index 9b67aca..748b1649 100644 --- a/chrome/browser/web_applications/extensions/bookmark_app_helper_installation_task_unittest.cc +++ b/chrome/browser/web_applications/extensions/bookmark_app_helper_installation_task_unittest.cc
@@ -25,15 +25,17 @@ #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/installable/installable_data.h" #include "chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.h" +#include "chrome/browser/web_applications/bookmark_apps/test_web_app_provider.h" #include "chrome/browser/web_applications/components/app_registrar.h" #include "chrome/browser/web_applications/components/externally_installed_web_app_prefs.h" #include "chrome/browser/web_applications/components/install_finalizer.h" #include "chrome/browser/web_applications/components/web_app_constants.h" #include "chrome/browser/web_applications/components/web_app_data_retriever.h" -#include "chrome/browser/web_applications/components/web_app_provider_base.h" #include "chrome/browser/web_applications/test/test_app_registrar.h" #include "chrome/browser/web_applications/test/test_data_retriever.h" #include "chrome/browser/web_applications/test/test_install_finalizer.h" +#include "chrome/browser/web_applications/web_app_provider.h" +#include "chrome/browser/web_applications/web_app_provider_factory.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/common/web_application_info.h" @@ -325,7 +327,9 @@ private: void SetUpTestingFactories() { - auto* provider = web_app::WebAppProviderBase::GetProviderBase(profile()); + auto* provider = web_app::TestWebAppProvider::Get(profile()); + provider->Start(); + BookmarkAppInstallManager* install_manager = static_cast<BookmarkAppInstallManager*>(&provider->install_manager());
diff --git a/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc b/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc index 738d45d..f66a6e33 100644 --- a/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc +++ b/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc
@@ -278,9 +278,7 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - DCHECK(profile()->AsTestingProfile()); - auto* provider = static_cast<web_app::TestWebAppProvider*>( - web_app::WebAppProvider::Get(profile())); + auto* provider = web_app::TestWebAppProvider::Get(profile()); auto registrar = std::make_unique<web_app::TestAppRegistrar>(); registrar_ = registrar.get(); @@ -300,6 +298,8 @@ provider->SetRegistrar(std::move(registrar)); provider->SetInstallManager(std::move(install_manager)); provider->SetInstallFinalizer(std::move(install_finalizer)); + + provider->Start(); } protected:
diff --git a/chrome/browser/web_applications/extensions/install_manager_bookmark_app_unittest.cc b/chrome/browser/web_applications/extensions/install_manager_bookmark_app_unittest.cc index 17eb323..5562de1 100644 --- a/chrome/browser/web_applications/extensions/install_manager_bookmark_app_unittest.cc +++ b/chrome/browser/web_applications/extensions/install_manager_bookmark_app_unittest.cc
@@ -132,9 +132,7 @@ web_contents_ = content::WebContentsTester::CreateTestWebContents(profile(), nullptr); - DCHECK(profile()->AsTestingProfile()); - auto* provider = static_cast<web_app::TestWebAppProvider*>( - web_app::WebAppProvider::Get(profile())); + auto* provider = web_app::TestWebAppProvider::Get(profile()); auto registrar = std::make_unique<BookmarkAppRegistrar>(profile()); registrar_ = registrar.get(); @@ -162,6 +160,8 @@ provider->SetRegistrar(std::move(registrar)); provider->SetInstallManager(std::move(install_manager)); provider->SetInstallFinalizer(std::move(install_finalizer)); + + provider->Start(); } void TearDown() override {
diff --git a/chrome/browser/web_applications/web_app_provider.cc b/chrome/browser/web_applications/web_app_provider.cc index 9c41eb73..bbad686b 100644 --- a/chrome/browser/web_applications/web_app_provider.cc +++ b/chrome/browser/web_applications/web_app_provider.cc
@@ -49,6 +49,10 @@ namespace { +#define DCHECK_IS_CONNECTED() \ + DCHECK(connected_) << "Attempted to access Web App subsystem while " \ + "WebAppProvider is not connected." + void OnExternalWebAppsSynchronized( std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { @@ -89,31 +93,36 @@ notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::Source<Profile>(profile_)); - - ConnectSubsystems(); } WebAppProvider::~WebAppProvider() = default; -void WebAppProvider::StartRegistry() { +void WebAppProvider::Start() { + CHECK(!started_); + + ConnectSubsystems(); started_ = true; - registrar_->Init(base::BindOnce(&WebAppProvider::OnRegistryReady, - weak_ptr_factory_.GetWeakPtr())); + + StartImpl(); } AppRegistrar& WebAppProvider::registrar() { + DCHECK_IS_CONNECTED(); return *registrar_; } InstallManager& WebAppProvider::install_manager() { + DCHECK_IS_CONNECTED(); return *install_manager_; } PendingAppManager& WebAppProvider::pending_app_manager() { + DCHECK_IS_CONNECTED(); return *pending_app_manager_; } WebAppPolicyManager* WebAppProvider::policy_manager() { + DCHECK_IS_CONNECTED(); return web_app_policy_manager_.get(); } @@ -123,6 +132,7 @@ } SystemWebAppManager& WebAppProvider::system_web_app_manager() { + DCHECK_IS_CONNECTED(); return *system_web_app_manager_; } @@ -144,6 +154,10 @@ audio_focus_id_map_.reset(); } +void WebAppProvider::StartImpl() { + StartRegistry(); +} + void WebAppProvider::CreateWebAppsSubsystems(Profile* profile) { database_factory_ = std::make_unique<WebAppDatabaseFactory>(profile); database_ = std::make_unique<WebAppDatabase>(database_factory_.get()); @@ -187,17 +201,23 @@ void WebAppProvider::ConnectSubsystems() { DCHECK(!started_); + install_manager_->SetSubsystems(registrar_.get(), install_finalizer_.get()); - if (base::FeatureList::IsEnabled(features::kDesktopPWAsWithoutExtensions)) { - // TODO(crbug.com/877898): Port all other managers to support BMO. - return; + // TODO(crbug.com/877898): Port all other managers to support BMO. + if (!base::FeatureList::IsEnabled(features::kDesktopPWAsWithoutExtensions)) { + pending_app_manager_->SetSubsystems(registrar_.get(), ui_manager_.get(), + install_finalizer_.get()); + web_app_policy_manager_->SetSubsystems(pending_app_manager_.get()); + system_web_app_manager_->SetSubsystems(pending_app_manager_.get(), + registrar_.get(), ui_manager_.get()); } - pending_app_manager_->SetSubsystems(registrar_.get(), ui_manager_.get(), - install_finalizer_.get()); - web_app_policy_manager_->SetSubsystems(pending_app_manager_.get()); - system_web_app_manager_->SetSubsystems(pending_app_manager_.get(), - registrar_.get(), ui_manager_.get()); + connected_ = true; +} + +void WebAppProvider::StartRegistry() { + registrar_->Init(base::BindOnce(&WebAppProvider::OnRegistryReady, + weak_ptr_factory_.GetWeakPtr())); } void WebAppProvider::OnRegistryReady() {
diff --git a/chrome/browser/web_applications/web_app_provider.h b/chrome/browser/web_applications/web_app_provider.h index be5cac9c..3cd2aaf 100644 --- a/chrome/browser/web_applications/web_app_provider.h +++ b/chrome/browser/web_applications/web_app_provider.h
@@ -68,11 +68,8 @@ explicit WebAppProvider(Profile* profile); ~WebAppProvider() override; - // TODO(crbug.com/973324): Wrap StartRegistry() with a Start() method that - // calls ConnectSubsystems(). - // Start registry. All subsystems depend on it. This will run all subsystem - // startup tasks. - void StartRegistry(); + // Start the Web App system. This will run subsystem startup tasks. + void Start(); // WebAppProviderBase: AppRegistrar& registrar() override; @@ -104,15 +101,18 @@ } protected: + virtual void StartImpl(); + // Create extension-independent subsystems. void CreateWebAppsSubsystems(Profile* profile); // ... or create legacy extension-based subsystems. void CreateBookmarkAppsSubsystems(Profile* profile); - // Wire together subsystems but do not start them (yet). Can be called - // multiple times before StartRegistry(). + // Wire together subsystems but do not start them (yet). void ConnectSubsystems(); + // Start registry. All other subsystems depend on it. + void StartRegistry(); void OnRegistryReady(); void OnScanForExternalWebApps(std::vector<ExternalInstallOptions>); @@ -145,8 +145,9 @@ Profile* profile_; - // Ensures that ConnectSubsystems() is not called after StartRegistry(). + // Ensures that ConnectSubsystems() is not called after Start(). bool started_ = false; + bool connected_ = false; base::WeakPtrFactory<WebAppProvider> weak_ptr_factory_{this};
diff --git a/chrome/browser/web_applications/web_app_provider_factory.cc b/chrome/browser/web_applications/web_app_provider_factory.cc index 4bdb59d..0381720 100644 --- a/chrome/browser/web_applications/web_app_provider_factory.cc +++ b/chrome/browser/web_applications/web_app_provider_factory.cc
@@ -30,7 +30,6 @@ "WebAppProvider", BrowserContextDependencyManager::GetInstance()) { WebAppProviderBaseFactory::SetInstance(this); - DependsOn( extensions::ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); } @@ -43,7 +42,7 @@ content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); WebAppProvider* provider = new WebAppProvider(profile); - provider->StartRegistry(); + provider->Start(); return provider; }
diff --git a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc index 7c93a9ed7..37696c0 100644 --- a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc +++ b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc
@@ -1724,20 +1724,25 @@ } } -// Tests that HasFillData() works correctly for fiiable and non-fillable fields. -TEST_F(PasswordAutofillAgentTest, HasFillData) { +// Tests that TryToShowTouchToFill() works correctly for fillable and +// non-fillable fields. +TEST_F(PasswordAutofillAgentTest, TryToShowTouchToFill) { // Initially no fill data is available. WebInputElement random_element = GetInputElementByID("random_field"); - EXPECT_FALSE(password_autofill_agent_->HasFillData(username_element_)); - EXPECT_FALSE(password_autofill_agent_->HasFillData(password_element_)); - EXPECT_FALSE(password_autofill_agent_->HasFillData(random_element)); + EXPECT_FALSE( + password_autofill_agent_->TryToShowTouchToFill(username_element_)); + EXPECT_FALSE( + password_autofill_agent_->TryToShowTouchToFill(password_element_)); + EXPECT_FALSE(password_autofill_agent_->TryToShowTouchToFill(random_element)); // This changes once fill data is simulated. |random_element| continue to // have no fill data, though. SimulateOnFillPasswordForm(fill_data_); - EXPECT_TRUE(password_autofill_agent_->HasFillData(username_element_)); - EXPECT_TRUE(password_autofill_agent_->HasFillData(password_element_)); - EXPECT_FALSE(password_autofill_agent_->HasFillData(random_element)); + EXPECT_TRUE( + password_autofill_agent_->TryToShowTouchToFill(username_element_)); + EXPECT_TRUE( + password_autofill_agent_->TryToShowTouchToFill(password_element_)); + EXPECT_FALSE(password_autofill_agent_->TryToShowTouchToFill(random_element)); } // Tests that |FillIntoFocusedField| doesn't fill read-only text fields.
diff --git a/chrome/test/base/in_process_browser_test.cc b/chrome/test/base/in_process_browser_test.cc index 7bfd9fb..afd3fb0 100644 --- a/chrome/test/base/in_process_browser_test.cc +++ b/chrome/test/base/in_process_browser_test.cc
@@ -126,7 +126,7 @@ // chromeos::device_sync::DeviceSyncImpl::Factory: std::unique_ptr<chromeos::device_sync::DeviceSyncBase> BuildInstance( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, service_manager::Connector* connector, const chromeos::device_sync::GcmDeviceInfoProvider*
diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc index f48dc43..34beb1d 100644 --- a/chrome/test/base/testing_profile.cc +++ b/chrome/test/base/testing_profile.cc
@@ -408,7 +408,7 @@ BrowserContext::Initialize(this, profile_path_); #if defined(OS_ANDROID) - identity::DisableInteractionWithSystemAccounts(); + signin::DisableInteractionWithSystemAccounts(); #endif // Normally this would happen during browser startup, but for tests
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index 6362de2..cee545d 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -4297,6 +4297,14 @@ ] }, + "CrostiniRootAccessAllowed": { + "os": ["chromeos"], + "test_policy": { "CrostiniRootAccessAllowed": false }, + "pref_mappings": [ + { "pref": "crostini.user_root_access_allowed_by_policy" } + ] + }, + "DeviceSamlLoginAuthenticationType": { },
diff --git a/chrome/test/data/webui/ntp4_browsertest.cc b/chrome/test/data/webui/ntp4_browsertest.cc index cdd0484..d244ccc 100644 --- a/chrome/test/data/webui/ntp4_browsertest.cc +++ b/chrome/test/data/webui/ntp4_browsertest.cc
@@ -16,5 +16,5 @@ void NTP4LoggedInWebUITest::SetLoginName(const std::string& name) { auto* identity_manager = IdentityManagerFactory::GetForProfile(browser()->profile()); - identity::SetPrimaryAccount(identity_manager, name); + signin::SetPrimaryAccount(identity_manager, name); }
diff --git a/chromeos/components/account_manager/account_manager.cc b/chromeos/components/account_manager/account_manager.cc index 1c31d5b..e92a8dc 100644 --- a/chromeos/components/account_manager/account_manager.cc +++ b/chromeos/components/account_manager/account_manager.cc
@@ -23,8 +23,8 @@ #include "google_apis/gaia/gaia_auth_consumer.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "google_apis/gaia/gaia_auth_util.h" +#include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/oauth2_access_token_fetcher_impl.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "third_party/protobuf/src/google/protobuf/message_lite.h" @@ -74,7 +74,7 @@ // static const char* const AccountManager::kInvalidToken = - OAuth2TokenServiceDelegate::kInvalidRefreshToken; + GaiaConstants::kInvalidRefreshToken; class AccountManager::GaiaTokenRevocationRequest : public GaiaAuthConsumer { public:
diff --git a/chromeos/services/device_sync/cryptauth_client_impl.cc b/chromeos/services/device_sync/cryptauth_client_impl.cc index 11efbe02..100d2fdb 100644 --- a/chromeos/services/device_sync/cryptauth_client_impl.cc +++ b/chromeos/services/device_sync/cryptauth_client_impl.cc
@@ -107,7 +107,7 @@ CryptAuthClientImpl::CryptAuthClientImpl( std::unique_ptr<CryptAuthApiCallFlow> api_call_flow, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const cryptauth::DeviceClassifier& device_classifier) : api_call_flow_(std::move(api_call_flow)), @@ -608,14 +608,14 @@ OAuth2AccessTokenManager::ScopeSet scopes; scopes.insert(kCryptAuthOAuth2Scope); - access_token_fetcher_ = std::make_unique< - identity::PrimaryAccountAccessTokenFetcher>( - "cryptauth_client", identity_manager_, scopes, - base::BindOnce(&CryptAuthClientImpl::OnAccessTokenFetched<ResponseProto>, - weak_ptr_factory_.GetWeakPtr(), request_type, - serialized_request, request_as_query_parameters, - response_callback), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + access_token_fetcher_ = + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( + "cryptauth_client", identity_manager_, scopes, + base::BindOnce( + &CryptAuthClientImpl::OnAccessTokenFetched<ResponseProto>, + weak_ptr_factory_.GetWeakPtr(), request_type, serialized_request, + request_as_query_parameters, response_callback), + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } template <class ResponseProto> @@ -626,7 +626,7 @@ request_as_query_parameters, const base::Callback<void(const ResponseProto&)>& response_callback, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) { @@ -686,7 +686,7 @@ // CryptAuthClientFactoryImpl CryptAuthClientFactoryImpl::CryptAuthClientFactoryImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const cryptauth::DeviceClassifier& device_classifier) : identity_manager_(identity_manager),
diff --git a/chromeos/services/device_sync/cryptauth_client_impl.h b/chromeos/services/device_sync/cryptauth_client_impl.h index 2f61d88d..0b672ce4 100644 --- a/chromeos/services/device_sync/cryptauth_client_impl.h +++ b/chromeos/services/device_sync/cryptauth_client_impl.h
@@ -18,10 +18,10 @@ #include "components/signin/public/identity_manager/access_token_info.h" #include "net/traffic_annotation/network_traffic_annotation.h" -namespace identity { +namespace signin { class IdentityManager; class PrimaryAccountAccessTokenFetcher; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -45,7 +45,7 @@ // methods are no longer needed. CryptAuthClientImpl( std::unique_ptr<CryptAuthApiCallFlow> api_call_flow, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const cryptauth::DeviceClassifier& device_classifier); ~CryptAuthClientImpl() override; @@ -145,7 +145,7 @@ request_as_query_parameters, const base::Callback<void(const ResponseProto&)>& response_callback, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // Called with CryptAuthApiCallFlow completes successfully to deserialize and // return the result. @@ -165,10 +165,10 @@ // Constructs and executes the actual HTTP request. std::unique_ptr<CryptAuthApiCallFlow> api_call_flow_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // Fetches the access token authorizing the API calls. - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; // The context for network requests. @@ -204,7 +204,7 @@ // |url_request_context|: The request context to make the HTTP requests. // |device_classifier|: Contains basic device information of the client. CryptAuthClientFactoryImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const cryptauth::DeviceClassifier& device_classifier); ~CryptAuthClientFactoryImpl() override; @@ -213,7 +213,7 @@ std::unique_ptr<CryptAuthClient> CreateInstance() override; private: - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; const scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; const cryptauth::DeviceClassifier device_classifier_;
diff --git a/chromeos/services/device_sync/cryptauth_client_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_client_impl_unittest.cc index b2d3054..78df6a6 100644 --- a/chromeos/services/device_sync/cryptauth_client_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_client_impl_unittest.cc
@@ -196,7 +196,7 @@ protected: base::test::ScopedTaskEnvironment scoped_task_environment_; - identity::IdentityTestEnvironment identity_test_environment_; + signin::IdentityTestEnvironment identity_test_environment_; // Owned by |client_|. StrictMock<MockCryptAuthApiCallFlow>* api_call_flow_;
diff --git a/chromeos/services/device_sync/device_sync_impl.cc b/chromeos/services/device_sync/device_sync_impl.cc index bccb226..64d50161 100644 --- a/chromeos/services/device_sync/device_sync_impl.cc +++ b/chromeos/services/device_sync/device_sync_impl.cc
@@ -217,7 +217,7 @@ DeviceSyncImpl::Factory::~Factory() = default; std::unique_ptr<DeviceSyncBase> DeviceSyncImpl::Factory::BuildInstance( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, service_manager::Connector* connector, const GcmDeviceInfoProvider* gcm_device_info_provider, @@ -300,7 +300,7 @@ } DeviceSyncImpl::DeviceSyncImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, service_manager::Connector* connector, const GcmDeviceInfoProvider* gcm_device_info_provider,
diff --git a/chromeos/services/device_sync/device_sync_impl.h b/chromeos/services/device_sync/device_sync_impl.h index bc8e70e..4c38d7f 100644 --- a/chromeos/services/device_sync/device_sync_impl.h +++ b/chromeos/services/device_sync/device_sync_impl.h
@@ -31,9 +31,9 @@ class GCMDriver; } // namespace gcm -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -76,7 +76,7 @@ // Note: |timer| should be a newly-created base::OneShotTimer object; this // parameter only exists for testing via dependency injection. virtual std::unique_ptr<DeviceSyncBase> BuildInstance( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, service_manager::Connector* connector, const GcmDeviceInfoProvider* gcm_device_info_provider, @@ -167,7 +167,7 @@ }; DeviceSyncImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, service_manager::Connector* connector, const GcmDeviceInfoProvider* gcm_device_info_provider, @@ -212,7 +212,7 @@ void SetPrefConnectionDelegateForTesting( std::unique_ptr<PrefConnectionDelegate> pref_connection_delegate); - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; gcm::GCMDriver* gcm_driver_; service_manager::Connector* connector_; const GcmDeviceInfoProvider* gcm_device_info_provider_;
diff --git a/chromeos/services/device_sync/device_sync_service.cc b/chromeos/services/device_sync/device_sync_service.cc index 6b1c9bde..7668765 100644 --- a/chromeos/services/device_sync/device_sync_service.cc +++ b/chromeos/services/device_sync/device_sync_service.cc
@@ -16,7 +16,7 @@ namespace device_sync { DeviceSyncService::DeviceSyncService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, const GcmDeviceInfoProvider* gcm_device_info_provider, ClientAppMetadataProvider* client_app_metadata_provider,
diff --git a/chromeos/services/device_sync/device_sync_service.h b/chromeos/services/device_sync/device_sync_service.h index 9fae89d..5bdc208 100644 --- a/chromeos/services/device_sync/device_sync_service.h +++ b/chromeos/services/device_sync/device_sync_service.h
@@ -17,9 +17,9 @@ class GCMDriver; } // namespace gcm -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -38,7 +38,7 @@ class DeviceSyncService : public service_manager::Service { public: DeviceSyncService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, const GcmDeviceInfoProvider* gcm_device_info_provider, ClientAppMetadataProvider* client_app_metadata_provider, @@ -55,7 +55,7 @@ service_manager::ServiceBinding service_binding_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; gcm::GCMDriver* gcm_driver_; const GcmDeviceInfoProvider* gcm_device_info_provider_; ClientAppMetadataProvider* client_app_metadata_provider_;
diff --git a/chromeos/services/device_sync/device_sync_service_unittest.cc b/chromeos/services/device_sync/device_sync_service_unittest.cc index 4ba12ff..e82bdc1 100644 --- a/chromeos/services/device_sync/device_sync_service_unittest.cc +++ b/chromeos/services/device_sync/device_sync_service_unittest.cc
@@ -409,7 +409,7 @@ public: FakeRemoteDeviceProviderFactory( const multidevice::RemoteDeviceList& initial_devices, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, FakeCryptAuthDeviceManagerFactory* fake_cryptauth_device_manager_factory, FakeCryptAuthEnrollmentManagerFactory* fake_cryptauth_enrollment_manager_factory, @@ -462,7 +462,7 @@ private: const multidevice::RemoteDeviceList& initial_devices_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; FakeCryptAuthDeviceManagerFactory* fake_cryptauth_device_manager_factory_; FakeCryptAuthEnrollmentManagerFactory* fake_cryptauth_enrollment_manager_factory_; @@ -562,7 +562,7 @@ // DeviceSyncImpl::Factory: std::unique_ptr<DeviceSyncBase> BuildInstance( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, service_manager::Connector* connector, const GcmDeviceInfoProvider* gcm_device_info_provider, @@ -611,7 +611,7 @@ // starts up since this is a CrOS-only service, and CrOS requires that // the user logs in. identity_test_environment_ = - std::make_unique<identity::IdentityTestEnvironment>(); + std::make_unique<signin::IdentityTestEnvironment>(); identity_test_environment_->MakePrimaryAccountAvailable(kTestEmail); fake_cryptauth_gcm_manager_factory_ = @@ -1160,7 +1160,7 @@ std::unique_ptr<FakeSoftwareFeatureManagerFactory> fake_software_feature_manager_factory_; - std::unique_ptr<identity::IdentityTestEnvironment> identity_test_environment_; + std::unique_ptr<signin::IdentityTestEnvironment> identity_test_environment_; std::unique_ptr<gcm::FakeGCMDriver> fake_gcm_driver_; std::unique_ptr<FakeGcmDeviceInfoProvider> fake_gcm_device_info_provider_;
diff --git a/chromeos/services/device_sync/public/cpp/device_sync_client_impl_unittest.cc b/chromeos/services/device_sync/public/cpp/device_sync_client_impl_unittest.cc index 5c3c209..0404f67 100644 --- a/chromeos/services/device_sync/public/cpp/device_sync_client_impl_unittest.cc +++ b/chromeos/services/device_sync/public/cpp/device_sync_client_impl_unittest.cc
@@ -61,7 +61,7 @@ // DeviceSyncImpl::Factory: std::unique_ptr<DeviceSyncBase> BuildInstance( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, service_manager::Connector* connector, const GcmDeviceInfoProvider* gcm_device_info_provider, @@ -152,7 +152,7 @@ std::make_unique<FakeClientAppMetadataProvider>(); identity_test_environment_ = - std::make_unique<identity::IdentityTestEnvironment>(); + std::make_unique<signin::IdentityTestEnvironment>(); identity_test_environment_->MakePrimaryAccountAvailable(kTestEmail); auto fake_device_sync = std::make_unique<FakeDeviceSync>(); @@ -423,7 +423,7 @@ const base::test::ScopedTaskEnvironment scoped_task_environment_; - std::unique_ptr<identity::IdentityTestEnvironment> identity_test_environment_; + std::unique_ptr<signin::IdentityTestEnvironment> identity_test_environment_; std::unique_ptr<gcm::FakeGCMDriver> fake_gcm_driver_; std::unique_ptr<FakeGcmDeviceInfoProvider> fake_gcm_device_info_provider_; std::unique_ptr<FakeClientAppMetadataProvider>
diff --git a/components/autofill/content/renderer/autofill_agent.cc b/components/autofill/content/renderer/autofill_agent.cc index bbd24d79..7b886347f 100644 --- a/components/autofill/content/renderer/autofill_agent.cc +++ b/components/autofill/content/renderer/autofill_agent.cc
@@ -639,7 +639,8 @@ // criteria are not met. WebString value = element.EditingValue(); if (value.length() > kMaxDataLength || - (!options.autofill_on_empty_values && value.IsEmpty()) || + (!IsKeyboardAccessoryEnabled() && !options.autofill_on_empty_values && + value.IsEmpty()) || (options.requires_caret_at_end && (element.SelectionStart() != element.SelectionEnd() || element.SelectionEnd() != static_cast<int>(value.length())))) { @@ -909,10 +910,11 @@ weak_ptr_factory_.GetWeakPtr(), element)); } -bool AutofillAgent::HasFillData(const WebFormControlElement& element) const { +bool AutofillAgent::TryToShowTouchToFill(const WebFormControlElement& element) { // This is currently only implemented for passwords. Consider supporting other // autofill types in the future as well. - return password_autofill_agent_->HasFillData(element); + return IsTouchToFillEnabled() && + password_autofill_agent_->TryToShowTouchToFill(element); } void AutofillAgent::SelectWasUpdated(
diff --git a/components/autofill/content/renderer/autofill_agent.h b/components/autofill/content/renderer/autofill_agent.h index c1c2b5d..ce3619c5 100644 --- a/components/autofill/content/renderer/autofill_agent.h +++ b/components/autofill/content/renderer/autofill_agent.h
@@ -204,7 +204,8 @@ const blink::WebFormControlElement& element) override; void SelectControlDidChange( const blink::WebFormControlElement& element) override; - bool HasFillData(const blink::WebFormControlElement& element) const override; + bool TryToShowTouchToFill( + const blink::WebFormControlElement& element) override; void HandleFocusChangeComplete();
diff --git a/components/autofill/content/renderer/password_autofill_agent.cc b/components/autofill/content/renderer/password_autofill_agent.cc index d6aa50c..a61ea84a 100644 --- a/components/autofill/content/renderer/password_autofill_agent.cc +++ b/components/autofill/content/renderer/password_autofill_agent.cc
@@ -955,8 +955,8 @@ return (password_form->username_element == element.NameForAutofill().Utf16()); } -bool PasswordAutofillAgent::HasFillData( - const WebFormControlElement& control_element) const { +bool PasswordAutofillAgent::TryToShowTouchToFill( + const WebFormControlElement& control_element) { const WebInputElement* element = ToWebInputElement(&control_element); return element && (base::Contains(web_input_to_password_info_, *element) || base::Contains(password_to_username_, *element));
diff --git a/components/autofill/content/renderer/password_autofill_agent.h b/components/autofill/content/renderer/password_autofill_agent.h index 183f210..3fbdf21 100644 --- a/components/autofill/content/renderer/password_autofill_agent.h +++ b/components/autofill/content/renderer/password_autofill_agent.h
@@ -179,8 +179,10 @@ // Returns whether the element is a username or password textfield. bool IsUsernameOrPasswordField(const blink::WebInputElement& element); - // Returns whether the agent has fill data stored for |control_element|. - bool HasFillData(const blink::WebFormControlElement& control_element) const; + // Asks the agent to show the touch to fill UI for |control_element|. Returns + // whether the agent was able to do so. + bool TryToShowTouchToFill( + const blink::WebFormControlElement& control_element); // Shows an Autofill popup with username suggestions for |element|. If // |show_all| is |true|, will show all possible suggestions for that element,
diff --git a/components/autofill/core/browser/DEPS b/components/autofill/core/browser/DEPS index df0208d..5e23fe7 100644 --- a/components/autofill/core/browser/DEPS +++ b/components/autofill/core/browser/DEPS
@@ -8,25 +8,7 @@ "+components/metrics", "+components/policy", "+components/security_state", - "+components/signin/core/browser", - # Use identity_manager.h instead of the below files; - # see https://groups.google.com/a/chromium.org/d/msg/chromium-dev/dgFLuxqZt1o/iEqkyoQQBwAJ for help and info. - "-components/signin/internal/identity_manager/account_fetcher_service.h", - "-components/signin/internal/identity_manager/account_info_fetcher.h", - "-components/signin/internal/identity_manager/account_tracker_service.h", - "-components/signin/internal/identity_manager/child_account_info_fetcher_android.h", - "-components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/gaia_cookie_manager_service.h", - "-components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_helper.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_token_fetcher.h", - "-components/signin/internal/identity_manager/primary_account_manager.h", - "-components/signin/internal/identity_manager/primary_account_policy_manager.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h", - "-components/signin/internal/identity_manager/ubertoken_fetcher_impl.h", "+components/signin/public", - "+components/sync", "+components/variations", "+components/version_info",
diff --git a/components/autofill/core/browser/autofill_client.h b/components/autofill/core/browser/autofill_client.h index 8b4766e9e..09dcb89 100644 --- a/components/autofill/core/browser/autofill_client.h +++ b/components/autofill/core/browser/autofill_client.h
@@ -32,7 +32,7 @@ class RectF; } -namespace identity { +namespace signin { class IdentityManager; } @@ -234,7 +234,7 @@ virtual syncer::SyncService* GetSyncService() = 0; // Gets the IdentityManager associated with the client. - virtual identity::IdentityManager* GetIdentityManager() = 0; + virtual signin::IdentityManager* GetIdentityManager() = 0; // Gets the FormDataImporter instance owned by the client. virtual FormDataImporter* GetFormDataImporter() = 0;
diff --git a/components/autofill/core/browser/payments/payments_client.cc b/components/autofill/core/browser/payments/payments_client.cc index 63ea112..0142417 100644 --- a/components/autofill/core/browser/payments/payments_client.cc +++ b/components/autofill/core/browser/payments/payments_client.cc
@@ -876,7 +876,7 @@ PaymentsClient::PaymentsClient( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, AccountInfoGetter* account_info_getter, bool is_off_the_record) : url_loader_factory_(url_loader_factory), @@ -1079,7 +1079,7 @@ void PaymentsClient::AccessTokenFetchFinished( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { DCHECK(token_fetcher_); token_fetcher_.reset(); @@ -1122,7 +1122,7 @@ account_id, kTokenFetchId, payments_scopes, base::BindOnce(&PaymentsClient::AccessTokenFetchFinished, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } void PaymentsClient::SetOAuth2TokenAndStartRequest() {
diff --git a/components/autofill/core/browser/payments/payments_client.h b/components/autofill/core/browser/payments/payments_client.h index 4b3d814..7242071 100644 --- a/components/autofill/core/browser/payments/payments_client.h +++ b/components/autofill/core/browser/payments/payments_client.h
@@ -21,9 +21,9 @@ #include "components/signin/public/identity_manager/access_token_info.h" #include "google_apis/gaia/google_service_auth_error.h" -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin namespace network { struct ResourceRequest; @@ -147,7 +147,7 @@ // denotes incognito mode. PaymentsClient( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - identity::IdentityManager* const identity_manager, + signin::IdentityManager* const identity_manager, AccountInfoGetter* const account_info_getter, bool is_off_the_record = false); @@ -240,7 +240,7 @@ // Callback that handles a completed access token request. void AccessTokenFetchFinished(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // Handles a completed access token request in the case of failure. void AccessTokenError(const GoogleServiceAuthError& error); @@ -258,7 +258,7 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; // Provided in constructor; not owned by PaymentsClient. - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; // Provided in constructor; not owned by PaymentsClient. AccountInfoGetter* const account_info_getter_; @@ -273,7 +273,7 @@ std::unique_ptr<network::SimpleURLLoader> simple_url_loader_; // The OAuth2 token fetcher for any account. - std::unique_ptr<identity::AccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::AccessTokenFetcher> token_fetcher_; // The OAuth2 token, or empty if not fetched. std::string access_token_;
diff --git a/components/autofill/core/browser/payments/payments_client_unittest.cc b/components/autofill/core/browser/payments/payments_client_unittest.cc index c4444d0..90710ef 100644 --- a/components/autofill/core/browser/payments/payments_client_unittest.cc +++ b/components/autofill/core/browser/payments/payments_client_unittest.cc
@@ -299,7 +299,7 @@ scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; TestPersonalDataManager test_personal_data_; std::unique_ptr<PaymentsClient> client_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; net::HttpRequestHeaders intercepted_headers_; bool has_variations_header_;
diff --git a/components/autofill/core/browser/payments/test_payments_client.cc b/components/autofill/core/browser/payments/test_payments_client.cc index ce6cde2..e4022a9d 100644 --- a/components/autofill/core/browser/payments/test_payments_client.cc +++ b/components/autofill/core/browser/payments/test_payments_client.cc
@@ -16,7 +16,7 @@ TestPaymentsClient::TestPaymentsClient( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, PersonalDataManager* personal_data_manager) : PaymentsClient(url_loader_factory_, identity_manager,
diff --git a/components/autofill/core/browser/payments/test_payments_client.h b/components/autofill/core/browser/payments/test_payments_client.h index 182d716..573abad 100644 --- a/components/autofill/core/browser/payments/test_payments_client.h +++ b/components/autofill/core/browser/payments/test_payments_client.h
@@ -25,7 +25,7 @@ public: TestPaymentsClient( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, PersonalDataManager* personal_data_manager); ~TestPaymentsClient() override;
diff --git a/components/autofill/core/browser/personal_data_manager.cc b/components/autofill/core/browser/personal_data_manager.cc index 8057115a..5d47a0f 100644 --- a/components/autofill/core/browser/personal_data_manager.cc +++ b/components/autofill/core/browser/personal_data_manager.cc
@@ -266,7 +266,7 @@ scoped_refptr<AutofillWebDataService> profile_database, scoped_refptr<AutofillWebDataService> account_database, PrefService* pref_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, AutofillProfileValidator* client_profile_validator, history::HistoryService* history_service, bool is_off_the_record) {
diff --git a/components/autofill/core/browser/personal_data_manager.h b/components/autofill/core/browser/personal_data_manager.h index d5be83b2..912b454 100644 --- a/components/autofill/core/browser/personal_data_manager.h +++ b/components/autofill/core/browser/personal_data_manager.h
@@ -71,7 +71,7 @@ public AutofillWebDataServiceObserverOnUISequence, public history::HistoryServiceObserver, public syncer::SyncServiceObserver, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public AccountInfoGetter { public: explicit PersonalDataManager(const std::string& app_locale); @@ -89,7 +89,7 @@ void Init(scoped_refptr<AutofillWebDataService> profile_database, scoped_refptr<AutofillWebDataService> account_database, PrefService* pref_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, AutofillProfileValidator* client_profile_validator, history::HistoryService* history_service, bool is_off_the_record); @@ -123,7 +123,7 @@ CoreAccountInfo GetAccountInfoForPaymentsServer() const override; bool IsSyncFeatureEnabled() const override; - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnAccountsCookieDeletedByUserAction() override; // Returns the current sync status. @@ -771,7 +771,7 @@ AutofillProfileValidator* client_profile_validator_ = nullptr; // The identity manager that this instance uses. Must outlive this instance. - identity::IdentityManager* identity_manager_ = nullptr; + signin::IdentityManager* identity_manager_ = nullptr; // The sync service this instances uses. Must outlive this instance. syncer::SyncService* sync_service_ = nullptr;
diff --git a/components/autofill/core/browser/personal_data_manager_unittest.cc b/components/autofill/core/browser/personal_data_manager_unittest.cc index 0d152c4d..e9b8ac07 100644 --- a/components/autofill/core/browser/personal_data_manager_unittest.cc +++ b/components/autofill/core/browser/personal_data_manager_unittest.cc
@@ -306,7 +306,7 @@ base::test::ScopedTaskEnvironment::MainThreadType::UI}; std::unique_ptr<PrefService> prefs_; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; syncer::TestSyncService sync_service_; scoped_refptr<AutofillWebDataService> profile_database_service_; scoped_refptr<AutofillWebDataService> account_database_service_;
diff --git a/components/autofill/core/browser/test_autofill_client.cc b/components/autofill/core/browser/test_autofill_client.cc index 5ce8e07..8a9b809 100644 --- a/components/autofill/core/browser/test_autofill_client.cc +++ b/components/autofill/core/browser/test_autofill_client.cc
@@ -34,7 +34,7 @@ return test_sync_service_; } -identity::IdentityManager* TestAutofillClient::GetIdentityManager() { +signin::IdentityManager* TestAutofillClient::GetIdentityManager() { return identity_test_env_.identity_manager(); }
diff --git a/components/autofill/core/browser/test_autofill_client.h b/components/autofill/core/browser/test_autofill_client.h index 912a525..68c1b327 100644 --- a/components/autofill/core/browser/test_autofill_client.h +++ b/components/autofill/core/browser/test_autofill_client.h
@@ -39,7 +39,7 @@ AutocompleteHistoryManager* GetAutocompleteHistoryManager() override; PrefService* GetPrefs() override; syncer::SyncService* GetSyncService() override; - identity::IdentityManager* GetIdentityManager() override; + signin::IdentityManager* GetIdentityManager() override; FormDataImporter* GetFormDataImporter() override; payments::PaymentsClient* GetPaymentsClient() override; StrikeDatabase* GetStrikeDatabase() override; @@ -174,7 +174,7 @@ private: ukm::TestAutoSetUkmRecorder test_ukm_recorder_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; syncer::SyncService* test_sync_service_ = nullptr; TestAddressNormalizer test_address_normalizer_; TestPersonalDataManager test_personal_data_manager_;
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 4b6e010..b0504b4f 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -208,6 +208,11 @@ // Controls whether to use modernized style for the Autofill dropdown. const base::Feature kAutofillRefreshStyleAndroid{ "AutofillRefreshStyleAndroid", base::FEATURE_DISABLED_BY_DEFAULT}; + +// Enables the touch to fill feature for Android. +const base::Feature kTouchToFillAndroid = {"TouchToFillAndroid", + base::FEATURE_DISABLED_BY_DEFAULT}; + #endif // OS_ANDROID #if defined(OS_ANDROID) || defined(OS_IOS)
diff --git a/components/autofill/core/common/autofill_features.h b/components/autofill/core/common/autofill_features.h index f88c04f4..e3a45a80 100644 --- a/components/autofill/core/common/autofill_features.h +++ b/components/autofill/core/common/autofill_features.h
@@ -62,6 +62,7 @@ #if defined(OS_ANDROID) extern const base::Feature kAutofillManualFallbackAndroid; extern const base::Feature kAutofillRefreshStyleAndroid; +extern const base::Feature kTouchToFillAndroid; #endif // OS_ANDROID #if defined(OS_ANDROID) || defined(OS_IOS)
diff --git a/components/autofill/core/common/autofill_util.cc b/components/autofill/core/common/autofill_util.cc index e735f67..19ec7815 100644 --- a/components/autofill/core/common/autofill_util.cc +++ b/components/autofill/core/common/autofill_util.cc
@@ -70,6 +70,14 @@ #endif } +bool IsTouchToFillEnabled() { +#if defined(OS_ANDROID) + return base::FeatureList::IsEnabled(features::kTouchToFillAndroid); +#else // !defined(OS_ANDROID) + return false; +#endif +} + unsigned int GetKeyboardAccessoryAnimationDuration() { #if defined(OS_ANDROID) return base::GetFieldTrialParamByFeatureAsInt(
diff --git a/components/autofill/core/common/autofill_util.h b/components/autofill/core/common/autofill_util.h index 21ab53a..e722a1c8 100644 --- a/components/autofill/core/common/autofill_util.h +++ b/components/autofill/core/common/autofill_util.h
@@ -38,6 +38,9 @@ // Returns true when keyboard accessory is enabled. bool IsKeyboardAccessoryEnabled(); +// Returns whether the Touch To Fill feature is enabled. +bool IsTouchToFillEnabled(); + // Returns animation duration for keyboard accessory. If 0, we do not animate. unsigned int GetKeyboardAccessoryAnimationDuration();
diff --git a/components/autofill/ios/browser/autofill_agent.mm b/components/autofill/ios/browser/autofill_agent.mm index 720d00a..55d7f476 100644 --- a/components/autofill/ios/browser/autofill_agent.mm +++ b/components/autofill/ios/browser/autofill_agent.mm
@@ -589,11 +589,11 @@ return; } // Check that the main frame has already been processed. - if (!web::GetMainWebFrame(webState)) { + if (!webState->GetWebFramesManager()->GetMainWebFrame()) { return; } if (!autofill::AutofillDriverIOS::FromWebStateAndWebFrame( - webState, web::GetMainWebFrame(webState)) + webState, webState->GetWebFramesManager()->GetMainWebFrame()) ->is_processed()) { return; } @@ -624,9 +624,7 @@ #pragma mark - Private methods - (void)processPage:(web::WebState*)webState { - web::WebFramesManager* framesManager = - web::WebFramesManager::FromWebState(webState); - DCHECK(framesManager); + web::WebFramesManager* framesManager = webState->GetWebFramesManager(); if (!framesManager->GetMainWebFrame()) { return; }
diff --git a/components/autofill/ios/browser/autofill_agent_unittests.mm b/components/autofill/ios/browser/autofill_agent_unittests.mm index 5001b9a..03ddeb89 100644 --- a/components/autofill/ios/browser/autofill_agent_unittests.mm +++ b/components/autofill/ios/browser/autofill_agent_unittests.mm
@@ -18,8 +18,8 @@ #import "components/autofill/ios/browser/js_autofill_manager.h" #include "components/prefs/pref_service.h" #import "ios/web/public/deprecated/crw_js_injection_receiver.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #include "ios/web/public/test/fakes/fake_web_frame.h" +#import "ios/web/public/test/fakes/fake_web_frames_manager.h" #include "ios/web/public/test/fakes/test_browser_state.h" #import "ios/web/public/test/fakes/test_web_state.h" #include "ios/web/public/test/test_web_thread_bundle.h" @@ -66,6 +66,19 @@ public: AutofillAgentTests() {} + void AddWebFrame(std::unique_ptr<web::WebFrame> frame) { + web::WebFrame* frame_ptr = frame.get(); + fake_web_frames_manager_->AddWebFrame(std::move(frame)); + test_web_state_.OnWebFrameDidBecomeAvailable(frame_ptr); + } + + void RemoveWebFrame(const std::string& frame_id) { + web::WebFrame* frame_ptr = + fake_web_frames_manager_->GetFrameWithId(frame_id); + test_web_state_.OnWebFrameWillBecomeUnavailable(frame_ptr); + fake_web_frames_manager_->RemoveWebFrame(frame_id); + } + void SetUp() override { PlatformTest::SetUp(); @@ -75,12 +88,14 @@ test_web_state_.SetBrowserState(&test_browser_state_); test_web_state_.SetJSInjectionReceiver(mock_js_injection_receiver_); test_web_state_.SetContentIsHTML(true); + auto frames_manager = std::make_unique<web::FakeWebFramesManager>(); + fake_web_frames_manager_ = frames_manager.get(); + test_web_state_.SetWebFramesManager(std::move(frames_manager)); GURL url("https://example.com"); test_web_state_.SetCurrentURL(url); - test_web_state_.CreateWebFramesManager(); auto main_frame = std::make_unique<web::FakeWebFrame>("frameID", true, url); fake_main_frame_ = main_frame.get(); - test_web_state_.AddWebFrame(std::move(main_frame)); + AddWebFrame(std::move(main_frame)); prefs_ = autofill::test::PrefServiceForTesting(); autofill::prefs::SetAutofillEnabled(prefs_.get(), true); @@ -93,6 +108,7 @@ web::TestBrowserState test_browser_state_; web::TestWebState test_web_state_; web::FakeWebFrame* fake_main_frame_ = nullptr; + web::FakeWebFramesManager* fake_web_frames_manager_ = nullptr; autofill::TestAutofillClient client_; std::unique_ptr<PrefService> prefs_; AutofillAgent* autofill_agent_; @@ -149,8 +165,9 @@ field.value = base::ASCIIToUTF16(""); field.is_autofilled = true; form.fields.push_back(field); - [autofill_agent_ fillFormData:form - inFrame:web::GetMainWebFrame(&test_web_state_)]; + [autofill_agent_ + fillFormData:form + inFrame:test_web_state_.GetWebFramesManager()->GetMainWebFrame()]; test_web_state_.WasShown(); EXPECT_EQ( "__gCrWeb.autofill.fillForm({\"fields\":{\"name\":{\"section\":\"\"," @@ -200,8 +217,9 @@ field.is_autofilled = true; form.fields.push_back(field); // Fields are in alphabetical order. - [autofill_agent_ fillFormData:form - inFrame:web::GetMainWebFrame(&test_web_state_)]; + [autofill_agent_ + fillFormData:form + inFrame:test_web_state_.GetWebFramesManager()->GetMainWebFrame()]; test_web_state_.WasShown(); EXPECT_EQ("__gCrWeb.autofill.fillForm({\"fields\":{\"field1\":{\"section\":" "\"\",\"value\":\"value " @@ -371,14 +389,14 @@ autofill::AutofillManager::DISABLE_AUTOFILL_DOWNLOAD_MANAGER); // Remove the current main frame. - test_web_state_.RemoveWebFrame(fake_main_frame_->GetFrameId()); + RemoveWebFrame(fake_main_frame_->GetFrameId()); // Both frames available, then page loaded. test_web_state_.SetLoading(true); auto main_frame_unique = std::make_unique<web::FakeWebFrame>("main", true, GURL()); web::FakeWebFrame* main_frame = main_frame_unique.get(); - test_web_state_.AddWebFrame(std::move(main_frame_unique)); + AddWebFrame(std::move(main_frame_unique)); autofill::AutofillDriverIOS* main_frame_driver = autofill::AutofillDriverIOS::FromWebStateAndWebFrame(&test_web_state_, main_frame); @@ -388,7 +406,7 @@ EXPECT_TRUE(main_frame_driver->is_processed()); }); FakeWebFrameCallback* iframe = iframe_unique.get(); - test_web_state_.AddWebFrame(std::move(iframe_unique)); + AddWebFrame(std::move(iframe_unique)); autofill::AutofillDriverIOS* iframe_driver = autofill::AutofillDriverIOS::FromWebStateAndWebFrame(&test_web_state_, iframe); @@ -399,8 +417,8 @@ test_web_state_.OnPageLoaded(web::PageLoadCompletionStatus::SUCCESS); EXPECT_TRUE(main_frame_driver->is_processed()); EXPECT_TRUE(iframe_driver->is_processed()); - test_web_state_.RemoveWebFrame(main_frame->GetFrameId()); - test_web_state_.RemoveWebFrame(iframe->GetFrameId()); + RemoveWebFrame(main_frame->GetFrameId()); + RemoveWebFrame(iframe->GetFrameId()); // Main frame available, then page loaded, then iframe available main_frame_unique = std::make_unique<web::FakeWebFrame>("main", true, GURL()); @@ -415,18 +433,18 @@ iframe_driver = autofill::AutofillDriverIOS::FromWebStateAndWebFrame( &test_web_state_, iframe); test_web_state_.SetLoading(true); - test_web_state_.AddWebFrame(std::move(main_frame_unique)); + AddWebFrame(std::move(main_frame_unique)); EXPECT_FALSE(main_frame_driver->is_processed()); EXPECT_FALSE(iframe_driver->is_processed()); test_web_state_.SetLoading(false); test_web_state_.OnPageLoaded(web::PageLoadCompletionStatus::SUCCESS); EXPECT_TRUE(main_frame_driver->is_processed()); EXPECT_FALSE(iframe_driver->is_processed()); - test_web_state_.AddWebFrame(std::move(iframe_unique)); + AddWebFrame(std::move(iframe_unique)); EXPECT_TRUE(main_frame_driver->is_processed()); EXPECT_TRUE(iframe_driver->is_processed()); - test_web_state_.RemoveWebFrame(main_frame->GetFrameId()); - test_web_state_.RemoveWebFrame(iframe->GetFrameId()); + RemoveWebFrame(main_frame->GetFrameId()); + RemoveWebFrame(iframe->GetFrameId()); // Page loaded, then main frame, then iframe main_frame_unique = std::make_unique<web::FakeWebFrame>("main", true, GURL()); @@ -445,14 +463,14 @@ test_web_state_.OnPageLoaded(web::PageLoadCompletionStatus::SUCCESS); EXPECT_FALSE(main_frame_driver->is_processed()); EXPECT_FALSE(iframe_driver->is_processed()); - test_web_state_.AddWebFrame(std::move(main_frame_unique)); + AddWebFrame(std::move(main_frame_unique)); EXPECT_TRUE(main_frame_driver->is_processed()); EXPECT_FALSE(iframe_driver->is_processed()); - test_web_state_.AddWebFrame(std::move(iframe_unique)); + AddWebFrame(std::move(iframe_unique)); EXPECT_TRUE(main_frame_driver->is_processed()); EXPECT_TRUE(iframe_driver->is_processed()); - test_web_state_.RemoveWebFrame(main_frame->GetFrameId()); - test_web_state_.RemoveWebFrame(iframe->GetFrameId()); + RemoveWebFrame(main_frame->GetFrameId()); + RemoveWebFrame(iframe->GetFrameId()); // Page loaded, then iframe, then main frame main_frame_unique = std::make_unique<web::FakeWebFrame>("main", true, GURL()); @@ -471,12 +489,12 @@ test_web_state_.OnPageLoaded(web::PageLoadCompletionStatus::SUCCESS); EXPECT_FALSE(main_frame_driver->is_processed()); EXPECT_FALSE(iframe_driver->is_processed()); - test_web_state_.AddWebFrame(std::move(iframe_unique)); + AddWebFrame(std::move(iframe_unique)); EXPECT_FALSE(main_frame_driver->is_processed()); EXPECT_FALSE(iframe_driver->is_processed()); - test_web_state_.AddWebFrame(std::move(main_frame_unique)); + AddWebFrame(std::move(main_frame_unique)); EXPECT_TRUE(main_frame_driver->is_processed()); EXPECT_TRUE(iframe_driver->is_processed()); - test_web_state_.RemoveWebFrame(main_frame->GetFrameId()); - test_web_state_.RemoveWebFrame(iframe->GetFrameId()); + RemoveWebFrame(main_frame->GetFrameId()); + RemoveWebFrame(iframe->GetFrameId()); }
diff --git a/components/autofill/ios/browser/autofill_driver_ios.mm b/components/autofill/ios/browser/autofill_driver_ios.mm index 718de85..784c028 100644 --- a/components/autofill/ios/browser/autofill_driver_ios.mm +++ b/components/autofill/ios/browser/autofill_driver_ios.mm
@@ -10,7 +10,7 @@ #include "components/autofill/ios/browser/autofill_driver_ios_webframe.h" #import "ios/web/common/origin_util.h" #include "ios/web/public/browser_state.h" -#import "ios/web/public/js_messaging/web_frame_util.h" +#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/web_state/web_state.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
diff --git a/components/autofill/ios/form_util/form_activity_tab_helper.h b/components/autofill/ios/form_util/form_activity_tab_helper.h index 5401298..7b2d7ba 100644 --- a/components/autofill/ios/form_util/form_activity_tab_helper.h +++ b/components/autofill/ios/form_util/form_activity_tab_helper.h
@@ -69,6 +69,9 @@ // The observers. base::ObserverList<FormActivityObserver>::Unchecked observers_; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + WEB_STATE_USER_DATA_KEY_DECL(); DISALLOW_COPY_AND_ASSIGN(FormActivityTabHelper);
diff --git a/components/autofill/ios/form_util/form_activity_tab_helper.mm b/components/autofill/ios/form_util/form_activity_tab_helper.mm index 3ba94de..2110fc1 100644 --- a/components/autofill/ios/form_util/form_activity_tab_helper.mm +++ b/components/autofill/ios/form_util/form_activity_tab_helper.mm
@@ -39,7 +39,7 @@ FormActivityTabHelper::FormActivityTabHelper(web::WebState* web_state) : web_state_(web_state) { web_state_->AddObserver(this); - web_state_->AddScriptCommandCallback( + subscription_ = web_state_->AddScriptCommandCallback( base::BindRepeating(&FormActivityTabHelper::OnFormCommand, base::Unretained(this)), kCommandPrefix); @@ -48,7 +48,6 @@ FormActivityTabHelper::~FormActivityTabHelper() { if (web_state_) { web_state_->RemoveObserver(this); - web_state_->RemoveScriptCommandCallback(kCommandPrefix); web_state_ = nullptr; } } @@ -131,7 +130,6 @@ void FormActivityTabHelper::WebStateDestroyed(web::WebState* web_state) { DCHECK_EQ(web_state_, web_state); - web_state_->RemoveScriptCommandCallback(kCommandPrefix); web_state_->RemoveObserver(this); web_state_ = nullptr; }
diff --git a/components/autofill/ios/form_util/form_activity_tab_helper_unittest.mm b/components/autofill/ios/form_util/form_activity_tab_helper_unittest.mm index aca9c6a4..406083f 100644 --- a/components/autofill/ios/form_util/form_activity_tab_helper_unittest.mm +++ b/components/autofill/ios/form_util/form_activity_tab_helper_unittest.mm
@@ -8,7 +8,6 @@ #import "components/autofill/ios/form_util/form_activity_observer.h" #import "components/autofill/ios/form_util/test_form_activity_observer.h" #include "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/fakes/test_web_client.h" #import "ios/web/public/test/fakes/test_web_state_observer_util.h" @@ -69,9 +68,10 @@ bool form_in_main_frame = true; EXPECT_TRUE(base::test::ios::WaitUntilConditionOrTimeout( base::test::ios::kWaitForJSCompletionTimeout, ^bool { - return web::GetMainWebFrame(web_state()) != nullptr; + return web_state()->GetWebFramesManager()->GetMainWebFrame() != nullptr; })); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state()); + web::WebFrame* main_frame = + web_state()->GetWebFramesManager()->GetMainWebFrame(); ExecuteJavaScript(@"document.getElementById('submit').click();"); ASSERT_TRUE(observer_->submit_document_info()); @@ -101,9 +101,10 @@ bool form_in_main_frame = true; EXPECT_TRUE(base::test::ios::WaitUntilConditionOrTimeout( base::test::ios::kWaitForJSCompletionTimeout, ^bool { - return web::GetMainWebFrame(web_state()) != nullptr; + return web_state()->GetWebFramesManager()->GetMainWebFrame() != nullptr; })); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state()); + web::WebFrame* main_frame = + web_state()->GetWebFramesManager()->GetMainWebFrame(); ExecuteJavaScript(@"document.getElementById('form').submit();"); ASSERT_TRUE(observer_->submit_document_info()); @@ -125,9 +126,10 @@ "</form>"); EXPECT_TRUE(base::test::ios::WaitUntilConditionOrTimeout( base::test::ios::kWaitForJSCompletionTimeout, ^bool { - return web::GetMainWebFrame(web_state()) != nullptr; + return web_state()->GetWebFramesManager()->GetMainWebFrame() != nullptr; })); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state()); + web::WebFrame* main_frame = + web_state()->GetWebFramesManager()->GetMainWebFrame(); ASSERT_FALSE(observer_->form_activity_info()); // First call will set document.activeElement (which is usually set by user // action. Second call will trigger the message.
diff --git a/components/autofill_assistant/browser/actions/prompt_action_unittest.cc b/components/autofill_assistant/browser/actions/prompt_action_unittest.cc index 46c09e09..1e7d19b 100644 --- a/components/autofill_assistant/browser/actions/prompt_action_unittest.cc +++ b/components/autofill_assistant/browser/actions/prompt_action_unittest.cc
@@ -28,6 +28,7 @@ using ::testing::Pointee; using ::testing::Property; using ::testing::SizeIs; +using ::testing::UnorderedElementsAre; class PromptActionTest : public testing::Test { public: @@ -127,7 +128,7 @@ EXPECT_THAT((*user_actions_)[0].direct_action().names, ElementsAre("ok")); EXPECT_FALSE((*user_actions_)[0].chip().empty()); EXPECT_THAT((*user_actions_)[1].direct_action().names, - ElementsAre("maybe", "I_guess")); + UnorderedElementsAre("maybe", "I_guess")); EXPECT_TRUE((*user_actions_)[1].chip().empty()); }
diff --git a/components/autofill_assistant/browser/controller.cc b/components/autofill_assistant/browser/controller.cc index 37d436a..05f2d98 100644 --- a/components/autofill_assistant/browser/controller.cc +++ b/components/autofill_assistant/browser/controller.cc
@@ -625,6 +625,7 @@ std::unique_ptr<TriggerContext> context, AutofillAssistantState end_state) { DCHECK(!script_tracker()->running()); + EnterState(AutofillAssistantState::RUNNING); touchable_element_area()->Clear(); @@ -777,11 +778,11 @@ state_ != AutofillAssistantState::STOPPED; } -void Controller::Start(const GURL& deeplink_url, +bool Controller::Start(const GURL& deeplink_url, std::unique_ptr<TriggerContext> trigger_context) { if (state_ != AutofillAssistantState::INACTIVE && state_ != AutofillAssistantState::TRACKING) - return; + return false; trigger_context_ = std::move(trigger_context); InitFromParameters(); @@ -795,6 +796,7 @@ IDS_AUTOFILL_ASSISTANT_LOADING, base::UTF8ToUTF16(deeplink_url_.host()))); SetProgress(kAutostartInitialProgress); EnterState(AutofillAssistantState::STARTING); + return true; } AutofillAssistantState Controller::GetState() {
diff --git a/components/autofill_assistant/browser/controller.h b/components/autofill_assistant/browser/controller.h index e63bc5b..9134bd5 100644 --- a/components/autofill_assistant/browser/controller.h +++ b/components/autofill_assistant/browser/controller.h
@@ -81,7 +81,7 @@ // running. // // Start() will overwrite any context previously set by Track(). - void Start(const GURL& deeplink_url, + bool Start(const GURL& deeplink_url, std::unique_ptr<TriggerContext> trigger_context); // Returns true if the controller is in a state where UI is necessary.
diff --git a/components/autofill_assistant/browser/direct_action.cc b/components/autofill_assistant/browser/direct_action.cc index 2ee6ec3..1bdf806 100644 --- a/components/autofill_assistant/browser/direct_action.cc +++ b/components/autofill_assistant/browser/direct_action.cc
@@ -14,7 +14,7 @@ DirectAction::DirectAction(const DirectActionProto& proto) { for (const std::string& name : proto.names()) { - names.emplace_back(name); + names.insert(name); } for (const std::string& argument : proto.required_arguments()) { required_arguments.emplace_back(argument);
diff --git a/components/autofill_assistant/browser/direct_action.h b/components/autofill_assistant/browser/direct_action.h index 8a9a332..4d69ae2 100644 --- a/components/autofill_assistant/browser/direct_action.h +++ b/components/autofill_assistant/browser/direct_action.h
@@ -5,6 +5,7 @@ #ifndef COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_DIRECT_ACTION_H_ #define COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_DIRECT_ACTION_H_ +#include <set> #include <string> #include <vector> @@ -27,7 +28,7 @@ bool empty() const { return names.empty(); } // Names of the direct action under which this action is available. Optional. - std::vector<std::string> names; + std::set<std::string> names; // Arguments that must be set to run the direct action. std::vector<std::string> required_arguments;
diff --git a/components/autofill_assistant/browser/script_tracker.cc b/components/autofill_assistant/browser/script_tracker.cc index 9caa8af..2bfc8423 100644 --- a/components/autofill_assistant/browser/script_tracker.cc +++ b/components/autofill_assistant/browser/script_tracker.cc
@@ -32,8 +32,10 @@ }); } -// Creates a value containing a vector of strings. -base::Value StringVectorToValue(const std::vector<std::string>& v) { +// Creates a value containing a vector of a simple type, accepted by base::Value +// constructor, from a container. +template <typename T> +base::Value ToValueArray(const T& v) { std::vector<base::Value> values; for (const auto& s : v) { values.emplace_back(base::Value(s)); @@ -178,14 +180,13 @@ script_js.SetKey("chip_type", base::Value(entry.chip.type)); base::Value direct_action_js = base::Value(base::Value::Type::DICTIONARY); - direct_action_js.SetKey("names", - StringVectorToValue(entry.direct_action.names)); + direct_action_js.SetKey("names", ToValueArray(entry.direct_action.names)); direct_action_js.SetKey( "required_arguments", - StringVectorToValue(entry.direct_action.required_arguments)); + ToValueArray(entry.direct_action.required_arguments)); direct_action_js.SetKey( "optional_arguments", - StringVectorToValue(entry.direct_action.optional_arguments)); + ToValueArray(entry.direct_action.optional_arguments)); script_js.SetKey("direct_action", std::move(direct_action_js)); runnable_scripts_js.push_back(std::move(script_js));
diff --git a/components/background_task_scheduler/android/proguard.flags b/components/background_task_scheduler/android/proguard.flags index 7840dac4..d727fb7 100644 --- a/components/background_task_scheduler/android/proguard.flags +++ b/components/background_task_scheduler/android/proguard.flags
@@ -3,17 +3,8 @@ # found in the LICENSE file. # Classes are created via reflection and persisted across app updates, so their -# class names must not be obfuscated. --keepnames class ** implements org.chromium.components.background_task_scheduler.BackgroundTask {} - -# Also need to keep their default constructors. --keepclassmembers class ** implements org.chromium.components.background_task_scheduler.BackgroundTask { - public <init>(); -} - -# TODO(agrieve): Delete this rule once r8 is fixed to not discard -# GCMBackgroundTask.<init>() with only the above rules. -# https://issuetracker.google.com/issues/137890409 --keep class ** implements org.chromium.components.background_task_scheduler.BackgroundTask { +# class names must not be obfuscated, and constructors kept. +-if class ** implements org.chromium.components.background_task_scheduler.BackgroundTask +-keep class <1> { public <init>(); }
diff --git a/components/browser_sync/BUILD.gn b/components/browser_sync/BUILD.gn index b2d469e..bd6a0ef 100644 --- a/components/browser_sync/BUILD.gn +++ b/components/browser_sync/BUILD.gn
@@ -86,8 +86,6 @@ "//base/test:test_support", "//components/bookmarks/browser", "//components/history/core/browser", - "//components/signin/core/browser", - "//components/signin/public/base:test_support", "//components/sync", "//components/sync:test_support", "//components/sync_preferences:test_support",
diff --git a/components/cronet/android/BUILD.gn b/components/cronet/android/BUILD.gn index de4455d..d9c9d40 100644 --- a/components/cronet/android/BUILD.gn +++ b/components/cronet/android/BUILD.gn
@@ -339,6 +339,9 @@ android_library("cronet_impl_fake_base_java") { java_files = [ "fake/java/org/chromium/net/test/FakeUrlResponse.java", + "fake/java/org/chromium/net/test/FakeCronetController.java", + "fake/java/org/chromium/net/test/FakeCronetEngine.java", + "fake/java/org/chromium/net/test/FakeCronetProvider.java", "fake/java/org/chromium/net/test/ResponseMatcher.java", "fake/java/org/chromium/net/test/UrlResponseMatcher.java", ] @@ -354,6 +357,9 @@ testonly = true java_files = [ "fake/javatests/org/chromium/net/test/FakeUrlResponseTest.java", + "fake/javatests/org/chromium/net/test/FakeCronetProviderTest.java", + "fake/javatests/org/chromium/net/test/FakeCronetEngineTest.java", + "fake/javatests/org/chromium/net/test/FakeCronetControllerTest.java", "fake/javatests/org/chromium/net/test/UrlResponseMatcherTest.java", ] @@ -361,6 +367,7 @@ ":cronet_api_java", ":cronet_impl_common_base_java", ":cronet_impl_fake_base_java", + ":cronet_impl_platform_base_java", "//base:base_java_test_support", "//third_party/android_sdk:android_test_base_java", "//third_party/android_support_test_runner:runner_java",
diff --git a/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetController.java b/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetController.java new file mode 100644 index 0000000..cd27906 --- /dev/null +++ b/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetController.java
@@ -0,0 +1,209 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.net.test; + +import android.content.Context; + +import org.chromium.net.CronetEngine; +import org.chromium.net.ExperimentalCronetEngine; +import org.chromium.net.UrlRequest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Controller for fake Cronet implementation. Allows a test to setup responses for + * {@link UrlRequest}s. If multiple {@link ResponseMatcher}s match a specific request, the first + * {@link ResponseMatcher} added takes precedence. + */ +public final class FakeCronetController { + // List of FakeCronetEngines so that FakeCronetEngine can be accessed when created with + // the {@link FakeCronetProvider}. + private static final List<CronetEngine> sInstances = + Collections.synchronizedList(new ArrayList<>()); + + // List of ResponseMatchers to be checked for a response to a request in place of a server. + private final List<ResponseMatcher> mResponseMatchers = + Collections.synchronizedList(new ArrayList<>()); + + /** + * Creates a fake {@link CronetEngine.Builder} that creates {@link CronetEngine}s that return + * fake {@link UrlRequests}. Once built, the {@link CronetEngine}'s {@link UrlRequest}s will + * retrieve responses from this {@link FakeCronetController}. + * + * @param context the Android context to build the fake {@link CronetEngine} from. + * @return a fake CronetEngine.Builder that uses this {@link FakeCronetController} to manage + * responses once it is built. + */ + public CronetEngine.Builder newFakeCronetEngineBuilder(Context context) { + FakeCronetEngine.Builder builder = new FakeCronetEngine.Builder(context); + builder.setController(this); + // FakeCronetEngine.Builder is not actually a CronetEngine.Builder, so construct one with + // the child of CronetEngine.Builder: ExperimentalCronetEngine.Builder. + return new ExperimentalCronetEngine.Builder(builder); + } + + /** + * Adds a {@link UrlResponseMatcher} that will respond to the provided URL with the provided + * {@link FakeUrlResponse}. Equivalent to: + * addResponseMatcher(new UrlResponseMatcher(url, response)). + * + * @param response a {@link FakeUrlResponse} to respond with + * @param url a url for which the response should be returned + */ + public void addResponseForUrl(FakeUrlResponse response, String url) { + addResponseMatcher(new UrlResponseMatcher(url, response)); + } + + /** + * Adds a {@link ResponseMatcher} to the list of {@link ResponseMatcher}s. + * + * @param matcher the {@link ResponseMatcher} that should be matched against a request + */ + public void addResponseMatcher(ResponseMatcher matcher) { + mResponseMatchers.add(matcher); + } + + /** + * Removes a specific {@link ResponseMatcher} from the list of {@link ResponseMatcher}s. + * + * @param matcher the {@link ResponseMatcher} to remove + */ + public void removeResponseMatcher(ResponseMatcher matcher) { + mResponseMatchers.remove(matcher); + } + + /** + * Removes all {@link ResponseMatcher}s from the list of {@link ResponseMatcher}s. + */ + public void clearResponseMatchers() { + mResponseMatchers.clear(); + } + + /** + * Adds a {@link FakeUrlResponse} to the list of responses that will redirect a + * {@link UrlRequest} to the specified URL. + * + * @param redirectLocation the URL to redirect the {@link UrlRequest} to + * @param url the URL that will trigger the redirect + */ + public void addRedirectResponse(String redirectLocation, String url) { + FakeUrlResponse redirectResponse = new FakeUrlResponse.Builder() + .setHttpStatusCode(302) + .addHeader("location", redirectLocation) + .build(); + addResponseForUrl(redirectResponse, url); + } + + /** + * Adds an {@link FakeUrlResponse} that fails with the specified HTTP code for the specified + * URL. + * + * @param statusCode the code for the {@link FakeUrlResponse} + * @param url the URL that should trigger the error response when requested by a + * {@link UrlRequest} + * @throws IllegalArgumentException if the HTTP status code is not an error code (code >= 400) + */ + public void addHttpErrorResponse(int statusCode, String url) { + addResponseForUrl(getFailedResponse(statusCode), url); + } + + // TODO(kirchman): Create a function to add a response that takes a CronetException. + + /** + * Adds a successful 200 code {@link FakeUrlResponse} that will match the specified + * URL when requested by a {@link UrlRequest}. + * + * @param url the URL that triggers the successful response + */ + public void addSuccessResponse(String url, String body) { + addResponseForUrl(new FakeUrlResponse.Builder().setResponseBody(body).build(), url); + } + + /** + * Returns the {@link CronetEngineController} for a specified {@link CronetEngine}. This method + * should be used in conjunction with {@link FakeCronetController.getInstances}. + * + * @param engine the fake {@link CronetEngine} to get the controller for. + * @return the controller for the specified fake {@link CronetEngine}. + */ + public static FakeCronetController getControllerForFakeEngine(CronetEngine engine) { + if (engine instanceof FakeCronetEngine) { + FakeCronetEngine fakeEngine = (FakeCronetEngine) engine; + return fakeEngine.getController(); + } + throw new IllegalArgumentException("Provided CronetEngine is not a fake CronetEngine"); + } + + /** + * Returns all created fake instances of {@link CronetEngine} that have not been shut down with + * {@link CronetEngine.shutdown()} in order of creation. Can be used to retrieve a controller + * in conjunction with {@link FakeCronetController.getControllerForFakeEngine}. + * + * @return a list of all fake {@link CronetEngine}s that have been created + */ + public static List<CronetEngine> getFakeCronetEngines() { + synchronized (sInstances) { + return new ArrayList<>(sInstances); + } + } + + /** + * Removes a fake {@link CronetEngine} from the list of {@link CronetEngine} instances. + * + * @param cronetEngine the instance to remove + */ + static void removeFakeCronetEngine(CronetEngine cronetEngine) { + sInstances.remove(cronetEngine); + } + + /** + * Add a CronetEngine to the list of CronetEngines. + * + * @param engine the {@link CronetEngine} to add + */ + static void addFakeCronetEngine(FakeCronetEngine engine) { + sInstances.add(engine); + } + + /** + * Gets a response for specified request details if there is one, or a "404" failed response + * if there is no {@link ResponseMatcher} with a {@link FakeUrlResponse} for this request. + * + * @param url the URL that the {@link UrlRequest} is connecting to + * @param httpMethod the HTTP method that the {@link UrlRequest} is using to connect with + * @param headers the headers supplied by the {@link UrlRequest} + * @return a {@link FakeUrlResponse} if there is one, or a failed "404" response if none found + */ + FakeUrlResponse getResponse( + String url, String httpMethod, List<Map.Entry<String, String>> headers) { + synchronized (mResponseMatchers) { + for (ResponseMatcher responseMatcher : mResponseMatchers) { + FakeUrlResponse matchedResponse = + responseMatcher.getMatchingResponse(url, httpMethod, headers); + if (matchedResponse != null) { + return matchedResponse; + } + } + } + return getFailedResponse(404); + } + + /** + * Creates and returns a failed response with the specified HTTP status code. + * + * @param statusCode the HTTP code that the returned response will have + * @return a {@link FakeUrlResponse} with the specified code + */ + private static FakeUrlResponse getFailedResponse(int statusCode) { + if (statusCode < 400) { + throw new IllegalArgumentException( + "Expected HTTP error code (code >= 400), but was: " + statusCode); + } + return new FakeUrlResponse.Builder().setHttpStatusCode(statusCode).build(); + } +}
diff --git a/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetEngine.java b/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetEngine.java new file mode 100644 index 0000000..f4d04b2 --- /dev/null +++ b/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetEngine.java
@@ -0,0 +1,277 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.net.test; + +import android.content.Context; +import android.support.annotation.GuardedBy; + +import org.chromium.net.BidirectionalStream; +import org.chromium.net.CronetEngine; +import org.chromium.net.ExperimentalBidirectionalStream; +import org.chromium.net.NetworkQualityRttListener; +import org.chromium.net.NetworkQualityThroughputListener; +import org.chromium.net.RequestFinishedInfo; +import org.chromium.net.UrlRequest; +import org.chromium.net.impl.CronetEngineBase; +import org.chromium.net.impl.CronetEngineBuilderImpl; +import org.chromium.net.impl.ImplVersion; +import org.chromium.net.impl.UrlRequestBase; + +import java.io.IOException; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandlerFactory; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executor; + +/** + * Fake {@link CronetEngine}. This implements CronetEngine. + */ +final class FakeCronetEngine extends CronetEngineBase { + /** + * Builds a {@link FakeCronetEngine}. This implements CronetEngine.Builder. + */ + static class Builder extends CronetEngineBuilderImpl { + private FakeCronetController mController; + + /** + * Builder for {@link FakeCronetEngine}. + * + * @param context Android {@link Context}. + */ + Builder(Context context) { + super(context); + } + + @Override + public FakeCronetEngine build() { + return new FakeCronetEngine(this); + } + + void setController(FakeCronetController controller) { + mController = controller; + } + } + + private final FakeCronetController mController; + + private final Object mLock = new Object(); + + @GuardedBy("mLock") + private boolean mIsShutdown; + + @GuardedBy("mLock") + private int mActiveRequestCount; + + /** + * Creates a {@link FakeCronetEngine}. Used when {@link FakeCronetEngine} is created with the + * {@link FakeCronetEngine.Builder}. + * + * @param builder a {@link CronetEngineBuilderImpl} to build this {@link CronetEngine} + * implementation from. + */ + private FakeCronetEngine(FakeCronetEngine.Builder builder) { + if (builder.mController != null) { + mController = builder.mController; + } else { + mController = new FakeCronetController(); + } + FakeCronetController.addFakeCronetEngine(this); + } + + /** + * Gets the controller associated with this instance that will be used for responses to + * {@link UrlRequest}s. + * + * @return the {@link FakeCronetCntroller} that controls this {@link FakeCronetEngine}. + */ + FakeCronetController getController() { + return mController; + } + + @Override + public ExperimentalBidirectionalStream.Builder newBidirectionalStreamBuilder( + String url, BidirectionalStream.Callback callback, Executor executor) { + synchronized (mLock) { + if (mIsShutdown) { + throw new IllegalStateException( + "This instance of CronetEngine has been shutdown and can no longer be " + + "used."); + } + throw new UnsupportedOperationException( + "The bidirectional stream API is not supported by the Fake implementation " + + "of CronetEngine."); + } + } + + @Override + public String getVersionString() { + return "FakeCronet/" + ImplVersion.getCronetVersionWithLastChange(); + } + + @Override + public void shutdown() { + synchronized (mLock) { + if (mActiveRequestCount != 0) { + throw new IllegalStateException("Cannot shutdown with active requests."); + } else { + mIsShutdown = true; + } + } + FakeCronetController.removeFakeCronetEngine(this); + } + + @Override + public void startNetLogToFile(String fileName, boolean logAll) {} + + @Override + public void startNetLogToDisk(String dirPath, boolean logAll, int maxSize) {} + + @Override + public void stopNetLog() {} + + @Override + public byte[] getGlobalMetricsDeltas() { + return new byte[0]; + } + + @Override + public int getEffectiveConnectionType() { + return EFFECTIVE_CONNECTION_TYPE_UNKNOWN; + } + + @Override + public int getHttpRttMs() { + return CONNECTION_METRIC_UNKNOWN; + } + + @Override + public int getTransportRttMs() { + return CONNECTION_METRIC_UNKNOWN; + } + + @Override + public int getDownstreamThroughputKbps() { + return CONNECTION_METRIC_UNKNOWN; + } + + @Override + public void configureNetworkQualityEstimatorForTesting(boolean useLocalHostRequests, + boolean useSmallerResponses, boolean disableOfflineCheck) {} + + @Override + public void addRttListener(NetworkQualityRttListener listener) {} + + @Override + public void removeRttListener(NetworkQualityRttListener listener) {} + + @Override + public void addThroughputListener(NetworkQualityThroughputListener listener) {} + + @Override + public void removeThroughputListener(NetworkQualityThroughputListener listener) {} + + @Override + public void addRequestFinishedListener(RequestFinishedInfo.Listener listener) {} + + @Override + public void removeRequestFinishedListener(RequestFinishedInfo.Listener listener) {} + + // TODO(crbug.com/669707) Instantiate a fake CronetHttpUrlConnection wrapping a FakeUrlRequest + // here. + @Override + public URLConnection openConnection(URL url) throws IOException { + throw new UnsupportedOperationException( + "The openConnection API is not supported by the Fake implementation of " + + "CronetEngine."); + } + + @Override + public URLConnection openConnection(URL url, Proxy proxy) throws IOException { + throw new UnsupportedOperationException( + "The openConnection API is not supported by the Fake implementation of " + + "CronetEngine."); + } + + @Override + public URLStreamHandlerFactory createURLStreamHandlerFactory() { + throw new UnsupportedOperationException( + "The URLStreamHandlerFactory API is not supported by the Fake implementation of " + + "CronetEngine."); + } + + @Override + protected UrlRequestBase createRequest(String url, UrlRequest.Callback callback, + Executor executor, int priority, Collection<Object> connectionAnnotations, + boolean disableCache, boolean disableConnectionMigration, boolean allowDirectExecutor, + boolean trafficStatsTagSet, int trafficStatsTag, boolean trafficStatsUidSet, + int trafficStatsUid, RequestFinishedInfo.Listener requestFinishedListener) { + synchronized (mLock) { + if (mIsShutdown) { + throw new IllegalStateException( + "This instance of CronetEngine has been shutdown and can no longer be " + + "used."); + } + // TODO(kirchman): Implement FakeUrlRequest. + throw new UnsupportedOperationException( + "The UrlRequest API is not supported by the Fake implementation of " + + "CronetEngine."); + } + } + + @Override + protected ExperimentalBidirectionalStream createBidirectionalStream(String url, + BidirectionalStream.Callback callback, Executor executor, String httpMethod, + List<Map.Entry<String, String>> requestHeaders, @StreamPriority int priority, + boolean delayRequestHeadersUntilFirstFlush, Collection<Object> connectionAnnotations, + boolean trafficStatsTagSet, int trafficStatsTag, boolean trafficStatsUidSet, + int trafficStatsUid) { + synchronized (mLock) { + if (mIsShutdown) { + throw new IllegalStateException( + "This instance of CronetEngine has been shutdown and can no longer be " + + "used."); + } + throw new UnsupportedOperationException( + "The BidirectionalStream API is not supported by the Fake implementation of " + + "CronetEngine."); + } + } + + /** + * Mark request as started to prevent shutdown when there are active + * requests, only if the engine is not shutdown. + * + * @return true if the engine is not shutdown and the request is marked as started. + */ + boolean startRequest() { + synchronized (mLock) { + if (!mIsShutdown) { + mActiveRequestCount++; + return true; + } + return false; + } + } + + /** + * Mark request as finished to allow shutdown when there are no active + * requests. + */ + void onRequestDestroyed() { + synchronized (mLock) { + // Sanity check. We should not be able to shutdown if there are still running requests. + if (mIsShutdown) { + throw new IllegalStateException( + "This instance of CronetEngine was shutdown. All requests must have been " + + "complete."); + } + mActiveRequestCount--; + } + } +}
diff --git a/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetProvider.java b/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetProvider.java new file mode 100644 index 0000000..9887689a --- /dev/null +++ b/components/cronet/android/fake/java/org/chromium/net/test/FakeCronetProvider.java
@@ -0,0 +1,70 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.net.test; + +import android.content.Context; + +import org.chromium.net.CronetEngine; +import org.chromium.net.CronetProvider; +import org.chromium.net.ExperimentalCronetEngine; +import org.chromium.net.ICronetEngineBuilder; +import org.chromium.net.impl.ImplVersion; + +import java.util.Arrays; + +/** + * Implementation of {@link CronetProvider} that creates {@link CronetEngine.Builder} + * for building the Fake implementation of {@link CronetEngine}. + * {@hide} + */ +public class FakeCronetProvider extends CronetProvider { + /** + * String returned by {@link CronetProvider#getName} for {@link CronetProvider} + * that provides the fake Cronet implementation. + */ + public static final String PROVIDER_NAME_FAKE = "Fake-Cronet-Provider"; + + /** + * Constructs a {@link FakeCronetProvider}. + * + * @param context Android context to use + */ + public FakeCronetProvider(Context context) { + super(context); + } + + @Override + public CronetEngine.Builder createBuilder() { + ICronetEngineBuilder impl = new FakeCronetEngine.Builder(mContext); + return new ExperimentalCronetEngine.Builder(impl); + } + + @Override + public String getName() { + return PROVIDER_NAME_FAKE; + } + + @Override + public String getVersion() { + return ImplVersion.getCronetVersion(); + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public int hashCode() { + return Arrays.hashCode(new Object[] {FakeCronetProvider.class, mContext}); + } + + @Override + public boolean equals(Object other) { + return other == this + || (other instanceof FakeCronetProvider + && this.mContext.equals(((FakeCronetProvider) other).mContext)); + } +}
diff --git a/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetControllerTest.java b/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetControllerTest.java new file mode 100644 index 0000000..e3182f49 --- /dev/null +++ b/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetControllerTest.java
@@ -0,0 +1,254 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.net.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.net.CronetEngine; +import org.chromium.net.impl.JavaCronetEngineBuilderImpl; + +import java.util.AbstractMap; +import java.util.List; +import java.util.Map; + +/** + * Test functionality of {@link FakeCronetController}. + */ +@RunWith(AndroidJUnit4.class) +public class FakeCronetControllerTest { + Context mContext; + FakeCronetController mFakeCronetController; + + @Before + public void setUp() { + mContext = InstrumentationRegistry.getTargetContext(); + mFakeCronetController = new FakeCronetController(); + } + + @Test + @SmallTest + public void testGetFakeCronetEnginesStartsEmpty() { + List<CronetEngine> engines = FakeCronetController.getFakeCronetEngines(); + assertEquals(0, engines.size()); + } + + @Test + @SmallTest + public void testGetFakeCronetEnginesIncludesCreatedEngineInOrder() { + // Create an instance with the controller. + CronetEngine engine = mFakeCronetController.newFakeCronetEngineBuilder(mContext).build(); + // Create an instance with the provider. + FakeCronetProvider provider = new FakeCronetProvider(mContext); + CronetEngine providerEngine = provider.createBuilder().build(); + List<CronetEngine> engines = FakeCronetController.getFakeCronetEngines(); + + assertTrue(engines.contains(engine)); + assertTrue(engines.contains(providerEngine)); + assertEquals(engine, engines.get(0)); + assertEquals(providerEngine, engines.get(1)); + } + + @Test + @SmallTest + public void testGetControllerGetsCorrectController() { + // Create an instance with the controller. + CronetEngine engine = mFakeCronetController.newFakeCronetEngineBuilder(mContext).build(); + CronetEngine engine2 = mFakeCronetController.newFakeCronetEngineBuilder(mContext).build(); + + // Create two engines with a second controller. + FakeCronetController newController = new FakeCronetController(); + CronetEngine newControllerEngine = + newController.newFakeCronetEngineBuilder(mContext).build(); + CronetEngine newControllerEngine2 = + newController.newFakeCronetEngineBuilder(mContext).build(); + + // Create an instance with the provider. + FakeCronetProvider provider = new FakeCronetProvider(mContext); + CronetEngine providerEngine = provider.createBuilder().build(); + + assertEquals( + mFakeCronetController, FakeCronetController.getControllerForFakeEngine(engine)); + assertEquals( + mFakeCronetController, FakeCronetController.getControllerForFakeEngine(engine2)); + assertEquals(newController, + FakeCronetController.getControllerForFakeEngine(newControllerEngine)); + assertEquals(newController, + FakeCronetController.getControllerForFakeEngine(newControllerEngine2)); + + // TODO(kirchman): Test which controller the provider-created engine uses once the fake + // UrlRequest class has been implemented. + assertNotEquals(mFakeCronetController, + FakeCronetController.getControllerForFakeEngine(providerEngine)); + assertNotEquals( + newController, FakeCronetController.getControllerForFakeEngine(providerEngine)); + assertNotNull(FakeCronetController.getControllerForFakeEngine(providerEngine)); + } + + @Test + @SmallTest + public void testAddNonFakeCronetEngineNotAllowed() { + CronetEngine javaEngine = new JavaCronetEngineBuilderImpl(mContext).build(); + + try { + FakeCronetController.getControllerForFakeEngine(javaEngine); + fail("Should not be able to get a controller for a non-fake CronetEngine."); + } catch (IllegalArgumentException e) { + assertEquals("Provided CronetEngine is not a fake CronetEngine", e.getMessage()); + } + } + + @Test + @SmallTest + public void testShutdownRemovesCronetEngine() { + CronetEngine engine = mFakeCronetController.newFakeCronetEngineBuilder(mContext).build(); + CronetEngine engine2 = mFakeCronetController.newFakeCronetEngineBuilder(mContext).build(); + List<CronetEngine> engines = FakeCronetController.getFakeCronetEngines(); + assertTrue(engines.contains(engine)); + assertTrue(engines.contains(engine2)); + + engine.shutdown(); + engines = FakeCronetController.getFakeCronetEngines(); + + assertFalse(engines.contains(engine)); + assertTrue(engines.contains(engine2)); + } + + @Test + @SmallTest + public void testResponseMatchersConsultedInOrderOfAddition() { + String url = "url"; + FakeUrlResponse response = + new FakeUrlResponse.Builder().setResponseBody("body text").build(); + ResponseMatcher matcher = new UrlResponseMatcher(url, response); + mFakeCronetController.addResponseMatcher(matcher); + mFakeCronetController.addSuccessResponse(url, "different text"); + + FakeUrlResponse foundResponse = + mFakeCronetController.getResponse(new String(url), null, null); + + assertEquals(response, foundResponse); + } + + @Test + @SmallTest + public void testRemoveResponseMatcher() { + String url = "url"; + FakeUrlResponse response = + new FakeUrlResponse.Builder().setResponseBody("body text").build(); + ResponseMatcher matcher = new UrlResponseMatcher(url, response); + mFakeCronetController.addResponseMatcher(matcher); + mFakeCronetController.removeResponseMatcher(matcher); + + FakeUrlResponse foundResponse = mFakeCronetController.getResponse(url, null, null); + + assertEquals(404, foundResponse.getHttpStatusCode()); + assertNotEquals(response, foundResponse); + } + + @Test + @SmallTest + public void testClearResponseMatchers() { + String url = "url"; + FakeUrlResponse response = + new FakeUrlResponse.Builder().setResponseBody("body text").build(); + ResponseMatcher matcher = new UrlResponseMatcher(url, response); + mFakeCronetController.addResponseMatcher(matcher); + mFakeCronetController.clearResponseMatchers(); + + FakeUrlResponse foundResponse = mFakeCronetController.getResponse(url, null, null); + + assertEquals(404, foundResponse.getHttpStatusCode()); + assertNotEquals(response, foundResponse); + } + + @Test + @SmallTest + public void testAddUrlResponseMatcher() { + String url = "url"; + FakeUrlResponse response = + new FakeUrlResponse.Builder().setResponseBody("body text").build(); + mFakeCronetController.addResponseForUrl(response, url); + + FakeUrlResponse foundResponse = mFakeCronetController.getResponse(url, null, null); + + assertEquals(foundResponse, response); + } + + @Test + @SmallTest + public void testDefaultResponseIs404() { + FakeUrlResponse foundResponse = mFakeCronetController.getResponse("url", null, null); + + assertEquals(404, foundResponse.getHttpStatusCode()); + } + + @Test + @SmallTest + public void testAddRedirectResponse() { + String url = "url"; + String location = "/TEST_REDIRECT_LOCATION"; + mFakeCronetController.addRedirectResponse(location, url); + + FakeUrlResponse foundResponse = mFakeCronetController.getResponse("url", null, null); + Map.Entry<String, String> headerEntry = new AbstractMap.SimpleEntry<>("location", location); + + assertTrue(foundResponse.getAllHeadersList().contains(headerEntry)); + assertTrue(foundResponse.getHttpStatusCode() >= 300); + assertTrue(foundResponse.getHttpStatusCode() < 400); + } + + @Test + @SmallTest + public void testAddErrorResponse() { + String url = "url"; + int httpStatusCode = 400; + mFakeCronetController.addHttpErrorResponse(httpStatusCode, url); + + FakeUrlResponse foundResponse = mFakeCronetController.getResponse(url, null, null); + + assertEquals(foundResponse.getHttpStatusCode(), httpStatusCode); + } + + @Test + @SmallTest + public void testAddErrorResponseWithNonErrorCodeThrowsException() { + int nonErrorCode = 200; + try { + mFakeCronetController.addHttpErrorResponse(nonErrorCode, "url"); + fail("Should not be able to add an error response with a non-error code."); + } catch (IllegalArgumentException e) { + assertEquals("Expected HTTP error code (code >= 400), but was: " + nonErrorCode, + e.getMessage()); + } + } + + @Test + @SmallTest + public void testAddSuccessResponse() { + String url = "url"; + String body = "TEST_BODY"; + mFakeCronetController.addSuccessResponse(url, body); + + FakeUrlResponse foundResponse = mFakeCronetController.getResponse(url, null, null); + + assertTrue(foundResponse.getHttpStatusCode() >= 200); + assertTrue(foundResponse.getHttpStatusCode() < 300); + assertEquals(body, foundResponse.getResponseBody()); + } +}
diff --git a/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetEngineTest.java b/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetEngineTest.java new file mode 100644 index 0000000..e8844ef7 --- /dev/null +++ b/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetEngineTest.java
@@ -0,0 +1,303 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.net.test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.net.CronetException; +import org.chromium.net.UrlRequest; +import org.chromium.net.UrlResponseInfo; +import org.chromium.net.impl.ImplVersion; + +import java.net.Proxy; +import java.nio.ByteBuffer; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Test functionality of {@link FakeCronetEngine}. + */ +@RunWith(AndroidJUnit4.class) +public class FakeCronetEngineTest { + Context mContext; + FakeCronetEngine mFakeCronetEngine; + UrlRequest.Callback mCallback; + ExecutorService mExecutor; + + @Before + public void setUp() { + mContext = InstrumentationRegistry.getTargetContext(); + mFakeCronetEngine = + (FakeCronetEngine) new FakeCronetProvider(mContext).createBuilder().build(); + mCallback = new UrlRequest.Callback() { + @Override + public void onRedirectReceived( + UrlRequest request, UrlResponseInfo info, String newLocationUrl) {} + + @Override + public void onResponseStarted(UrlRequest request, UrlResponseInfo info) {} + + @Override + public void onReadCompleted( + UrlRequest request, UrlResponseInfo info, ByteBuffer byteBuffer) {} + + @Override + public void onSucceeded(UrlRequest request, UrlResponseInfo info) {} + + @Override + public void onFailed(UrlRequest request, UrlResponseInfo info, CronetException error) {} + + @Override + public void onCanceled(UrlRequest request, UrlResponseInfo info) {} + }; + mExecutor = Executors.newSingleThreadExecutor(); + } + + @Test + @SmallTest + public void testShutdownEngineThrowsExceptionWhenApiCalled() { + mFakeCronetEngine.shutdown(); + + try { + mFakeCronetEngine.newUrlRequestBuilder("", mCallback, mExecutor).build(); + fail("newUrlRequestBuilder API not checked for shutdown engine."); + } catch (IllegalStateException e) { + assertEquals( + "This instance of CronetEngine has been shutdown and can no longer be used.", + e.getMessage()); + } + } + + @Test + @SmallTest + public void testShutdownEngineThrowsExceptionWhenBidirectionalStreamApiCalled() { + mFakeCronetEngine.shutdown(); + + try { + mFakeCronetEngine.newBidirectionalStreamBuilder("", null, null); + fail("newBidirectionalStreamBuilder API not checked for shutdown engine."); + } catch (IllegalStateException e) { + assertEquals( + "This instance of CronetEngine has been shutdown and can no longer be used.", + e.getMessage()); + } + } + + @Test + @SmallTest + public void testExceptionForNewBidirectionalStreamApi() { + try { + mFakeCronetEngine.newBidirectionalStreamBuilder("", null, null); + fail("newBidirectionalStreamBuilder API should not be available."); + } catch (UnsupportedOperationException e) { + assertEquals("The bidirectional stream API is not supported by the Fake implementation " + + "of CronetEngine.", + e.getMessage()); + } + } + + @Test + @SmallTest + public void testExceptionForNewUrlRequestBuilderApi() { + try { + mFakeCronetEngine.newUrlRequestBuilder("", mCallback, mExecutor).build(); + fail("newUrlRequestBuilder API should not be available."); + } catch (UnsupportedOperationException e) { + assertEquals("The UrlRequest API is not supported by the Fake implementation " + + "of CronetEngine.", + e.getMessage()); + } + } + + @Test + @SmallTest + public void testExceptionForOpenConnectionApi() { + try { + mFakeCronetEngine.openConnection(null); + fail("openConnection API should not be available."); + } catch (Exception e) { + assertEquals("The openConnection API is not supported by the Fake implementation of " + + "CronetEngine.", + e.getMessage()); + } + } + + @Test + @SmallTest + public void testExceptionForOpenConnectionApiWithProxy() { + try { + mFakeCronetEngine.openConnection(null, Proxy.NO_PROXY); + fail("openConnection API should not be available."); + } catch (Exception e) { + assertEquals("The openConnection API is not supported by the Fake implementation of " + + "CronetEngine.", + e.getMessage()); + } + } + + @Test + @SmallTest + public void testExceptionForCreateStreamHandlerFactoryApi() { + try { + mFakeCronetEngine.createURLStreamHandlerFactory(); + fail("createURLStreamHandlerFactory API should not be available."); + } catch (UnsupportedOperationException e) { + assertEquals( + "The URLStreamHandlerFactory API is not supported by the Fake implementation of" + + " CronetEngine.", + e.getMessage()); + } + } + + @Test + @SmallTest + public void testGetVersionString() { + assertEquals("FakeCronet/" + ImplVersion.getCronetVersionWithLastChange(), + mFakeCronetEngine.getVersionString()); + } + + @Test + @SmallTest + public void testStartNetLogToFile() { + mFakeCronetEngine.startNetLogToFile("", false); + } + + @Test + @SmallTest + public void testStartNetLogToDisk() { + mFakeCronetEngine.startNetLogToDisk("", false, 0); + } + + @Test + @SmallTest + public void testStopNetLog() { + mFakeCronetEngine.stopNetLog(); + } + + @Test + @SmallTest + public void testGetGlobalMetricsDeltas() { + assertTrue(mFakeCronetEngine.getGlobalMetricsDeltas().length == 0); + } + + @Test + @SmallTest + public void testGetEffectiveConnectionType() { + assertEquals(FakeCronetEngine.EFFECTIVE_CONNECTION_TYPE_UNKNOWN, + mFakeCronetEngine.getEffectiveConnectionType()); + } + + @Test + @SmallTest + public void testGetHttpRttMs() { + assertEquals(FakeCronetEngine.CONNECTION_METRIC_UNKNOWN, mFakeCronetEngine.getHttpRttMs()); + } + + @Test + @SmallTest + public void testGetTransportRttMs() { + assertEquals( + FakeCronetEngine.CONNECTION_METRIC_UNKNOWN, mFakeCronetEngine.getTransportRttMs()); + } + + @Test + @SmallTest + public void testGetDownstreamThroughputKbps() { + assertEquals(FakeCronetEngine.CONNECTION_METRIC_UNKNOWN, + mFakeCronetEngine.getDownstreamThroughputKbps()); + } + + @Test + @SmallTest + public void testConfigureNetworkQualityEstimatorForTesting() { + mFakeCronetEngine.configureNetworkQualityEstimatorForTesting(false, false, false); + } + + @Test + @SmallTest + public void testAddRttListener() { + mFakeCronetEngine.addRttListener(null); + } + + @Test + @SmallTest + public void testRemoveRttListener() { + mFakeCronetEngine.removeRttListener(null); + } + + @Test + @SmallTest + public void testAddThroughputListener() { + mFakeCronetEngine.addThroughputListener(null); + } + + @Test + @SmallTest + public void testRemoveThroughputListener() { + mFakeCronetEngine.removeThroughputListener(null); + } + + @Test + @SmallTest + public void testAddRequestFinishedListener() { + mFakeCronetEngine.addRequestFinishedListener(null); + } + + @Test + @SmallTest + public void testRemoveRequestFinishedListener() { + mFakeCronetEngine.removeRequestFinishedListener(null); + } + + @Test + @SmallTest + public void testShutdownBlockedWhenRequestCountNotZero() { + // Start a request and verify the engine can't be shutdown. + assertTrue(mFakeCronetEngine.startRequest()); + try { + mFakeCronetEngine.shutdown(); + fail("Shutdown not checked for active requests."); + } catch (IllegalStateException e) { + assertEquals("Cannot shutdown with active requests.", e.getMessage()); + } + + // Finish the request and verify the engine can be shutdown. + mFakeCronetEngine.onRequestDestroyed(); + mFakeCronetEngine.shutdown(); + } + + @Test + @SmallTest + public void testCantStartRequestAfterEngineShutdown() { + mFakeCronetEngine.shutdown(); + assertFalse(mFakeCronetEngine.startRequest()); + } + + @Test + @SmallTest + public void testCantDecrementOnceShutdown() { + mFakeCronetEngine.shutdown(); + + try { + mFakeCronetEngine.onRequestDestroyed(); + fail("onRequestDestroyed not checked for shutdown engine"); + } catch (IllegalStateException e) { + assertEquals("This instance of CronetEngine was shutdown. All requests must have been " + + "complete.", + e.getMessage()); + } + } +}
diff --git a/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetProviderTest.java b/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetProviderTest.java new file mode 100644 index 0000000..a8e4958 --- /dev/null +++ b/components/cronet/android/fake/javatests/org/chromium/net/test/FakeCronetProviderTest.java
@@ -0,0 +1,66 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.net.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.net.impl.ImplVersion; + +/** + * Test functionality of {@link FakeCronetProvider}. + */ +@RunWith(AndroidJUnit4.class) +public class FakeCronetProviderTest { + Context mContext; + FakeCronetProvider mProvider; + + @Before + public void setUp() { + mContext = InstrumentationRegistry.getTargetContext(); + mProvider = new FakeCronetProvider(mContext); + } + + @Test + @SmallTest + public void testGetName() { + String expectedName = "Fake-Cronet-Provider"; + assertEquals(expectedName, mProvider.getName()); + } + + @Test + @SmallTest + public void testGetVersion() { + assertEquals(ImplVersion.getCronetVersion(), mProvider.getVersion()); + } + + @Test + @SmallTest + public void testIsEnabled() { + assertTrue(mProvider.isEnabled()); + } + + @Test + @SmallTest + public void testHashCode() { + FakeCronetProvider otherProvider = new FakeCronetProvider(mContext); + assertEquals(otherProvider.hashCode(), mProvider.hashCode()); + } + + @Test + @SmallTest + public void testEquals() { + assertTrue(mProvider.equals(new FakeCronetProvider(mContext))); + } +}
diff --git a/components/drive/service/drive_api_service.cc b/components/drive/service/drive_api_service.cc index 8cd55ee..c12a253 100644 --- a/components/drive/service/drive_api_service.cc +++ b/components/drive/service/drive_api_service.cc
@@ -223,7 +223,7 @@ } DriveAPIService::DriveAPIService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, base::SequencedTaskRunner* blocking_task_runner, const GURL& base_url,
diff --git a/components/drive/service/drive_api_service.h b/components/drive/service/drive_api_service.h index ac78cf16..01ae61b 100644 --- a/components/drive/service/drive_api_service.h +++ b/components/drive/service/drive_api_service.h
@@ -37,7 +37,7 @@ } // namespace drive } // namespace google_apis -namespace identity { +namespace signin { class IdentityManager; } @@ -109,7 +109,7 @@ // |traffic_annotation| will be used to annotate the network request that will // be created to perform this service. DriveAPIService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, base::SequencedTaskRunner* blocking_task_runner, const GURL& base_url, @@ -267,7 +267,7 @@ // The class is expected to run on UI thread. base::ThreadChecker thread_checker_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; std::unique_ptr<google_apis::RequestSender> sender_;
diff --git a/components/feed/core/feed_networking_host.cc b/components/feed/core/feed_networking_host.cc index 2af229e..bfc314f 100644 --- a/components/feed/core/feed_networking_host.cc +++ b/components/feed/core/feed_networking_host.cc
@@ -31,7 +31,7 @@ #include "services/network/public/cpp/simple_url_loader.h" #include "third_party/zlib/google/compression_utils.h" -using IdentityManager = identity::IdentityManager; +using IdentityManager = signin::IdentityManager; namespace { @@ -69,7 +69,7 @@ void StartAccessTokenFetch(); void AccessTokenFetchFinished(base::TimeTicks token_start_ticks, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); void StartLoader(); std::unique_ptr<network::SimpleURLLoader> MakeLoader(); void SetRequestHeaders(network::ResourceRequest* request) const; @@ -81,7 +81,7 @@ std::string access_token_; const std::vector<uint8_t> request_body_; IdentityManager* const identity_manager_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; std::unique_ptr<network::SimpleURLLoader> simple_loader_; FeedNetworkingHost::ResponseCallback done_callback_; network::SharedURLLoaderFactory* loader_factory_; @@ -129,17 +129,17 @@ identity::ScopeSet scopes{kAuthenticationScope}; // It's safe to pass base::Unretained(this) since deleting the token fetcher // will prevent the callback from being completed. - token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "feed", identity_manager_, scopes, base::BindOnce(&NetworkFetch::AccessTokenFetchFinished, base::Unretained(this), tick_clock_->NowTicks()), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void NetworkFetch::AccessTokenFetchFinished( base::TimeTicks token_start_ticks, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { UMA_HISTOGRAM_ENUMERATION("ContentSuggestions.Feed.Network.TokenFetchStatus", error.state(), GoogleServiceAuthError::NUM_STATES); @@ -290,7 +290,7 @@ } FeedNetworkingHost::FeedNetworkingHost( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const std::string& api_key, scoped_refptr<network::SharedURLLoaderFactory> loader_factory, const base::TickClock* tick_clock)
diff --git a/components/feed/core/feed_networking_host.h b/components/feed/core/feed_networking_host.h index daf11c0..96c118c 100644 --- a/components/feed/core/feed_networking_host.h +++ b/components/feed/core/feed_networking_host.h
@@ -22,7 +22,7 @@ class TickClock; } -namespace identity { +namespace signin { class IdentityManager; } @@ -46,7 +46,7 @@ std::vector<uint8_t> response_bytes)>; FeedNetworkingHost( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const std::string& api_key, scoped_refptr<network::SharedURLLoaderFactory> loader_factory, const base::TickClock* tick_clock); @@ -75,7 +75,7 @@ base::flat_set<std::unique_ptr<NetworkFetch>, base::UniquePtrComparator> pending_requests_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; const std::string api_key_; scoped_refptr<network::SharedURLLoaderFactory> loader_factory_; const base::TickClock* tick_clock_;
diff --git a/components/feed/core/feed_networking_host_unittest.cc b/components/feed/core/feed_networking_host_unittest.cc index e38d912..57c9db4 100644 --- a/components/feed/core/feed_networking_host_unittest.cc +++ b/components/feed/core/feed_networking_host_unittest.cc
@@ -78,7 +78,7 @@ FeedNetworkingHost* service() { return net_service_.get(); } - identity::IdentityTestEnvironment* identity_env() { + signin::IdentityTestEnvironment* identity_env() { return &identity_test_env_; } @@ -140,7 +140,7 @@ base::test::ScopedTaskEnvironment::TimeSource::MOCK_TIME}; private: - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; std::unique_ptr<FeedNetworkingHost> net_service_; network::TestURLLoaderFactory test_factory_; scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_;
diff --git a/components/gcm_driver/account_tracker.cc b/components/gcm_driver/account_tracker.cc index 2ce236d..1a875bc 100644 --- a/components/gcm_driver/account_tracker.cc +++ b/components/gcm_driver/account_tracker.cc
@@ -15,7 +15,7 @@ namespace gcm { AccountTracker::AccountTracker( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : identity_manager_(identity_manager), url_loader_factory_(std::move(url_loader_factory)), @@ -203,7 +203,7 @@ } AccountIdFetcher::AccountIdFetcher( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, AccountTracker* tracker, const std::string& account_key) @@ -226,12 +226,12 @@ account_key_, "gaia_account_tracker", scopes, base::BindOnce(&AccountIdFetcher::AccessTokenFetched, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } void AccountIdFetcher::AccessTokenFetched( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { access_token_fetcher_.reset(); if (error != GoogleServiceAuthError::AuthErrorNone()) {
diff --git a/components/gcm_driver/account_tracker.h b/components/gcm_driver/account_tracker.h index 6061e38..70ae1f6 100644 --- a/components/gcm_driver/account_tracker.h +++ b/components/gcm_driver/account_tracker.h
@@ -18,7 +18,7 @@ class GoogleServiceAuthError; -namespace identity { +namespace signin { struct AccessTokenInfo; } @@ -45,10 +45,10 @@ // 2. Add/Remove and SignIn/SignOut pairs are always generated in order. // 3. SignIn follows Add, and there will be a SignOut between SignIn & Remove. // 4. If there is no primary account, there are no other accounts. -class AccountTracker : public identity::IdentityManager::Observer { +class AccountTracker : public signin::IdentityManager::Observer { public: AccountTracker( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~AccountTracker() override; @@ -80,7 +80,7 @@ bool is_signed_in; }; - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnPrimaryAccountSet( const CoreAccountInfo& primary_account_info) override; void OnPrimaryAccountCleared( @@ -109,7 +109,7 @@ void StartFetchingUserInfo(const std::string& account_key); void DeleteFetcher(AccountIdFetcher* fetcher); - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; std::map<std::string, std::unique_ptr<AccountIdFetcher>> user_info_requests_; std::map<std::string, AccountState> accounts_; @@ -120,7 +120,7 @@ class AccountIdFetcher : public gaia::GaiaOAuthClient::Delegate { public: AccountIdFetcher( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, AccountTracker* tracker, const std::string& account_key); @@ -131,7 +131,7 @@ void Start(); void AccessTokenFetched(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // gaia::GaiaOAuthClient::Delegate implementation. void OnGetUserIdResponse(const std::string& gaia_id) override; @@ -139,12 +139,12 @@ void OnNetworkError(int response_code) override; private: - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; AccountTracker* tracker_; const std::string account_key_; - std::unique_ptr<identity::AccessTokenFetcher> access_token_fetcher_; + std::unique_ptr<signin::AccessTokenFetcher> access_token_fetcher_; std::unique_ptr<gaia::GaiaOAuthClient> gaia_oauth_client_; };
diff --git a/components/gcm_driver/account_tracker_unittest.cc b/components/gcm_driver/account_tracker_unittest.cc index 7846a18..f1da246 100644 --- a/components/gcm_driver/account_tracker_unittest.cc +++ b/components/gcm_driver/account_tracker_unittest.cc
@@ -277,12 +277,12 @@ #if !defined(OS_CHROMEOS) void NotifyLogoutOfPrimaryAccountOnly() { identity_test_env_.ClearPrimaryAccount( - identity::ClearPrimaryAccountPolicy::KEEP_ALL_ACCOUNTS); + signin::ClearPrimaryAccountPolicy::KEEP_ALL_ACCOUNTS); } void NotifyLogoutOfAllAccounts() { identity_test_env_.ClearPrimaryAccount( - identity::ClearPrimaryAccountPolicy::REMOVE_ALL_ACCOUNTS); + signin::ClearPrimaryAccountPolicy::REMOVE_ALL_ACCOUNTS); } #endif @@ -334,7 +334,7 @@ base::test::ScopedTaskEnvironment task_environment_{ base::test::ScopedTaskEnvironment::MainThreadType::IO}; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; std::unique_ptr<AccountTracker> account_tracker_; AccountTrackerObserver observer_;
diff --git a/components/gcm_driver/gcm_account_tracker.cc b/components/gcm_driver/gcm_account_tracker.cc index f68f375..18d7109 100644 --- a/components/gcm_driver/gcm_account_tracker.cc +++ b/components/gcm_driver/gcm_account_tracker.cc
@@ -49,7 +49,7 @@ GCMAccountTracker::GCMAccountTracker( std::unique_ptr<AccountTracker> account_tracker, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, GCMDriver* driver) : account_tracker_(account_tracker.release()), identity_manager_(identity_manager), @@ -115,7 +115,7 @@ void GCMAccountTracker::OnAccessTokenFetchCompleteForAccount( std::string account_id, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { auto iter = account_infos_.find(account_id); DCHECK(iter != account_infos_.end()); if (iter != account_infos_.end()) { @@ -297,13 +297,13 @@ // NOTE: It is safe to use base::Unretained() here as |token_fetcher| is owned // by this object and guarantees that it will not invoke its callback after // its destruction. - std::unique_ptr<identity::AccessTokenFetcher> token_fetcher = + std::unique_ptr<signin::AccessTokenFetcher> token_fetcher = identity_manager_->CreateAccessTokenFetcherForAccount( account_iter->first, kGCMAccountTrackerName, scopes, base::BindOnce( &GCMAccountTracker::OnAccessTokenFetchCompleteForAccount, base::Unretained(this), account_iter->first), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); DCHECK(pending_token_requests_.count(account_iter->first) == 0); pending_token_requests_.emplace(account_iter->first,
diff --git a/components/gcm_driver/gcm_account_tracker.h b/components/gcm_driver/gcm_account_tracker.h index 333761b..79df8202 100644 --- a/components/gcm_driver/gcm_account_tracker.h +++ b/components/gcm_driver/gcm_account_tracker.h
@@ -18,10 +18,10 @@ #include "components/gcm_driver/gcm_connection_observer.h" #include "components/signin/public/identity_manager/access_token_fetcher.h" -namespace identity { +namespace signin { struct AccessTokenInfo; class IdentityManager; -} +} // namespace signin namespace base { class Time; @@ -76,7 +76,7 @@ // |account_tracker| is used to deliver information about the accounts present // in the browser context to |driver|. GCMAccountTracker(std::unique_ptr<AccountTracker> account_tracker, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, GCMDriver* driver); ~GCMAccountTracker() override; @@ -107,7 +107,7 @@ void OnAccessTokenFetchCompleteForAccount( std::string account_id, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // GCMConnectionObserver overrides. void OnConnected(const net::IPEndPoint& ip_endpoint) override; @@ -142,7 +142,7 @@ // Account tracker. std::unique_ptr<AccountTracker> account_tracker_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; GCMDriver* driver_; @@ -156,7 +156,7 @@ // completion or upon signout of the account for which the request is being // made. using AccountIDToTokenFetcherMap = - std::map<std::string, std::unique_ptr<identity::AccessTokenFetcher>>; + std::map<std::string, std::unique_ptr<signin::AccessTokenFetcher>>; AccountIDToTokenFetcherMap pending_token_requests_; // Creates weak pointers used to postpone reporting tokens. See
diff --git a/components/gcm_driver/gcm_account_tracker_unittest.cc b/components/gcm_driver/gcm_account_tracker_unittest.cc index 8edb81f..1364489 100644 --- a/components/gcm_driver/gcm_account_tracker_unittest.cc +++ b/components/gcm_driver/gcm_account_tracker_unittest.cc
@@ -206,7 +206,7 @@ base::test::ScopedTaskEnvironment task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; std::unique_ptr<GCMAccountTracker> tracker_; };
diff --git a/components/gcm_driver/gcm_profile_service.cc b/components/gcm_driver/gcm_profile_service.cc index 3fb0845..b26cf41 100644 --- a/components/gcm_driver/gcm_profile_service.cc +++ b/components/gcm_driver/gcm_profile_service.cc
@@ -38,15 +38,15 @@ // Identity observer only has actual work to do when the user is actually signed // in. It ensures that account tracker is taking class GCMProfileService::IdentityObserver - : public identity::IdentityManager::Observer { + : public signin::IdentityManager::Observer { public: IdentityObserver( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, GCMDriver* driver); ~IdentityObserver() override; - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnPrimaryAccountSet( const CoreAccountInfo& primary_account_info) override; void OnPrimaryAccountCleared( @@ -57,7 +57,7 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); GCMDriver* driver_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; std::unique_ptr<GCMAccountTracker> gcm_account_tracker_; // The account ID that this service is responsible for. Empty when the service @@ -71,7 +71,7 @@ }; GCMProfileService::IdentityObserver::IdentityObserver( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, GCMDriver* driver) : driver_(driver), identity_manager_(identity_manager) { @@ -152,7 +152,7 @@ network::NetworkConnectionTracker* network_connection_tracker, version_info::Channel channel, const std::string& product_category_for_subtypes, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<GCMClientFactory> gcm_client_factory, const scoped_refptr<base::SequencedTaskRunner>& ui_task_runner, const scoped_refptr<base::SequencedTaskRunner>& io_task_runner,
diff --git a/components/gcm_driver/gcm_profile_service.h b/components/gcm_driver/gcm_profile_service.h index 8f3595f..91633d2 100644 --- a/components/gcm_driver/gcm_profile_service.h +++ b/components/gcm_driver/gcm_profile_service.h
@@ -26,7 +26,7 @@ class SequencedTaskRunner; } -namespace identity { +namespace signin { class IdentityManager; } @@ -63,7 +63,7 @@ network::NetworkConnectionTracker* network_connection_tracker, version_info::Channel channel, const std::string& product_category_for_subtypes, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, std::unique_ptr<GCMClientFactory> gcm_client_factory, const scoped_refptr<base::SequencedTaskRunner>& ui_task_runner, const scoped_refptr<base::SequencedTaskRunner>& io_task_runner, @@ -90,7 +90,7 @@ std::unique_ptr<GCMDriver> driver_; #if !BUILDFLAG(USE_GCM_FROM_PLATFORM) - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
diff --git a/components/history/core/browser/web_history_service.cc b/components/history/core/browser/web_history_service.cc index 3ccb0f2..2013cef 100644 --- a/components/history/core/browser/web_history_service.cc +++ b/components/history/core/browser/web_history_service.cc
@@ -83,7 +83,7 @@ friend class history::WebHistoryService; RequestImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const GURL& url, const WebHistoryService::CompletionCallback& callback, @@ -102,7 +102,7 @@ } void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) { @@ -168,11 +168,11 @@ oauth_scopes.insert(kHistoryOAuthScope); access_token_fetcher_ = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "web_history", identity_manager_, oauth_scopes, base::BindOnce(&RequestImpl::OnAccessTokenFetchComplete, base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); is_pending_ = true; } @@ -227,7 +227,7 @@ user_agent_ = user_agent; } - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; // The URL of the API endpoint. @@ -242,7 +242,7 @@ // The user agent header used with this request. std::string user_agent_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; // The current OAuth2 access token. @@ -347,7 +347,7 @@ } WebHistoryService::WebHistoryService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : identity_manager_(identity_manager), url_loader_factory_(std::move(url_loader_factory)) {}
diff --git a/components/history/core/browser/web_history_service.h b/components/history/core/browser/web_history_service.h index 17ef38ef..da530df 100644 --- a/components/history/core/browser/web_history_service.h +++ b/components/history/core/browser/web_history_service.h
@@ -25,7 +25,7 @@ class DictionaryValue; } -namespace identity { +namespace signin { class IdentityManager; } @@ -97,7 +97,7 @@ typedef base::Callback<void(Request*, bool success)> CompletionCallback; WebHistoryService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~WebHistoryService() override; @@ -220,7 +220,7 @@ // Stores pointer to IdentityManager instance. It must outlive the // WebHistoryService and can be null during tests. - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // Request context getter to use. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
diff --git a/components/invalidation/impl/BUILD.gn b/components/invalidation/impl/BUILD.gn index 3d4d86a..67ab71f8 100644 --- a/components/invalidation/impl/BUILD.gn +++ b/components/invalidation/impl/BUILD.gn
@@ -146,7 +146,6 @@ "//components/gcm_driver/instance_id:test_support", "//components/prefs", "//components/prefs:test_support", - "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//components/sync_preferences:test_support", "//google_apis:test_support",
diff --git a/components/invalidation/impl/fcm_invalidation_service_unittest.cc b/components/invalidation/impl/fcm_invalidation_service_unittest.cc index 11845ac..e8a99ce 100644 --- a/components/invalidation/impl/fcm_invalidation_service_unittest.cc +++ b/components/invalidation/impl/fcm_invalidation_service_unittest.cc
@@ -207,7 +207,7 @@ std::unique_ptr<gcm::GCMDriver> gcm_driver_; std::unique_ptr<MockInstanceIDDriver> mock_instance_id_driver_; std::unique_ptr<MockInstanceID> mock_instance_id_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; std::unique_ptr<invalidation::IdentityProvider> identity_provider_; syncer::FCMInvalidationListener* fake_listener_; // Owned by the service. network::TestURLLoaderFactory url_loader_factory_;
diff --git a/components/invalidation/impl/gcm_invalidation_bridge_unittest.cc b/components/invalidation/impl/gcm_invalidation_bridge_unittest.cc index 7d215a7..e8efe7a 100644 --- a/components/invalidation/impl/gcm_invalidation_bridge_unittest.cc +++ b/components/invalidation/impl/gcm_invalidation_bridge_unittest.cc
@@ -99,7 +99,7 @@ } base::test::ScopedTaskEnvironment task_environment_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; std::unique_ptr<gcm::GCMDriver> gcm_driver_; std::unique_ptr<ProfileIdentityProvider> identity_provider_;
diff --git a/components/invalidation/impl/per_user_topic_registration_manager_unittest.cc b/components/invalidation/impl/per_user_topic_registration_manager_unittest.cc index 843009c..7b270ca 100644 --- a/components/invalidation/impl/per_user_topic_registration_manager_unittest.cc +++ b/components/invalidation/impl/per_user_topic_registration_manager_unittest.cc
@@ -187,7 +187,7 @@ network::TestURLLoaderFactory url_loader_factory_; TestingPrefServiceSimple pref_service_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; std::unique_ptr<invalidation::ProfileIdentityProvider> identity_provider_; RegistrationManagerStateObserver state_observer_;
diff --git a/components/invalidation/impl/profile_identity_provider.cc b/components/invalidation/impl/profile_identity_provider.cc index 5e8c649..1917980 100644 --- a/components/invalidation/impl/profile_identity_provider.cc +++ b/components/invalidation/impl/profile_identity_provider.cc
@@ -17,19 +17,18 @@ public: AccessTokenFetcherAdaptor(const CoreAccountId& active_account_id, const std::string& oauth_consumer_name, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const identity::ScopeSet& scopes, ActiveAccountAccessTokenCallback callback); ~AccessTokenFetcherAdaptor() override = default; private: // Invokes |callback_| with (|error|, |access_token_info.token|). - void HandleTokenRequestCompletion( - GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + void HandleTokenRequestCompletion(GoogleServiceAuthError error, + signin::AccessTokenInfo access_token_info); ActiveAccountAccessTokenCallback callback_; - std::unique_ptr<identity::AccessTokenFetcher> access_token_fetcher_; + std::unique_ptr<signin::AccessTokenFetcher> access_token_fetcher_; DISALLOW_COPY_AND_ASSIGN(AccessTokenFetcherAdaptor); }; @@ -37,7 +36,7 @@ AccessTokenFetcherAdaptor::AccessTokenFetcherAdaptor( const CoreAccountId& active_account_id, const std::string& oauth_consumer_name, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const identity::ScopeSet& scopes, ActiveAccountAccessTokenCallback callback) : callback_(std::move(callback)) { @@ -45,12 +44,12 @@ active_account_id, oauth_consumer_name, scopes, base::BindOnce(&AccessTokenFetcherAdaptor::HandleTokenRequestCompletion, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } void AccessTokenFetcherAdaptor::HandleTokenRequestCompletion( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { access_token_fetcher_.reset(); std::move(callback_).Run(error, access_token_info.token); @@ -59,7 +58,7 @@ } // namespace ProfileIdentityProvider::ProfileIdentityProvider( - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : identity_manager_(identity_manager) { identity_manager_->AddObserver(this); }
diff --git a/components/invalidation/impl/profile_identity_provider.h b/components/invalidation/impl/profile_identity_provider.h index 31e0b8cc..09d89e4 100644 --- a/components/invalidation/impl/profile_identity_provider.h +++ b/components/invalidation/impl/profile_identity_provider.h
@@ -14,9 +14,9 @@ // An identity provider implementation that's backed by IdentityManager class ProfileIdentityProvider : public IdentityProvider, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: - ProfileIdentityProvider(identity::IdentityManager* identity_manager); + ProfileIdentityProvider(signin::IdentityManager* identity_manager); ~ProfileIdentityProvider() override; // IdentityProvider: @@ -30,14 +30,14 @@ const std::string& access_token) override; void SetActiveAccountId(const CoreAccountId& account_id) override; - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info) override; void OnRefreshTokenRemovedForAccount( const CoreAccountId& account_id) override; private: - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; CoreAccountId active_account_id_;
diff --git a/components/invalidation/impl/ticl_invalidation_service_unittest.cc b/components/invalidation/impl/ticl_invalidation_service_unittest.cc index 8a13d7d6..03223d2 100644 --- a/components/invalidation/impl/ticl_invalidation_service_unittest.cc +++ b/components/invalidation/impl/ticl_invalidation_service_unittest.cc
@@ -80,7 +80,7 @@ } base::test::ScopedTaskEnvironment scoped_task_environment_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; std::unique_ptr<gcm::GCMDriver> gcm_driver_; std::unique_ptr<invalidation::IdentityProvider> identity_provider_; syncer::FakeInvalidator* fake_invalidator_; // Owned by the service.
diff --git a/components/journey/journey_info_fetcher.cc b/components/journey/journey_info_fetcher.cc index 0a620586..c1d6fcd 100644 --- a/components/journey/journey_info_fetcher.cc +++ b/components/journey/journey_info_fetcher.cc
@@ -19,7 +19,7 @@ } // namespace JourneyInfoFetcher::JourneyInfoFetcher( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const scoped_refptr<network::SharedURLLoaderFactory>& loader_factory) : identity_manager_(identity_manager), loader_factory_(loader_factory) {} @@ -42,18 +42,18 @@ return; OAuth2AccessTokenManager::ScopeSet scopes{kChromeSyncScope}; - token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "journey_info", identity_manager_, scopes, base::BindOnce(&JourneyInfoFetcher::AccessTokenFetchFinished, base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void JourneyInfoFetcher::AccessTokenFetchFinished( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { DCHECK(token_fetcher_); - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_deleter(std::move(token_fetcher_)); if (error.state() != GoogleServiceAuthError::NONE) {
diff --git a/components/journey/journey_info_fetcher.h b/components/journey/journey_info_fetcher.h index e79e5cc..bb1cf0bd 100644 --- a/components/journey/journey_info_fetcher.h +++ b/components/journey/journey_info_fetcher.h
@@ -18,9 +18,9 @@ class Value; } // namespace base -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -37,7 +37,7 @@ class JourneyInfoFetcher { public: JourneyInfoFetcher( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const scoped_refptr<network::SharedURLLoaderFactory>& loader_factory); ~JourneyInfoFetcher(); @@ -60,7 +60,7 @@ const std::string& oauth_access_token); void AccessTokenFetchFinished(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); void AccessTokenError(const GoogleServiceAuthError& error); @@ -73,9 +73,9 @@ base::Optional<base::Value> result, const std::string& error_detail); - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; const scoped_refptr<network::SharedURLLoaderFactory> loader_factory_;
diff --git a/components/journey/journey_info_fetcher_unittest.cc b/components/journey/journey_info_fetcher_unittest.cc index 9033d9ff..789a619 100644 --- a/components/journey/journey_info_fetcher_unittest.cc +++ b/components/journey/journey_info_fetcher_unittest.cc
@@ -136,14 +136,14 @@ return &test_url_loader_factory_; } - identity::IdentityTestEnvironment& identity_test_env() { + signin::IdentityTestEnvironment& identity_test_env() { return identity_test_env_; } private: base::test::ScopedTaskEnvironment scoped_task_environment_; data_decoder::TestingJsonParser::ScopedFactoryOverride factory_override_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; MockFetchResponseAvailableCallback mock_callback_; network::TestURLLoaderFactory test_url_loader_factory_; std::unique_ptr<JourneyInfoFetcher> journey_info_fetcher_;
diff --git a/components/ntp_snippets/content_suggestions_service.cc b/components/ntp_snippets/content_suggestions_service.cc index e7188ed8..f93ac91 100644 --- a/components/ntp_snippets/content_suggestions_service.cc +++ b/components/ntp_snippets/content_suggestions_service.cc
@@ -55,7 +55,7 @@ ContentSuggestionsService::ContentSuggestionsService( State state, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, history::HistoryService* history_service, favicon::LargeIconService* large_icon_service, PrefService* pref_service, @@ -517,7 +517,7 @@ observer.OnSuggestionInvalidated(suggestion_id); } } -// identity::IdentityManager::Observer implementation +// signin::IdentityManager::Observer implementation void ContentSuggestionsService::OnPrimaryAccountSet( const CoreAccountInfo& account_info) { OnSignInStateChanged(/*has_signed_in=*/true);
diff --git a/components/ntp_snippets/content_suggestions_service.h b/components/ntp_snippets/content_suggestions_service.h index 1aff3e3..26533e26 100644 --- a/components/ntp_snippets/content_suggestions_service.h +++ b/components/ntp_snippets/content_suggestions_service.h
@@ -48,7 +48,7 @@ // them grouped into categories. There can be at most one provider per category. class ContentSuggestionsService : public KeyedService, public ContentSuggestionsProvider::Observer, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public history::HistoryServiceObserver { public: class Observer { @@ -97,7 +97,7 @@ ContentSuggestionsService( State state, - identity::IdentityManager* + signin::IdentityManager* identity_manager, // Can be nullptr in unittests. history::HistoryService* history_service, // Can be nullptr in unittests. // Can be nullptr in unittests. @@ -279,7 +279,7 @@ ContentSuggestionsProvider* provider, const ContentSuggestion::ID& suggestion_id) override; - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnPrimaryAccountSet(const CoreAccountInfo& account_info) override; void OnPrimaryAccountCleared(const CoreAccountInfo& account_info) override; @@ -377,7 +377,7 @@ // Observer for the IdentityManager. All observers are notified when the // signin state changes so that they can refresh their list of suggestions. - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; // Observer for the HistoryService. All providers are notified when history is
diff --git a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc index c2cb157..b2143db 100644 --- a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc +++ b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc
@@ -155,7 +155,7 @@ bool RemoteSuggestionsFetcherImpl::skip_api_key_check_for_testing_ = false; RemoteSuggestionsFetcherImpl::RemoteSuggestionsFetcherImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, PrefService* pref_service, UrlLanguageHistogram* language_histogram, @@ -283,17 +283,17 @@ base::Time token_start_time = clock_->Now(); identity::ScopeSet scopes{kContentSuggestionsApiScope}; - token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "ntp_snippets", identity_manager_, scopes, base::BindOnce(&RemoteSuggestionsFetcherImpl::AccessTokenFetchFinished, base::Unretained(this), token_start_time), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void RemoteSuggestionsFetcherImpl::AccessTokenFetchFinished( base::Time token_start_time, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { DCHECK(token_fetcher_); token_fetcher_.reset();
diff --git a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h index 465afa1..23110e3 100644 --- a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h +++ b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h
@@ -27,10 +27,10 @@ class Value; } // namespace base -namespace identity { +namespace signin { class IdentityManager; class PrimaryAccountAccessTokenFetcher; -} // namespace identity +} // namespace signin namespace language { class UrlLanguageHistogram; @@ -47,7 +47,7 @@ class RemoteSuggestionsFetcherImpl : public RemoteSuggestionsFetcher { public: RemoteSuggestionsFetcherImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, PrefService* pref_service, language::UrlLanguageHistogram* language_histogram, @@ -85,7 +85,7 @@ void AccessTokenFetchFinished(base::Time token_start_time, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); void AccessTokenError(const GoogleServiceAuthError& error); void JsonRequestDone(std::unique_ptr<internal::JsonRequest> request, @@ -108,9 +108,9 @@ OptionalFetchedCategories fetched_categories); // Authentication for signed-in users. - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; // Holds the URL loader factory scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
diff --git a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc index 948a8201..42a2904 100644 --- a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc
@@ -256,7 +256,7 @@ base::test::ScopedTaskEnvironment scoped_task_environment_{ base::test::ScopedTaskEnvironment::TimeSource::MOCK_TIME}; std::map<std::string, std::string> default_variation_params_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; network::TestURLLoaderFactory test_url_loader_factory_; private:
diff --git a/components/omnibox/browser/document_suggestions_service.cc b/components/omnibox/browser/document_suggestions_service.cc index 2606da3..9881fee 100644 --- a/components/omnibox/browser/document_suggestions_service.cc +++ b/components/omnibox/browser/document_suggestions_service.cc
@@ -60,7 +60,7 @@ } // namespace DocumentSuggestionsService::DocumentSuggestionsService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : url_loader_factory_(url_loader_factory), identity_manager_(identity_manager), @@ -116,17 +116,17 @@ std::string scope = "https://www.googleapis.com/auth/cloud_search.query"; identity::ScopeSet scopes; scopes.insert(scope); - token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "document_suggestions_service", identity_manager_, scopes, base::BindOnce(&DocumentSuggestionsService::AccessTokenAvailable, base::Unretained(this), std::move(request), std::move(request_body), traffic_annotation, std::move(start_callback), std::move(completion_callback)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void DocumentSuggestionsService::StopCreatingDocumentSuggestionsRequest() { - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_deleter(std::move(token_fetcher_)); } @@ -137,7 +137,7 @@ StartCallback start_callback, CompletionCallback completion_callback, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { DCHECK(token_fetcher_); token_fetcher_.reset();
diff --git a/components/omnibox/browser/document_suggestions_service.h b/components/omnibox/browser/document_suggestions_service.h index fc9591f1..680ba2b 100644 --- a/components/omnibox/browser/document_suggestions_service.h +++ b/components/omnibox/browser/document_suggestions_service.h
@@ -16,10 +16,10 @@ #include "services/network/public/cpp/simple_url_loader.h" #include "url/gurl.h" -namespace identity { +namespace signin { class IdentityManager; class PrimaryAccountAccessTokenFetcher; -} // namespace identity +} // namespace signin class GoogleServiceAuthError; class TemplateURLService; @@ -29,7 +29,7 @@ public: // null may be passed for params, but no request will be issued. DocumentSuggestionsService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~DocumentSuggestionsService() override; @@ -60,7 +60,7 @@ StartCallback start_callback, CompletionCallback completion_callback, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // Activates a loader for |request|, wiring it up to |completion_callback|, // and calls |start_callback|. If |request_body| isn't empty, it will be @@ -74,11 +74,11 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // Helper for fetching OAuth2 access tokens. Non-null when we have a token // available, or while a token fetch is in progress. - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; DISALLOW_COPY_AND_ASSIGN(DocumentSuggestionsService); };
diff --git a/components/omnibox/browser/remote_suggestions_service.cc b/components/omnibox/browser/remote_suggestions_service.cc index 2441a8e..13348bb 100644 --- a/components/omnibox/browser/remote_suggestions_service.cc +++ b/components/omnibox/browser/remote_suggestions_service.cc
@@ -87,7 +87,7 @@ } // namespace RemoteSuggestionsService::RemoteSuggestionsService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : url_loader_factory_(url_loader_factory), identity_manager_(identity_manager), @@ -117,7 +117,7 @@ } void RemoteSuggestionsService::StopCreatingSuggestionsRequest() { - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_deleter(std::move(token_fetcher_)); } @@ -305,13 +305,13 @@ // Create the oauth2 token fetcher. const identity::ScopeSet scopes{ "https://www.googleapis.com/auth/cusco-chrome-extension"}; - token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "remote_suggestions_service", identity_manager_, scopes, base::BindOnce(&RemoteSuggestionsService::AccessTokenAvailable, base::Unretained(this), std::move(request), std::move(request_body), traffic_annotation, std::move(start_callback), std::move(completion_callback)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void RemoteSuggestionsService::AccessTokenAvailable( @@ -321,7 +321,7 @@ StartCallback start_callback, CompletionCallback completion_callback, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { DCHECK(token_fetcher_); token_fetcher_.reset();
diff --git a/components/omnibox/browser/remote_suggestions_service.h b/components/omnibox/browser/remote_suggestions_service.h index 64eddc4..2bff36de 100644 --- a/components/omnibox/browser/remote_suggestions_service.h +++ b/components/omnibox/browser/remote_suggestions_service.h
@@ -19,10 +19,10 @@ namespace base { class Time; } -namespace identity { +namespace signin { class IdentityManager; class PrimaryAccountAccessTokenFetcher; -} // namespace identity +} // namespace signin class GoogleServiceAuthError; class TemplateURLService; @@ -44,7 +44,7 @@ // |identity_manager| may be null but only unauthenticated requests will // issued. RemoteSuggestionsService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~RemoteSuggestionsService() override; @@ -170,7 +170,7 @@ StartCallback start_callback, CompletionCallback completion_callback, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // Activates a loader for |request|, wiring it up to |completion_callback|, // and calls |start_callback|. If |request_body| isn't empty, it will be @@ -183,11 +183,11 @@ CompletionCallback completion_callback); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // Helper for fetching OAuth2 access tokens. This is non-null when an access // token request is currently in progress. - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsService); };
diff --git a/components/password_manager/core/browser/password_form_filling.cc b/components/password_manager/core/browser/password_form_filling.cc index 19269a8..02531a90 100644 --- a/components/password_manager/core/browser/password_form_filling.cc +++ b/components/password_manager/core/browser/password_form_filling.cc
@@ -7,6 +7,7 @@ #include "base/feature_list.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" +#include "components/autofill/core/common/autofill_util.h" #include "components/autofill/core/common/password_form.h" #include "components/autofill/core/common/password_form_fill_data.h" #include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" @@ -149,11 +150,6 @@ base::FeatureList::IsEnabled(features::kFillOnAccountSelectHttp) && !client->IsMainFrameSecure(); - // Suppress autofilling on Android in case the Touch To Fill feature is - // enabled. - const bool enable_touch_to_fill = - base::FeatureList::IsEnabled(features::kTouchToFillAndroid); - // Proceed to autofill. // Note that we provide the choices but don't actually prefill a value if: // (1) we are in Incognito mode, or @@ -177,7 +173,7 @@ wait_for_username_reason = WaitForUsernameReason::kFormNotGoodForFilling; } else if (enable_foas_on_http) { wait_for_username_reason = WaitForUsernameReason::kFoasOnHTTP; - } else if (enable_touch_to_fill) { + } else if (autofill::IsTouchToFillEnabled()) { wait_for_username_reason = WaitForUsernameReason::kTouchToFill; }
diff --git a/components/password_manager/core/browser/password_form_filling_unittest.cc b/components/password_manager/core/browser/password_form_filling_unittest.cc index 42fa14e..f13c7778 100644 --- a/components/password_manager/core/browser/password_form_filling_unittest.cc +++ b/components/password_manager/core/browser/password_form_filling_unittest.cc
@@ -12,6 +12,8 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" #include "base/test/test_mock_time_task_runner.h" +#include "build/build_config.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/password_form.h" #include "components/autofill/core/common/password_form_fill_data.h" #include "components/password_manager/core/browser/password_form_metrics_recorder.h" @@ -254,6 +256,7 @@ } } +#if defined(OS_ANDROID) TEST_F(PasswordFormFillingTest, TouchToFill) { std::map<base::string16, const autofill::PasswordForm*> best_matches; best_matches.emplace(saved_match_.username_value, &saved_match_); @@ -262,7 +265,7 @@ SCOPED_TRACE(testing::Message() << "Enable Touch To Fill: " << std::boolalpha << enable_touch_to_fill); base::test::ScopedFeatureList features; - features.InitWithFeatureState(features::kTouchToFillAndroid, + features.InitWithFeatureState(autofill::features::kTouchToFillAndroid, enable_touch_to_fill); LikelyFormFilling likely_form_filling = SendFillInformationToRenderer( @@ -274,5 +277,6 @@ likely_form_filling); } } +#endif } // namespace password_manager
diff --git a/components/password_manager/core/browser/password_sync_util.cc b/components/password_manager/core/browser/password_sync_util.cc index 92e1b25..7d43c6e7 100644 --- a/components/password_manager/core/browser/password_sync_util.cc +++ b/components/password_manager/core/browser/password_sync_util.cc
@@ -33,7 +33,7 @@ std::string GetSyncUsernameIfSyncingPasswords( const syncer::SyncService* sync_service, - const identity::IdentityManager* identity_manager) { + const signin::IdentityManager* identity_manager) { if (!identity_manager) return std::string(); @@ -47,10 +47,9 @@ return identity_manager->GetPrimaryAccountInfo().email; } -bool IsSyncAccountCredential( - const autofill::PasswordForm& form, - const syncer::SyncService* sync_service, - const identity::IdentityManager* identity_manager) { +bool IsSyncAccountCredential(const autofill::PasswordForm& form, + const syncer::SyncService* sync_service, + const signin::IdentityManager* identity_manager) { if (!IsGaiaCredentialPage(form.signon_realm)) return false; @@ -66,7 +65,7 @@ } bool ShouldSavePasswordHash(const autofill::PasswordForm& form, - const identity::IdentityManager* identity_manager, + const signin::IdentityManager* identity_manager, PrefService* prefs) { #if defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED) bool is_protected_credential_url = @@ -98,7 +97,7 @@ } bool IsSyncAccountEmail(const std::string& username, - const identity::IdentityManager* identity_manager) { + const signin::IdentityManager* identity_manager) { // |identity_manager| can be null if user is not signed in. if (!identity_manager) return false;
diff --git a/components/password_manager/core/browser/password_sync_util.h b/components/password_manager/core/browser/password_sync_util.h index 861597a..ae8097e3c 100644 --- a/components/password_manager/core/browser/password_sync_util.h +++ b/components/password_manager/core/browser/password_sync_util.h
@@ -11,7 +11,7 @@ #include "components/prefs/pref_service.h" #include "components/sync/driver/sync_service.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -25,24 +25,24 @@ // (http://crbug.com/393626). std::string GetSyncUsernameIfSyncingPasswords( const syncer::SyncService* sync_service, - const identity::IdentityManager* identity_manager); + const signin::IdentityManager* identity_manager); // Returns true if |form| corresponds to the account specified by // GetSyncUsernameIfSyncingPasswords. Returns false if // GetSyncUsernameIfSyncingPasswords does not specify any account. bool IsSyncAccountCredential(const autofill::PasswordForm& form, const syncer::SyncService* sync_service, - const identity::IdentityManager* identity_manager); + const signin::IdentityManager* identity_manager); // If |form| doesn't match GAIA sign-on realm or enterprise-specified password // protection URL, returns false. Otherwise, return true. bool ShouldSavePasswordHash(const autofill::PasswordForm& form, - const identity::IdentityManager* identity_manager, + const signin::IdentityManager* identity_manager, PrefService* prefs); // If |username| matches sync account. bool IsSyncAccountEmail(const std::string& username, - const identity::IdentityManager* identity_manager); + const signin::IdentityManager* identity_manager); // If |signon_realm| matches Gaia signon realm. bool IsGaiaCredentialPage(const std::string& signon_realm);
diff --git a/components/password_manager/core/browser/password_sync_util_unittest.cc b/components/password_manager/core/browser/password_sync_util_unittest.cc index 301190e..af91600 100644 --- a/components/password_manager/core/browser/password_sync_util_unittest.cc +++ b/components/password_manager/core/browser/password_sync_util_unittest.cc
@@ -37,7 +37,7 @@ std::string fake_sync_username; std::string expected_result; const syncer::SyncService* sync_service; - const identity::IdentityManager* identity_manager; + const signin::IdentityManager* identity_manager; } kTestCases[] = { {TestCase::NOT_SYNCING_PASSWORDS, "a@example.org", std::string(), sync_service(), identity_manager()},
diff --git a/components/password_manager/core/browser/store_metrics_reporter.cc b/components/password_manager/core/browser/store_metrics_reporter.cc index d4e8104..a967212 100644 --- a/components/password_manager/core/browser/store_metrics_reporter.cc +++ b/components/password_manager/core/browser/store_metrics_reporter.cc
@@ -16,7 +16,7 @@ bool password_manager_enabled, PasswordManagerClient* client, const syncer::SyncService* sync_service, - const identity::IdentityManager* identity_manager, + const signin::IdentityManager* identity_manager, PrefService* prefs) { password_manager::PasswordStore* store = client->GetPasswordStore(); // May be null in tests.
diff --git a/components/password_manager/core/browser/store_metrics_reporter.h b/components/password_manager/core/browser/store_metrics_reporter.h index f0a759a..2d61d82 100644 --- a/components/password_manager/core/browser/store_metrics_reporter.h +++ b/components/password_manager/core/browser/store_metrics_reporter.h
@@ -9,7 +9,7 @@ class PrefService; -namespace identity { +namespace signin { class IdentityManager; } @@ -38,7 +38,7 @@ StoreMetricsReporter(bool password_manager_enabled, PasswordManagerClient* client, const syncer::SyncService* sync_service, - const identity::IdentityManager* identity_manager, + const signin::IdentityManager* identity_manager, PrefService* prefs); ~StoreMetricsReporter();
diff --git a/components/password_manager/core/browser/sync_credentials_filter.h b/components/password_manager/core/browser/sync_credentials_filter.h index eb8197d..dbcac09 100644 --- a/components/password_manager/core/browser/sync_credentials_filter.h +++ b/components/password_manager/core/browser/sync_credentials_filter.h
@@ -16,7 +16,7 @@ #include "components/password_manager/core/browser/password_manager_client.h" #include "components/sync/driver/sync_service.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -28,7 +28,7 @@ using SyncServiceFactoryFunction = base::RepeatingCallback<const syncer::SyncService*(void)>; using IdentityManagerFactoryFunction = - base::RepeatingCallback<const identity::IdentityManager*(void)>; + base::RepeatingCallback<const signin::IdentityManager*(void)>; // Implements protection of sync credentials. Uses |client| to get the last // commited entry URL for a check against GAIA reauth site. Uses the factory
diff --git a/components/password_manager/core/browser/sync_username_test_base.cc b/components/password_manager/core/browser/sync_username_test_base.cc index 86e4ec9..bf541ac 100644 --- a/components/password_manager/core/browser/sync_username_test_base.cc +++ b/components/password_manager/core/browser/sync_username_test_base.cc
@@ -19,7 +19,7 @@ // not allow logging in without a previously log-out. // So make sure tests only log in once and that the email is the same in case // of FakeSigninAs calls roll. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = identity_test_env_.identity_manager(); if (identity_manager->HasPrimaryAccount()) { DCHECK_EQ(identity_manager->GetPrimaryAccountInfo().email, email);
diff --git a/components/password_manager/core/browser/sync_username_test_base.h b/components/password_manager/core/browser/sync_username_test_base.h index 34527ec..330953d 100644 --- a/components/password_manager/core/browser/sync_username_test_base.h +++ b/components/password_manager/core/browser/sync_username_test_base.h
@@ -38,13 +38,13 @@ const syncer::SyncService* sync_service() const { return &sync_service_; } - const identity::IdentityManager* identity_manager() { + const signin::IdentityManager* identity_manager() { return identity_test_env_.identity_manager(); } private: base::test::ScopedTaskEnvironment scoped_task_env_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; syncer::TestSyncService sync_service_; };
diff --git a/components/password_manager/core/common/password_manager_features.cc b/components/password_manager/core/common/password_manager_features.cc index 9e4e1ab0..82b9802 100644 --- a/components/password_manager/core/common/password_manager_features.cc +++ b/components/password_manager/core/common/password_manager_features.cc
@@ -77,10 +77,6 @@ const base::Feature kRecoverPasswordsForSyncUsers = { "RecoverPasswordsForSyncUsers", base::FEATURE_ENABLED_BY_DEFAULT}; -// Enables the touch to fill feature for Android. -const base::Feature kTouchToFillAndroid = {"TouchToFillAndroid", - base::FEATURE_DISABLED_BY_DEFAULT}; - // Forces password generation to ask user to update the password instead of // overwriting silently. const base::Feature kGenerationNoOverwrites = {
diff --git a/components/password_manager/core/common/password_manager_features.h b/components/password_manager/core/common/password_manager_features.h index fec5465..bfb0bf3 100644 --- a/components/password_manager/core/common/password_manager_features.h +++ b/components/password_manager/core/common/password_manager_features.h
@@ -31,7 +31,6 @@ extern const base::Feature kPasswordImport; extern const base::Feature kPasswordManagerOnboardingAndroid; extern const base::Feature kRecoverPasswordsForSyncUsers; -extern const base::Feature kTouchToFillAndroid; extern const base::Feature kGenerationNoOverwrites; extern const base::Feature kUsernameFirstFlow;
diff --git a/components/password_manager/ios/password_form_helper.mm b/components/password_manager/ios/password_form_helper.mm index 8f6f0d98..29f6900c 100644 --- a/components/password_manager/ios/password_form_helper.mm +++ b/components/password_manager/ios/password_form_helper.mm
@@ -99,6 +99,9 @@ // Bridge to observe form activity in |_webState|. std::unique_ptr<autofill::FormActivityObserverBridge> _formActivityObserverBridge; + + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; } #pragma mark - Properties @@ -137,7 +140,8 @@ [weakSelf handleScriptCommand:JSON]; } }); - _webState->AddScriptCommandCallback(callback, kCommandPrefix); + subscription_ = + _webState->AddScriptCommandCallback(callback, kCommandPrefix); } return self; } @@ -146,7 +150,6 @@ - (void)dealloc { if (_webState) { - _webState->RemoveScriptCommandCallback(kCommandPrefix); _webState->RemoveObserver(_webStateObserverBridge.get()); } } @@ -156,7 +159,6 @@ - (void)webStateDestroyed:(web::WebState*)webState { DCHECK_EQ(_webState, webState); if (_webState) { - _webState->RemoveScriptCommandCallback(kCommandPrefix); _webState->RemoveObserver(_webStateObserverBridge.get()); _webState = nullptr; }
diff --git a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.cc b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.cc index 4b30b46..f05f509 100644 --- a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.cc +++ b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.cc
@@ -33,20 +33,20 @@ public: IdentityManagerHelper() = default; - void FetchAccessToken(identity::IdentityManager* identity_manager, + void FetchAccessToken(signin::IdentityManager* identity_manager, const std::string& username, const StringCallback& callback); private: void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); StringCallback callback_; - std::unique_ptr<identity::AccessTokenFetcher> access_token_fetcher_; + std::unique_ptr<signin::AccessTokenFetcher> access_token_fetcher_; }; void CloudPolicyClientRegistrationHelper::IdentityManagerHelper:: - FetchAccessToken(identity::IdentityManager* identity_manager, + FetchAccessToken(signin::IdentityManager* identity_manager, const std::string& account_id, const StringCallback& callback) { DCHECK(!access_token_fetcher_); @@ -65,12 +65,12 @@ base::BindOnce(&CloudPolicyClientRegistrationHelper:: IdentityManagerHelper::OnAccessTokenFetchComplete, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } void CloudPolicyClientRegistrationHelper::IdentityManagerHelper:: OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { DCHECK(access_token_fetcher_); access_token_fetcher_.reset(); @@ -95,7 +95,7 @@ } void CloudPolicyClientRegistrationHelper::StartRegistration( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const std::string& account_id, const base::Closure& callback) { DVLOG(1) << "Starting registration process with account_id";
diff --git a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h index b66ad78..828eddb 100644 --- a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h +++ b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h
@@ -19,7 +19,7 @@ #include "components/policy/policy_export.h" #include "components/policy/proto/device_management_backend.pb.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -46,7 +46,7 @@ // supplied IdentityManager to mint the new token for the userinfo // and DM services, using the |account_id|. // |callback| is invoked when the registration is complete. - void StartRegistration(identity::IdentityManager* identity_manager, + void StartRegistration(signin::IdentityManager* identity_manager, const std::string& account_id, const base::Closure& callback);
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 7d64d1905..dd754292 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -993,6 +993,7 @@ 'CrostiniAllowed', 'DeviceUnaffiliatedCrostiniAllowed', 'CrostiniExportImportUIAllowed', + 'CrostiniRootAccessAllowed', ] }, { @@ -13378,6 +13379,25 @@ 'desc': '''If the policy is set to false, the export / import UI will not be available to users, however it is still possible to use 'lxc' commands directly in the virtual machine to export and import container images.''', }, { + 'name': 'CrostiniRootAccessAllowed', + 'type': 'main', + 'schema': { 'type': 'boolean' }, + 'supported_on': ['chrome_os:77-'], + 'future': True, + 'features': { + 'dynamic_refresh': True, + 'per_profile': True, + }, + 'example_value': False, + 'id': 576, + 'caption': '''User is allowed to have root access to Crostini containers''', + 'tags': ['system-security'], + 'desc': '''Allow this user root access to Crostini containers. + + If the policy is set to true of left unset root access to Crostini containers will be granted to the user. + If the policy is set to false, root access to both existing and new Crostini containers will not be granted to the user.''', + }, + { 'name': 'SafeBrowsingWhitelistDomains', 'type': 'list', 'schema': { @@ -17049,6 +17069,6 @@ ], 'placeholders': [], 'deleted_policy_ids': [412, 546, 562], - 'highest_id_currently_used': 575, + 'highest_id_currently_used': 576, 'highest_atomic_group_id_currently_used': 37 }
diff --git a/components/search_provider_logos/BUILD.gn b/components/search_provider_logos/BUILD.gn index e4ff83bc..5895f9b1 100644 --- a/components/search_provider_logos/BUILD.gn +++ b/components/search_provider_logos/BUILD.gn
@@ -32,7 +32,6 @@ "//components/image_fetcher/core", "//components/keyed_service/core", "//components/search_engines", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//net", "//services/network/public/cpp", @@ -96,7 +95,6 @@ "//base/test:test_support", "//components/image_fetcher/core", "//components/search_engines", - "//components/signin/core/browser", "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//components/sync_preferences:test_support",
diff --git a/components/search_provider_logos/DEPS b/components/search_provider_logos/DEPS index 8805f9d..3f14730 100644 --- a/components/search_provider_logos/DEPS +++ b/components/search_provider_logos/DEPS
@@ -2,25 +2,7 @@ "+components/image_fetcher/core", "+components/keyed_service/core", "+components/search_engines", - "+components/signin/core/browser", - # Use identity_manager.h instead of the below files; - # see https://groups.google.com/a/chromium.org/d/msg/chromium-dev/dgFLuxqZt1o/iEqkyoQQBwAJ for help and info. - "-components/signin/internal/identity_manager/account_fetcher_service.h", - "-components/signin/internal/identity_manager/account_info_fetcher.h", - "-components/signin/internal/identity_manager/account_tracker_service.h", - "-components/signin/internal/identity_manager/child_account_info_fetcher_android.h", - "-components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/gaia_cookie_manager_service.h", - "-components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_helper.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_token_fetcher.h", - "-components/signin/internal/identity_manager/primary_account_manager.h", - "-components/signin/internal/identity_manager/primary_account_policy_manager.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h", - "-components/signin/internal/identity_manager/ubertoken_fetcher_impl.h", "+components/signin/public", - "+components/sync_preferences/testing_pref_service_syncable.h", "+net", "+services/network/public/cpp",
diff --git a/components/search_provider_logos/logo_service_impl.cc b/components/search_provider_logos/logo_service_impl.cc index 1470f59..b3daa5e3 100644 --- a/components/search_provider_logos/logo_service_impl.cc +++ b/components/search_provider_logos/logo_service_impl.cc
@@ -179,7 +179,7 @@ LogoServiceImpl::LogoServiceImpl( const base::FilePath& cache_directory, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, TemplateURLService* template_url_service, std::unique_ptr<image_fetcher::ImageDecoder> image_decoder, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, @@ -731,7 +731,7 @@ } void LogoServiceImpl::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo&, + const signin::AccountsInCookieJarInfo&, const GoogleServiceAuthError&) { // Clear any cached logo, since it may be personalized (e.g. birthday Doodle). if (!clock_) {
diff --git a/components/search_provider_logos/logo_service_impl.h b/components/search_provider_logos/logo_service_impl.h index 3593ead..4d26bf2 100644 --- a/components/search_provider_logos/logo_service_impl.h +++ b/components/search_provider_logos/logo_service_impl.h
@@ -42,11 +42,11 @@ class LogoObserver; class LogoServiceImpl : public LogoService, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: LogoServiceImpl( const base::FilePath& cache_directory, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, TemplateURLService* template_url_service, std::unique_ptr<image_fetcher::ImageDecoder> image_decoder, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, @@ -103,8 +103,8 @@ const int kDownloadOutcomeNotTracked = -1; - // identity::IdentityManager::Observer implementation. - void OnAccountsInCookieUpdated(const identity::AccountsInCookieJarInfo&, + // signin::IdentityManager::Observer implementation. + void OnAccountsInCookieUpdated(const signin::AccountsInCookieJarInfo&, const GoogleServiceAuthError&) override; // Clear any cached logo we might have. Useful on sign-out to get rid of @@ -171,7 +171,7 @@ // Constructor arguments. const base::FilePath cache_directory_; - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; TemplateURLService* const template_url_service_; const scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
diff --git a/components/search_provider_logos/logo_service_impl_unittest.cc b/components/search_provider_logos/logo_service_impl_unittest.cc index 0eeb41d..9e797f3 100644 --- a/components/search_provider_logos/logo_service_impl_unittest.cc +++ b/components/search_provider_logos/logo_service_impl_unittest.cc
@@ -327,14 +327,14 @@ public: explicit SigninHelper() : identity_test_env_(&test_url_loader_factory_) {} - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return identity_test_env_.identity_manager(); } void SignIn() { std::string email("user@gmail.com"); identity_test_env_.SetCookieAccounts( - {{email, identity::GetTestGaiaIdForEmail(email)}}); + {{email, signin::GetTestGaiaIdForEmail(email)}}); } void SignOut() { @@ -343,7 +343,7 @@ private: network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; }; class LogoServiceImplTest : public ::testing::Test {
diff --git a/components/signin/DEPS b/components/signin/DEPS index 49bcd04..8001065 100644 --- a/components/signin/DEPS +++ b/components/signin/DEPS
@@ -7,7 +7,10 @@ "+components/os_crypt", "+components/prefs", "+components/sync_preferences", - "+components/signin", + # Subdirectories of //components/signin must explicitly allow deps on each + # other based on the conceptual deps structure. + "-components/signin", + "+components/signin/public", "+components/user_manager", "+components/webdata/common", "+crypto",
diff --git a/components/signin/core/browser/about_signin_internals.cc b/components/signin/core/browser/about_signin_internals.cc index 8d23fe0..3032fad8 100644 --- a/components/signin/core/browser/about_signin_internals.cc +++ b/components/signin/core/browser/about_signin_internals.cc
@@ -23,7 +23,7 @@ #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/diagnostics_provider.h" #include "components/signin/public/identity_manager/identity_manager.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "components/signin/public/identity_manager/load_credentials_state.h" #include "net/base/backoff_entry.h" namespace { @@ -112,27 +112,27 @@ } std::string TokenServiceLoadCredentialsStateToLabel( - OAuth2TokenServiceDelegate::LoadCredentialsState state) { + signin::LoadCredentialsState state) { switch (state) { - case OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_NOT_STARTED: + case signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED: return "Load credentials not started"; - case OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_IN_PROGRESS: + case signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS: return "Load credentials in progress"; - case OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS: + case signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS: return "Load credentials finished with success"; - case OAuth2TokenServiceDelegate:: + case signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_DB_CANNOT_BE_OPENED: return "Load credentials failed with datase cannot be opened error"; - case OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_DB_ERRORS: + case signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_DB_ERRORS: return "Load credentials failed with database errors"; - case OAuth2TokenServiceDelegate:: + case signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_DECRYPT_ERRORS: return "Load credentials failed with decrypt errors"; - case OAuth2TokenServiceDelegate:: + case signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT: return "Load credentials failed with no refresh token for signed in " "account"; - case OAuth2TokenServiceDelegate:: + case signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_UNKNOWN_ERRORS: return "Load credentials failed with unknown errors"; } @@ -206,7 +206,7 @@ } // anonymous namespace AboutSigninInternals::AboutSigninInternals( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninErrorController* signin_error_controller, signin::AccountConsistencyMethod account_consistency) : identity_manager_(identity_manager), @@ -465,7 +465,7 @@ } void AboutSigninInternals::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { if (error.state() != GoogleServiceAuthError::NONE) return; @@ -596,7 +596,7 @@ std::unique_ptr<base::DictionaryValue> AboutSigninInternals::SigninStatus::ToValue( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninErrorController* signin_error_controller, SigninClient* signin_client, signin::AccountConsistencyMethod account_consistency) { @@ -613,7 +613,7 @@ AddSectionEntry( basic_info, "Signin Status", identity_manager->HasPrimaryAccount() ? "Signed In" : "Not Signed In"); - OAuth2TokenServiceDelegate::LoadCredentialsState load_tokens_state = + signin::LoadCredentialsState load_tokens_state = identity_manager->GetDiagnosticsProvider() ->GetDetailedStateOfLoadingOfRefreshTokens(); AddSectionEntry(basic_info, "TokenService Load Status",
diff --git a/components/signin/core/browser/about_signin_internals.h b/components/signin/core/browser/about_signin_internals.h index 1fcdc99..9b34c7d 100644 --- a/components/signin/core/browser/about_signin_internals.h +++ b/components/signin/core/browser/about_signin_internals.h
@@ -23,7 +23,7 @@ #include "components/signin/public/identity_manager/identity_manager.h" #include "services/identity/public/cpp/scope_set.h" -namespace identity { +namespace signin { struct AccountsInCookieJarInfo; } @@ -39,8 +39,8 @@ class AboutSigninInternals : public KeyedService, public content_settings::Observer, SigninErrorController::Observer, - identity::IdentityManager::Observer, - identity::IdentityManager::DiagnosticsObserver { + signin::IdentityManager::Observer, + signin::IdentityManager::DiagnosticsObserver { public: class Observer { public: @@ -52,7 +52,7 @@ virtual void OnCookieAccountsFetched(const base::DictionaryValue* info) = 0; }; - AboutSigninInternals(identity::IdentityManager* identity_manager, + AboutSigninInternals(signin::IdentityManager* identity_manager, SigninErrorController* signin_error_controller, signin::AccountConsistencyMethod account_consistency); ~AboutSigninInternals() override; @@ -92,9 +92,9 @@ // } std::unique_ptr<base::DictionaryValue> GetSigninStatus(); - // identity::IdentityManager::Observer implementations. + // signin::IdentityManager::Observer implementations. void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; private: @@ -176,7 +176,7 @@ // }], // } std::unique_ptr<base::DictionaryValue> ToValue( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninErrorController* signin_error_controller, SigninClient* signin_client, signin::AccountConsistencyMethod account_consistency); @@ -225,7 +225,7 @@ const std::string& resource_identifier) override; // Weak pointer to the identity manager. - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // Weak pointer to the client. SigninClient* client_;
diff --git a/components/signin/core/browser/account_investigator.cc b/components/signin/core/browser/account_investigator.cc index 0343af6a..ba15883 100644 --- a/components/signin/core/browser/account_investigator.cc +++ b/components/signin/core/browser/account_investigator.cc
@@ -43,7 +43,7 @@ AccountInvestigator::AccountInvestigator( PrefService* pref_service, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : pref_service_(pref_service), identity_manager_(identity_manager) {} AccountInvestigator::~AccountInvestigator() {} @@ -74,7 +74,7 @@ } void AccountInvestigator::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { if (error != GoogleServiceAuthError::AuthErrorNone()) { // If we are pending periodic reporting, leave the flag set, and we will
diff --git a/components/signin/core/browser/account_investigator.h b/components/signin/core/browser/account_investigator.h index 25651d0..0a7b9538 100644 --- a/components/signin/core/browser/account_investigator.h +++ b/components/signin/core/browser/account_investigator.h
@@ -21,9 +21,9 @@ class Time; } // namespace base -namespace identity { +namespace signin { struct AccountsInCookieJarInfo; -} // namespace identity +} // namespace signin namespace signin_metrics { enum class AccountRelation; @@ -35,7 +35,7 @@ // is to watch for changes in relation between Chrome and content area accounts // and emit metrics about their relation. class AccountInvestigator : public KeyedService, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // The targeted interval to perform periodic reporting. If chrome is not // active at the end of an interval, reporting will be done as soon as @@ -43,7 +43,7 @@ static const base::TimeDelta kPeriodicReportingInterval; AccountInvestigator(PrefService* pref_service, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~AccountInvestigator() override; static void RegisterPrefs(PrefRegistrySimple* registry); @@ -54,9 +54,9 @@ // KeyedService: void Shutdown() override; - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; private: @@ -109,7 +109,7 @@ signin_metrics::ReportingType type); PrefService* pref_service_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // Handles invoking our periodic logic at the right time. As part of our // handling of this call we reset the timer for the next loop.
diff --git a/components/signin/core/browser/account_investigator_unittest.cc b/components/signin/core/browser/account_investigator_unittest.cc index 8acfa51..c752ee4 100644 --- a/components/signin/core/browser/account_investigator_unittest.cc +++ b/components/signin/core/browser/account_investigator_unittest.cc
@@ -37,7 +37,7 @@ ~AccountInvestigatorTest() override { investigator_.Shutdown(); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } PrefService* pref_service() { return &prefs_; } @@ -136,7 +136,7 @@ base::test::ScopedTaskEnvironment task_environment_; sync_preferences::TestingPrefServiceSyncable prefs_; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; AccountInvestigator investigator_; std::map<ReportingType, std::string> suffix_ = { {ReportingType::PERIODIC, "_Periodic"}, @@ -162,9 +162,9 @@ // NOTE: IdentityTestEnvironment uses a prefix for generating gaia IDs: // "gaia_id_for_". For this reason, the tests prefix expected account IDs // used so that there is a match. -const std::string kGaiaId1 = identity::GetTestGaiaIdForEmail("1@mail.com"); -const std::string kGaiaId2 = identity::GetTestGaiaIdForEmail("2@mail.com"); -const std::string kGaiaId3 = identity::GetTestGaiaIdForEmail("3@mail.com"); +const std::string kGaiaId1 = signin::GetTestGaiaIdForEmail("1@mail.com"); +const std::string kGaiaId2 = signin::GetTestGaiaIdForEmail("2@mail.com"); +const std::string kGaiaId3 = signin::GetTestGaiaIdForEmail("3@mail.com"); const ListedAccount one(Account(kGaiaId1)); const ListedAccount two(Account(kGaiaId2)); @@ -261,7 +261,7 @@ TEST_F(AccountInvestigatorTest, OnGaiaAccountsInCookieUpdatedError) { const HistogramTester histogram_tester; - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { /*accounts_are_fresh=*/true, just_one, no_accounts}; GoogleServiceAuthError error(GoogleServiceAuthError::SERVICE_UNAVAILABLE); investigator()->OnAccountsInCookieUpdated(accounts_in_cookie_jar_info, error); @@ -271,7 +271,7 @@ TEST_F(AccountInvestigatorTest, OnGaiaAccountsInCookieUpdatedOnChange) { const HistogramTester histogram_tester; - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { /*accounts_are_fresh=*/true, just_one, no_accounts}; investigator()->OnAccountsInCookieUpdated( accounts_in_cookie_jar_info, GoogleServiceAuthError::AuthErrorNone()); @@ -282,14 +282,14 @@ TEST_F(AccountInvestigatorTest, OnGaiaAccountsInCookieUpdatedSigninOnly) { // Initial update to simulate the update on first-time-run. investigator()->OnAccountsInCookieUpdated( - identity::AccountsInCookieJarInfo(), + signin::AccountsInCookieJarInfo(), GoogleServiceAuthError::AuthErrorNone()); const HistogramTester histogram_tester; identity_test_env()->SetPrimaryAccount("1@mail.com"); pref_service()->SetString(prefs::kGaiaCookieHash, Hash(just_one, no_accounts)); - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { /*accounts_are_fresh=*/true, just_one, no_accounts}; investigator()->OnAccountsInCookieUpdated( accounts_in_cookie_jar_info, GoogleServiceAuthError::AuthErrorNone()); @@ -303,7 +303,7 @@ OnGaiaAccountsInCookieUpdatedSigninSignOutOfContent) { const HistogramTester histogram_tester; identity_test_env()->SetPrimaryAccount("1@mail.com"); - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { /*accounts_are_fresh=*/true, just_one, no_accounts}; investigator()->OnAccountsInCookieUpdated( accounts_in_cookie_jar_info, GoogleServiceAuthError::AuthErrorNone()); @@ -353,7 +353,7 @@ std::string email("f@bar.com"); identity_test_env()->SetCookieAccounts( - {{email, identity::GetTestGaiaIdForEmail(email)}}); + {{email, signin::GetTestGaiaIdForEmail(email)}}); EXPECT_FALSE(*periodic_pending()); ExpectSharedReportHistograms(ReportingType::PERIODIC, histogram_tester,
diff --git a/components/signin/core/browser/account_reconcilor.cc b/components/signin/core/browser/account_reconcilor.cc index 474dc938..f609c05f 100644 --- a/components/signin/core/browser/account_reconcilor.cc +++ b/components/signin/core/browser/account_reconcilor.cc
@@ -80,7 +80,7 @@ // Revokes tokens for all accounts in chrome_accounts but the primary account. // Returns true if tokens were revoked, and false if the function did nothing. bool RevokeAllSecondaryTokens( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, signin::AccountReconcilorDelegate::RevokeTokenOption revoke_option, const CoreAccountId& primary_account, bool is_account_consistency_enforced, @@ -141,7 +141,7 @@ // Returns true if gaia_accounts contains an invalid account that is unknown to // the identity manager. bool HasUnknownInvalidAccountInCookie( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const std::vector<gaia::ListedAccount>& gaia_accounts) { for (const gaia::ListedAccount& account : gaia_accounts) { if (!account.valid && @@ -182,7 +182,7 @@ } AccountReconcilor::AccountReconcilor( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* client, std::unique_ptr<signin::AccountReconcilorDelegate> delegate) : delegate_(std::move(delegate)), @@ -476,7 +476,7 @@ // Rely on the IdentityManager to manage calls to and responses from // ListAccounts. - identity::AccountsInCookieJarInfo accounts_in_cookie_jar = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar = identity_manager_->GetAccountsInCookieJar(); if (accounts_in_cookie_jar.accounts_are_fresh) { OnAccountsInCookieUpdated( @@ -548,7 +548,7 @@ } void AccountReconcilor::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { const std::vector<gaia::ListedAccount>& accounts( accounts_in_cookie_jar_info.signed_in_accounts); @@ -694,6 +694,9 @@ DCHECK(delegate_->IsUnknownInvalidAccountInCookieAllowed()) << "Only supported in UPDATE mode"; + delegate_->MaybeLogInconsistencyReason(primary_account, chrome_accounts, + gaia_accounts, first_execution_); + size_t number_gaia_accounts = gaia_accounts.size(); // If there are any accounts in the gaia cookie but not in chrome, then // those accounts need to be removed from the cookie. This means we need
diff --git a/components/signin/core/browser/account_reconcilor.h b/components/signin/core/browser/account_reconcilor.h index f6a37f35..387cd6f 100644 --- a/components/signin/core/browser/account_reconcilor.h +++ b/components/signin/core/browser/account_reconcilor.h
@@ -42,7 +42,7 @@ class AccountReconcilor : public KeyedService, public content_settings::Observer, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // When an instance of this class exists, the account reconcilor is suspended. // It will automatically restart when all instances of Lock have been @@ -94,7 +94,7 @@ }; AccountReconcilor( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* client, std::unique_ptr<signin::AccountReconcilorDelegate> delegate); ~AccountReconcilor() override; @@ -146,6 +146,8 @@ FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorEndpointParamTest, ProfileAlreadyConnected); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestTable, TableRowTest); + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestTable, + InconsistencyReasonLogging); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestDiceMultilogin, TableRowTest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestMirrorMultilogin, TableRowTest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestMiceMultilogin, TableRowTest); @@ -284,15 +286,14 @@ ContentSettingsType content_type, const std::string& resource_identifier) override; - - // Overridden from identity::IdentityManager::Observer. + // Overridden from signin::IdentityManager::Observer. void OnEndBatchOfRefreshTokenStateChanges() override; void OnRefreshTokensLoaded() override; void OnErrorStateOfRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info, const GoogleServiceAuthError& error) override; void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; void OnAccountsCookieDeletedByUserAction() override; @@ -330,7 +331,7 @@ std::unique_ptr<signin::AccountReconcilorDelegate> delegate_; // The IdentityManager associated with this reconcilor. - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // The SigninClient associated with this reconcilor. SigninClient* client_;
diff --git a/components/signin/core/browser/account_reconcilor_delegate.cc b/components/signin/core/browser/account_reconcilor_delegate.cc index 1308b93..3cf1a3b 100644 --- a/components/signin/core/browser/account_reconcilor_delegate.cc +++ b/components/signin/core/browser/account_reconcilor_delegate.cc
@@ -18,6 +18,12 @@ return false; } +void AccountReconcilorDelegate::MaybeLogInconsistencyReason( + const CoreAccountId& primary_account, + const std::vector<CoreAccountId>& chrome_accounts, + const std::vector<gaia::ListedAccount>& gaia_accounts, + bool first_execution) const {} + gaia::GaiaSource AccountReconcilorDelegate::GetGaiaApiSource() const { NOTREACHED() << "Reconcile is not enabled, no Gaia API calls should be made."; return gaia::GaiaSource::kChrome;
diff --git a/components/signin/core/browser/account_reconcilor_delegate.h b/components/signin/core/browser/account_reconcilor_delegate.h index b47ac90..ab7cf8a 100644 --- a/components/signin/core/browser/account_reconcilor_delegate.h +++ b/components/signin/core/browser/account_reconcilor_delegate.h
@@ -43,6 +43,13 @@ // changes to the accounts are made. Defaults to false. virtual bool IsAccountConsistencyEnforced() const; + // Computes inconsistency reason and uploads it to UMA. + virtual void MaybeLogInconsistencyReason( + const CoreAccountId& primary_account, + const std::vector<CoreAccountId>& chrome_accounts, + const std::vector<gaia::ListedAccount>& gaia_accounts, + bool first_execution) const; + // Returns the value to set in the "source" parameter for Gaia API calls. virtual gaia::GaiaSource GetGaiaApiSource() const;
diff --git a/components/signin/core/browser/account_reconcilor_unittest.cc b/components/signin/core/browser/account_reconcilor_unittest.cc index 42bb765..c259b7e 100644 --- a/components/signin/core/browser/account_reconcilor_unittest.cc +++ b/components/signin/core/browser/account_reconcilor_unittest.cc
@@ -97,7 +97,7 @@ class DummyAccountReconcilorWithDelegate : public AccountReconcilor { public: DummyAccountReconcilorWithDelegate( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* client, signin::AccountConsistencyMethod account_consistency) : AccountReconcilor( @@ -115,7 +115,7 @@ // Takes ownership of |delegate|. // gmock can't work with move only parameters. DummyAccountReconcilorWithDelegate( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* client, signin::AccountReconcilorDelegate* delegate) : AccountReconcilor( @@ -131,7 +131,7 @@ static std::unique_ptr<signin::AccountReconcilorDelegate> CreateAccountReconcilorDelegate( SigninClient* signin_client, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, signin::AccountConsistencyMethod account_consistency) { switch (account_consistency) { case signin::AccountConsistencyMethod::kMirror: @@ -162,12 +162,12 @@ : public testing::StrictMock<DummyAccountReconcilorWithDelegate> { public: explicit MockAccountReconcilor( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* client, signin::AccountConsistencyMethod account_consistency); explicit MockAccountReconcilor( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* client, std::unique_ptr<signin::AccountReconcilorDelegate> delegate); @@ -178,7 +178,7 @@ }; MockAccountReconcilor::MockAccountReconcilor( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* client, signin::AccountConsistencyMethod account_consistency) : testing::StrictMock<DummyAccountReconcilorWithDelegate>( @@ -187,7 +187,7 @@ account_consistency) {} MockAccountReconcilor::MockAccountReconcilor( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninClient* client, std::unique_ptr<signin::AccountReconcilorDelegate> delegate) : testing::StrictMock<DummyAccountReconcilorWithDelegate>( @@ -226,7 +226,7 @@ AccountReconcilorTest(); ~AccountReconcilorTest() override; - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } TestSigninClient* test_signin_client() { return &test_signin_client_; } @@ -266,7 +266,7 @@ signin::AccountConsistencyMethod account_consistency_; sync_preferences::TestingPrefServiceSyncable pref_service_; TestSigninClient test_signin_client_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; std::unique_ptr<MockAccountReconcilor> mock_reconcilor_; base::HistogramTester histogram_tester_; @@ -425,6 +425,8 @@ const char* gaia_api_calls_multilogin; const char* tokens_after_reconcile_multilogin; const char* cookies_after_reconcile_multilogin; + // Int represents AccountReconcilorDelegate::InconsistencyReason. + const int inconsistency_reason; }; std::vector<AccountReconcilorTestTableParam> GenerateTestCasesFromParams( @@ -472,11 +474,11 @@ AccountReconcilorTestTable() { accounts_['A'] = {"a@gmail.com", - identity::GetTestGaiaIdForEmail("a@gmail.com")}; + signin::GetTestGaiaIdForEmail("a@gmail.com")}; accounts_['B'] = {"b@gmail.com", - identity::GetTestGaiaIdForEmail("b@gmail.com")}; + signin::GetTestGaiaIdForEmail("b@gmail.com")}; accounts_['C'] = {"c@gmail.com", - identity::GetTestGaiaIdForEmail("c@gmail.com")}; + signin::GetTestGaiaIdForEmail("c@gmail.com")}; } // Build Tokens from string. @@ -556,7 +558,7 @@ identity_test_env()->MakeAccountAvailable(token.email).account_id; } if (token.has_error) { - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_test_env()->identity_manager(), account_id, GoogleServiceAuthError( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)); @@ -727,165 +729,165 @@ // x: The next cookie is marked "invalid". // - First Run: true if this is the first reconcile (i.e. Chrome startup). // ------------------------------------------------------------------------- - // Tokens|Cookies|First Run|Gaia calls|Tokens aft.|Cookies aft.|M.calls| M.Tokens aft.| M.Cookies aft.| + // Tokens|Cookies|First Run|Gaia calls|Tokens aft.|Cookies aft.|M.calls| M.Tokens aft.| M.Cookies aft.| AccountReconcilorDelegate::InconsistencyReason | // ------------------------------------------------------------------------- // First reconcile (Chrome restart): Rebuild the Gaia cookie to match the // tokens. Make the Sync account the default account in the Gaia cookie. // Sync enabled. - { "", "A", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xA"}, - { "*AB", "AB", IsFirstReconcile::kBoth, "", "*AB", "AB", "", "*AB", "AB"}, - { "*A", "A", IsFirstReconcile::kBoth, "", "*A", "A", "", "*A" , "A"}, + { "", "A", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xA", 3}, + { "*AB", "AB", IsFirstReconcile::kBoth, "", "*AB", "AB", "", "*AB", "AB", 0}, + { "*A", "A", IsFirstReconcile::kBoth, "", "*A", "A", "", "*A" , "A", 0}, - { "*A", "", IsFirstReconcile::kFirst, "A", "*A", "A", "UA", "*A" , "A"}, - { "*A", "", IsFirstReconcile::kNotFirst, "A", "*A", "A", "PA", "*A" , "A"}, + { "*A", "", IsFirstReconcile::kFirst, "A", "*A", "A", "UA", "*A" , "A", 1}, + { "*A", "", IsFirstReconcile::kNotFirst, "A", "*A", "A", "PA", "*A" , "A", 1}, - { "*A", "B", IsFirstReconcile::kFirst, "XA", "*A", "A", "UA", "*A" , "A"}, - { "*A", "B", IsFirstReconcile::kNotFirst, "XA", "*A", "A", "PA", "*A" , "xBA"}, + { "*A", "B", IsFirstReconcile::kFirst, "XA", "*A", "A", "UA", "*A" , "A", 1}, + { "*A", "B", IsFirstReconcile::kNotFirst, "XA", "*A", "A", "PA", "*A" , "xBA", 1}, - { "*A", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "PA", "*A" , "AxB"}, + { "*A", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "PA", "*A" , "AxB", 5}, - { "*AB", "BA", IsFirstReconcile::kFirst, "XAB", "*AB", "AB", "UAB", "*AB", "AB"}, - { "*AB", "BA", IsFirstReconcile::kNotFirst, "", "*AB", "BA", "", "*AB", "BA"}, + { "*AB", "BA", IsFirstReconcile::kFirst, "XAB", "*AB", "AB", "UAB", "*AB", "AB", 7}, + { "*AB", "BA", IsFirstReconcile::kNotFirst, "", "*AB", "BA", "", "*AB", "BA", 0}, - { "*AB", "A", IsFirstReconcile::kBoth, "B", "*AB", "AB", "PAB", "*AB", "AB"}, + { "*AB", "A", IsFirstReconcile::kBoth, "B", "*AB", "AB", "PAB", "*AB", "AB", 4}, - { "*AB", "B", IsFirstReconcile::kFirst, "XAB", "*AB", "AB", "UAB", "*AB", "AB"}, - { "*AB", "B", IsFirstReconcile::kNotFirst, "A", "*AB", "BA", "PAB", "*AB", "BA"}, + { "*AB", "B", IsFirstReconcile::kFirst, "XAB", "*AB", "AB", "UAB", "*AB", "AB", 1}, + { "*AB", "B", IsFirstReconcile::kNotFirst, "A", "*AB", "BA", "PAB", "*AB", "BA", 1}, - { "*AB", "", IsFirstReconcile::kFirst, "AB", "*AB", "AB", "UAB", "*AB", "AB"}, - { "*AB", "", IsFirstReconcile::kNotFirst, "AB", "*AB", "AB", "PAB", "*AB", "AB"}, + { "*AB", "", IsFirstReconcile::kFirst, "AB", "*AB", "AB", "UAB", "*AB", "AB", 1}, + { "*AB", "", IsFirstReconcile::kNotFirst, "AB", "*AB", "AB", "PAB", "*AB", "AB", 1}, // Sync enabled, token error on primary. - { "*xAB", "AB", IsFirstReconcile::kBoth, "X", "*xA", "" , "PB", "*xAB", "xAB"}, - { "*xAB", "BA", IsFirstReconcile::kBoth, "XB", "*xAB", "B", "PB", "*xAB", "BxA"}, - { "*xAB", "A", IsFirstReconcile::kBoth, "X", "*xA", "" , "PB", "*xAB", "xAB"}, - { "*xAB", "B", IsFirstReconcile::kBoth, "", "*xAB", "B", "", "*xAB", "B" }, - { "*xAB", "", IsFirstReconcile::kBoth, "B", "*xAB", "B", "PB", "*xAB", "B" }, + { "*xAB", "AB", IsFirstReconcile::kBoth, "X", "*xA", "" , "PB", "*xAB", "xAB", 2}, + { "*xAB", "BA", IsFirstReconcile::kBoth, "XB", "*xAB", "B", "PB", "*xAB", "BxA", 2}, + { "*xAB", "A", IsFirstReconcile::kBoth, "X", "*xA", "" , "PB", "*xAB", "xAB", 2}, + { "*xAB", "B", IsFirstReconcile::kBoth, "", "*xAB", "B", "", "*xAB", "B" , 0}, + { "*xAB", "", IsFirstReconcile::kBoth, "B", "*xAB", "B", "PB", "*xAB", "B" , 0}, // Sync enabled, token error on secondary. - { "*AxB", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "PA", "*A", "AxB"}, + { "*AxB", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "PA", "*A", "AxB", 5}, - { "*AxB", "BA", IsFirstReconcile::kFirst, "XA", "*A", "A", "UA", "*A", "A" }, - { "*AxB", "BA", IsFirstReconcile::kNotFirst, "XA", "*A", "A", "PA", "*A", "xBA"}, + { "*AxB", "BA", IsFirstReconcile::kFirst, "XA", "*A", "A", "UA", "*A", "A" , 5}, + { "*AxB", "BA", IsFirstReconcile::kNotFirst, "XA", "*A", "A", "PA", "*A", "xBA", 5}, - { "*AxB", "A", IsFirstReconcile::kBoth, "", "*A", "A", "", "*A", "A" }, + { "*AxB", "A", IsFirstReconcile::kBoth, "", "*A", "A", "", "*A", "A" , 0 }, - { "*AxB", "B", IsFirstReconcile::kFirst, "XA", "*A", "A", "UA", "*A", "A" }, - { "*AxB", "B", IsFirstReconcile::kNotFirst, "XA", "*A", "A", "PA", "*A", "xBA"}, + { "*AxB", "B", IsFirstReconcile::kFirst, "XA", "*A", "A", "UA", "*A", "A" , 1}, + { "*AxB", "B", IsFirstReconcile::kNotFirst, "XA", "*A", "A", "PA", "*A", "xBA", 1 }, - { "*AxB", "", IsFirstReconcile::kFirst, "A", "*A", "A", "UA", "*A", "A" }, - { "*AxB", "", IsFirstReconcile::kNotFirst, "A", "*A", "A", "PA", "*A", "A"}, + { "*AxB", "", IsFirstReconcile::kFirst, "A", "*A", "A", "UA", "*A", "A", 1}, + { "*AxB", "", IsFirstReconcile::kNotFirst, "A", "*A", "A", "PA", "*A", "A", 1}, // Sync enabled, token error on both accounts. - { "*xAxB", "AB", IsFirstReconcile::kBoth, "X", "*xA", "", "P", "*xA", "xAxB"}, - { "*xAxB", "BA", IsFirstReconcile::kBoth, "X", "*xA", "", "P", "*xA", "xBxA"}, - { "*xAxB", "A", IsFirstReconcile::kBoth, "X", "*xA", "", "P", "*xA", "xA" }, - { "*xAxB", "B", IsFirstReconcile::kBoth, "X", "*xA", "", "P", "*xA", "xB" }, - { "*xAxB", "", IsFirstReconcile::kBoth, "", "*xA", "", "", "*xA", "" }, + { "*xAxB", "AB", IsFirstReconcile::kBoth, "X", "*xA", "", "P", "*xA", "xAxB", 2}, + { "*xAxB", "BA", IsFirstReconcile::kBoth, "X", "*xA", "", "P", "*xA", "xBxA", 2}, + { "*xAxB", "A", IsFirstReconcile::kBoth, "X", "*xA", "", "P", "*xA", "xA", 2}, + { "*xAxB", "B", IsFirstReconcile::kBoth, "X", "*xA", "", "P", "*xA", "xB", 5}, + { "*xAxB", "", IsFirstReconcile::kBoth, "", "*xA", "", "", "*xA", "", 0}, // Sync disabled. - { "AB", "AB", IsFirstReconcile::kBoth, "", "AB", "AB", "", "AB", "AB"}, - { "AB", "BA", IsFirstReconcile::kBoth, "", "AB", "BA", "", "AB", "BA"}, - { "AB", "A", IsFirstReconcile::kBoth, "B", "AB", "AB", "PAB", "AB", "AB"}, - { "AB", "B", IsFirstReconcile::kBoth, "A", "AB", "BA", "PAB", "AB", "BA"}, - { "AB", "", IsFirstReconcile::kBoth, "AB", "AB", "AB", "PAB", "AB", "AB"}, + { "AB", "AB", IsFirstReconcile::kBoth, "", "AB", "AB", "", "AB", "AB", 0}, + { "AB", "BA", IsFirstReconcile::kBoth, "", "AB", "BA", "", "AB", "BA", 0}, + { "AB", "A", IsFirstReconcile::kBoth, "B", "AB", "AB", "PAB", "AB", "AB", 4}, + { "AB", "B", IsFirstReconcile::kBoth, "A", "AB", "BA", "PAB", "AB", "BA", 4}, + { "AB", "", IsFirstReconcile::kBoth, "AB", "AB", "AB", "PAB", "AB", "AB", 0}, // Sync disabled, token error on first account. - { "xAB", "AB", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xAB"}, - { "xAB", "AB", IsFirstReconcile::kNotFirst, "X", "", "" , "PB", "B", "xAB"}, + { "xAB", "AB", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xAB", 3}, + { "xAB", "AB", IsFirstReconcile::kNotFirst, "X", "", "" , "PB", "B", "xAB", 3}, - { "xAB", "BA", IsFirstReconcile::kBoth, "XB", "B", "B", "PB", "B", "BxA"}, + { "xAB", "BA", IsFirstReconcile::kBoth, "XB", "B", "B", "PB", "B", "BxA", 5}, - { "xAB", "A", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xAB"}, - { "xAB", "A", IsFirstReconcile::kNotFirst, "X", "", "" , "PB", "B", "xAB"}, + { "xAB", "A", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xAB", 3}, + { "xAB", "A", IsFirstReconcile::kNotFirst, "X", "", "" , "PB", "B", "xAB", 3}, - { "xAB", "B", IsFirstReconcile::kBoth, "", "B", "B", "", "B", "B"}, + { "xAB", "B", IsFirstReconcile::kBoth, "", "B", "B", "", "B", "B", 0}, - { "xAB", "", IsFirstReconcile::kBoth, "B", "B", "B", "PB", "B", "B"}, + { "xAB", "", IsFirstReconcile::kBoth, "B", "B", "B", "PB", "B", "B", 0}, // Sync disabled, token error on second account . - { "AxB", "AB", IsFirstReconcile::kBoth, "XA", "A", "A", "PA", "A", "AxB"}, + { "AxB", "AB", IsFirstReconcile::kBoth, "XA", "A", "A", "PA", "A", "AxB", 5}, - { "AxB", "BA", IsFirstReconcile::kFirst, "XA", "A", "A", "PA", "A", "xBA"}, - { "AxB", "BA", IsFirstReconcile::kNotFirst, "X", "", "" , "PA", "A", "xBA"}, + { "AxB", "BA", IsFirstReconcile::kFirst, "XA", "A", "A", "PA", "A", "xBA", 3}, + { "AxB", "BA", IsFirstReconcile::kNotFirst, "X", "", "" , "PA", "A", "xBA", 3}, - { "AxB", "A", IsFirstReconcile::kBoth, "", "A", "A", "", "A", "A"}, + { "AxB", "A", IsFirstReconcile::kBoth, "", "A", "A", "", "A", "A", 0}, - { "AxB", "B", IsFirstReconcile::kFirst, "XA", "A", "A", "PA", "A", "xBA"}, - { "AxB", "B", IsFirstReconcile::kNotFirst, "X", "", "" , "PA", "A", "xBA"}, + { "AxB", "B", IsFirstReconcile::kFirst, "XA", "A", "A", "PA", "A", "xBA", 3}, + { "AxB", "B", IsFirstReconcile::kNotFirst, "X", "", "" , "PA", "A", "xBA", 3}, - { "AxB", "", IsFirstReconcile::kBoth, "A", "A", "A", "PA", "A", "A"}, + { "AxB", "", IsFirstReconcile::kBoth, "A", "A", "A", "PA", "A", "A", 0}, // Sync disabled, token error on both accounts. - { "xAxB", "AB", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xAxB"}, - { "xAxB", "BA", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xBxA"}, - { "xAxB", "A", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xA"}, - { "xAxB", "B", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xB"}, - { "xAxB", "", IsFirstReconcile::kBoth, "", "", "", "", "", ""}, + { "xAxB", "AB", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xAxB", 3}, + { "xAxB", "BA", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xBxA", 3}, + { "xAxB", "A", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xA", 3}, + { "xAxB", "B", IsFirstReconcile::kBoth, "X", "", "", "P", "", "xB", 3}, + { "xAxB", "", IsFirstReconcile::kBoth, "", "", "", "", "", "", 0}, // Account marked as invalid in cookies. // No difference between cookies and tokens, do not do do anything. // Do not logout. Regression tests for http://crbug.com/854799 - { "", "xA", IsFirstReconcile::kBoth, "", "", "xA", "", "", "xA"}, - { "", "xAxB", IsFirstReconcile::kBoth, "", "", "xAxB", "", "", "xAxB"}, - { "xA", "xA", IsFirstReconcile::kBoth, "", "", "xA", "", "", "xA"}, - { "xAB", "xAB", IsFirstReconcile::kBoth, "", "B", "xAB", "", "B", "xAB"}, - { "AxB", "AxC", IsFirstReconcile::kBoth, "", "A", "AxC", "", "A", "AxC"}, - { "B", "xAB", IsFirstReconcile::kBoth, "", "B", "xAB", "", "B", "xAB"}, - { "*xA", "xA", IsFirstReconcile::kBoth, "", "*xA", "xA", "", "*xA", "xA"}, - { "*xA", "xB", IsFirstReconcile::kBoth, "", "*xA", "xB", "", "*xA", "xB"}, - { "*xAB", "xAB", IsFirstReconcile::kBoth, "", "*xAB", "xAB", "", "*xAB", "xAB"}, - { "*AxB", "xBA", IsFirstReconcile::kNotFirst, "", "*A", "xBA", "", "*A", "xBA"}, + { "", "xA", IsFirstReconcile::kBoth, "", "", "xA", "", "", "xA", 0}, + { "", "xAxB", IsFirstReconcile::kBoth, "", "", "xAxB", "", "", "xAxB", 0}, + { "xA", "xA", IsFirstReconcile::kBoth, "", "", "xA", "", "", "xA", 0}, + { "xAB", "xAB", IsFirstReconcile::kBoth, "", "B", "xAB", "", "B", "xAB", 0}, + { "AxB", "AxC", IsFirstReconcile::kBoth, "", "A", "AxC", "", "A", "AxC", 0}, + { "B", "xAB", IsFirstReconcile::kBoth, "", "B", "xAB", "", "B", "xAB", 0}, + { "*xA", "xA", IsFirstReconcile::kBoth, "", "*xA", "xA", "", "*xA", "xA", 0}, + { "*xA", "xB", IsFirstReconcile::kBoth, "", "*xA", "xB", "", "*xA", "xB", 0}, + { "*xAB", "xAB", IsFirstReconcile::kBoth, "", "*xAB", "xAB", "", "*xAB", "xAB", 0}, + { "*AxB", "xBA", IsFirstReconcile::kNotFirst, "", "*A", "xBA", "", "*A", "xBA", 0}, // Appending a new cookie after the invalid one. - { "B", "xA", IsFirstReconcile::kBoth, "B", "B", "xAB", "PB", "B", "xAB"}, - { "xAB", "xA", IsFirstReconcile::kBoth, "B", "B", "xAB", "PB", "B", "xAB"}, + { "B", "xA", IsFirstReconcile::kBoth, "B", "B", "xAB", "PB", "B", "xAB", 4}, + { "xAB", "xA", IsFirstReconcile::kBoth, "B", "B", "xAB", "PB", "B", "xAB", 4}, // Refresh existing cookies. - { "AB", "xAB", IsFirstReconcile::kBoth, "A", "AB", "AB", "PAB","AB", "AB"}, - { "*AB", "xBxA", IsFirstReconcile::kNotFirst, "BA", "*AB", "BA", "PAB","*AB", "BA"}, + { "AB", "xAB", IsFirstReconcile::kBoth, "A", "AB", "AB", "PAB","AB", "AB", 4}, + { "*AB", "xBxA", IsFirstReconcile::kNotFirst, "BA", "*AB", "BA", "PAB","*AB", "BA", 1}, // Appending and invalidating cookies at the same time. // Difference should disappear after migrating to Multilogin. - { "xAB", "xAC", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xAxCB"}, - { "xAB", "xAC", IsFirstReconcile::kNotFirst, "X", "", "", "PB", "B", "xAxCB"}, + { "xAB", "xAC", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xAxCB", 6}, + { "xAB", "xAC", IsFirstReconcile::kNotFirst, "X", "", "", "PB", "B", "xAxCB", 6}, - { "xAB", "AxC", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xAxCB"}, - { "xAB", "AxC", IsFirstReconcile::kNotFirst, "X", "", "", "PB", "B", "xAxCB"}, + { "xAB", "AxC", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xAxCB", 3}, + { "xAB", "AxC", IsFirstReconcile::kNotFirst, "X", "", "", "PB", "B", "xAxCB", 3}, - { "*xAB", "xABC", IsFirstReconcile::kFirst, "XB", "*xAB", "B", "PB", "*xAB", "xABxC"}, - { "*xAB", "xABC", IsFirstReconcile::kNotFirst, "X", "*xA", "", "PB", "*xAB", "xABxC"}, + { "*xAB", "xABC", IsFirstReconcile::kFirst, "XB", "*xAB", "B", "PB", "*xAB", "xABxC", 5}, + { "*xAB", "xABC", IsFirstReconcile::kNotFirst, "X", "*xA", "", "PB", "*xAB", "xABxC", 5}, - { "xAB", "xABC", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xABxC"}, - { "xAB", "xABC", IsFirstReconcile::kNotFirst, "X", "", "", "PB", "B", "xABxC"}, + { "xAB", "xABC", IsFirstReconcile::kFirst, "XB", "B", "B", "PB", "B", "xABxC", 5}, + { "xAB", "xABC", IsFirstReconcile::kNotFirst, "X", "", "", "PB", "B", "xABxC", 5}, // Miscellaneous cases. // Check that unknown Gaia accounts are signed out. - { "*A", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "PA", "*A", "AxB"}, + { "*A", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "PA", "*A", "AxB", 5}, // Check that Gaia default account is kept in first position. - { "AB", "BC", IsFirstReconcile::kBoth, "XBA","AB", "BA", "PAB","AB", "BxCA"}, + { "AB", "BC", IsFirstReconcile::kBoth, "XBA","AB", "BA", "PAB","AB", "BxCA", 6}, // Check that Gaia cookie order is preserved for B. - { "*ABC", "CB", IsFirstReconcile::kFirst, "XABC","*ABC", "ABC", "UABC","*ABC","ABC"}, + { "*ABC", "CB", IsFirstReconcile::kFirst, "XABC","*ABC", "ABC", "UABC","*ABC","ABC", 1}, // Required for idempotency check. - { "", "", IsFirstReconcile::kNotFirst, "", "", "", "", "", ""}, - { "", "xA", IsFirstReconcile::kNotFirst, "", "", "xA", "", "", "xA"}, - { "", "xB", IsFirstReconcile::kNotFirst, "", "", "xB", "", "", "xB"}, - { "", "xAxB", IsFirstReconcile::kNotFirst, "", "", "xAxB", "", "", "xAxB"}, - { "", "xBxA", IsFirstReconcile::kNotFirst, "", "", "xBxA", "", "", "xBxA"}, - { "*A", "A", IsFirstReconcile::kNotFirst, "", "*A", "A", "", "*A", "A"}, - { "*A", "xBA", IsFirstReconcile::kNotFirst, "", "*A", "xBA", "", "*A", "xBA"}, - { "*A", "AxB", IsFirstReconcile::kNotFirst, "", "*A", "AxB", "", "*A", "AxB"}, - { "A", "A", IsFirstReconcile::kNotFirst, "", "A", "A", "", "A", "A"}, - { "A", "xBA", IsFirstReconcile::kNotFirst, "", "A", "xBA", "", "A", "xBA"}, - { "A", "AxB", IsFirstReconcile::kNotFirst, "", "A", "AxB", "", "A", "AxB"}, - { "B", "B", IsFirstReconcile::kNotFirst, "", "B", "B", "", "B", "B"}, - { "B", "xAB", IsFirstReconcile::kNotFirst, "", "B", "xAB", "", "B", "xAB"}, - { "B", "BxA", IsFirstReconcile::kNotFirst, "", "B", "BxA", "", "B", "BxA"}, - { "*xA", "", IsFirstReconcile::kNotFirst, "", "*xA", "", "", "*xA", ""}, - { "*xA", "xAxB", IsFirstReconcile::kNotFirst, "", "*xA", "xAxB", "", "*xA", "xAxB"}, - { "*xA", "xBxA", IsFirstReconcile::kNotFirst, "", "*xA", "xBxA", "", "*xA", "xBxA"}, - { "*xA", "xA", IsFirstReconcile::kNotFirst, "", "*xA", "xA", "", "*xA", "xA"}, - { "*xA", "xB", IsFirstReconcile::kNotFirst, "", "*xA", "xB", "", "*xA", "xB"}, - { "*xAB", "B", IsFirstReconcile::kNotFirst, "", "*xAB", "B", "", "*xAB", "B"}, - { "*xAB", "BxA", IsFirstReconcile::kNotFirst, "", "*xAB", "BxA", "", "*xAB", "BxA"}, - { "*xAB", "xAB", IsFirstReconcile::kNotFirst, "", "*xAB", "xAB", "", "*xAB", "xAB"}, - { "*xAB", "xABxC",IsFirstReconcile::kNotFirst, "", "*xAB", "xABxC","", "*xAB", "xABxC"}, - { "A", "AxC", IsFirstReconcile::kNotFirst, "", "A", "AxC", "", "A", "AxC"}, - { "AB", "BxCA", IsFirstReconcile::kNotFirst, "", "AB", "BxCA", "", "AB", "BxCA"}, - { "B", "xABxC",IsFirstReconcile::kNotFirst, "", "B", "xABxC","", "B", "xABxC"}, - { "B", "xAxCB",IsFirstReconcile::kNotFirst, "", "B", "xAxCB","", "B", "xAxCB"}, - { "*ABC", "ACB", IsFirstReconcile::kNotFirst, "", "*ABC", "ACB", "", "*ABC", "ACB"}, - { "*ABC", "ABC", IsFirstReconcile::kNotFirst, "", "*ABC", "ABC", "", "*ABC", "ABC"} + { "", "", IsFirstReconcile::kNotFirst, "", "", "", "", "", "", 0}, + { "", "xA", IsFirstReconcile::kNotFirst, "", "", "xA", "", "", "xA", 0}, + { "", "xB", IsFirstReconcile::kNotFirst, "", "", "xB", "", "", "xB", 0}, + { "", "xAxB", IsFirstReconcile::kNotFirst, "", "", "xAxB", "", "", "xAxB", 0}, + { "", "xBxA", IsFirstReconcile::kNotFirst, "", "", "xBxA", "", "", "xBxA", 0}, + { "*A", "A", IsFirstReconcile::kNotFirst, "", "*A", "A", "", "*A", "A", 0}, + { "*A", "xBA", IsFirstReconcile::kNotFirst, "", "*A", "xBA", "", "*A", "xBA", 0}, + { "*A", "AxB", IsFirstReconcile::kNotFirst, "", "*A", "AxB", "", "*A", "AxB", 0}, + { "A", "A", IsFirstReconcile::kNotFirst, "", "A", "A", "", "A", "A", 0}, + { "A", "xBA", IsFirstReconcile::kNotFirst, "", "A", "xBA", "", "A", "xBA", 0}, + { "A", "AxB", IsFirstReconcile::kNotFirst, "", "A", "AxB", "", "A", "AxB", 0}, + { "B", "B", IsFirstReconcile::kNotFirst, "", "B", "B", "", "B", "B", 0}, + { "B", "xAB", IsFirstReconcile::kNotFirst, "", "B", "xAB", "", "B", "xAB", 0}, + { "B", "BxA", IsFirstReconcile::kNotFirst, "", "B", "BxA", "", "B", "BxA", 0}, + { "*xA", "", IsFirstReconcile::kNotFirst, "", "*xA", "", "", "*xA", "", 0}, + { "*xA", "xAxB", IsFirstReconcile::kNotFirst, "", "*xA", "xAxB", "", "*xA", "xAxB", 0}, + { "*xA", "xBxA", IsFirstReconcile::kNotFirst, "", "*xA", "xBxA", "", "*xA", "xBxA", 0}, + { "*xA", "xA", IsFirstReconcile::kNotFirst, "", "*xA", "xA", "", "*xA", "xA", 0}, + { "*xA", "xB", IsFirstReconcile::kNotFirst, "", "*xA", "xB", "", "*xA", "xB", 0}, + { "*xAB", "B", IsFirstReconcile::kNotFirst, "", "*xAB", "B", "", "*xAB", "B", 0}, + { "*xAB", "BxA", IsFirstReconcile::kNotFirst, "", "*xAB", "BxA", "", "*xAB", "BxA", 0}, + { "*xAB", "xAB", IsFirstReconcile::kNotFirst, "", "*xAB", "xAB", "", "*xAB", "xAB", 0}, + { "*xAB", "xABxC",IsFirstReconcile::kNotFirst, "", "*xAB", "xABxC","", "*xAB", "xABxC", 0}, + { "A", "AxC", IsFirstReconcile::kNotFirst, "", "A", "AxC", "", "A", "AxC", 0}, + { "AB", "BxCA", IsFirstReconcile::kNotFirst, "", "AB", "BxCA", "", "AB", "BxCA", 0}, + { "B", "xABxC",IsFirstReconcile::kNotFirst, "", "B", "xABxC","", "B", "xABxC", 0}, + { "B", "xAxCB",IsFirstReconcile::kNotFirst, "", "B", "xAxCB","", "B", "xAxCB", 0}, + { "*ABC", "ACB", IsFirstReconcile::kNotFirst, "", "*ABC", "ACB", "", "*ABC", "ACB", 0}, + { "*ABC", "ABC", IsFirstReconcile::kNotFirst, "", "*ABC", "ABC", "", "*ABC", "ABC", 0} }; // clang-format on @@ -948,7 +950,7 @@ AccountReconcilor* reconcilor = GetMockReconcilor(); ASSERT_TRUE(reconcilor->first_execution_); reconcilor->first_execution_ = - GetParam().is_first_reconcile == IsFirstReconcile::kFirst ? true : false; + GetParam().is_first_reconcile == IsFirstReconcile::kFirst; reconcilor->StartReconcile(); for (int i = 0; GetParam().gaia_api_calls[i] != '\0'; ++i) { if (GetParam().gaia_api_calls[i] == 'X') @@ -984,6 +986,44 @@ base::RunLoop().RunUntilIdle(); } +// Checks one row of the kDiceParams table above. +TEST_P(AccountReconcilorTestTable, InconsistencyReasonLogging) { + // Enable Dice Migration. + SetAccountConsistency(signin::AccountConsistencyMethod::kDiceMigration); + // Setup cookies. + std::vector<Cookie> cookies = ParseCookieString(GetParam().cookies); + ConfigureCookieManagerService(cookies); + // Setup tokens. This triggers listing cookies so we need to setup cookies + // before that. + SetupTokens(); + // Call list accounts now so that the next call completes synchronously. + identity_test_env()->identity_manager()->GetAccountsInCookieJar(); + base::RunLoop().RunUntilIdle(); + + EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(testing::_)) + .WillRepeatedly(testing::Return()); + EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()) + .WillRepeatedly(testing::Return()); + // Reconcile. + AccountReconcilor* reconcilor = GetMockReconcilor(); + bool first_execution = + GetParam().is_first_reconcile == IsFirstReconcile::kFirst; + reconcilor->first_execution_ = first_execution; + reconcilor->StartReconcile(); + reconcilor->add_to_cookie_.clear(); + reconcilor->CalculateIfReconcileIsDone(); + ASSERT_FALSE(reconcilor->is_reconcile_started_); + std::string histogram_name_suffix = + first_execution ? "FirstExecution" : "NotFirstExecution"; + + histogram_tester()->ExpectUniqueSample( + "Signin.DiceMigrationNotReady.Reason." + histogram_name_suffix, + GetParam().inconsistency_reason, 1); + + ConfigureCookieManagerService({}); + base::RunLoop().RunUntilIdle(); +} + INSTANTIATE_TEST_SUITE_P( DiceTable, AccountReconcilorTestTable, @@ -1178,7 +1218,7 @@ DiceReconcileReuseGaiaFirstAccount) { // Add account "other" to the Gaia cookie. signin::SetListAccountsResponseTwoAccounts( - "other@gmail.com", identity::GetTestGaiaIdForEmail("other@gmail.com"), + "other@gmail.com", signin::GetTestGaiaIdForEmail("other@gmail.com"), "foo@gmail.com", "9999", &test_url_loader_factory_); // Add accounts "user" and "other" to the token service. @@ -1236,8 +1276,8 @@ // Making account available (setting a refresh token) triggers listing cookies // so we need to setup cookies before that. signin::SetListAccountsResponseTwoAccounts( - "other@gmail.com", identity::GetTestGaiaIdForEmail("other@gmail.com"), - "user@gmail.com", identity::GetTestGaiaIdForEmail("user@gmail.com"), + "other@gmail.com", signin::GetTestGaiaIdForEmail("other@gmail.com"), + "user@gmail.com", signin::GetTestGaiaIdForEmail("user@gmail.com"), &test_url_loader_factory_); AccountInfo account_info_1 = @@ -1390,7 +1430,7 @@ // (setting a refresh token) triggers listing cookies so we need to setup // cookies before that. signin::SetListAccountsResponseOneAccount( - "user@gmail.com", identity::GetTestGaiaIdForEmail("user@gmail.com"), + "user@gmail.com", signin::GetTestGaiaIdForEmail("user@gmail.com"), &test_url_loader_factory_); AccountInfo account_info = identity_test_env()->MakeAccountAvailable("user@gmail.com"); @@ -1423,7 +1463,7 @@ // (setting a refresh token) triggers listing cookies so we need to setup // cookies before that. signin::SetListAccountsResponseOneAccount( - "user@gmail.com", identity::GetTestGaiaIdForEmail("user@gmail.com"), + "user@gmail.com", signin::GetTestGaiaIdForEmail("user@gmail.com"), &test_url_loader_factory_); AccountInfo account_info = identity_test_env()->MakeAccountAvailable("user@gmail.com"); @@ -1634,7 +1674,7 @@ EXPECT_FALSE( identity_manager->HasAccountWithRefreshTokenInPersistentErrorState( primary_account_id)); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_test_env()->identity_manager(), primary_account_id, GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason:: @@ -2036,7 +2076,7 @@ base::RunLoop().RunUntilIdle(); ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_RUNNING, reconcilor->GetState()); - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = identity_test_env()->identity_manager()->GetAccountsInCookieJar(); ASSERT_TRUE(accounts_in_cookie_jar_info.accounts_are_fresh); ASSERT_EQ(1u, accounts_in_cookie_jar_info.signed_in_accounts.size()); @@ -2057,7 +2097,7 @@ ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_RUNNING, reconcilor->GetState()); base::RunLoop().RunUntilIdle(); - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = identity_test_env()->identity_manager()->GetAccountsInCookieJar(); ASSERT_FALSE(accounts_in_cookie_jar_info.accounts_are_fresh); ASSERT_EQ(0u, accounts_in_cookie_jar_info.signed_in_accounts.size()); @@ -2098,7 +2138,7 @@ // Add extra cookie change notification. Reconcilor should ignore it. gaia::ListedAccount listed_account = ListedAccountFromCookieParams(cookie_params, account_id); - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = { /*accounts_are_fresh=*/true, {listed_account}, {}}; reconcilor->OnAccountsInCookieUpdated( accounts_in_cookie_jar_info, GoogleServiceAuthError::AuthErrorNone()); @@ -2156,7 +2196,7 @@ base::RunLoop().RunUntilIdle(); std::vector<gaia::ListedAccount> accounts; // This will be the first call to ListAccounts. - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = identity_test_env()->identity_manager()->GetAccountsInCookieJar(); ASSERT_FALSE(accounts_in_cookie_jar_info.accounts_are_fresh); ASSERT_FALSE(reconcilor->is_reconcile_started_); @@ -2239,8 +2279,7 @@ // as "dots@gmail.com" as returned by gaia::ParseListAccountsData(). TEST_P(AccountReconcilorMirrorEndpointParamTest, StartReconcileNoopWithDots) { if (identity_test_env()->identity_manager()->GetAccountIdMigrationState() != - identity::IdentityManager::AccountIdMigrationState:: - MIGRATION_NOT_STARTED) { + signin::IdentityManager::AccountIdMigrationState::MIGRATION_NOT_STARTED) { return; } @@ -2337,10 +2376,10 @@ } TEST_F(AccountReconcilorTest, AuthErrorTriggersListAccount) { - class TestGaiaCookieObserver : public identity::IdentityManager::Observer { + class TestGaiaCookieObserver : public signin::IdentityManager::Observer { public: void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override { cookies_updated_ = true; } @@ -2376,7 +2415,7 @@ // Set an authentication error. ASSERT_FALSE(observer.cookies_updated_); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_test_env()->identity_manager(), account_id, GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason:: @@ -2494,7 +2533,7 @@ // Check that reconcile is aborted if there is token error on primary account. TEST_P(AccountReconcilorMirrorEndpointParamTest, TokenErrorOnPrimary) { AccountInfo account_info = ConnectProfileToAccount("user@gmail.com"); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_test_env()->identity_manager(), account_info.account_id, GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)); @@ -2518,7 +2557,7 @@ const CoreAccountId account_id2 = account_info2.account_id; const std::string email3 = "third@gmail.com"; - const std::string gaia_id3 = identity::GetTestGaiaIdForEmail(email3); + const std::string gaia_id3 = signin::GetTestGaiaIdForEmail(email3); const CoreAccountId account_id3 = PickAccountIdForAccount(gaia_id3, email3); signin::SetListAccountsResponseOneAccount( @@ -2947,7 +2986,7 @@ // Now that we've tried once, the token service knows that the primary // account has an auth error. - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_test_env()->identity_manager(), account_id1, error); // A second attempt to reconcile should be a noop. @@ -2965,7 +3004,7 @@ identity_test_env()->MakeAccountAvailable("other@gmail.com").account_id; // Mark the secondary account in auth error state. - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_test_env()->identity_manager(), account_id2, GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
diff --git a/components/signin/core/browser/consistency_cookie_manager_android.cc b/components/signin/core/browser/consistency_cookie_manager_android.cc index 7a0f6ff..5b04424 100644 --- a/components/signin/core/browser/consistency_cookie_manager_android.cc +++ b/components/signin/core/browser/consistency_cookie_manager_android.cc
@@ -10,7 +10,7 @@ namespace signin { ConsistencyCookieManagerAndroid::ConsistencyCookieManagerAndroid( - identity::IdentityManager* identity_manager, + IdentityManager* identity_manager, SigninClient* signin_client, AccountReconcilor* reconcilor) : ConsistencyCookieManagerBase(signin_client, reconcilor) {
diff --git a/components/signin/core/browser/consistency_cookie_manager_android.h b/components/signin/core/browser/consistency_cookie_manager_android.h index ab2b7af..093b8898 100644 --- a/components/signin/core/browser/consistency_cookie_manager_android.h +++ b/components/signin/core/browser/consistency_cookie_manager_android.h
@@ -9,19 +9,17 @@ #include "base/macros.h" #include "components/signin/core/browser/consistency_cookie_manager_base.h" -namespace identity { -class IdentityManager; -} - class SigninClient; namespace signin { +class IdentityManager; + // ConsistencyCookieManagerAndroid subclasses ConsistencyCookieManagerBase to // watch whether there are pending updates to the account list on the Java side. class ConsistencyCookieManagerAndroid : public ConsistencyCookieManagerBase { public: - ConsistencyCookieManagerAndroid(identity::IdentityManager* identity_manager, + ConsistencyCookieManagerAndroid(IdentityManager* identity_manager, SigninClient* signin_client, AccountReconcilor* reconcilor);
diff --git a/components/signin/core/browser/consistency_cookie_manager_unittest.cc b/components/signin/core/browser/consistency_cookie_manager_unittest.cc index c28fda9..5023f2c 100644 --- a/components/signin/core/browser/consistency_cookie_manager_unittest.cc +++ b/components/signin/core/browser/consistency_cookie_manager_unittest.cc
@@ -60,8 +60,7 @@ network::mojom::CookieManager::SetCanonicalCookieCallback callback)); }; -class FakeConsistencyCookieManager - : public signin::ConsistencyCookieManagerBase { +class FakeConsistencyCookieManager : public ConsistencyCookieManagerBase { public: FakeConsistencyCookieManager(SigninClient* signin_client, AccountReconcilor* reconcilor) @@ -108,7 +107,7 @@ MockCookieManager* mock_cookie_manager_ = nullptr; TestSigninClient signin_client_; - identity::IdentityTestEnvironment identity_test_env_; + IdentityTestEnvironment identity_test_env_; std::unique_ptr<AccountReconcilor> reconcilor_; };
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.cc b/components/signin/core/browser/dice_account_reconcilor_delegate.cc index f57af3f..bc560b6 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.cc
@@ -32,6 +32,85 @@ return account_consistency_ == AccountConsistencyMethod::kDice; } +DiceAccountReconcilorDelegate::InconsistencyReason +DiceAccountReconcilorDelegate::GetInconsistencyReason( + const CoreAccountId& primary_account, + const std::vector<CoreAccountId>& chrome_accounts, + const std::vector<gaia::ListedAccount>& gaia_accounts, + bool first_execution) const { + std::vector<CoreAccountId> valid_gaia_accounts_ids; + for (const gaia::ListedAccount& gaia_account : gaia_accounts) { + if (gaia_account.valid) + valid_gaia_accounts_ids.push_back(gaia_account.id); + } + + bool primary_account_has_token = false; + if (!primary_account.empty()) { + primary_account_has_token = + base::Contains(chrome_accounts, primary_account); + bool primary_account_has_cookie = + base::Contains(valid_gaia_accounts_ids, primary_account); + if (primary_account_has_token && !primary_account_has_cookie) + return InconsistencyReason::kMissingSyncCookie; + + if (!primary_account_has_token && primary_account_has_cookie) + return InconsistencyReason::kSyncAccountAuthError; + } + + bool missing_first_web_account_token = + primary_account.empty() && !gaia_accounts.empty() && + gaia_accounts[0].valid && + !base::Contains(chrome_accounts, gaia_accounts[0].id); + + if (missing_first_web_account_token) + return InconsistencyReason::kMissingFirstWebAccountToken; + + std::sort(valid_gaia_accounts_ids.begin(), valid_gaia_accounts_ids.end()); + std::vector<CoreAccountId> sorted_chrome_accounts(chrome_accounts); + std::sort(sorted_chrome_accounts.begin(), sorted_chrome_accounts.end()); + bool missing_token = + !base::STLIncludes(sorted_chrome_accounts, valid_gaia_accounts_ids); + bool missing_cookie = + !base::STLIncludes(valid_gaia_accounts_ids, sorted_chrome_accounts); + + if (missing_token && missing_cookie) + return InconsistencyReason::kCookieTokenMismatch; + + if (missing_token) + return InconsistencyReason::kMissingSecondaryToken; + + if (missing_cookie) + return InconsistencyReason::kMissingSecondaryCookie; + + if (first_execution && primary_account_has_token && + gaia_accounts[0].id != primary_account && gaia_accounts[0].valid) + return InconsistencyReason::kSyncCookieNotFirst; + + return InconsistencyReason::kNone; +} + +void DiceAccountReconcilorDelegate::MaybeLogInconsistencyReason( + const CoreAccountId& primary_account, + const std::vector<CoreAccountId>& chrome_accounts, + const std::vector<gaia::ListedAccount>& gaia_accounts, + bool first_execution) const { + if (account_consistency_ != AccountConsistencyMethod::kDiceMigration) + return; + + InconsistencyReason inconsistency_reason = GetInconsistencyReason( + primary_account, chrome_accounts, gaia_accounts, first_execution); + + if (first_execution) { + UMA_HISTOGRAM_ENUMERATION( + "Signin.DiceMigrationNotReady.Reason.FirstExecution", + inconsistency_reason); + } else { + UMA_HISTOGRAM_ENUMERATION( + "Signin.DiceMigrationNotReady.Reason.NotFirstExecution", + inconsistency_reason); + } +} + gaia::GaiaSource DiceAccountReconcilorDelegate::GetGaiaApiSource() const { return gaia::GaiaSource::kAccountReconcilorDice; }
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.h b/components/signin/core/browser/dice_account_reconcilor_delegate.h index 57e09ae..d62c037 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.h +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.h
@@ -25,6 +25,11 @@ // AccountReconcilorDelegate: bool IsReconcileEnabled() const override; bool IsAccountConsistencyEnforced() const override; + void MaybeLogInconsistencyReason( + const CoreAccountId& primary_account, + const std::vector<CoreAccountId>& chrome_accounts, + const std::vector<gaia::ListedAccount>& gaia_accounts, + bool first_execution) const override; gaia::GaiaSource GetGaiaApiSource() const override; CoreAccountId GetFirstGaiaAccountForReconcile( const std::vector<CoreAccountId>& chrome_accounts, @@ -39,6 +44,30 @@ bool ShouldRevokeTokensOnCookieDeleted() override; private: + // Possible inconsistency reasons between tokens and gaia cookies. + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + enum class InconsistencyReason { + // Consistent + kNone = 0, + // Inconsistent + kMissingSyncCookie = 1, + kSyncAccountAuthError = 2, + kMissingFirstWebAccountToken = 3, + kMissingSecondaryCookie = 4, + kMissingSecondaryToken = 5, + kCookieTokenMismatch = 6, + kSyncCookieNotFirst = 7, + kMaxValue = kSyncCookieNotFirst + }; + + // Computes inconsistency reason between tokens and gaia cookies. + InconsistencyReason GetInconsistencyReason( + const CoreAccountId& primary_account, + const std::vector<CoreAccountId>& chrome_accounts, + const std::vector<gaia::ListedAccount>& gaia_accounts, + bool first_execution) const; + std::vector<CoreAccountId> GetChromeAccountsForReconcile( const std::vector<CoreAccountId>& chrome_accounts, const CoreAccountId& primary_account,
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc b/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc index c270b74..5e3134224 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc
@@ -36,10 +36,9 @@ // Dice is enabled, revoke only tokens in error state. DiceAccountReconcilorDelegate delegate(&client, AccountConsistencyMethod::kDice); - EXPECT_EQ( - signin::AccountReconcilorDelegate::RevokeTokenOption::kRevokeIfInError, - delegate.ShouldRevokeSecondaryTokensBeforeReconcile( - std::vector<gaia::ListedAccount>())); + EXPECT_EQ(AccountReconcilorDelegate::RevokeTokenOption::kRevokeIfInError, + delegate.ShouldRevokeSecondaryTokensBeforeReconcile( + std::vector<gaia::ListedAccount>())); } { DiceAccountReconcilorDelegate delegate( @@ -47,12 +46,11 @@ // Gaia accounts are not empty, don't revoke. gaia::ListedAccount gaia_account; gaia_account.id = CoreAccountId("other"); - EXPECT_EQ( - signin::AccountReconcilorDelegate::RevokeTokenOption::kDoNotRevoke, - delegate.ShouldRevokeSecondaryTokensBeforeReconcile( - std::vector<gaia::ListedAccount>{gaia_account})); + EXPECT_EQ(AccountReconcilorDelegate::RevokeTokenOption::kDoNotRevoke, + delegate.ShouldRevokeSecondaryTokensBeforeReconcile( + std::vector<gaia::ListedAccount>{gaia_account})); // Revoke. - EXPECT_EQ(signin::AccountReconcilorDelegate::RevokeTokenOption::kRevoke, + EXPECT_EQ(AccountReconcilorDelegate::RevokeTokenOption::kRevoke, delegate.ShouldRevokeSecondaryTokensBeforeReconcile( std::vector<gaia::ListedAccount>())); }
diff --git a/components/signin/core/browser/mirror_account_reconcilor_delegate.cc b/components/signin/core/browser/mirror_account_reconcilor_delegate.cc index adf8c80..db56be5 100644 --- a/components/signin/core/browser/mirror_account_reconcilor_delegate.cc +++ b/components/signin/core/browser/mirror_account_reconcilor_delegate.cc
@@ -10,7 +10,7 @@ namespace signin { MirrorAccountReconcilorDelegate::MirrorAccountReconcilorDelegate( - identity::IdentityManager* identity_manager) + IdentityManager* identity_manager) : identity_manager_(identity_manager) { DCHECK(identity_manager_); identity_manager_->AddObserver(this);
diff --git a/components/signin/core/browser/mirror_account_reconcilor_delegate.h b/components/signin/core/browser/mirror_account_reconcilor_delegate.h index 5f4dc7c..bc465861 100644 --- a/components/signin/core/browser/mirror_account_reconcilor_delegate.h +++ b/components/signin/core/browser/mirror_account_reconcilor_delegate.h
@@ -15,12 +15,10 @@ namespace signin { // AccountReconcilorDelegate specialized for Mirror. -class MirrorAccountReconcilorDelegate - : public AccountReconcilorDelegate, - public identity::IdentityManager::Observer { +class MirrorAccountReconcilorDelegate : public AccountReconcilorDelegate, + public IdentityManager::Observer { public: - explicit MirrorAccountReconcilorDelegate( - identity::IdentityManager* identity_manager); + explicit MirrorAccountReconcilorDelegate(IdentityManager* identity_manager); ~MirrorAccountReconcilorDelegate() override; protected: @@ -52,7 +50,7 @@ void OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) override; - identity::IdentityManager* identity_manager_; + IdentityManager* identity_manager_; DISALLOW_COPY_AND_ASSIGN(MirrorAccountReconcilorDelegate); };
diff --git a/components/signin/core/browser/signin_error_controller.cc b/components/signin/core/browser/signin_error_controller.cc index 45c63c1..bbfd519f 100644 --- a/components/signin/core/browser/signin_error_controller.cc +++ b/components/signin/core/browser/signin_error_controller.cc
@@ -8,7 +8,7 @@ SigninErrorController::SigninErrorController( AccountMode mode, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : account_mode_(mode), identity_manager_(identity_manager), scoped_identity_manager_observer_(this),
diff --git a/components/signin/core/browser/signin_error_controller.h b/components/signin/core/browser/signin_error_controller.h index e06a2f1b..b1f6486 100644 --- a/components/signin/core/browser/signin_error_controller.h +++ b/components/signin/core/browser/signin_error_controller.h
@@ -21,7 +21,7 @@ // AuthStatusProvider to report their current authentication state, and should // invoke AuthStatusChanged() when their authentication state may have changed. class SigninErrorController : public KeyedService, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: enum class AccountMode { // Signin error controller monitors all the accounts. When multiple accounts @@ -42,7 +42,7 @@ }; SigninErrorController(AccountMode mode, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~SigninErrorController() override; // KeyedService implementation: @@ -75,7 +75,7 @@ const std::string& prev_account_id, const GoogleServiceAuthError::State& prev_error_state); - // identity::IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnEndBatchOfRefreshTokenStateChanges() override; void OnErrorStateOfRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info, @@ -86,9 +86,9 @@ const CoreAccountInfo& previous_primary_account_info) override; const AccountMode account_mode_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; - ScopedObserver<identity::IdentityManager, SigninErrorController> + ScopedObserver<signin::IdentityManager, SigninErrorController> scoped_identity_manager_observer_; // The account that generated the last auth error.
diff --git a/components/signin/core/browser/signin_error_controller_unittest.cc b/components/signin/core/browser/signin_error_controller_unittest.cc index 2c3b2f42..92b478f 100644 --- a/components/signin/core/browser/signin_error_controller_unittest.cc +++ b/components/signin/core/browser/signin_error_controller_unittest.cc
@@ -36,7 +36,7 @@ EXPECT_CALL(observer, OnErrorChanged()).Times(0); base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; SigninErrorController error_controller( SigninErrorController::AccountMode::ANY_ACCOUNT, identity_test_env.identity_manager()); @@ -84,7 +84,7 @@ TEST(SigninErrorControllerTest, AccountTransitionAnyAccount) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; std::string test_account_id = identity_test_env.MakeAccountAvailable(kTestEmail).account_id; @@ -115,8 +115,8 @@ #if !defined(OS_CHROMEOS) TEST(SigninErrorControllerTest, AccountTransitionPrimaryAccount) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment identity_test_env; - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityTestEnvironment identity_test_env; + signin::PrimaryAccountMutator* primary_account_mutator = identity_test_env.identity_manager()->GetPrimaryAccountMutator(); std::string test_account_id = @@ -144,7 +144,7 @@ // Change the primary account to the account with an error and check that the // error controller updates its error status accordingly. primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, signin_metrics::FORCE_SIGNOUT_ALWAYS_ALLOWED_FOR_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC); identity_test_env.SetPrimaryAccount(kTestEmail); @@ -160,7 +160,7 @@ // Change the primary account again and check that the error controller // updates its error status accordingly. primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, signin_metrics::FORCE_SIGNOUT_ALWAYS_ALLOWED_FOR_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC); identity_test_env.SetPrimaryAccount(kOtherTestEmail); @@ -170,7 +170,7 @@ // Sign out and check that that the error controller updates its error status // accordingly. primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, signin_metrics::FORCE_SIGNOUT_ALWAYS_ALLOWED_FOR_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC); ASSERT_FALSE(error_controller.HasError()); @@ -180,7 +180,7 @@ // Verify that SigninErrorController handles errors properly. TEST(SigninErrorControllerTest, AuthStatusEnumerateAllErrors) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; std::string test_account_id = identity_test_env.MakeAccountAvailable(kTestEmail).account_id; @@ -227,7 +227,7 @@ // Verify that existing error is not replaced by new error. TEST(SigninErrorControllerTest, AuthStatusChange) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; std::string test_account_id = identity_test_env.MakeAccountAvailable(kTestEmail).account_id; @@ -283,7 +283,7 @@ TEST(SigninErrorControllerTest, PrimaryAccountErrorsArePreferredToSecondaryAccountErrors) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; AccountInfo primary_account_info = identity_test_env.MakePrimaryAccountAvailable(kPrimaryAccountEmail); @@ -330,7 +330,7 @@ TEST(SigninErrorControllerTest, PrimaryAccountErrorsAreSticky) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment identity_test_env; + signin::IdentityTestEnvironment identity_test_env; AccountInfo primary_account_info = identity_test_env.MakePrimaryAccountAvailable(kPrimaryAccountEmail);
diff --git a/components/signin/core/browser/signin_investigator_unittest.cc b/components/signin/core/browser/signin_investigator_unittest.cc index 0ac8977..31df9131 100644 --- a/components/signin/core/browser/signin_investigator_unittest.cc +++ b/components/signin/core/browser/signin_investigator_unittest.cc
@@ -35,7 +35,7 @@ private: base::test::ScopedTaskEnvironment task_environment_; sync_preferences::TestingPrefServiceSyncable prefs_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; }; } // namespace
diff --git a/components/signin/core/browser/signin_status_metrics_provider.cc b/components/signin/core/browser/signin_status_metrics_provider.cc index d5e0522..279eab3 100644 --- a/components/signin/core/browser/signin_status_metrics_provider.cc +++ b/components/signin/core/browser/signin_status_metrics_provider.cc
@@ -52,7 +52,7 @@ } void SigninStatusMetricsProvider::OnIdentityManagerCreated( - identity::IdentityManager* identity_manager) { + signin::IdentityManager* identity_manager) { // Whenever a new profile is created, a new IdentityManager will be created // for it. This ensures that all sign-in or sign-out actions of all opened // profiles are being monitored. @@ -68,7 +68,7 @@ } void SigninStatusMetricsProvider::OnIdentityManagerShutdown( - identity::IdentityManager* identity_manager) { + signin::IdentityManager* identity_manager) { if (scoped_observer_.IsObserving(identity_manager)) scoped_observer_.Remove(identity_manager); } @@ -101,7 +101,7 @@ delegate_->Initialize(); // Start observing all already-created IdentityManagers. - for (identity::IdentityManager* manager : + for (signin::IdentityManager* manager : delegate_->GetIdentityManagersForAllAccounts()) { DCHECK(!scoped_observer_.IsObserving(manager)); scoped_observer_.Add(manager);
diff --git a/components/signin/core/browser/signin_status_metrics_provider.h b/components/signin/core/browser/signin_status_metrics_provider.h index d2bd167..f28f472 100644 --- a/components/signin/core/browser/signin_status_metrics_provider.h +++ b/components/signin/core/browser/signin_status_metrics_provider.h
@@ -28,7 +28,7 @@ // record the value into a histogram before UMA log is uploaded on platform // Windows, Linux, Mac and Android. class SigninStatusMetricsProvider : public SigninStatusMetricsProviderBase, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: ~SigninStatusMetricsProvider() override; @@ -41,10 +41,10 @@ std::unique_ptr<SigninStatusMetricsProviderDelegate> delegate); // Update the sign-in status when a IdentityManager is created. - void OnIdentityManagerCreated(identity::IdentityManager* identity_manager); + void OnIdentityManagerCreated(signin::IdentityManager* identity_manager); // Update the sign-in status when a IdentityManager is shut down. - void OnIdentityManagerShutdown(identity::IdentityManager* identity_manager); + void OnIdentityManagerShutdown(signin::IdentityManager* identity_manager); // Updates the initial sign-in status. For testing purpose only. void UpdateInitialSigninStatusForTesting(size_t total_count, @@ -90,7 +90,7 @@ // Used to track the IdentityManagers that this instance is observing so that // this instance can be removed as an observer on its destruction. - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> scoped_observer_; // Whether the instance is for testing or not.
diff --git a/components/signin/core/browser/signin_status_metrics_provider_delegate.h b/components/signin/core/browser/signin_status_metrics_provider_delegate.h index 763a8b7c..b97ee435 100644 --- a/components/signin/core/browser/signin_status_metrics_provider_delegate.h +++ b/components/signin/core/browser/signin_status_metrics_provider_delegate.h
@@ -14,7 +14,7 @@ class SigninStatusMetricsProvider; -namespace identity { +namespace signin { class IdentityManager; } @@ -48,7 +48,7 @@ virtual AccountsStatus GetStatusOfAllAccounts() = 0; // Returns the IdentityManager instance (if any) associated with each account. - virtual std::vector<identity::IdentityManager*> + virtual std::vector<signin::IdentityManager*> GetIdentityManagersForAllAccounts() = 0; protected:
diff --git a/components/signin/internal/identity_manager/BUILD.gn b/components/signin/internal/identity_manager/BUILD.gn index 44b9630..e1e4fac 100644 --- a/components/signin/internal/identity_manager/BUILD.gn +++ b/components/signin/internal/identity_manager/BUILD.gn
@@ -24,6 +24,8 @@ "gaia_cookie_manager_service.h", "mutable_profile_oauth2_token_service_delegate.cc", "mutable_profile_oauth2_token_service_delegate.h", + "oauth2_token_service_delegate.cc", + "oauth2_token_service_delegate.h", "oauth2_token_service_delegate_android.cc", "oauth2_token_service_delegate_android.h", "oauth_multilogin_helper.cc", @@ -116,6 +118,7 @@ "gaia_cookie_manager_service_unittest.cc", "mutable_profile_oauth2_token_service_delegate_unittest.cc", "oauth2_token_service_delegate_android_unittest.cc", + "oauth2_token_service_delegate_unittest.cc", "oauth_multilogin_helper_unittest.cc", "oauth_multilogin_token_fetcher_unittest.cc", "primary_account_manager_unittest.cc", @@ -144,7 +147,6 @@ "//components/sync_preferences:test_support", "//components/webdata/common", "//google_apis", - "//google_apis:test_support", "//net", "//net:test_support", "//services/network:test_support", @@ -172,6 +174,8 @@ testonly = true sources = [ + "fake_oauth2_token_service_delegate.cc", + "fake_oauth2_token_service_delegate.h", "fake_profile_oauth2_token_service.cc", "fake_profile_oauth2_token_service.h", ]
diff --git a/components/signin/internal/identity_manager/DEPS b/components/signin/internal/identity_manager/DEPS index d98ceef..4485df3 100644 --- a/components/signin/internal/identity_manager/DEPS +++ b/components/signin/internal/identity_manager/DEPS
@@ -2,3 +2,15 @@ "+chromeos/constants/chromeos_switches.h", "+mojo/public", ] + +specific_include_rules = { + "account_tracker_service.cc": [ + "+components/signin/core/browser/android/jni_headers/AccountTrackerService_jni.h", + ], + "child_account_info_fetcher_android.cc": [ + "+components/signin/core/browser/android/jni_headers/ChildAccountInfoFetcher_jni.h", + ], + "oauth2_token_service_delegate_android.cc": [ + "+components/signin/core/browser/android/jni_headers/OAuth2TokenService_jni.h", + ], +}
diff --git a/components/signin/internal/identity_manager/account_fetcher_service.h b/components/signin/internal/identity_manager/account_fetcher_service.h index 3e208b5..0cd1249 100644 --- a/components/signin/internal/identity_manager/account_fetcher_service.h +++ b/components/signin/internal/identity_manager/account_fetcher_service.h
@@ -15,7 +15,6 @@ #include "base/sequence_checker.h" #include "base/timer/timer.h" #include "build/build_config.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "google_apis/gaia/oauth2_token_service_observer.h" class AccountInfoFetcher;
diff --git a/components/signin/internal/identity_manager/account_tracker_service.h b/components/signin/internal/identity_manager/account_tracker_service.h index 273ca21..5fc76f4 100644 --- a/components/signin/internal/identity_manager/account_tracker_service.h +++ b/components/signin/internal/identity_manager/account_tracker_service.h
@@ -37,7 +37,7 @@ class Image; } -namespace identity { +namespace signin { class IdentityManager; void SimulateSuccessfulFetchOfAccountInfo(IdentityManager*, const std::string&, @@ -48,7 +48,7 @@ const std::string&, const std::string&, const std::string&); -} // namespace identity +} // namespace signin // Retrieves and caches GAIA information about Google Accounts. class AccountTrackerService { @@ -148,8 +148,8 @@ private: friend class AccountFetcherService; - friend void identity::SimulateSuccessfulFetchOfAccountInfo( - identity::IdentityManager*, + friend void signin::SimulateSuccessfulFetchOfAccountInfo( + signin::IdentityManager*, const std::string&, const std::string&, const std::string&,
diff --git a/components/signin/internal/identity_manager/accounts_cookie_mutator_impl.cc b/components/signin/internal/identity_manager/accounts_cookie_mutator_impl.cc index 1b81b81..d2b158e 100644 --- a/components/signin/internal/identity_manager/accounts_cookie_mutator_impl.cc +++ b/components/signin/internal/identity_manager/accounts_cookie_mutator_impl.cc
@@ -11,7 +11,7 @@ #include "google_apis/gaia/core_account_id.h" #include "google_apis/gaia/google_service_auth_error.h" -namespace identity { +namespace signin { AccountsCookieMutatorImpl::AccountsCookieMutatorImpl( GaiaCookieManagerService* gaia_cookie_manager_service, @@ -44,7 +44,7 @@ void AccountsCookieMutatorImpl::SetAccountsInCookie( const std::vector<CoreAccountId>& account_ids, gaia::GaiaSource source, - base::OnceCallback<void(signin::SetAccountsInCookieResult)> + base::OnceCallback<void(SetAccountsInCookieResult)> set_accounts_in_cookies_completed_callback) { std::vector<GaiaCookieManagerService::AccountIdGaiaIdPair> accounts; for (const auto& account_id : account_ids) { @@ -63,4 +63,4 @@ gaia_cookie_manager_service_->LogOutAllAccounts(source); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h b/components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h index bb7c4eb..0aa6dac10 100644 --- a/components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h +++ b/components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h
@@ -18,7 +18,7 @@ enum class GaiaSource; } -namespace identity { +namespace signin { // Concrete implementation of the AccountsCookieMutator interface. class AccountsCookieMutatorImpl : public AccountsCookieMutator { @@ -42,7 +42,7 @@ void SetAccountsInCookie( const std::vector<CoreAccountId>& account_ids, gaia::GaiaSource source, - base::OnceCallback<void(signin::SetAccountsInCookieResult)> + base::OnceCallback<void(SetAccountsInCookieResult)> set_accounts_in_cookies_completed_callback) override; void TriggerCookieJarUpdate() override; @@ -56,6 +56,6 @@ DISALLOW_COPY_AND_ASSIGN(AccountsCookieMutatorImpl); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_ACCOUNTS_COOKIE_MUTATOR_IMPL_H_
diff --git a/components/signin/internal/identity_manager/accounts_mutator_impl.cc b/components/signin/internal/identity_manager/accounts_mutator_impl.cc index 5423800..bff6a3de 100644 --- a/components/signin/internal/identity_manager/accounts_mutator_impl.cc +++ b/components/signin/internal/identity_manager/accounts_mutator_impl.cc
@@ -13,9 +13,9 @@ #include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/account_info.h" #include "google_apis/gaia/core_account_id.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "google_apis/gaia/gaia_constants.h" -namespace identity { +namespace signin { AccountsMutatorImpl::AccountsMutatorImpl( ProfileOAuth2TokenService* token_service, @@ -83,7 +83,7 @@ AccountInfo primary_account_info = primary_account_manager_->GetAuthenticatedAccountInfo(); AddOrUpdateAccount(primary_account_info.gaia, primary_account_info.email, - OAuth2TokenServiceDelegate::kInvalidRefreshToken, + GaiaConstants::kInvalidRefreshToken, primary_account_info.is_under_advanced_protection, source); } @@ -102,7 +102,7 @@ // to the device ID of the current mutator on the server. Reset the device ID // of the current mutator to avoid tying it with the new mutator. See // https://crbug.com/813928#c16 - signin::RecreateSigninScopedDeviceId(pref_service_); + RecreateSigninScopedDeviceId(pref_service_); } #endif @@ -113,4 +113,4 @@ signin_metrics::SourceForRefreshTokenOperation::kSupervisedUser_InitSync); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/internal/identity_manager/accounts_mutator_impl.h b/components/signin/internal/identity_manager/accounts_mutator_impl.h index 353220e..0dc2ca05 100644 --- a/components/signin/internal/identity_manager/accounts_mutator_impl.h +++ b/components/signin/internal/identity_manager/accounts_mutator_impl.h
@@ -21,7 +21,7 @@ class PrimaryAccountManager; class ProfileOAuth2TokenService; -namespace identity { +namespace signin { // Concrete implementation of the AccountsMutatorImpl interface. class AccountsMutatorImpl : public AccountsMutator { @@ -70,6 +70,6 @@ DISALLOW_COPY_AND_ASSIGN(AccountsMutatorImpl); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_ACCOUNTS_MUTATOR_IMPL_H_
diff --git a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc index 87e00c3..28d3532 100644 --- a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc +++ b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc
@@ -5,9 +5,9 @@ #include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h" #include "base/logging.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" -namespace identity { +namespace signin { DeviceAccountsSynchronizerImpl::DeviceAccountsSynchronizerImpl( OAuth2TokenServiceDelegate* token_service_delegate) @@ -26,4 +26,4 @@ token_service_delegate_->ReloadAccountFromSystem(account_id); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h index 32dff8ea..5acf70c1 100644 --- a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h +++ b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h
@@ -9,7 +9,7 @@ class OAuth2TokenServiceDelegate; -namespace identity { +namespace signin { // Concrete implementation of DeviceAccountsSynchronizer interface. class DeviceAccountsSynchronizerImpl : public DeviceAccountsSynchronizer { @@ -26,6 +26,6 @@ OAuth2TokenServiceDelegate* token_service_delegate_ = nullptr; }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_IMPL_H_
diff --git a/components/signin/internal/identity_manager/diagnostics_provider_impl.cc b/components/signin/internal/identity_manager/diagnostics_provider_impl.cc index b270945..c2ec141 100644 --- a/components/signin/internal/identity_manager/diagnostics_provider_impl.cc +++ b/components/signin/internal/identity_manager/diagnostics_provider_impl.cc
@@ -5,10 +5,10 @@ #include "components/signin/internal/identity_manager/diagnostics_provider_impl.h" #include "components/signin/internal/identity_manager/gaia_cookie_manager_service.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" -namespace identity { +namespace signin { DiagnosticsProviderImpl::DiagnosticsProviderImpl( ProfileOAuth2TokenService* profile_oauth2_token_service, @@ -21,7 +21,7 @@ DiagnosticsProviderImpl::~DiagnosticsProviderImpl() {} -OAuth2TokenServiceDelegate::LoadCredentialsState +signin::LoadCredentialsState DiagnosticsProviderImpl::GetDetailedStateOfLoadingOfRefreshTokens() const { DCHECK(profile_oauth2_token_service_->GetDelegate()); return profile_oauth2_token_service_->GetDelegate()->load_credentials_state(); @@ -41,4 +41,4 @@ return gaia_cookie_manager_service_->GetBackoffEntry()->GetTimeUntilRelease(); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/internal/identity_manager/diagnostics_provider_impl.h b/components/signin/internal/identity_manager/diagnostics_provider_impl.h index 54664d5..2035715c 100644 --- a/components/signin/internal/identity_manager/diagnostics_provider_impl.h +++ b/components/signin/internal/identity_manager/diagnostics_provider_impl.h
@@ -11,7 +11,7 @@ class GaiaCookieManagerService; class ProfileOAuth2TokenService; -namespace identity { +namespace signin { // Concrete implementation of the DiagnosticsProvider interface. class DiagnosticsProviderImpl final : public DiagnosticsProvider { @@ -22,8 +22,8 @@ ~DiagnosticsProviderImpl() override; // Returns the state of the load credentials operation. - OAuth2TokenServiceDelegate::LoadCredentialsState - GetDetailedStateOfLoadingOfRefreshTokens() const override; + signin::LoadCredentialsState GetDetailedStateOfLoadingOfRefreshTokens() + const override; // Returns the time until a access token request can be sent (will be zero if // the release time is in the past). @@ -40,6 +40,6 @@ DISALLOW_COPY_AND_ASSIGN(DiagnosticsProviderImpl); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_DIAGNOSTICS_PROVIDER_IMPL_H_
diff --git a/google_apis/gaia/fake_oauth2_token_service_delegate.cc b/components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.cc similarity index 90% rename from google_apis/gaia/fake_oauth2_token_service_delegate.cc rename to components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.cc index 95d849c..2838f06 100644 --- a/google_apis/gaia/fake_oauth2_token_service_delegate.cc +++ b/components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.cc
@@ -2,7 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "google_apis/gaia/fake_oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h" + +#include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" +#include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/oauth2_access_token_fetcher_impl.h" namespace { @@ -26,8 +29,7 @@ FakeOAuth2TokenServiceDelegate::AccountInfo::AccountInfo( const std::string& refresh_token) - : refresh_token(refresh_token), - error(GoogleServiceAuthError::NONE) {} + : refresh_token(refresh_token), error(GoogleServiceAuthError::NONE) {} FakeOAuth2TokenServiceDelegate::FakeOAuth2TokenServiceDelegate() : shared_factory_( @@ -35,8 +37,7 @@ &test_url_loader_factory_)), backoff_entry_(&kBackoffPolicy) {} -FakeOAuth2TokenServiceDelegate::~FakeOAuth2TokenServiceDelegate() { -} +FakeOAuth2TokenServiceDelegate::~FakeOAuth2TokenServiceDelegate() = default; std::unique_ptr<OAuth2AccessTokenFetcher> FakeOAuth2TokenServiceDelegate::CreateAccessTokenFetcher( @@ -88,7 +89,8 @@ void FakeOAuth2TokenServiceDelegate::LoadCredentials( const CoreAccountId& primary_account_id) { - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); FireRefreshTokensLoaded(); } @@ -111,7 +113,7 @@ // rejected by the client and is thus not valid. So set the appropriate // error in that case. This logic is essentially duplicated from // MutableProfileOAuth2TokenServiceDelegate. - if (token == kInvalidRefreshToken) { + if (token == GaiaConstants::kInvalidRefreshToken) { refresh_tokens_[account_id]->error = GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason:: @@ -127,7 +129,7 @@ } void FakeOAuth2TokenServiceDelegate::ExtractCredentials( - OAuth2TokenService* to_service, + ProfileOAuth2TokenService* to_service, const CoreAccountId& account_id) { auto it = refresh_tokens_.find(account_id); DCHECK(it != refresh_tokens_.end());
diff --git a/google_apis/gaia/fake_oauth2_token_service_delegate.h b/components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h similarity index 86% rename from google_apis/gaia/fake_oauth2_token_service_delegate.h rename to components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h index d651ccd..db48978 100644 --- a/google_apis/gaia/fake_oauth2_token_service_delegate.h +++ b/components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_SIGNIN_FAKE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ -#define CHROME_BROWSER_SIGNIN_FAKE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ +#ifndef COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_FAKE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ +#define COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_FAKE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ #include <memory> #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "google_apis/gaia/google_service_auth_error.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" @@ -41,7 +41,7 @@ void UpdateCredentials(const CoreAccountId& account_id, const std::string& refresh_token) override; void RevokeCredentials(const CoreAccountId& account_id) override; - void ExtractCredentials(OAuth2TokenService* to_service, + void ExtractCredentials(ProfileOAuth2TokenService* to_service, const CoreAccountId& account_id) override; scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() @@ -83,4 +83,4 @@ DISALLOW_COPY_AND_ASSIGN(FakeOAuth2TokenServiceDelegate); }; -#endif +#endif // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_FAKE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_
diff --git a/components/signin/internal/identity_manager/fake_profile_oauth2_token_service.cc b/components/signin/internal/identity_manager/fake_profile_oauth2_token_service.cc index 4ced897..4dc859b 100644 --- a/components/signin/internal/identity_manager/fake_profile_oauth2_token_service.cc +++ b/components/signin/internal/identity_manager/fake_profile_oauth2_token_service.cc
@@ -6,7 +6,7 @@ #include <memory> -#include "google_apis/gaia/fake_oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h" FakeProfileOAuth2TokenService::FakeProfileOAuth2TokenService( PrefService* user_prefs)
diff --git a/components/signin/internal/identity_manager/gaia_cookie_manager_service.cc b/components/signin/internal/identity_manager/gaia_cookie_manager_service.cc index b7383734..e4dc4d2 100644 --- a/components/signin/internal/identity_manager/gaia_cookie_manager_service.cc +++ b/components/signin/internal/identity_manager/gaia_cookie_manager_service.cc
@@ -29,7 +29,6 @@ #include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_urls.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/cookies/cookie_change_dispatcher.h"
diff --git a/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.cc b/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.cc index 6c06338..d3a0e82 100644 --- a/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.cc +++ b/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.cc
@@ -112,15 +112,14 @@ DCHECK(!new_token.empty()); TokenStateTransition transition = TokenStateTransition::kCount; if (existing_token.empty()) { - transition = (new_token == OAuth2TokenServiceDelegate::kInvalidRefreshToken) + transition = (new_token == GaiaConstants::kInvalidRefreshToken) ? TokenStateTransition::kNoneToInvalid : TokenStateTransition::kNoneToRegular; - } else if (existing_token == - OAuth2TokenServiceDelegate::kInvalidRefreshToken) { + } else if (existing_token == GaiaConstants::kInvalidRefreshToken) { transition = TokenStateTransition::kInvalidToRegular; } else { // Existing token is a regular token. - transition = (new_token == OAuth2TokenServiceDelegate::kInvalidRefreshToken) + transition = (new_token == GaiaConstants::kInvalidRefreshToken) ? TokenStateTransition::kRegularToInvalid : TokenStateTransition::kRegularToRegular; } @@ -130,18 +129,16 @@ // Record metrics when a token was loaded. void RecordTokenLoaded(const std::string& token) { - RecordTokenStateTransition( - (token == OAuth2TokenServiceDelegate::kInvalidRefreshToken) - ? TokenStateTransition::kLoadInvalid - : TokenStateTransition::kLoadRegular); + RecordTokenStateTransition((token == GaiaConstants::kInvalidRefreshToken) + ? TokenStateTransition::kLoadInvalid + : TokenStateTransition::kLoadRegular); } // Record metrics when a token was revoked. void RecordTokenRevoked(const std::string& token) { - RecordTokenStateTransition( - (token == OAuth2TokenServiceDelegate::kInvalidRefreshToken) - ? TokenStateTransition::kInvalidToNone - : TokenStateTransition::kRegularToNone); + RecordTokenStateTransition((token == GaiaConstants::kInvalidRefreshToken) + ? TokenStateTransition::kInvalidToNone + : TokenStateTransition::kRegularToNone); } std::string ApplyAccountIdPrefix(const std::string& account_id) { @@ -160,21 +157,22 @@ return CoreAccountId(prefixed_account_id.substr(kAccountIdPrefixLength)); } -OAuth2TokenServiceDelegate::LoadCredentialsState -LoadCredentialsStateFromTokenResult(TokenServiceTable::Result token_result) { +signin::LoadCredentialsState LoadCredentialsStateFromTokenResult( + TokenServiceTable::Result token_result) { switch (token_result) { case TokenServiceTable::TOKEN_DB_RESULT_SQL_INVALID_STATEMENT: case TokenServiceTable::TOKEN_DB_RESULT_BAD_ENTRY: - return OAuth2TokenServiceDelegate:: + return signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_DB_ERRORS; case TokenServiceTable::TOKEN_DB_RESULT_DECRYPT_ERROR: - return OAuth2TokenServiceDelegate:: + return signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_DECRYPT_ERRORS; case TokenServiceTable::TOKEN_DB_RESULT_SUCCESS: - return OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS; + return signin::LoadCredentialsState:: + LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS; } NOTREACHED(); - return OAuth2TokenServiceDelegate:: + return signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_UNKNOWN_ERRORS; } @@ -492,19 +490,22 @@ void MutableProfileOAuth2TokenServiceDelegate::LoadCredentials( const CoreAccountId& primary_account_id) { - if (load_credentials_state() == LOAD_CREDENTIALS_IN_PROGRESS) { + if (load_credentials_state() == + signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS) { VLOG(1) << "Load credentials operation already in progress"; return; } - set_load_credentials_state(LOAD_CREDENTIALS_IN_PROGRESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS); #if defined(OS_CHROMEOS) // TODO(sinhak): Remove this ifdef block after Account Manager is switched on. // ChromeOS OOBE loads credentials without a primary account and expects this // to be a no-op. See http://crbug.com/891818 if (primary_account_id.empty()) { - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); FinishLoadingCredentials(); return; } @@ -520,7 +521,9 @@ if (!token_web_data_) { // This case only exists in unit tests that do not care about loading // credentials. - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_UNKNOWN_ERRORS); + set_load_credentials_state( + signin::LoadCredentialsState:: + LOAD_CREDENTIALS_FINISHED_WITH_UNKNOWN_ERRORS); FinishLoadingCredentials(); return; } @@ -557,7 +560,8 @@ token_result->GetValue().db_result)); } else { set_load_credentials_state( - LOAD_CREDENTIALS_FINISHED_WITH_DB_CANNOT_BE_OPENED); + signin::LoadCredentialsState:: + LOAD_CREDENTIALS_FINISHED_WITH_DB_CANNOT_BE_OPENED); } // Make sure that we have an entry for |loading_primary_account_id_| in the @@ -565,11 +569,14 @@ // while this profile is connected to an account. if (!loading_primary_account_id_.empty() && refresh_tokens_.count(loading_primary_account_id_) == 0) { - if (load_credentials_state() == LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS) { + if (load_credentials_state() == + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS) { set_load_credentials_state( - LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT); + signin::LoadCredentialsState:: + LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT); } - AddAccountStatus(loading_primary_account_id_, kInvalidRefreshToken, + AddAccountStatus(loading_primary_account_id_, + GaiaConstants::kInvalidRefreshToken, GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason:: CREDENTIALS_MISSING)); @@ -696,7 +703,7 @@ if (load_account && revoke_all_tokens_on_load_) { if (account_id == loading_primary_account_id_) { RevokeCredentialsOnServer(refresh_token); - refresh_token = kInvalidRefreshToken; + refresh_token = GaiaConstants::kInvalidRefreshToken; PersistCredentials(account_id, refresh_token); } else { load_account = false; @@ -757,7 +764,8 @@ DCHECK(!account_id.empty()); DCHECK(!refresh_token.empty()); - bool is_refresh_token_invalidated = refresh_token == kInvalidRefreshToken; + bool is_refresh_token_invalidated = + refresh_token == GaiaConstants::kInvalidRefreshToken; GoogleServiceAuthError error = is_refresh_token_invalidated ? GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( @@ -816,13 +824,15 @@ VLOG(1) << "MutablePO2TS::RevokeAllCredentials"; ScopedBatchChange batch(this); - if (load_credentials_state() == LOAD_CREDENTIALS_IN_PROGRESS) { + if (load_credentials_state() == + signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS) { VLOG(1) << "MutablePO2TS::RevokeAllCredentials before tokens are loaded."; // If |RevokeAllCredentials| is called while credentials are being loaded, // then the load must be cancelled and the load credentials state updated. DCHECK_NE(0, web_data_service_request_); CancelWebTokenFetch(); - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); FinishLoadingCredentials(); } @@ -859,7 +869,7 @@ const std::string& refresh_token) { DCHECK(!refresh_token.empty()); - if (refresh_token == kInvalidRefreshToken) + if (refresh_token == GaiaConstants::kInvalidRefreshToken) return; // Keep track or all server revoke requests. This way they can be deleted @@ -877,7 +887,7 @@ } void MutableProfileOAuth2TokenServiceDelegate::ExtractCredentials( - OAuth2TokenService* to_service, + ProfileOAuth2TokenService* to_service, const CoreAccountId& account_id) { static_cast<ProfileOAuth2TokenService*>(to_service) ->UpdateCredentials(account_id, GetRefreshToken(account_id),
diff --git a/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.h b/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.h index 0ae2b2cd5..4da219e 100644 --- a/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.h +++ b/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.h
@@ -13,11 +13,11 @@ #include "base/macros.h" #include "base/threading/thread_checker.h" #include "components/signin/internal/identity_manager/account_tracker_service.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" #include "components/signin/public/base/account_consistency_method.h" #include "components/webdata/common/web_data_service_base.h" #include "components/webdata/common/web_data_service_consumer.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" #include "net/base/backoff_entry.h" #include "services/network/public/cpp/network_connection_tracker.h" @@ -69,7 +69,7 @@ const std::string& refresh_token) override; void RevokeAllCredentials() override; void RevokeCredentials(const CoreAccountId& account_id) override; - void ExtractCredentials(OAuth2TokenService* to_service, + void ExtractCredentials(ProfileOAuth2TokenService* to_service, const CoreAccountId& account_id) override; void Shutdown() override;
diff --git a/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate_unittest.cc b/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate_unittest.cc index 08578d2..dc260814 100644 --- a/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate_unittest.cc +++ b/components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate_unittest.cc
@@ -21,6 +21,7 @@ #include "build/buildflag.h" #include "components/os_crypt/os_crypt_mocker.h" #include "components/prefs/scoped_user_pref_update.h" +#include "components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h" #include "components/signin/internal/identity_manager/primary_account_manager.h" #include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" #include "components/signin/public/base/account_consistency_method.h" @@ -33,7 +34,6 @@ #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/webdata/common/web_data_service_base.h" #include "components/webdata/common/web_database_service.h" -#include "google_apis/gaia/fake_oauth2_token_service_delegate.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h" @@ -379,12 +379,13 @@ // Ensure DB is clean. oauth2_service_delegate_->RevokeAllCredentials(); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_NOT_STARTED, + EXPECT_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED, oauth2_service_delegate_->load_credentials_state()); oauth2_service_delegate_->LoadCredentials(""); base::RunLoop().RunUntilIdle(); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - oauth2_service_delegate_->load_credentials_state()); + EXPECT_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + oauth2_service_delegate_->load_credentials_state()); } TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, @@ -398,13 +399,13 @@ ResetObserverCounts(); // Perform a load from an empty DB. - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_NOT_STARTED, + EXPECT_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED, oauth2_service_delegate_->load_credentials_state()); oauth2_service_delegate_->LoadCredentials("account_id"); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_IN_PROGRESS, + EXPECT_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS, oauth2_service_delegate_->load_credentials_state()); base::RunLoop().RunUntilIdle(); - EXPECT_EQ(OAuth2TokenServiceDelegate:: + EXPECT_EQ(signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT, oauth2_service_delegate_->load_credentials_state()); EXPECT_EQ(GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( @@ -428,7 +429,7 @@ // is in the refresh_token map. EXPECT_EQ(1U, oauth2_service_delegate_->refresh_tokens_.size()); EXPECT_EQ( - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken, + GaiaConstants::kInvalidRefreshToken, oauth2_service_delegate_->refresh_tokens_[account_id].refresh_token); // Setup a DB with tokens that don't require upgrade and clear memory. oauth2_service_delegate_->UpdateCredentials(account_id, "refresh_token"); @@ -439,11 +440,12 @@ ResetObserverCounts(); oauth2_service_delegate_->LoadCredentials(account_id); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_IN_PROGRESS, + EXPECT_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS, oauth2_service_delegate_->load_credentials_state()); base::RunLoop().RunUntilIdle(); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - oauth2_service_delegate_->load_credentials_state()); + EXPECT_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + oauth2_service_delegate_->load_credentials_state()); EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(), oauth2_service_delegate_->GetAuthError(account_id)); EXPECT_EQ(2, token_available_count_); @@ -477,14 +479,15 @@ oauth2_service_delegate_->RevokeAllCredentials(); ResetObserverCounts(); // Perform a load from an empty DB. - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_NOT_STARTED, + EXPECT_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED, oauth2_service_delegate_->load_credentials_state()); oauth2_service_delegate_->LoadCredentials(""); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_IN_PROGRESS, + EXPECT_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS, oauth2_service_delegate_->load_credentials_state()); base::RunLoop().RunUntilIdle(); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - oauth2_service_delegate_->load_credentials_state()); + EXPECT_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + oauth2_service_delegate_->load_credentials_state()); EXPECT_EQ(1, end_batch_changes_); EXPECT_EQ(0, auth_error_changed_count_); ExpectOneTokensLoadedNotification(); @@ -502,11 +505,12 @@ ResetObserverCounts(); oauth2_service_delegate_->LoadCredentials(""); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_IN_PROGRESS, + EXPECT_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS, oauth2_service_delegate_->load_credentials_state()); base::RunLoop().RunUntilIdle(); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - oauth2_service_delegate_->load_credentials_state()); + EXPECT_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + oauth2_service_delegate_->load_credentials_state()); EXPECT_EQ(2, token_available_count_); EXPECT_EQ(0, token_revoked_count_); EXPECT_EQ(1, tokens_loaded_count_); @@ -560,8 +564,9 @@ primary_account.account_id)); EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable( secondary_account.account_id)); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - oauth2_service_delegate_->load_credentials_state()); + EXPECT_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + oauth2_service_delegate_->load_credentials_state()); EXPECT_FALSE(pref_service_.GetBoolean(prefs::kTokenServiceDiceCompatible)); } @@ -601,8 +606,9 @@ primary_account.account_id)); EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable( secondary_account.account_id)); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - oauth2_service_delegate_->load_credentials_state()); + EXPECT_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + oauth2_service_delegate_->load_credentials_state()); EXPECT_TRUE(pref_service_.GetBoolean(prefs::kTokenServiceDiceCompatible)); } @@ -640,8 +646,9 @@ EXPECT_EQ(1, auth_error_changed_count_); EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable( primary_account.account_id)); - EXPECT_EQ(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - oauth2_service_delegate_->load_credentials_state()); + EXPECT_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + oauth2_service_delegate_->load_credentials_state()); EXPECT_TRUE(pref_service_.GetBoolean(prefs::kTokenServiceDiceCompatible)); } @@ -679,14 +686,14 @@ EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable( primary_account.account_id)); EXPECT_EQ( - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken, + GaiaConstants::kInvalidRefreshToken, oauth2_service_delegate_->refresh_tokens_[primary_account.account_id] .refresh_token); EXPECT_EQ( GoogleServiceAuthError::InvalidGaiaCredentialsReason::CREDENTIALS_MISSING, oauth2_service_delegate_->GetAuthError(primary_account.account_id) .GetInvalidGaiaCredentialsReason()); - EXPECT_EQ(OAuth2TokenServiceDelegate:: + EXPECT_EQ(signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT, oauth2_service_delegate_->load_credentials_state()); @@ -844,8 +851,7 @@ InitializeOAuth2ServiceDelegate(signin::AccountConsistencyMethod::kDisabled); ASSERT_TRUE(oauth2_service_delegate_->server_revokes_.empty()); oauth2_service_delegate_->UpdateCredentials( - account_id, - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken); + account_id, GaiaConstants::kInvalidRefreshToken); EXPECT_TRUE(oauth2_service_delegate_->server_revokes_.empty()); EXPECT_EQ(1, auth_error_changed_count_); ExpectOneTokenAvailableNotification(); @@ -913,14 +919,13 @@ InitializeOAuth2ServiceDelegate(signin::AccountConsistencyMethod::kDice); std::map<std::string, std::string> tokens; const CoreAccountId account_id("account_id"); - tokens["AccountId-account_id"] = - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken; + tokens["AccountId-account_id"] = GaiaConstants::kInvalidRefreshToken; oauth2_service_delegate_->LoadAllCredentialsIntoMemory(tokens); EXPECT_EQ(1u, oauth2_service_delegate_->GetAccounts().size()); EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(account_id)); - EXPECT_STREQ(MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken, + EXPECT_STREQ(GaiaConstants::kInvalidRefreshToken, oauth2_service_delegate_->GetRefreshToken(account_id).c_str()); // The account is in authentication error. @@ -1359,8 +1364,7 @@ // Start with the SigninErrorController in error state, so that it calls // OnErrorChanged() from AddProvider(). oauth2_service_delegate_->UpdateCredentials( - "error_account_id", - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken); + "error_account_id", GaiaConstants::kInvalidRefreshToken); TokenServiceErrorObserver token_service_observer( oauth2_service_delegate_.get()); @@ -1391,8 +1395,7 @@ oauth2_service_delegate_->GetAuthError("foo")); // Add account with invalid token. oauth2_service_delegate_->UpdateCredentials( - "account_id_2", - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken); + "account_id_2", GaiaConstants::kInvalidRefreshToken); EXPECT_EQ(GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason:: CREDENTIALS_REJECTED_BY_CLIENT), @@ -1447,8 +1450,7 @@ oauth2_service_delegate_.get()); oauth2_service_delegate_->AddObserver(&token_service_observer); oauth2_service_delegate_->UpdateCredentials( - "account_id", - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken); + "account_id", GaiaConstants::kInvalidRefreshToken); EXPECT_TRUE(token_service_observer.token_available_); EXPECT_TRUE(token_service_observer.error_changed_); oauth2_service_delegate_->RemoveObserver(&token_service_observer); @@ -1479,7 +1481,7 @@ EXPECT_FALSE( oauth2_service_delegate_->RefreshTokenIsAvailable(secondary_account)); EXPECT_STREQ( - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken, + GaiaConstants::kInvalidRefreshToken, oauth2_service_delegate_->GetRefreshToken(primary_account).c_str()); EXPECT_EQ(GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( GoogleServiceAuthError::InvalidGaiaCredentialsReason:: @@ -1502,7 +1504,7 @@ EXPECT_FALSE( oauth2_service_delegate_->RefreshTokenIsAvailable(secondary_account)); EXPECT_STREQ( - MutableProfileOAuth2TokenServiceDelegate::kInvalidRefreshToken, + GaiaConstants::kInvalidRefreshToken, oauth2_service_delegate_->GetRefreshToken(primary_account).c_str()); EXPECT_TRUE(oauth2_service_delegate_->server_revokes_.empty()); } @@ -1569,9 +1571,9 @@ "Signin.RefreshTokenUpdated.ToValidToken.Source", Source::kDiceResponseHandler_Signin, 1); - token_service.UpdateCredentials( - "account_id_2", OAuth2TokenServiceDelegate::kInvalidRefreshToken, - Source::kDiceResponseHandler_Signin); + token_service.UpdateCredentials("account_id_2", + GaiaConstants::kInvalidRefreshToken, + Source::kDiceResponseHandler_Signin); EXPECT_EQ("DiceResponseHandler::Signin", source_for_refresh_token_available_); h_tester.ExpectUniqueSample(
diff --git a/google_apis/gaia/oauth2_token_service_delegate.cc b/components/signin/internal/identity_manager/oauth2_token_service_delegate.cc similarity index 92% rename from google_apis/gaia/oauth2_token_service_delegate.cc rename to components/signin/internal/identity_manager/oauth2_token_service_delegate.cc index 445a79cf1..bf45eb6 100644 --- a/google_apis/gaia/oauth2_token_service_delegate.cc +++ b/components/signin/internal/identity_manager/oauth2_token_service_delegate.cc
@@ -2,17 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "google_apis/gaia/oauth2_access_token_consumer.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "google_apis/gaia/oauth2_token_service_observer.h" #include "services/network/public/cpp/shared_url_loader_factory.h" -// static -const char OAuth2TokenServiceDelegate::kInvalidRefreshToken[] = - "invalid_refresh_token"; - OAuth2TokenServiceDelegate::ScopedBatchChange::ScopedBatchChange( OAuth2TokenServiceDelegate* delegate) : delegate_(delegate) { @@ -27,8 +22,7 @@ OAuth2TokenServiceDelegate::OAuth2TokenServiceDelegate() : batch_change_depth_(0) {} -OAuth2TokenServiceDelegate::~OAuth2TokenServiceDelegate() { -} +OAuth2TokenServiceDelegate::~OAuth2TokenServiceDelegate() = default; bool OAuth2TokenServiceDelegate::ValidateAccountId( const CoreAccountId& account_id) const { @@ -128,7 +122,7 @@ } void OAuth2TokenServiceDelegate::ExtractCredentials( - OAuth2TokenService* to_service, + ProfileOAuth2TokenService* to_service, const CoreAccountId& account_id) { NOTREACHED(); }
diff --git a/google_apis/gaia/oauth2_token_service_delegate.h b/components/signin/internal/identity_manager/oauth2_token_service_delegate.h similarity index 86% rename from google_apis/gaia/oauth2_token_service_delegate.h rename to components/signin/internal/identity_manager/oauth2_token_service_delegate.h index 1a0818c..4f17665 100644 --- a/google_apis/gaia/oauth2_token_service_delegate.h +++ b/components/signin/internal/identity_manager/oauth2_token_service_delegate.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ -#define GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ +#ifndef COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ +#define COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ #include <memory> #include <set> @@ -14,9 +14,9 @@ #include "base/memory/ref_counted.h" #include "base/observer_list.h" #include "build/build_config.h" +#include "components/signin/public/identity_manager/load_credentials_state.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/google_service_auth_error.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "net/base/backoff_entry.h" namespace network { @@ -26,27 +26,13 @@ class OAuth2AccessTokenFetcher; class OAuth2AccessTokenConsumer; class OAuth2TokenServiceObserver; +class ProfileOAuth2TokenService; // Abstract base class to fetch and maintain refresh tokens from various // entities. Concrete subclasses should implement RefreshTokenIsAvailable and // CreateAccessTokenFetcher properly. class OAuth2TokenServiceDelegate { public: - // Refresh token guaranteed to be invalid. Can be passed to - // UpdateCredentials() to force an authentication error. - static const char kInvalidRefreshToken[]; - - enum LoadCredentialsState { - LOAD_CREDENTIALS_NOT_STARTED, - LOAD_CREDENTIALS_IN_PROGRESS, - LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - LOAD_CREDENTIALS_FINISHED_WITH_DB_CANNOT_BE_OPENED, - LOAD_CREDENTIALS_FINISHED_WITH_DB_ERRORS, - LOAD_CREDENTIALS_FINISHED_WITH_DECRYPT_ERRORS, - LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT, - LOAD_CREDENTIALS_FINISHED_WITH_UNKNOWN_ERRORS, - }; - OAuth2TokenServiceDelegate(); virtual ~OAuth2TokenServiceDelegate(); @@ -119,7 +105,7 @@ virtual void LoadCredentials(const CoreAccountId& primary_account_id); // Returns the state of the load credentials operation. - LoadCredentialsState load_credentials_state() const { + signin::LoadCredentialsState load_credentials_state() const { return load_credentials_state_; } @@ -127,7 +113,7 @@ // and moves them to |to_service|. The credentials are not revoked on the // server, but the OnRefreshTokenRevoked() notification is sent to the // observers. - virtual void ExtractCredentials(OAuth2TokenService* to_service, + virtual void ExtractCredentials(ProfileOAuth2TokenService* to_service, const CoreAccountId& account_id); // Attempts to fix the error if possible. Returns true if the error was fixed @@ -156,7 +142,7 @@ // ----------------------------------------------------------------------- protected: - void set_load_credentials_state(LoadCredentialsState state) { + void set_load_credentials_state(signin::LoadCredentialsState state) { load_credentials_state_ = state; } @@ -187,7 +173,8 @@ observer_list_; // The state of the load credentials operation. - LoadCredentialsState load_credentials_state_ = LOAD_CREDENTIALS_NOT_STARTED; + signin::LoadCredentialsState load_credentials_state_ = + signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED; void StartBatchChanges(); void EndBatchChanges(); @@ -198,4 +185,4 @@ DISALLOW_COPY_AND_ASSIGN(OAuth2TokenServiceDelegate); }; -#endif // GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ +#endif // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_OAUTH2_TOKEN_SERVICE_DELEGATE_H_
diff --git a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc index cac72ea..7f7ad9eb 100644 --- a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc +++ b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc
@@ -424,8 +424,10 @@ void OAuth2TokenServiceDelegateAndroid::FireRefreshTokensLoaded() { DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::FireRefreshTokensLoaded"; - DCHECK_EQ(LOAD_CREDENTIALS_IN_PROGRESS, load_credentials_state()); - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); + DCHECK_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS, + load_credentials_state()); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); OAuth2TokenServiceDelegate::FireRefreshTokensLoaded(); } @@ -444,8 +446,10 @@ void OAuth2TokenServiceDelegateAndroid::LoadCredentials( const CoreAccountId& primary_account_id) { - DCHECK_EQ(LOAD_CREDENTIALS_NOT_STARTED, load_credentials_state()); - set_load_credentials_state(LOAD_CREDENTIALS_IN_PROGRESS); + DCHECK_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED, + load_credentials_state()); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS); if (primary_account_id.empty() && !base::FeatureList::IsEnabled(signin::kMiceFeature)) { FireRefreshTokensLoaded();
diff --git a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h index 2f40023..0445219 100644 --- a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h +++ b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h
@@ -16,9 +16,9 @@ #include "base/macros.h" #include "base/time/time.h" #include "components/signin/internal/identity_manager/account_tracker_service.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" #include "google_apis/gaia/google_service_auth_error.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" // A specialization of OAuth2TokenServiceDelegate that will be returned by // OAuth2TokenServiceDelegateFactory for OS_ANDROID. This instance uses
diff --git a/google_apis/gaia/oauth2_token_service_delegate_unittest.cc b/components/signin/internal/identity_manager/oauth2_token_service_delegate_unittest.cc similarity index 91% rename from google_apis/gaia/oauth2_token_service_delegate_unittest.cc rename to components/signin/internal/identity_manager/oauth2_token_service_delegate_unittest.cc index 09725ea..fbea332 100644 --- a/google_apis/gaia/oauth2_token_service_delegate_unittest.cc +++ b/components/signin/internal/identity_manager/oauth2_token_service_delegate_unittest.cc
@@ -7,10 +7,10 @@ #include <string> #include "base/macros.h" -#include "google_apis/gaia/fake_oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" #include "google_apis/gaia/oauth2_token_service_observer.h" #include "services/network/test/test_utils.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/components/signin/internal/identity_manager/oauth_multilogin_helper.cc b/components/signin/internal/identity_manager/oauth_multilogin_helper.cc index 189b1dc..e5a3146 100644 --- a/components/signin/internal/identity_manager/oauth_multilogin_helper.cc +++ b/components/signin/internal/identity_manager/oauth_multilogin_helper.cc
@@ -54,7 +54,7 @@ ProfileOAuth2TokenService* token_service, const std::vector<GaiaCookieManagerService::AccountIdGaiaIdPair>& accounts, const std::string& external_cc_result, - base::OnceCallback<void(signin::SetAccountsInCookieResult)> callback) + base::OnceCallback<void(SetAccountsInCookieResult)> callback) : signin_client_(signin_client), token_service_(token_service), accounts_(accounts), @@ -84,7 +84,7 @@ for (const auto& account : accounts_) account_ids.push_back(account.first); - token_fetcher_ = std::make_unique<signin::OAuthMultiloginTokenFetcher>( + token_fetcher_ = std::make_unique<OAuthMultiloginTokenFetcher>( signin_client_, token_service_, account_ids, base::BindOnce(&OAuthMultiloginHelper::OnAccessTokensSuccess, base::Unretained(this)), @@ -114,10 +114,9 @@ void OAuthMultiloginHelper::OnAccessTokensFailure( const GoogleServiceAuthError& error) { token_fetcher_.reset(); - std::move(callback_).Run( - error.IsTransientError() - ? signin::SetAccountsInCookieResult::kTransientError - : signin::SetAccountsInCookieResult::kPersistentError); + std::move(callback_).Run(error.IsTransientError() + ? SetAccountsInCookieResult::kTransientError + : SetAccountsInCookieResult::kPersistentError); // Do not add anything below this line, because this may be deleted. } @@ -166,9 +165,9 @@ StartFetchingTokens(); return; } - std::move(callback_).Run( - is_transient_error ? signin::SetAccountsInCookieResult::kTransientError - : signin::SetAccountsInCookieResult::kPersistentError); + std::move(callback_).Run(is_transient_error + ? SetAccountsInCookieResult::kTransientError + : SetAccountsInCookieResult::kPersistentError); // Do not add anything below this line, because this may be deleted. } @@ -219,7 +218,7 @@ } UMA_HISTOGRAM_BOOLEAN("Signin.SetCookieSuccess", success); if (cookies_to_set_.empty()) - std::move(callback_).Run(signin::SetAccountsInCookieResult::kSuccess); + std::move(callback_).Run(SetAccountsInCookieResult::kSuccess); // Do not add anything below this line, because this may be deleted. }
diff --git a/components/signin/internal/identity_manager/oauth_multilogin_helper.h b/components/signin/internal/identity_manager/oauth_multilogin_helper.h index c225f2cf..e91721e 100644 --- a/components/signin/internal/identity_manager/oauth_multilogin_helper.h +++ b/components/signin/internal/identity_manager/oauth_multilogin_helper.h
@@ -43,7 +43,7 @@ const std::vector<GaiaCookieManagerService::AccountIdGaiaIdPair>& accounts, const std::string& external_cc_result, - base::OnceCallback<void(signin::SetAccountsInCookieResult)> callback); + base::OnceCallback<void(SetAccountsInCookieResult)> callback); ~OAuthMultiloginHelper() override; @@ -83,7 +83,7 @@ // Access tokens, in the same order as the account ids. std::vector<GaiaAuthFetcher::MultiloginTokenIDPair> gaia_id_token_pairs_; - base::OnceCallback<void(signin::SetAccountsInCookieResult)> callback_; + base::OnceCallback<void(SetAccountsInCookieResult)> callback_; std::unique_ptr<GaiaAuthFetcher> gaia_auth_fetcher_; std::unique_ptr<OAuthMultiloginTokenFetcher> token_fetcher_;
diff --git a/components/signin/internal/identity_manager/oauth_multilogin_helper_unittest.cc b/components/signin/internal/identity_manager/oauth_multilogin_helper_unittest.cc index 9b79031..9ad5f88 100644 --- a/components/signin/internal/identity_manager/oauth_multilogin_helper_unittest.cc +++ b/components/signin/internal/identity_manager/oauth_multilogin_helper_unittest.cc
@@ -211,7 +211,7 @@ MockTokenService* token_service() { return &mock_token_service_; } protected: - void OnOAuthMultiloginFinished(signin::SetAccountsInCookieResult result) { + void OnOAuthMultiloginFinished(SetAccountsInCookieResult result) { DCHECK(!callback_called_); callback_called_ = true; result_ = result; @@ -220,7 +220,7 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; bool callback_called_ = false; - signin::SetAccountsInCookieResult result_; + SetAccountsInCookieResult result_; TestingPrefServiceSimple pref_service_; MockCookieManager* mock_cookie_manager_; // Owned by test_signin_client_ @@ -254,7 +254,7 @@ url_loader()->AddResponse(multilogin_url(), kMultiloginSuccessResponse); EXPECT_FALSE(url_loader()->IsPending(multilogin_url())); EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kSuccess, result_); + EXPECT_EQ(SetAccountsInCookieResult::kSuccess, result_); } // Multiple cookies in the multilogin response. @@ -289,7 +289,7 @@ kMultiloginSuccessResponseTwoCookies); EXPECT_FALSE(url_loader()->IsPending(multilogin_url())); EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kSuccess, result_); + EXPECT_EQ(SetAccountsInCookieResult::kSuccess, result_); } // Multiple cookies in the multilogin response. @@ -326,7 +326,7 @@ EXPECT_FALSE( url_loader()->IsPending(multilogin_url_with_external_cc_result())); EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kSuccess, result_); + EXPECT_EQ(SetAccountsInCookieResult::kSuccess, result_); } // Failure to get the access token. @@ -339,7 +339,7 @@ kAccountId, GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)); EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kPersistentError, result_); + EXPECT_EQ(SetAccountsInCookieResult::kPersistentError, result_); } // Retry on transient errors in the multilogin call. @@ -375,7 +375,7 @@ url_loader()->AddResponse(multilogin_url(), kMultiloginSuccessResponse); EXPECT_FALSE(url_loader()->IsPending(multilogin_url())); EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kSuccess, result_); + EXPECT_EQ(SetAccountsInCookieResult::kSuccess, result_); } // Stop retrying after too many transient errors in the multilogin call. @@ -400,7 +400,7 @@ // Failure after exceeding the maximum number of retries. EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kTransientError, result_); + EXPECT_EQ(SetAccountsInCookieResult::kTransientError, result_); } // Persistent error in the multilogin call. @@ -420,7 +420,7 @@ url_loader()->AddResponse(multilogin_url(), "blah"); // Unexpected response. EXPECT_FALSE(url_loader()->IsPending(multilogin_url())); EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kPersistentError, result_); + EXPECT_EQ(SetAccountsInCookieResult::kPersistentError, result_); } // Retry on "invalid token" in the multilogin response. @@ -468,7 +468,7 @@ url_loader()->AddResponse(multilogin_url(), kMultiloginSuccessResponse); EXPECT_FALSE(url_loader()->IsPending(multilogin_url())); EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kSuccess, result_); + EXPECT_EQ(SetAccountsInCookieResult::kSuccess, result_); } // Retry on "invalid token" in the multilogin response. @@ -505,7 +505,7 @@ // The maximum number of retries is reached, fail. EXPECT_FALSE(url_loader()->IsPending(multilogin_url())); EXPECT_TRUE(callback_called_); - EXPECT_EQ(signin::SetAccountsInCookieResult::kTransientError, result_); + EXPECT_EQ(SetAccountsInCookieResult::kTransientError, result_); } } // namespace signin
diff --git a/components/signin/internal/identity_manager/primary_account_manager_unittest.cc b/components/signin/internal/identity_manager/primary_account_manager_unittest.cc index baa35df..05802433 100644 --- a/components/signin/internal/identity_manager/primary_account_manager_unittest.cc +++ b/components/signin/internal/identity_manager/primary_account_manager_unittest.cc
@@ -18,13 +18,13 @@ #include "components/prefs/testing_pref_service.h" #include "components/signin/internal/identity_manager/account_fetcher_service.h" #include "components/signin/internal/identity_manager/account_tracker_service.h" +#include "components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h" #include "components/signin/internal/identity_manager/primary_account_policy_manager.h" #include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" #include "components/signin/public/base/account_consistency_method.h" #include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/base/test_signin_client.h" #include "components/sync_preferences/testing_pref_service_syncable.h" -#include "google_apis/gaia/fake_oauth2_token_service_delegate.h" #include "testing/gtest/include/gtest/gtest.h" #if !defined(OS_CHROMEOS)
diff --git a/components/signin/internal/identity_manager/primary_account_mutator_impl.cc b/components/signin/internal/identity_manager/primary_account_mutator_impl.cc index e873a88..f9d1eba 100644 --- a/components/signin/internal/identity_manager/primary_account_mutator_impl.cc +++ b/components/signin/internal/identity_manager/primary_account_mutator_impl.cc
@@ -14,7 +14,7 @@ #include "components/signin/public/base/signin_pref_names.h" #include "google_apis/gaia/core_account_id.h" -namespace identity { +namespace signin { PrimaryAccountMutatorImpl::PrimaryAccountMutatorImpl( AccountTrackerService* account_tracker, @@ -87,4 +87,4 @@ } #endif -} // namespace identity +} // namespace signin
diff --git a/components/signin/internal/identity_manager/primary_account_mutator_impl.h b/components/signin/internal/identity_manager/primary_account_mutator_impl.h index d8ec968..f15e6c1 100644 --- a/components/signin/internal/identity_manager/primary_account_mutator_impl.h +++ b/components/signin/internal/identity_manager/primary_account_mutator_impl.h
@@ -13,7 +13,7 @@ class PrefService; class PrimaryAccountManager; -namespace identity { +namespace signin { // Concrete implementation of PrimaryAccountMutator that is based on the // PrimaryAccountManager API. @@ -45,6 +45,6 @@ PrefService* pref_service_ = nullptr; }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_PRIMARY_ACCOUNT_MUTATOR_IMPL_H_
diff --git a/components/signin/internal/identity_manager/primary_account_policy_manager_impl.cc b/components/signin/internal/identity_manager/primary_account_policy_manager_impl.cc index c09404e..426aa6b 100644 --- a/components/signin/internal/identity_manager/primary_account_policy_manager_impl.cc +++ b/components/signin/internal/identity_manager/primary_account_policy_manager_impl.cc
@@ -103,5 +103,5 @@ if (!local_state) return true; - return identity::IsUsernameAllowedByPatternFromPrefs(local_state, username); + return signin::IsUsernameAllowedByPatternFromPrefs(local_state, username); }
diff --git a/components/signin/internal/identity_manager/primary_account_policy_manager_impl_unittest.cc b/components/signin/internal/identity_manager/primary_account_policy_manager_impl_unittest.cc index e166b560..8016c4c5 100644 --- a/components/signin/internal/identity_manager/primary_account_policy_manager_impl_unittest.cc +++ b/components/signin/internal/identity_manager/primary_account_policy_manager_impl_unittest.cc
@@ -10,6 +10,7 @@ #include "base/test/scoped_task_environment.h" #include "components/prefs/testing_pref_service.h" #include "components/signin/internal/identity_manager/account_tracker_service.h" +#include "components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h" #include "components/signin/internal/identity_manager/primary_account_manager.h" #include "components/signin/internal/identity_manager/primary_account_policy_manager_impl.h" #include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" @@ -17,7 +18,6 @@ #include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/base/test_signin_client.h" #include "components/sync_preferences/testing_pref_service_syncable.h" -#include "google_apis/gaia/fake_oauth2_token_service_delegate.h" #include "testing/gtest/include/gtest/gtest.h" class PrimaryAccountPolicyManagerImplTest : public testing::Test {
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service.cc b/components/signin/internal/identity_manager/profile_oauth2_token_service.cc index bf3f8ad..d108f70 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service.cc +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service.cc
@@ -9,6 +9,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/prefs/pref_registry_simple.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "components/signin/public/base/device_id_helper.h" #include "components/signin/public/base/signin_pref_names.h" #include "google_apis/gaia/gaia_constants.h" @@ -16,7 +17,6 @@ #include "google_apis/gaia/oauth2_access_token_consumer.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h" #include "google_apis/gaia/oauth2_access_token_manager.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" #include "services/network/public/cpp/shared_url_loader_factory.h" using signin_metrics::SourceForRefreshTokenOperation; @@ -69,8 +69,8 @@ ProfileOAuth2TokenService::ProfileOAuth2TokenService( PrefService* user_prefs, std::unique_ptr<OAuth2TokenServiceDelegate> delegate) - : OAuth2TokenService(std::move(delegate)), - user_prefs_(user_prefs), + : user_prefs_(user_prefs), + delegate_(std::move(delegate)), all_credentials_loaded_(false) { DCHECK(user_prefs_); DCHECK(delegate_); @@ -135,6 +135,15 @@ std::string()); } +OAuth2TokenServiceDelegate* ProfileOAuth2TokenService::GetDelegate() { + return delegate_.get(); +} + +const OAuth2TokenServiceDelegate* ProfileOAuth2TokenService::GetDelegate() + const { + return delegate_.get(); +} + void ProfileOAuth2TokenService::AddObserver( OAuth2TokenServiceObserver* observer) { delegate_->AddObserver(observer); @@ -401,9 +410,9 @@ void ProfileOAuth2TokenService::OnRefreshTokensLoaded() { all_credentials_loaded_ = true; - DCHECK_NE(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_NOT_STARTED, + DCHECK_NE(signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED, GetDelegate()->load_credentials_state()); - DCHECK_NE(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_IN_PROGRESS, + DCHECK_NE(signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS, GetDelegate()->load_credentials_state()); // Reset the state for update refresh token operations to Unknown as this @@ -435,21 +444,21 @@ bool ProfileOAuth2TokenService::HasLoadCredentialsFinishedWithNoErrors() { switch (GetDelegate()->load_credentials_state()) { - case OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_NOT_STARTED: - case OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_IN_PROGRESS: + case signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED: + case signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS: // LoadCredentials has not finished. return false; - case OAuth2TokenServiceDelegate:: + case signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_DB_CANNOT_BE_OPENED: - case OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_DB_ERRORS: - case OAuth2TokenServiceDelegate:: + case signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_DB_ERRORS: + case signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_DECRYPT_ERRORS: - case OAuth2TokenServiceDelegate:: + case signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_UNKNOWN_ERRORS: // LoadCredentials finished, but with errors return false; - case OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS: - case OAuth2TokenServiceDelegate:: + case signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS: + case signin::LoadCredentialsState:: LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT: // Load credentials finished with success. return true;
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service.h b/components/signin/internal/identity_manager/profile_oauth2_token_service.h index e9f2b01..16975f56 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service.h +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service.h
@@ -19,11 +19,10 @@ #include "google_apis/gaia/core_account_id.h" #include "google_apis/gaia/google_service_auth_error.h" #include "google_apis/gaia/oauth2_access_token_manager.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "google_apis/gaia/oauth2_token_service_observer.h" #include "net/base/backoff_entry.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -36,7 +35,22 @@ // OAuth2 access tokens for a given set of scopes using the OAuth2 login // refresh tokens. // -// See |OAuth2TokenService| for usage details. +// To use this service, call StartRequest() with a given set of scopes and a +// consumer of the request results. The consumer is required to outlive the +// request. The request can be deleted. The consumer may be called back +// asynchronously with the fetch results. +// +// - If the consumer is not called back before the request is deleted, it will +// never be called back. +// Note in this case, the actual network requests are not canceled and the +// cache will be populated with the fetched results; it is just the consumer +// callback that is aborted. +// +// - Otherwise the consumer will be called back with the request and the fetch +// results. +// +// The caller of StartRequest() owns the returned request and is responsible to +// delete the request even once the callback has been invoked. // // Note: after StartRequest returns, in-flight requests will continue // even if the TokenService refresh token that was used to initiate @@ -45,8 +59,7 @@ // won't be cached. // // Note: requests should be started from the UI thread. -class ProfileOAuth2TokenService : public OAuth2TokenService, - public OAuth2AccessTokenManager::Delegate, +class ProfileOAuth2TokenService : public OAuth2AccessTokenManager::Delegate, public OAuth2TokenServiceObserver { public: typedef base::RepeatingCallback<void(const CoreAccountId& /* account_id */, @@ -81,6 +94,9 @@ // Registers per-profile prefs. static void RegisterProfilePrefs(PrefRegistrySimple* registry); + OAuth2TokenServiceDelegate* GetDelegate(); + const OAuth2TokenServiceDelegate* GetDelegate() const; + // Add or remove observers of this token service. void AddObserver(OAuth2TokenServiceObserver* observer); void RemoveObserver(OAuth2TokenServiceObserver* observer); @@ -252,7 +268,7 @@ OAuth2AccessTokenManager* GetAccessTokenManager(); private: - friend class identity::IdentityManager; + friend class signin::IdentityManager; // OAuth2TokenServiceObserver implementation. void OnRefreshTokenAvailable(const CoreAccountId& account_id) override; @@ -279,6 +295,8 @@ PrefService* user_prefs_; + std::unique_ptr<OAuth2TokenServiceDelegate> delegate_; + // Whether all credentials have been loaded. bool all_credentials_loaded_;
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.cc b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.cc index 98b4770..3a064c6 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.cc +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.cc
@@ -93,7 +93,9 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, OAuth2AccessTokenConsumer* consumer) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, load_credentials_state()); + DCHECK_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + load_credentials_state()); ValidateAccountId(account_id); @@ -131,7 +133,8 @@ // |GetOAuthAccountIdsFromAccountKeys|. bool ProfileOAuth2TokenServiceDelegateChromeOS::RefreshTokenIsAvailable( const CoreAccountId& account_id) const { - if (load_credentials_state() != LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS) { + if (load_credentials_state() != + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS) { return false; } @@ -201,10 +204,12 @@ const CoreAccountId& primary_account_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (load_credentials_state() != LOAD_CREDENTIALS_NOT_STARTED) { + if (load_credentials_state() != + signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED) { return; } - set_load_credentials_state(LOAD_CREDENTIALS_IN_PROGRESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS); if (!is_regular_profile_) { // |LoadCredentials| needs to complete successfully for a successful Profile @@ -213,7 +218,8 @@ // to them. Note: They do have access to an Account Manager instance, but // that instance is never set up (|AccountManager::Initialize|). Also, see // http://crbug.com/891818 - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); FireRefreshTokensLoaded(); return; } @@ -254,7 +260,9 @@ // Accounts) we can be sure that |account_id| is present in // |AccountTrackerService|. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, load_credentials_state()); + DCHECK_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + load_credentials_state()); DCHECK(!account_id.empty()); DCHECK(!refresh_token.empty()); @@ -287,9 +295,11 @@ // This callback should only be triggered during |LoadCredentials|, which // implies that |load_credentials_state())| should in // |LOAD_CREDENTIALS_IN_PROGRESS| state. - DCHECK_EQ(LOAD_CREDENTIALS_IN_PROGRESS, load_credentials_state()); + DCHECK_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS, + load_credentials_state()); - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); // The typical order of |OAuth2TokenServiceObserver| callbacks is: // 1. OnRefreshTokenAvailable // 2. OnEndBatchChanges @@ -350,7 +360,9 @@ void ProfileOAuth2TokenServiceDelegateChromeOS::OnAccountRemoved( const chromeos::AccountManager::Account& account) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, load_credentials_state()); + DCHECK_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + load_credentials_state()); auto it = account_keys_.find(account.key); if (it == account_keys_.end()) {
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h index bebc41b..cfa68b6 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h
@@ -15,7 +15,7 @@ #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" #include "chromeos/components/account_manager/account_manager.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "services/network/public/cpp/network_connection_tracker.h" class AccountTrackerService;
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos_unittest.cc b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos_unittest.cc index b020319..d44601f1 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos_unittest.cc +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos_unittest.cc
@@ -25,7 +25,6 @@ #include "google_apis/gaia/oauth2_access_token_consumer.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h" #include "google_apis/gaia/oauth2_access_token_manager_test_util.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "google_apis/gaia/oauth2_token_service_observer.h" #include "services/network/test/test_network_connection_tracker.h" #include "testing/gtest/include/gtest/gtest.h" @@ -242,15 +241,13 @@ EXPECT_FALSE(observer.refresh_tokens_loaded_); delegate->LoadCredentials("" /* primary_account_id */); EXPECT_TRUE(observer.refresh_tokens_loaded_); - EXPECT_EQ(OAuth2TokenServiceDelegate::LoadCredentialsState:: - LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + EXPECT_EQ(LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, delegate->load_credentials_state()); } TEST_F(CrOSOAuthDelegateTest, RefreshTokenIsAvailableReturnsTrueForValidGaiaTokens) { - EXPECT_EQ(OAuth2TokenServiceDelegate::LoadCredentialsState:: - LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + EXPECT_EQ(LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, delegate_->load_credentials_state()); EXPECT_FALSE(delegate_->RefreshTokenIsAvailable(account_info_.account_id)); @@ -266,8 +263,7 @@ TEST_F(CrOSOAuthDelegateTest, RefreshTokenIsAvailableReturnsTrueForInvalidGaiaTokens) { - EXPECT_EQ(OAuth2TokenServiceDelegate::LoadCredentialsState:: - LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + EXPECT_EQ(LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, delegate_->load_credentials_state()); EXPECT_FALSE(delegate_->RefreshTokenIsAvailable(account_info_.account_id)); @@ -484,8 +480,7 @@ TEST_F(CrOSOAuthDelegateTest, RefreshTokenMustBeAvailableForAllAccountsReturnedByGetAccounts) { - EXPECT_EQ(OAuth2TokenServiceDelegate::LoadCredentialsState:: - LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + EXPECT_EQ(LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, delegate_->load_credentials_state()); EXPECT_TRUE(delegate_->GetAccounts().empty()); const std::string kUserEmail2 = "random-email2@example.com";
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.h b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.h index 009f0e9..e6e848f 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.h +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.h
@@ -12,7 +12,7 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/threading/thread_checker.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" class AccountTrackerService; class DeviceAccountsProvider;
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.mm b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.mm index f924796..17e96fd 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.mm +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.mm
@@ -179,8 +179,10 @@ const CoreAccountId& primary_account_id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK_EQ(LOAD_CREDENTIALS_NOT_STARTED, load_credentials_state()); - set_load_credentials_state(LOAD_CREDENTIALS_IN_PROGRESS); + DCHECK_EQ(signin::LoadCredentialsState::LOAD_CREDENTIALS_NOT_STARTED, + load_credentials_state()); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_IN_PROGRESS); // Clean-up stale data from prefs. ClearExcludedSecondaryAccounts(); @@ -188,14 +190,16 @@ if (primary_account_id.empty()) { // On startup, always fire refresh token loaded even if there is nothing // to load (not authenticated). - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); FireRefreshTokensLoaded(); return; } ReloadCredentials(); - set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); + set_load_credentials_state( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); FireRefreshTokensLoaded(); }
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_unittest.cc b/components/signin/internal/identity_manager/profile_oauth2_token_service_unittest.cc index 4973017..bf1b570b 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service_unittest.cc +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_unittest.cc
@@ -11,7 +11,7 @@ #include "base/run_loop.h" #include "base/threading/platform_thread.h" #include "components/prefs/testing_pref_service.h" -#include "google_apis/gaia/fake_oauth2_token_service_delegate.h" +#include "components/signin/internal/identity_manager/fake_oauth2_token_service_delegate.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h"
diff --git a/components/signin/ios/browser/DEPS b/components/signin/ios/browser/DEPS new file mode 100644 index 0000000..1cbae6d8 --- /dev/null +++ b/components/signin/ios/browser/DEPS
@@ -0,0 +1,10 @@ +specific_include_rules = { + "account_consistency_service.mm": [ + "+components/signin/core/browser/account_reconcilor.h", + "+components/signin/core/browser/signin_header_helper.h", + ], + "account_consistency_service_unittest.mm": [ + "+components/signin/core/browser/account_reconcilor.h", + "+components/signin/core/browser/account_reconcilor_delegate.h", + ], +}
diff --git a/components/signin/ios/browser/account_consistency_service.h b/components/signin/ios/browser/account_consistency_service.h index 942c1586..3d53f0a 100644 --- a/components/signin/ios/browser/account_consistency_service.h +++ b/components/signin/ios/browser/account_consistency_service.h
@@ -42,7 +42,7 @@ // // This is currently only used when WKWebView is enabled. class AccountConsistencyService : public KeyedService, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public ActiveStateManager::Observer { public: // Name of the preference property that persists the domains that have a @@ -54,7 +54,7 @@ PrefService* prefs, AccountReconcilor* account_reconcilor, scoped_refptr<content_settings::CookieSettings> cookie_settings, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~AccountConsistencyService() override; // Registers the preferences used by AccountConsistencyService. @@ -151,7 +151,7 @@ void OnPrimaryAccountCleared( const CoreAccountInfo& previous_account_info) override; void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; // ActiveStateManager::Observer implementation. @@ -170,7 +170,7 @@ scoped_refptr<content_settings::CookieSettings> cookie_settings_; // Identity manager, observed to be notified of primary account signin and // signout events. - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // Whether a CHROME_CONNECTED cookie request is currently being applied. bool applying_cookie_requests_;
diff --git a/components/signin/ios/browser/account_consistency_service.mm b/components/signin/ios/browser/account_consistency_service.mm index 5b1ef2e..0f8da0c 100644 --- a/components/signin/ios/browser/account_consistency_service.mm +++ b/components/signin/ios/browser/account_consistency_service.mm
@@ -222,7 +222,7 @@ PrefService* prefs, AccountReconcilor* account_reconcilor, scoped_refptr<content_settings::CookieSettings> cookie_settings, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : browser_state_(browser_state), prefs_(prefs), account_reconcilor_(account_reconcilor), @@ -489,7 +489,7 @@ } void AccountConsistencyService::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { AddChromeConnectedCookies(); }
diff --git a/components/signin/ios/browser/account_consistency_service_unittest.mm b/components/signin/ios/browser/account_consistency_service_unittest.mm index 17305e6..66f0de1 100644 --- a/components/signin/ios/browser/account_consistency_service_unittest.mm +++ b/components/signin/ios/browser/account_consistency_service_unittest.mm
@@ -60,7 +60,7 @@ PrefService* prefs, AccountReconcilor* account_reconcilor, scoped_refptr<content_settings::CookieSettings> cookie_settings, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : AccountConsistencyService(browser_state, prefs, account_reconcilor, @@ -135,7 +135,7 @@ web_view_load_expection_count_ = 0; signin_client_.reset( new TestSigninClient(&prefs_, &test_url_loader_factory_)); - identity_test_env_.reset(new identity::IdentityTestEnvironment( + identity_test_env_.reset(new signin::IdentityTestEnvironment( /*test_url_loader_factory=*/nullptr, &prefs_, signin::AccountConsistencyMethod::kDisabled, signin_client_.get())); settings_map_ = new HostContentSettingsMap( @@ -187,14 +187,14 @@ } void SignIn() { - identity::MakePrimaryAccountAvailable( - identity_test_env_->identity_manager(), "user@gmail.com"); + signin::MakePrimaryAccountAvailable(identity_test_env_->identity_manager(), + "user@gmail.com"); EXPECT_EQ(0, web_view_load_expection_count_); } void SignOutAndSimulateGaiaCookieManagerServiceLogout() { - identity::ClearPrimaryAccount(identity_test_env_->identity_manager(), - identity::ClearPrimaryAccountPolicy::DEFAULT); + signin::ClearPrimaryAccount(identity_test_env_->identity_manager(), + signin::ClearPrimaryAccountPolicy::DEFAULT); SimulateGaiaCookieManagerServiceLogout(true); } @@ -241,7 +241,7 @@ TestWebState web_state_; network::TestURLLoaderFactory test_url_loader_factory_; - std::unique_ptr<identity::IdentityTestEnvironment> identity_test_env_; + std::unique_ptr<signin::IdentityTestEnvironment> identity_test_env_; // AccountConsistencyService being tested. Actually a // FakeAccountConsistencyService to be able to use a mock web view. std::unique_ptr<AccountConsistencyService> account_consistency_service_;
diff --git a/components/signin/public/identity_manager/BUILD.gn b/components/signin/public/identity_manager/BUILD.gn index edb4671..a5bf5eba 100644 --- a/components/signin/public/identity_manager/BUILD.gn +++ b/components/signin/public/identity_manager/BUILD.gn
@@ -22,6 +22,7 @@ "identity_manager_builder.h", "identity_utils.cc", "identity_utils.h", + "load_credentials_state.h", "primary_account_access_token_fetcher.cc", "primary_account_access_token_fetcher.h", "primary_account_mutator.h",
diff --git a/components/signin/public/identity_manager/DEPS b/components/signin/public/identity_manager/DEPS new file mode 100644 index 0000000..eada2e2 --- /dev/null +++ b/components/signin/public/identity_manager/DEPS
@@ -0,0 +1,3 @@ +include_rules = [ + "+components/signin/internal", +]
diff --git a/components/signin/public/identity_manager/access_token_fetcher.cc b/components/signin/public/identity_manager/access_token_fetcher.cc index e2b4eab4..200770b 100644 --- a/components/signin/public/identity_manager/access_token_fetcher.cc +++ b/components/signin/public/identity_manager/access_token_fetcher.cc
@@ -12,7 +12,7 @@ #include "google_apis/gaia/google_service_auth_error.h" #include "services/network/public/cpp/shared_url_loader_factory.h" -namespace identity { +namespace signin { AccessTokenFetcher::AccessTokenFetcher(const CoreAccountId& account_id, const std::string& oauth_consumer_name, @@ -187,4 +187,4 @@ std::move(callback_).Run(std::move(error), std::move(access_token_info)); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/access_token_fetcher.h b/components/signin/public/identity_manager/access_token_fetcher.h index e5bc9de..0ee97625 100644 --- a/components/signin/public/identity_manager/access_token_fetcher.h +++ b/components/signin/public/identity_manager/access_token_fetcher.h
@@ -24,7 +24,7 @@ class GoogleServiceAuthError; class ProfileOAuth2TokenService; -namespace identity { +namespace signin { struct AccessTokenInfo; // Helper class to ease the task of obtaining an OAuth2 access token for a @@ -146,6 +146,6 @@ DISALLOW_COPY_AND_ASSIGN(AccessTokenFetcher); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCESS_TOKEN_FETCHER_H_
diff --git a/components/signin/public/identity_manager/access_token_fetcher_unittest.cc b/components/signin/public/identity_manager/access_token_fetcher_unittest.cc index ce989887..c16c340 100644 --- a/components/signin/public/identity_manager/access_token_fetcher_unittest.cc +++ b/components/signin/public/identity_manager/access_token_fetcher_unittest.cc
@@ -13,11 +13,11 @@ #include "components/prefs/testing_pref_service.h" #include "components/signin/internal/identity_manager/account_tracker_service.h" #include "components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/oauth2_access_token_consumer.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" @@ -28,7 +28,7 @@ using testing::_; using testing::StrictMock; -namespace identity { +namespace signin { namespace { @@ -608,4 +608,4 @@ access_token_info().id_token)); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/access_token_info.cc b/components/signin/public/identity_manager/access_token_info.cc index b4c7acfa..8b377ad2 100644 --- a/components/signin/public/identity_manager/access_token_info.cc +++ b/components/signin/public/identity_manager/access_token_info.cc
@@ -4,7 +4,7 @@ #include "components/signin/public/identity_manager/access_token_info.h" -namespace identity { +namespace signin { bool operator==(const AccessTokenInfo& lhs, const AccessTokenInfo& rhs) { return (lhs.token == rhs.token) && @@ -12,4 +12,4 @@ (lhs.id_token == rhs.id_token); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/access_token_info.h b/components/signin/public/identity_manager/access_token_info.h index 5be2a07e..974a15fd 100644 --- a/components/signin/public/identity_manager/access_token_info.h +++ b/components/signin/public/identity_manager/access_token_info.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "base/time/time.h" -namespace identity { +namespace signin { // Container for a valid access token plus associated metadata. struct AccessTokenInfo { @@ -37,6 +37,6 @@ // Defined for testing purposes only. bool operator==(const AccessTokenInfo& lhs, const AccessTokenInfo& rhs); -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCESS_TOKEN_INFO_H_
diff --git a/components/signin/public/identity_manager/accounts_cookie_mutator.h b/components/signin/public/identity_manager/accounts_cookie_mutator.h index a7bd3e7..af5dd83 100644 --- a/components/signin/public/identity_manager/accounts_cookie_mutator.h +++ b/components/signin/public/identity_manager/accounts_cookie_mutator.h
@@ -11,14 +11,12 @@ #include "base/macros.h" #include "google_apis/gaia/gaia_auth_fetcher.h" -namespace signin { -enum class SetAccountsInCookieResult; -} - struct CoreAccountId; class GoogleServiceAuthError; -namespace identity { +namespace signin { + +enum class SetAccountsInCookieResult; // AccountsCookieMutator is the interface to support merging known local Google // accounts into the cookie jar tracking the list of logged-in Google sessions. @@ -58,7 +56,7 @@ virtual void SetAccountsInCookie( const std::vector<CoreAccountId>& account_ids, gaia::GaiaSource source, - base::OnceCallback<void(signin::SetAccountsInCookieResult)> + base::OnceCallback<void(SetAccountsInCookieResult)> set_accounts_in_cookies_completed_callback) = 0; // Triggers a ListAccounts fetch. Can be used in circumstances where clients @@ -72,6 +70,6 @@ DISALLOW_COPY_AND_ASSIGN(AccountsCookieMutator); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCOUNTS_COOKIE_MUTATOR_H_
diff --git a/components/signin/public/identity_manager/accounts_cookie_mutator_unittest.cc b/components/signin/public/identity_manager/accounts_cookie_mutator_unittest.cc index 635429bd..add100d3 100644 --- a/components/signin/public/identity_manager/accounts_cookie_mutator_unittest.cc +++ b/components/signin/public/identity_manager/accounts_cookie_mutator_unittest.cc
@@ -57,14 +57,14 @@ } // namespace -namespace identity { +namespace signin { class AccountsCookieMutatorTest : public testing::Test { public: AccountsCookieMutatorTest() : test_signin_client_(&prefs_), identity_test_env_(/*test_url_loader_factory=*/nullptr, &prefs_, - signin::AccountConsistencyMethod::kDisabled, + AccountConsistencyMethod::kDisabled, &test_signin_client_) {} ~AccountsCookieMutatorTest() override {} @@ -113,18 +113,16 @@ std::string(kTestOAuthMultiLoginResponse), net::HTTP_OK); break; case AccountsCookiesMutatorAction::kTriggerCookieJarUpdateNoAccounts: - signin::SetListAccountsResponseNoAccounts(GetTestURLLoaderFactory()); + SetListAccountsResponseNoAccounts(GetTestURLLoaderFactory()); break; case AccountsCookiesMutatorAction::kTriggerCookieJarUpdateOneAccount: - signin::SetListAccountsResponseOneAccount( - kTestAccountEmail, kTestAccountGaiaId, GetTestURLLoaderFactory()); + SetListAccountsResponseOneAccount(kTestAccountEmail, kTestAccountGaiaId, + GetTestURLLoaderFactory()); break; } } - identity::IdentityTestEnvironment* identity_test_env() { - return &identity_test_env_; - } + IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } TestIdentityManagerObserver* identity_manager_observer() { return identity_test_env_.identity_manager_observer(); @@ -142,7 +140,7 @@ base::test::ScopedTaskEnvironment task_environment_; sync_preferences::TestingPrefServiceSyncable prefs_; TestSigninClient test_signin_client_; - identity::IdentityTestEnvironment identity_test_env_; + IdentityTestEnvironment identity_test_env_; DISALLOW_COPY_AND_ASSIGN(AccountsCookieMutatorTest); }; @@ -282,10 +280,8 @@ accounts_cookie_mutator()->SetAccountsInCookie( accounts_ids, gaia::GaiaSource::kChrome, base::BindOnce( - [](base::OnceClosure quit_closure, - signin::SetAccountsInCookieResult result) { - EXPECT_EQ(result, - signin::SetAccountsInCookieResult::kPersistentError); + [](base::OnceClosure quit_closure, SetAccountsInCookieResult result) { + EXPECT_EQ(result, SetAccountsInCookieResult::kPersistentError); std::move(quit_closure).Run(); }, run_loop.QuitClosure())); @@ -309,10 +305,8 @@ accounts_cookie_mutator()->SetAccountsInCookie( accounts_ids, gaia::GaiaSource::kChrome, base::BindOnce( - [](base::OnceClosure quit_closure, - signin::SetAccountsInCookieResult result) { - EXPECT_EQ(result, - signin::SetAccountsInCookieResult::kPersistentError); + [](base::OnceClosure quit_closure, SetAccountsInCookieResult result) { + EXPECT_EQ(result, SetAccountsInCookieResult::kPersistentError); std::move(quit_closure).Run(); }, run_loop.QuitClosure())); @@ -337,9 +331,8 @@ accounts_cookie_mutator()->SetAccountsInCookie( accounts_ids, gaia::GaiaSource::kChrome, base::BindOnce( - [](base::OnceClosure quit_closure, - signin::SetAccountsInCookieResult result) { - EXPECT_EQ(result, signin::SetAccountsInCookieResult::kSuccess); + [](base::OnceClosure quit_closure, SetAccountsInCookieResult result) { + EXPECT_EQ(result, SetAccountsInCookieResult::kSuccess); std::move(quit_closure).Run(); }, run_loop.QuitClosure())); @@ -426,4 +419,4 @@ run_loop.Run(); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/accounts_in_cookie_jar_info.cc b/components/signin/public/identity_manager/accounts_in_cookie_jar_info.cc index 993b40d..840c204 100644 --- a/components/signin/public/identity_manager/accounts_in_cookie_jar_info.cc +++ b/components/signin/public/identity_manager/accounts_in_cookie_jar_info.cc
@@ -4,7 +4,7 @@ #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" -namespace identity { +namespace signin { AccountsInCookieJarInfo::AccountsInCookieJarInfo() = default; @@ -27,4 +27,4 @@ AccountsInCookieJarInfo::~AccountsInCookieJarInfo() = default; -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/accounts_in_cookie_jar_info.h b/components/signin/public/identity_manager/accounts_in_cookie_jar_info.h index 0057278..1b54539d 100644 --- a/components/signin/public/identity_manager/accounts_in_cookie_jar_info.h +++ b/components/signin/public/identity_manager/accounts_in_cookie_jar_info.h
@@ -9,7 +9,7 @@ #include "google_apis/gaia/gaia_auth_util.h" -namespace identity { +namespace signin { // Container for a response to get the accounts in the cookie jar. struct AccountsInCookieJarInfo { @@ -32,6 +32,6 @@ ~AccountsInCookieJarInfo(); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCOUNTS_IN_COOKIE_JAR_INFO_H_
diff --git a/components/signin/public/identity_manager/accounts_mutator.h b/components/signin/public/identity_manager/accounts_mutator.h index 92b105c..eb556987 100644 --- a/components/signin/public/identity_manager/accounts_mutator.h +++ b/components/signin/public/identity_manager/accounts_mutator.h
@@ -17,7 +17,7 @@ struct CoreAccountId; -namespace identity { +namespace signin { // AccountsMutator is the interface to support seeding of account info and // mutation of refresh tokens for the user's Gaia accounts. @@ -77,6 +77,6 @@ DISALLOW_COPY_AND_ASSIGN(AccountsMutator); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCOUNTS_MUTATOR_H_
diff --git a/components/signin/public/identity_manager/accounts_mutator_unittest.cc b/components/signin/public/identity_manager/accounts_mutator_unittest.cc index 9f6e6b3..98669f6 100644 --- a/components/signin/public/identity_manager/accounts_mutator_unittest.cc +++ b/components/signin/public/identity_manager/accounts_mutator_unittest.cc
@@ -28,12 +28,12 @@ const char kRefreshToken2[] = "refresh_token_2"; const char kSupervisedUserPseudoEmail[] = "managed_user@localhost"; -// Class that observes diagnostics updates from identity::IdentityManager. +// Class that observes diagnostics updates from signin::IdentityManager. class TestIdentityManagerDiagnosticsObserver - : public identity::IdentityManager::DiagnosticsObserver { + : public signin::IdentityManager::DiagnosticsObserver { public: explicit TestIdentityManagerDiagnosticsObserver( - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : identity_manager_(identity_manager) { identity_manager_->AddDiagnosticsObserver(this); } @@ -54,7 +54,7 @@ const std::string& token_remover_source() { return token_remover_source_; } private: - // identity::IdentityManager::DiagnosticsObserver: + // signin::IdentityManager::DiagnosticsObserver: void OnRefreshTokenUpdatedForAccountFromSource( const CoreAccountId& account_id, bool is_refresh_token_valid, @@ -71,7 +71,7 @@ token_remover_source_ = source; } - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; std::string token_updator_account_id_; std::string token_updator_source_; std::string token_remover_account_id_; @@ -81,7 +81,7 @@ } // namespace -namespace identity { +namespace signin { class AccountsMutatorTest : public testing::Test { public: AccountsMutatorTest() @@ -92,7 +92,7 @@ PrefService* pref_service() { return &prefs_; } - identity::IdentityManager* identity_manager() { + IdentityManager* identity_manager() { return identity_test_env_.identity_manager(); } @@ -113,7 +113,7 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; sync_preferences::TestingPrefServiceSyncable prefs_; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_env_; + IdentityTestEnvironment identity_test_env_; TestIdentityManagerDiagnosticsObserver identity_manager_diagnostics_observer_; DISALLOW_COPY_AND_ASSIGN(AccountsMutatorTest); @@ -323,8 +323,8 @@ // Set up the primary account. std::string primary_account_email("primary.account@example.com"); - AccountInfo primary_account_info = identity::MakePrimaryAccountAvailable( - identity_manager(), primary_account_email); + AccountInfo primary_account_info = + MakePrimaryAccountAvailable(identity_manager(), primary_account_email); // Now try invalidating the primary account, and check that it gets updated. base::RunLoop run_loop; @@ -361,8 +361,8 @@ // Set up the primary account. std::string primary_account_email("primary.account@example.com"); - AccountInfo primary_account_info = identity::MakePrimaryAccountAvailable( - identity_manager(), primary_account_email); + AccountInfo primary_account_info = + MakePrimaryAccountAvailable(identity_manager(), primary_account_email); // Next, add a secondary account. base::RunLoop run_loop; @@ -563,7 +563,7 @@ DCHECK(accounts_mutator()); AccountInfo account_info = - identity::MakeAccountAvailable(identity_manager(), kTestEmail); + MakeAccountAvailable(identity_manager(), kTestEmail); EXPECT_TRUE( identity_manager()->HasAccountWithRefreshToken(account_info.account_id)); EXPECT_FALSE( @@ -575,14 +575,14 @@ auto* other_accounts_mutator = other_identity_test_env.identity_manager()->GetAccountsMutator(); - std::string device_id_1 = signin::GetOrCreateScopedDeviceId(pref_service()); + std::string device_id_1 = GetOrCreateScopedDeviceId(pref_service()); EXPECT_FALSE(device_id_1.empty()); accounts_mutator()->MoveAccount(other_accounts_mutator, account_info.account_id); EXPECT_EQ(0U, identity_manager()->GetAccountsWithRefreshTokens().size()); - std::string device_id_2 = signin::GetOrCreateScopedDeviceId(pref_service()); + std::string device_id_2 = GetOrCreateScopedDeviceId(pref_service()); EXPECT_FALSE(device_id_2.empty()); // |device_id_1| and |device_id_2| should be different as the divice ID is // recreated in MoveAccount(). @@ -680,4 +680,4 @@ identity_manager_diagnostics_observer()->token_remover_source()); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/device_accounts_synchronizer.h b/components/signin/public/identity_manager/device_accounts_synchronizer.h index a31976b..bf99d7c 100644 --- a/components/signin/public/identity_manager/device_accounts_synchronizer.h +++ b/components/signin/public/identity_manager/device_accounts_synchronizer.h
@@ -7,7 +7,7 @@ #include "google_apis/gaia/core_account_id.h" -namespace identity { +namespace signin { // DeviceAccountsSynchronizer is the interface to support seeding the accounts // information from a device-level store. @@ -36,6 +36,6 @@ delete; }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_H_
diff --git a/components/signin/public/identity_manager/diagnostics_provider.h b/components/signin/public/identity_manager/diagnostics_provider.h index fc9634bf..37d0c090 100644 --- a/components/signin/public/identity_manager/diagnostics_provider.h +++ b/components/signin/public/identity_manager/diagnostics_provider.h
@@ -6,9 +6,10 @@ #define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_DIAGNOSTICS_PROVIDER_H_ #include "base/macros.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "base/time/time.h" +#include "components/signin/public/identity_manager/load_credentials_state.h" -namespace identity { +namespace signin { // DiagnosticsProvider is the interface to obtain diagnostics about // IdentityManager internals. @@ -18,7 +19,7 @@ virtual ~DiagnosticsProvider() = default; // Returns the state of the load credentials operation. - virtual OAuth2TokenServiceDelegate::LoadCredentialsState + virtual signin::LoadCredentialsState GetDetailedStateOfLoadingOfRefreshTokens() const = 0; // Returns the time until a access token request can be sent (will be zero if @@ -33,6 +34,6 @@ DISALLOW_COPY_AND_ASSIGN(DiagnosticsProvider); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_DIAGNOSTICS_PROVIDER_H_
diff --git a/components/signin/public/identity_manager/diagnostics_provider_unittest.cc b/components/signin/public/identity_manager/diagnostics_provider_unittest.cc index 5f38109..87fb50f 100644 --- a/components/signin/public/identity_manager/diagnostics_provider_unittest.cc +++ b/components/signin/public/identity_manager/diagnostics_provider_unittest.cc
@@ -9,6 +9,7 @@ #include "base/test/scoped_task_environment.h" #include "components/signin/public/identity_manager/accounts_cookie_mutator.h" #include "components/signin/public/identity_manager/identity_test_environment.h" +#include "components/signin/public/identity_manager/load_credentials_state.h" #include "testing/gtest/include/gtest/gtest.h" const char kAccountId[] = "user@gmail.com"; @@ -19,11 +20,11 @@ public: DiagnosticsProviderTest() = default; - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } - identity::DiagnosticsProvider* diagnostics_provider() { + signin::DiagnosticsProvider* diagnostics_provider() { return identity_test_env_.identity_manager()->GetDiagnosticsProvider(); } @@ -31,7 +32,7 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; private: - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; DISALLOW_COPY_AND_ASSIGN(DiagnosticsProviderTest); }; @@ -46,9 +47,9 @@ } TEST_F(DiagnosticsProviderTest, GetDetailedStateOfLoadingOfRefreshTokens) { - EXPECT_EQ(OAuth2TokenServiceDelegate::LoadCredentialsState:: - LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, - diagnostics_provider()->GetDetailedStateOfLoadingOfRefreshTokens()); + EXPECT_EQ( + signin::LoadCredentialsState::LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + diagnostics_provider()->GetDetailedStateOfLoadingOfRefreshTokens()); } TEST_F(DiagnosticsProviderTest, GetDelayBeforeMakingAccessTokenRequests) {
diff --git a/components/signin/public/identity_manager/identity_manager.cc b/components/signin/public/identity_manager/identity_manager.cc index 367ad382..de180ab 100644 --- a/components/signin/public/identity_manager/identity_manager.cc +++ b/components/signin/public/identity_manager/identity_manager.cc
@@ -28,7 +28,7 @@ #include "components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.h" #endif -namespace identity { +namespace signin { namespace { @@ -186,7 +186,7 @@ IdentityManager::CreateAccessTokenFetcherForAccount( const CoreAccountId& account_id, const std::string& oauth_consumer_name, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, AccessTokenFetcher::TokenCallback callback, AccessTokenFetcher::Mode mode) { return std::make_unique<AccessTokenFetcher>(account_id, oauth_consumer_name, @@ -199,7 +199,7 @@ const CoreAccountId& account_id, const std::string& oauth_consumer_name, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, AccessTokenFetcher::TokenCallback callback, AccessTokenFetcher::Mode mode) { return std::make_unique<AccessTokenFetcher>( @@ -213,7 +213,7 @@ const std::string& client_id, const std::string& client_secret, const std::string& oauth_consumer_name, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, AccessTokenFetcher::TokenCallback callback, AccessTokenFetcher::Mode mode) { return std::make_unique<AccessTokenFetcher>( @@ -223,7 +223,7 @@ void IdentityManager::RemoveAccessTokenFromCache( const CoreAccountId& account_id, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, const std::string& access_token) { token_service_->InvalidateAccessToken(account_id, scopes, access_token); } @@ -340,14 +340,14 @@ return GetAccountInfoForAccountWithRefreshToken(account_info.account_id); } -std::unique_ptr<signin::UbertokenFetcher> +std::unique_ptr<UbertokenFetcher> IdentityManager::CreateUbertokenFetcherForAccount( const CoreAccountId& account_id, - signin::UbertokenFetcher::CompletionCallback callback, + UbertokenFetcher::CompletionCallback callback, gaia::GaiaSource source, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, bool bount_to_channel_id) { - return std::make_unique<signin::UbertokenFetcherImpl>( + return std::make_unique<UbertokenFetcherImpl>( account_id, token_service_.get(), std::move(callback), source, url_loader_factory, bount_to_channel_id); } @@ -648,7 +648,7 @@ void IdentityManager::OnAccessTokenRequested(const CoreAccountId& account_id, const std::string& consumer_id, - const ScopeSet& scopes) { + const identity::ScopeSet& scopes) { for (auto& observer : diagnostics_observer_list_) { observer.OnAccessTokenRequested(account_id, consumer_id, scopes); } @@ -657,7 +657,7 @@ void IdentityManager::OnFetchAccessTokenComplete( const CoreAccountId& account_id, const std::string& consumer_id, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, GoogleServiceAuthError error, base::Time expiration_time) { for (auto& observer : diagnostics_observer_list_) @@ -666,7 +666,7 @@ } void IdentityManager::OnAccessTokenRemoved(const CoreAccountId& account_id, - const ScopeSet& scopes) { + const identity::ScopeSet& scopes) { for (auto& observer : diagnostics_observer_list_) observer.OnAccessTokenRemovedFromCache(account_id, scopes); } @@ -702,4 +702,4 @@ UpdateUnconsentedPrimaryAccount(); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/identity_manager.h b/components/signin/public/identity_manager/identity_manager.h index bfa5c9e..3bb9165 100644 --- a/components/signin/public/identity_manager/identity_manager.h +++ b/components/signin/public/identity_manager/identity_manager.h
@@ -43,7 +43,7 @@ class PrimaryAccountManager; class ProfileOAuth2TokenService; -namespace identity { +namespace signin { class AccountsMutator; class AccountsCookieMutator; @@ -54,7 +54,7 @@ class DiagnosticsProvider; class PrimaryAccountMutator; enum class ClearPrimaryAccountPolicy; -struct CookieParams; +struct CookieParamsForTest; // Gives access to information about the user's Google identities. See // ./README.md for detailed documentation. @@ -192,7 +192,7 @@ std::unique_ptr<AccessTokenFetcher> CreateAccessTokenFetcherForAccount( const CoreAccountId& account_id, const std::string& oauth_consumer_name, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, AccessTokenFetcher::TokenCallback callback, AccessTokenFetcher::Mode mode) WARN_UNUSED_RESULT; @@ -202,7 +202,7 @@ const CoreAccountId& account_id, const std::string& oauth_consumer_name, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, AccessTokenFetcher::TokenCallback callback, AccessTokenFetcher::Mode mode) WARN_UNUSED_RESULT; @@ -214,7 +214,7 @@ const std::string& client_id, const std::string& client_secret, const std::string& oauth_consumer_name, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, AccessTokenFetcher::TokenCallback callback, AccessTokenFetcher::Mode mode) WARN_UNUSED_RESULT; @@ -223,7 +223,7 @@ // request for |account_id| and |scopes| will fetch a new token from the // network. Otherwise, is a no-op. void RemoveAccessTokenFromCache(const CoreAccountId& account_id, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, const std::string& access_token); // Provides the information of all accounts that have refresh tokens. @@ -293,9 +293,9 @@ // Creates an UbertokenFetcher given the passed-in information, allowing // to specify a custom |url_loader_factory| as well. - std::unique_ptr<signin::UbertokenFetcher> CreateUbertokenFetcherForAccount( + std::unique_ptr<UbertokenFetcher> CreateUbertokenFetcherForAccount( const CoreAccountId& account_id, - signin::UbertokenFetcher::CompletionCallback callback, + UbertokenFetcher::CompletionCallback callback, gaia::GaiaSource source, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, bool bound_to_channel_id = true); @@ -338,19 +338,20 @@ // Called when receiving request for access token. virtual void OnAccessTokenRequested(const CoreAccountId& account_id, const std::string& consumer_id, - const ScopeSet& scopes) {} + const identity::ScopeSet& scopes) {} // Called when an access token request is completed. Contains diagnostic // information about the access token request. virtual void OnAccessTokenRequestCompleted(const CoreAccountId& account_id, const std::string& consumer_id, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, GoogleServiceAuthError error, base::Time expiration_time) {} // Called when an access token was removed. - virtual void OnAccessTokenRemovedFromCache(const CoreAccountId& account_id, - const ScopeSet& scopes) {} + virtual void OnAccessTokenRemovedFromCache( + const CoreAccountId& account_id, + const identity::ScopeSet& scopes) {} // Called when a new refresh token is available. Contains diagnostic // information about the source of the operation. @@ -522,7 +523,7 @@ friend void SetCookieAccounts( IdentityManager* identity_manager, network::TestURLLoaderFactory* test_url_loader_factory, - const std::vector<identity::CookieParams>& cookie_accounts); + const std::vector<CookieParamsForTest>& cookie_accounts); friend void SimulateSuccessfulFetchOfAccountInfo( IdentityManager* identity_manager, @@ -639,14 +640,14 @@ // OAuth2AccessTokenManager::DiagnosticsObserver void OnAccessTokenRequested(const CoreAccountId& account_id, const std::string& consumer_id, - const ScopeSet& scopes) override; + const identity::ScopeSet& scopes) override; void OnFetchAccessTokenComplete(const CoreAccountId& account_id, const std::string& consumer_id, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, GoogleServiceAuthError error, base::Time expiration_time) override; void OnAccessTokenRemoved(const CoreAccountId& account_id, - const ScopeSet& scopes) override; + const identity::ScopeSet& scopes) override; // ProfileOAuth2TokenService callbacks: void OnRefreshTokenAvailableFromSource(const CoreAccountId& account_id, @@ -697,6 +698,6 @@ DISALLOW_COPY_AND_ASSIGN(IdentityManager); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_MANAGER_H_
diff --git a/components/signin/public/identity_manager/identity_manager_builder.cc b/components/signin/public/identity_manager/identity_manager_builder.cc index 5613f46..7dc60a28 100644 --- a/components/signin/public/identity_manager/identity_manager_builder.cc +++ b/components/signin/public/identity_manager/identity_manager_builder.cc
@@ -42,7 +42,7 @@ #include "components/signin/internal/identity_manager/primary_account_policy_manager_impl.h" #endif -namespace identity { +namespace signin { namespace { @@ -56,7 +56,7 @@ std::unique_ptr<PrimaryAccountManager> BuildPrimaryAccountManager( SigninClient* client, - signin::AccountConsistencyMethod account_consistency, + AccountConsistencyMethod account_consistency, AccountTrackerService* account_tracker_service, ProfileOAuth2TokenService* token_service, PrefService* local_state) { @@ -135,12 +135,11 @@ account_tracker_service.get(), token_service.get(), params->local_state); - auto primary_account_mutator = - std::make_unique<identity::PrimaryAccountMutatorImpl>( - account_tracker_service.get(), primary_account_manager.get(), - params->pref_service); + auto primary_account_mutator = std::make_unique<PrimaryAccountMutatorImpl>( + account_tracker_service.get(), primary_account_manager.get(), + params->pref_service); - std::unique_ptr<identity::AccountsMutator> accounts_mutator = + std::unique_ptr<AccountsMutator> accounts_mutator = BuildAccountsMutator(params->pref_service, account_tracker_service.get(), token_service.get(), primary_account_manager.get()); @@ -171,4 +170,4 @@ std::move(device_accounts_synchronizer)); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/identity_manager_builder.h b/components/signin/public/identity_manager/identity_manager_builder.h index 70ef4be..e9c6300 100644 --- a/components/signin/public/identity_manager/identity_manager_builder.h +++ b/components/signin/public/identity_manager/identity_manager_builder.h
@@ -39,24 +39,21 @@ class NetworkConnectionTracker; } -namespace signin { -enum class AccountConsistencyMethod; -} - #if defined(OS_CHROMEOS) namespace chromeos { class AccountManager; } #endif -namespace identity { +namespace signin { +enum class AccountConsistencyMethod; class IdentityManager; struct IdentityManagerBuildParams { IdentityManagerBuildParams(); ~IdentityManagerBuildParams(); - signin::AccountConsistencyMethod account_consistency; + AccountConsistencyMethod account_consistency; std::unique_ptr<AccountTrackerService> account_tracker_service; std::unique_ptr<image_fetcher::ImageDecoder> image_decoder; PrefService* local_state; @@ -90,6 +87,6 @@ std::unique_ptr<IdentityManager> BuildIdentityManager( IdentityManagerBuildParams* params); -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_MANAGER_BUILDER_H_
diff --git a/components/signin/public/identity_manager/identity_manager_unittest.cc b/components/signin/public/identity_manager/identity_manager_unittest.cc index bf79ab7..5c25a6d 100644 --- a/components/signin/public/identity_manager/identity_manager_unittest.cc +++ b/components/signin/public/identity_manager/identity_manager_unittest.cc
@@ -23,6 +23,7 @@ #include "components/signin/internal/identity_manager/diagnostics_provider_impl.h" #include "components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h" #include "components/signin/internal/identity_manager/gaia_cookie_manager_service.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "components/signin/internal/identity_manager/primary_account_manager.h" #include "components/signin/internal/identity_manager/primary_account_policy_manager_impl.h" #include "components/signin/public/base/account_consistency_method.h" @@ -40,7 +41,6 @@ #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/core_account_id.h" #include "google_apis/gaia/google_service_auth_error.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_cookie_manager.h" #include "services/network/test/test_url_loader_factory.h" @@ -50,7 +50,7 @@ #include "components/signin/internal/identity_manager/child_account_info_fetcher_android.h" #endif -namespace identity { +namespace signin { namespace { const char kTestConsumerId[] = "dummy_consumer"; @@ -95,7 +95,7 @@ // OAuth2AccessTokenManager: void InvalidateAccessTokenImpl(const CoreAccountId& account_id, const std::string& client_id, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, const std::string& access_token) override { if (on_access_token_invalidated_callback_) { EXPECT_EQ(expected_account_id_to_invalidate_, account_id); @@ -207,15 +207,16 @@ std::move(on_access_token_requested_callback_).Run(); } - void OnAccessTokenRemovedFromCache(const CoreAccountId& account_id, - const ScopeSet& scopes) override { + void OnAccessTokenRemovedFromCache( + const CoreAccountId& account_id, + const identity::ScopeSet& scopes) override { token_remover_account_id_ = account_id; token_remover_scopes_ = scopes; } void OnAccessTokenRequestCompleted(const CoreAccountId& account_id, const std::string& consumer_id, - const ScopeSet& scopes, + const identity::ScopeSet& scopes, GoogleServiceAuthError error, base::Time expiration_time) override { access_token_request_completed_account_id_ = account_id; @@ -251,7 +252,7 @@ IdentityManager::RegisterLocalStatePrefs(pref_service_.registry()); RecreateIdentityManager( - signin::AccountConsistencyMethod::kDisabled, + AccountConsistencyMethod::kDisabled, PrimaryAccountManagerSetup::kWithAuthenticatedAccout); } @@ -292,7 +293,7 @@ // performing some other setup. void RecreateIdentityManager() { RecreateIdentityManager( - signin::AccountConsistencyMethod::kDisabled, + AccountConsistencyMethod::kDisabled, PrimaryAccountManagerSetup::kNoAuthenticatedAccount); } @@ -302,7 +303,7 @@ // IdentityManager and its dependencies, then remakes them. Dependencies that // outlive PrimaryAccountManager (e.g. SigninClient) will be reused. void RecreateIdentityManager( - signin::AccountConsistencyMethod account_consistency, + AccountConsistencyMethod account_consistency, PrimaryAccountManagerSetup primary_account_manager_setup) { // Remove observers first, otherwise IdentityManager destruction might // trigger a DCHECK because there are still living observers. @@ -325,7 +326,7 @@ &signin_client_, token_service.get(), account_tracker_service.get(), std::make_unique<image_fetcher::FakeImageDecoder>()); - DCHECK_EQ(account_consistency, signin::AccountConsistencyMethod::kDisabled) + DCHECK_EQ(account_consistency, AccountConsistencyMethod::kDisabled) << "AccountConsistency is not used by PrimaryAccountManager"; std::unique_ptr<PrimaryAccountPolicyManager> policy_manager; #if !defined(OS_CHROMEOS) @@ -386,9 +387,8 @@ network::mojom::CookieChangeCause::EXPLICIT); } - void SimulateOAuthMultiloginFinished( - GaiaCookieManagerService* manager, - signin::SetAccountsInCookieResult error) { + void SimulateOAuthMultiloginFinished(GaiaCookieManagerService* manager, + SetAccountsInCookieResult error) { manager->OnSetAccountsFinished(error); } @@ -1347,7 +1347,7 @@ identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback( run_loop.QuitClosure()); - signin::SetListAccountsResponseNoAccounts(test_url_loader_factory()); + SetListAccountsResponseNoAccounts(test_url_loader_factory()); // Forces the processing of OnCookieChange and it calls // OnGaiaAccountsInCookieUpdated. identity_manager()->ForceTriggerOnCookieChange(); @@ -1615,7 +1615,7 @@ identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback( run_loop.QuitClosure()); - signin::SetListAccountsResponseNoAccounts(test_url_loader_factory()); + SetListAccountsResponseNoAccounts(test_url_loader_factory()); identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts(); run_loop.Run(); @@ -1632,8 +1632,8 @@ identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback( run_loop.QuitClosure()); - signin::SetListAccountsResponseOneAccount(kTestEmail, kTestGaiaId, - test_url_loader_factory()); + SetListAccountsResponseOneAccount(kTestEmail, kTestGaiaId, + test_url_loader_factory()); identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts(); run_loop.Run(); @@ -1659,9 +1659,8 @@ identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback( run_loop.QuitClosure()); - signin::SetListAccountsResponseTwoAccounts(kTestEmail, kTestGaiaId, - kTestEmail2, kTestGaiaId2, - test_url_loader_factory()); + SetListAccountsResponseTwoAccounts(kTestEmail, kTestGaiaId, kTestEmail2, + kTestGaiaId2, test_url_loader_factory()); identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts(); run_loop.Run(); @@ -1702,7 +1701,7 @@ identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback( run_loop.QuitClosure()); - signin::SetListAccountsResponseWithParams( + SetListAccountsResponseWithParams( {{kTestEmail, kTestGaiaId, true /* valid */, signed_out_status.account_1 /* signed_out */, true /* verified */}, {kTestEmail2, kTestGaiaId2, true /* valid */, @@ -1760,7 +1759,7 @@ run_loop.QuitClosure()); // Configure list accounts to return a permanent Gaia auth error. - signin::SetListAccountsResponseWebLoginRequired(test_url_loader_factory()); + SetListAccountsResponseWebLoginRequired(test_url_loader_factory()); identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts(); run_loop.Run(); @@ -1777,7 +1776,7 @@ identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback( run_loop.QuitClosure()); - signin::SetListAccountsResponseNoAccounts(test_url_loader_factory()); + SetListAccountsResponseNoAccounts(test_url_loader_factory()); // Do an initial call to GetAccountsInCookieJar(). This call should return no // accounts but should also trigger an internal update and eventual @@ -1805,8 +1804,8 @@ identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback( run_loop.QuitClosure()); - signin::SetListAccountsResponseOneAccount(kTestEmail, kTestGaiaId, - test_url_loader_factory()); + SetListAccountsResponseOneAccount(kTestEmail, kTestGaiaId, + test_url_loader_factory()); // Do an initial call to GetAccountsInCookieJar(). This call should return no // accounts but should also trigger an internal update and eventual @@ -1842,9 +1841,8 @@ identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback( run_loop.QuitClosure()); - signin::SetListAccountsResponseTwoAccounts(kTestEmail, kTestGaiaId, - kTestEmail2, kTestGaiaId2, - test_url_loader_factory()); + SetListAccountsResponseTwoAccounts(kTestEmail, kTestGaiaId, kTestEmail2, + kTestGaiaId2, test_url_loader_factory()); // Do an initial call to GetAccountsInCookieJar(). This call should return no // accounts but should also trigger an internal update and eventual @@ -1941,11 +1939,11 @@ {kTestAccountId, kTestAccountId.id}, {kTestAccountId2, kTestAccountId2.id}}; - signin::SetAccountsInCookieResult + SetAccountsInCookieResult error_from_set_accounts_in_cookie_completed_callback; auto completion_callback = base::BindLambdaForTesting( [&error_from_set_accounts_in_cookie_completed_callback]( - signin::SetAccountsInCookieResult error) { + SetAccountsInCookieResult error) { error_from_set_accounts_in_cookie_completed_callback = error; }); @@ -1955,10 +1953,10 @@ SimulateOAuthMultiloginFinished( identity_manager()->GetGaiaCookieManagerService(), - signin::SetAccountsInCookieResult::kSuccess); + SetAccountsInCookieResult::kSuccess); EXPECT_EQ(error_from_set_accounts_in_cookie_completed_callback, - signin::SetAccountsInCookieResult::kSuccess); + SetAccountsInCookieResult::kSuccess); } TEST_F(IdentityManagerTest, @@ -1969,11 +1967,11 @@ {kTestAccountId, kTestAccountId.id}, {kTestAccountId2, kTestAccountId2.id}}; - signin::SetAccountsInCookieResult + SetAccountsInCookieResult error_from_set_accounts_in_cookie_completed_callback; auto completion_callback = base::BindLambdaForTesting( [&error_from_set_accounts_in_cookie_completed_callback]( - signin::SetAccountsInCookieResult error) { + SetAccountsInCookieResult error) { error_from_set_accounts_in_cookie_completed_callback = error; }); @@ -1982,8 +1980,7 @@ accounts, gaia::GaiaSource::kChrome, std::move(completion_callback)); // Sample an erroneous response. - signin::SetAccountsInCookieResult error = - signin::SetAccountsInCookieResult::kPersistentError; + SetAccountsInCookieResult error = SetAccountsInCookieResult::kPersistentError; SimulateOAuthMultiloginFinished( identity_manager()->GetGaiaCookieManagerService(), error); @@ -2288,4 +2285,4 @@ } #endif -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/identity_test_environment.cc b/components/signin/public/identity_manager/identity_test_environment.cc index 255443d..6c03341 100644 --- a/components/signin/public/identity_manager/identity_test_environment.cc +++ b/components/signin/public/identity_manager/identity_test_environment.cc
@@ -42,7 +42,7 @@ #include "components/signin/internal/identity_manager/accounts_mutator_impl.h" #endif -namespace identity { +namespace signin { class IdentityManagerDependenciesOwner { public: @@ -103,7 +103,7 @@ IdentityTestEnvironment::IdentityTestEnvironment( network::TestURLLoaderFactory* test_url_loader_factory, sync_preferences::TestingPrefServiceSyncable* pref_service, - signin::AccountConsistencyMethod account_consistency, + AccountConsistencyMethod account_consistency, TestSigninClient* test_signin_client) : IdentityTestEnvironment( std::make_unique<IdentityManagerDependenciesOwner>( @@ -136,7 +136,7 @@ IdentityTestEnvironment::IdentityTestEnvironment( std::unique_ptr<IdentityManagerDependenciesOwner> dependencies_owner, network::TestURLLoaderFactory* test_url_loader_factory, - signin::AccountConsistencyMethod account_consistency) { + AccountConsistencyMethod account_consistency) { dependencies_owner_ = std::move(dependencies_owner); TestSigninClient* test_signin_client = dependencies_owner_->signin_client(); if (test_url_loader_factory) @@ -161,7 +161,7 @@ SigninClient* signin_client, PrefService* pref_service, base::FilePath user_data_dir, - signin::AccountConsistencyMethod account_consistency) { + AccountConsistencyMethod account_consistency) { auto account_tracker_service = std::make_unique<AccountTrackerService>(); account_tracker_service->Initialize(pref_service, user_data_dir); @@ -243,62 +243,62 @@ CoreAccountInfo IdentityTestEnvironment::SetPrimaryAccount( const std::string& email) { - return identity::SetPrimaryAccount(identity_manager(), email); + return signin::SetPrimaryAccount(identity_manager(), email); } void IdentityTestEnvironment::SetRefreshTokenForPrimaryAccount() { - identity::SetRefreshTokenForPrimaryAccount(identity_manager()); + signin::SetRefreshTokenForPrimaryAccount(identity_manager()); } void IdentityTestEnvironment::SetInvalidRefreshTokenForPrimaryAccount() { - identity::SetInvalidRefreshTokenForPrimaryAccount(identity_manager()); + signin::SetInvalidRefreshTokenForPrimaryAccount(identity_manager()); } void IdentityTestEnvironment::RemoveRefreshTokenForPrimaryAccount() { - identity::RemoveRefreshTokenForPrimaryAccount(identity_manager()); + signin::RemoveRefreshTokenForPrimaryAccount(identity_manager()); } AccountInfo IdentityTestEnvironment::MakePrimaryAccountAvailable( const std::string& email) { - return identity::MakePrimaryAccountAvailable(identity_manager(), email); + return signin::MakePrimaryAccountAvailable(identity_manager(), email); } void IdentityTestEnvironment::ClearPrimaryAccount( ClearPrimaryAccountPolicy policy) { - identity::ClearPrimaryAccount(identity_manager(), policy); + signin::ClearPrimaryAccount(identity_manager(), policy); } AccountInfo IdentityTestEnvironment::MakeAccountAvailable( const std::string& email) { - return identity::MakeAccountAvailable(identity_manager(), email); + return signin::MakeAccountAvailable(identity_manager(), email); } void IdentityTestEnvironment::SetRefreshTokenForAccount( const CoreAccountId& account_id) { - return identity::SetRefreshTokenForAccount(identity_manager(), account_id); + return signin::SetRefreshTokenForAccount(identity_manager(), account_id); } void IdentityTestEnvironment::SetInvalidRefreshTokenForAccount( const CoreAccountId& account_id) { - return identity::SetInvalidRefreshTokenForAccount(identity_manager(), - account_id); + return signin::SetInvalidRefreshTokenForAccount(identity_manager(), + account_id); } void IdentityTestEnvironment::RemoveRefreshTokenForAccount( const CoreAccountId& account_id) { - return identity::RemoveRefreshTokenForAccount(identity_manager(), account_id); + return signin::RemoveRefreshTokenForAccount(identity_manager(), account_id); } void IdentityTestEnvironment::UpdatePersistentErrorOfRefreshTokenForAccount( const CoreAccountId& account_id, const GoogleServiceAuthError& auth_error) { - return identity::UpdatePersistentErrorOfRefreshTokenForAccount( + return signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager(), account_id, auth_error); } void IdentityTestEnvironment::SetCookieAccounts( - const std::vector<CookieParams>& cookie_accounts) { - identity::SetCookieAccounts( + const std::vector<CookieParamsForTest>& cookie_accounts) { + signin::SetCookieAccounts( identity_manager(), dependencies_owner_->signin_client()->GetTestURLLoaderFactory(), cookie_accounts); @@ -453,7 +453,7 @@ void IdentityTestEnvironment::UpdateAccountInfoForAccount( AccountInfo account_info) { - identity::UpdateAccountInfoForAccount(identity_manager(), account_info); + signin::UpdateAccountInfoForAccount(identity_manager(), account_info); } void IdentityTestEnvironment::ResetToAccountsNotYetLoadedFromDiskState() { @@ -470,8 +470,8 @@ void IdentityTestEnvironment::SetFreshnessOfAccountsInGaiaCookie( bool accounts_are_fresh) { - identity::SetFreshnessOfAccountsInGaiaCookie(identity_manager(), - accounts_are_fresh); + signin::SetFreshnessOfAccountsInGaiaCookie(identity_manager(), + accounts_are_fresh); } void IdentityTestEnvironment::EnableRemovalOfExtendedAccountInfo() { @@ -487,7 +487,7 @@ const std::string& given_name, const std::string& locale, const std::string& picture_url) { - identity::SimulateSuccessfulFetchOfAccountInfo( + signin::SimulateSuccessfulFetchOfAccountInfo( identity_manager(), account_id, email, gaia, hosted_domain, full_name, given_name, locale, picture_url); } @@ -502,4 +502,4 @@ ->OnMergeSessionFailure(auth_error); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/identity_test_environment.h b/components/signin/public/identity_manager/identity_test_environment.h index 2babc39..3b5efc73 100644 --- a/components/signin/public/identity_manager/identity_test_environment.h +++ b/components/signin/public/identity_manager/identity_test_environment.h
@@ -28,7 +28,7 @@ class TestURLLoaderFactory; } -namespace identity { +namespace signin { class IdentityManagerDependenciesOwner; class TestIdentityManagerObserver; @@ -71,8 +71,8 @@ IdentityTestEnvironment( network::TestURLLoaderFactory* test_url_loader_factory = nullptr, sync_preferences::TestingPrefServiceSyncable* pref_service = nullptr, - signin::AccountConsistencyMethod account_consistency = - signin::AccountConsistencyMethod::kDisabled, + AccountConsistencyMethod account_consistency = + AccountConsistencyMethod::kDisabled, TestSigninClient* test_signin_client = nullptr); ~IdentityTestEnvironment() override; @@ -154,7 +154,8 @@ // Puts the given accounts into the Gaia cookie, replacing any previous // accounts. Blocks until the accounts have been set. - void SetCookieAccounts(const std::vector<CookieParams>& cookie_accounts); + void SetCookieAccounts( + const std::vector<CookieParamsForTest>& cookie_accounts); // When this is set, access token requests will be automatically granted with // an access token value of "access_token". @@ -296,7 +297,7 @@ IdentityTestEnvironment( std::unique_ptr<IdentityManagerDependenciesOwner> dependencies_owner, network::TestURLLoaderFactory* test_url_loader_factory, - signin::AccountConsistencyMethod account_consistency); + AccountConsistencyMethod account_consistency); // Constructs an IdentityTestEnvironment that uses the supplied // |identity_manager|. @@ -353,8 +354,8 @@ SigninClient* signin_client, PrefService* pref_service, base::FilePath user_data_dir, - signin::AccountConsistencyMethod account_consistency = - signin::AccountConsistencyMethod::kDisabled); + AccountConsistencyMethod account_consistency = + AccountConsistencyMethod::kDisabled); // Shared constructor initialization logic. void Initialize(); @@ -364,6 +365,6 @@ DISALLOW_COPY_AND_ASSIGN(IdentityTestEnvironment); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_TEST_ENVIRONMENT_H_
diff --git a/components/signin/public/identity_manager/identity_test_environment_unittest.cc b/components/signin/public/identity_manager/identity_test_environment_unittest.cc index 574afdb..9c03209a 100644 --- a/components/signin/public/identity_manager/identity_test_environment_unittest.cc +++ b/components/signin/public/identity_manager/identity_test_environment_unittest.cc
@@ -9,7 +9,7 @@ #include "components/signin/public/identity_manager/access_token_info.h" #include "testing/gtest/include/gtest/gtest.h" -namespace identity { +namespace signin { class IdentityTestEnvironmentTest : public testing::Test { public: @@ -30,15 +30,15 @@ TEST_F(IdentityTestEnvironmentTest, IdentityTestEnvironmentCancelsPendingRequestsOnDestruction) { - std::unique_ptr<identity::IdentityTestEnvironment> identity_test_environment = - std::make_unique<identity::IdentityTestEnvironment>(); + std::unique_ptr<IdentityTestEnvironment> identity_test_environment = + std::make_unique<IdentityTestEnvironment>(); identity_test_environment->MakePrimaryAccountAvailable("primary@example.com"); AccessTokenFetcher::TokenCallback callback = base::BindOnce( [](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {}); std::set<std::string> scopes{"scope"}; - std::unique_ptr<identity::AccessTokenFetcher> fetcher = + std::unique_ptr<AccessTokenFetcher> fetcher = identity_test_environment->identity_manager() ->CreateAccessTokenFetcherForAccount( identity_test_environment->identity_manager() @@ -54,4 +54,4 @@ fetcher.reset(); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/identity_test_utils.cc b/components/signin/public/identity_manager/identity_test_utils.cc index 577600c9..a84d5a650 100644 --- a/components/signin/public/identity_manager/identity_test_utils.cc +++ b/components/signin/public/identity_manager/identity_test_utils.cc
@@ -10,19 +10,20 @@ #include "build/build_config.h" #include "components/signin/internal/identity_manager/account_tracker_service.h" #include "components/signin/internal/identity_manager/gaia_cookie_manager_service.h" +#include "components/signin/internal/identity_manager/oauth2_token_service_delegate.h" #include "components/signin/internal/identity_manager/primary_account_manager.h" #include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" #include "components/signin/public/base/list_accounts_test_utils.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/test_identity_manager_observer.h" #include "google_apis/gaia/gaia_auth_util.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "google_apis/gaia/gaia_constants.h" #if defined(OS_ANDROID) #include "components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h" #endif -namespace identity { +namespace signin { namespace { @@ -219,8 +220,8 @@ // as tokens finish loading. WaitForLoadCredentialsToComplete(identity_manager); - identity::SetCookieAccounts(identity_manager, test_url_loader_factory, - {{email, gaia_id}}); + SetCookieAccounts(identity_manager, test_url_loader_factory, + {{email, gaia_id}}); account_tracker_service->SeedAccountInfo(gaia_id, email); @@ -245,11 +246,11 @@ void SetInvalidRefreshTokenForAccount(IdentityManager* identity_manager, const std::string& account_id) { - UpdateRefreshTokenForAccount( - identity_manager->GetTokenService(), + UpdateRefreshTokenForAccount(identity_manager->GetTokenService(), - identity_manager->GetAccountTrackerService(), identity_manager, - account_id, OAuth2TokenServiceDelegate::kInvalidRefreshToken); + identity_manager->GetAccountTrackerService(), + identity_manager, account_id, + GaiaConstants::kInvalidRefreshToken); } void RemoveRefreshTokenForAccount(IdentityManager* identity_manager, @@ -267,12 +268,13 @@ run_loop.Run(); } -void SetCookieAccounts(IdentityManager* identity_manager, - network::TestURLLoaderFactory* test_url_loader_factory, - const std::vector<CookieParams>& cookie_accounts) { +void SetCookieAccounts( + IdentityManager* identity_manager, + network::TestURLLoaderFactory* test_url_loader_factory, + const std::vector<CookieParamsForTest>& cookie_accounts) { // Convert |cookie_accounts| to the format list_accounts_test_utils wants. - std::vector<signin::CookieParams> gaia_cookie_accounts; - for (const CookieParams& params : cookie_accounts) { + std::vector<CookieParams> gaia_cookie_accounts; + for (const CookieParamsForTest& params : cookie_accounts) { gaia_cookie_accounts.push_back({params.email, params.gaia_id, /*valid=*/true, /*signed_out=*/false, /*verified=*/true}); @@ -282,8 +284,8 @@ TestIdentityManagerObserver cookie_observer(identity_manager); cookie_observer.SetOnAccountsInCookieUpdatedCallback(run_loop.QuitClosure()); - signin::SetListAccountsResponseWithParams(gaia_cookie_accounts, - test_url_loader_factory); + SetListAccountsResponseWithParams(gaia_cookie_accounts, + test_url_loader_factory); GaiaCookieManagerService* cookie_manager = identity_manager->GetGaiaCookieManagerService(); @@ -371,4 +373,4 @@ account_tracker_service->SetAccountInfoFromUserInfo(account_id, &user_info); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/identity_test_utils.h b/components/signin/public/identity_manager/identity_test_utils.h index 7892cdd7..c7842e60 100644 --- a/components/signin/public/identity_manager/identity_test_utils.h +++ b/components/signin/public/identity_manager/identity_test_utils.h
@@ -24,7 +24,7 @@ // to use IdentityTestEnvironment. Any such usage should only be temporary, // i.e., should be followed as quickly as possible by conversion of the test // code to use IdentityTestEnvironment. -namespace identity { +namespace signin { // Controls whether to keep or remove accounts when clearing the primary // account. @@ -37,7 +37,7 @@ REMOVE_ALL_ACCOUNTS }; -struct CookieParams { +struct CookieParamsForTest { std::string email; std::string gaia_id; }; @@ -139,7 +139,7 @@ // NOTE: See disclaimer at top of file re: direct usage. void SetCookieAccounts(IdentityManager* identity_manager, network::TestURLLoaderFactory* test_url_loader_factory, - const std::vector<CookieParams>& cookie_accounts); + const std::vector<CookieParamsForTest>& cookie_accounts); // Updates the info for |account_info.account_id|, which must be a known // account. @@ -182,6 +182,6 @@ const std::string& given_name, const std::string& locale, const std::string& picture_url); -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_TEST_UTILS_H_
diff --git a/components/signin/public/identity_manager/identity_utils.cc b/components/signin/public/identity_manager/identity_utils.cc index d603019..11061a1 100644 --- a/components/signin/public/identity_manager/identity_utils.cc +++ b/components/signin/public/identity_manager/identity_utils.cc
@@ -12,7 +12,7 @@ #include "components/signin/public/base/signin_pref_names.h" #include "third_party/icu/source/i18n/unicode/regex.h" -namespace identity { +namespace signin { namespace { @@ -58,4 +58,4 @@ username, prefs->GetString(prefs::kGoogleServicesUsernamePattern)); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/identity_utils.h b/components/signin/public/identity_manager/identity_utils.h index 3806aca..62927ab4e 100644 --- a/components/signin/public/identity_manager/identity_utils.h +++ b/components/signin/public/identity_manager/identity_utils.h
@@ -16,13 +16,13 @@ class PrefService; -namespace identity { +namespace signin { // Returns true if the username is allowed based on a pattern registered // |prefs::kGoogleServicesUsernamePattern| with the preferences service // referenced by |prefs|. bool IsUsernameAllowedByPatternFromPrefs(const PrefService* prefs, const std::string& username); -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_UTILS_H_
diff --git a/components/signin/public/identity_manager/identity_utils_unittest.cc b/components/signin/public/identity_manager/identity_utils_unittest.cc index b3d58fe..0be69dd 100644 --- a/components/signin/public/identity_manager/identity_utils_unittest.cc +++ b/components/signin/public/identity_manager/identity_utils_unittest.cc
@@ -43,68 +43,55 @@ TEST_F(IdentityUtilsTest, IsUsernameAllowedByPatternFromPrefs_EmptyPatterns) { prefs()->SetString(prefs::kGoogleServicesUsernamePattern, ""); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, " "); - EXPECT_FALSE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_FALSE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); } TEST_F(IdentityUtilsTest, IsUsernameAllowedByPatternFromPrefs_InvalidWildcardPatterns) { - // identity::IsUsernameAllowedByPatternFromPrefs should recognize invalid + // signin::IsUsernameAllowedByPatternFromPrefs should recognize invalid // wildcard patterns like "*@foo.com" and insert a "." before them // automatically. prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kValidWildcardPattern); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kInvalidWildcardPattern); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); } TEST_F(IdentityUtilsTest, IsUsernameAllowedByPatternFromPrefs_MatchingWildcardPatterns) { prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kMatchingPattern1); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kMatchingPattern2); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kMatchingPattern3); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kMatchingPattern4); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kMatchingPattern5); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kMatchingPattern6); - EXPECT_TRUE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_TRUE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kNonMatchingPattern); - EXPECT_FALSE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_FALSE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kNonMatchingUsernamePattern); - EXPECT_FALSE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_FALSE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); prefs()->SetString(prefs::kGoogleServicesUsernamePattern, kNonMatchingDomainPattern); - EXPECT_FALSE( - identity::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); + EXPECT_FALSE(signin::IsUsernameAllowedByPatternFromPrefs(prefs(), kUsername)); }
diff --git a/components/signin/public/identity_manager/load_credentials_state.h b/components/signin/public/identity_manager/load_credentials_state.h new file mode 100644 index 0000000..cd850586 --- /dev/null +++ b/components/signin/public/identity_manager/load_credentials_state.h
@@ -0,0 +1,25 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_LOAD_CREDENTIALS_STATE_H_ +#define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_LOAD_CREDENTIALS_STATE_H_ + +namespace signin { + +enum class LoadCredentialsState { + // Describes the status of the operation of loading OAuth2 refresh tokens from + // disk. + LOAD_CREDENTIALS_NOT_STARTED, + LOAD_CREDENTIALS_IN_PROGRESS, + LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, + LOAD_CREDENTIALS_FINISHED_WITH_DB_CANNOT_BE_OPENED, + LOAD_CREDENTIALS_FINISHED_WITH_DB_ERRORS, + LOAD_CREDENTIALS_FINISHED_WITH_DECRYPT_ERRORS, + LOAD_CREDENTIALS_FINISHED_WITH_NO_TOKEN_FOR_PRIMARY_ACCOUNT, + LOAD_CREDENTIALS_FINISHED_WITH_UNKNOWN_ERRORS, +}; + +} // namespace signin + +#endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_LOAD_CREDENTIALS_STATE_H_
diff --git a/components/signin/public/identity_manager/objc/identity_manager_observer_bridge.h b/components/signin/public/identity_manager/objc/identity_manager_observer_bridge.h index 620ff9b..3101764c 100644 --- a/components/signin/public/identity_manager/objc/identity_manager_observer_bridge.h +++ b/components/signin/public/identity_manager/objc/identity_manager_observer_bridge.h
@@ -29,13 +29,13 @@ - (void)onRefreshTokenRemovedForAccount:(const std::string&)accountId; - (void)onRefreshTokensLoaded; - (void)onAccountsInCookieUpdated: - (const identity::AccountsInCookieJarInfo&)accountsInCookieJarInfo + (const signin::AccountsInCookieJarInfo&)accountsInCookieJarInfo error:(const GoogleServiceAuthError&)error; - (void)onEndBatchOfRefreshTokenStateChanges; @end -namespace identity { +namespace signin { // Bridge class that listens for |IdentityManager| notifications and // passes them to its Objective-C delegate. @@ -57,7 +57,7 @@ const CoreAccountId& account_id) override; void OnRefreshTokensLoaded() override; void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; void OnEndBatchOfRefreshTokenStateChanges() override; @@ -70,6 +70,6 @@ DISALLOW_COPY_AND_ASSIGN(IdentityManagerObserverBridge); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_OBJC_IDENTITY_MANAGER_OBSERVER_BRIDGE_H_
diff --git a/components/signin/public/identity_manager/objc/identity_manager_observer_bridge.mm b/components/signin/public/identity_manager/objc/identity_manager_observer_bridge.mm index 0496cfae..4826a43 100644 --- a/components/signin/public/identity_manager/objc/identity_manager_observer_bridge.mm +++ b/components/signin/public/identity_manager/objc/identity_manager_observer_bridge.mm
@@ -8,7 +8,7 @@ #error "This file requires ARC support." #endif -namespace identity { +namespace signin { IdentityManagerObserverBridge::IdentityManagerObserverBridge( IdentityManager* identity_manager, @@ -58,7 +58,7 @@ } void IdentityManagerObserverBridge::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { if ([delegate_ respondsToSelector:@selector(onAccountsInCookieUpdated: error:)]) { @@ -74,4 +74,4 @@ } } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/primary_account_access_token_fetcher.cc b/components/signin/public/identity_manager/primary_account_access_token_fetcher.cc index 125211a..5a1415fa 100644 --- a/components/signin/public/identity_manager/primary_account_access_token_fetcher.cc +++ b/components/signin/public/identity_manager/primary_account_access_token_fetcher.cc
@@ -11,7 +11,7 @@ #include "components/signin/public/identity_manager/access_token_info.h" #include "google_apis/gaia/google_service_auth_error.h" -namespace identity { +namespace signin { PrimaryAccountAccessTokenFetcher::PrimaryAccountAccessTokenFetcher( const std::string& oauth_consumer_name, @@ -122,4 +122,4 @@ std::move(callback_).Run(std::move(error), std::move(access_token_info)); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/primary_account_access_token_fetcher.h b/components/signin/public/identity_manager/primary_account_access_token_fetcher.h index ede7648..68436bc1 100644 --- a/components/signin/public/identity_manager/primary_account_access_token_fetcher.h +++ b/components/signin/public/identity_manager/primary_account_access_token_fetcher.h
@@ -16,7 +16,7 @@ class GoogleServiceAuthError; -namespace identity { +namespace signin { struct AccessTokenInfo; // Helper class to ease the task of obtaining an OAuth2 access token for the @@ -100,6 +100,6 @@ DISALLOW_COPY_AND_ASSIGN(PrimaryAccountAccessTokenFetcher); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_PRIMARY_ACCOUNT_ACCESS_TOKEN_FETCHER_H_
diff --git a/components/signin/public/identity_manager/primary_account_access_token_fetcher_unittest.cc b/components/signin/public/identity_manager/primary_account_access_token_fetcher_unittest.cc index ac6cf9d8..b0136c69c 100644 --- a/components/signin/public/identity_manager/primary_account_access_token_fetcher_unittest.cc +++ b/components/signin/public/identity_manager/primary_account_access_token_fetcher_unittest.cc
@@ -21,7 +21,7 @@ using testing::InvokeWithoutArgs; using testing::StrictMock; -namespace identity { +namespace signin { namespace { @@ -398,4 +398,4 @@ GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE)); } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/primary_account_mutator.h b/components/signin/public/identity_manager/primary_account_mutator.h index 0aec24a6..94755ef 100644 --- a/components/signin/public/identity_manager/primary_account_mutator.h +++ b/components/signin/public/identity_manager/primary_account_mutator.h
@@ -14,7 +14,7 @@ struct CoreAccountId; -namespace identity { +namespace signin { // PrimaryAccountMutator is the interface to set and clear the primary account // (see IdentityManager for more information). @@ -82,6 +82,6 @@ #endif }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_PRIMARY_ACCOUNT_MUTATOR_H_
diff --git a/components/signin/public/identity_manager/primary_account_mutator_unittest.cc b/components/signin/public/identity_manager/primary_account_mutator_unittest.cc index 603c46e..cc1e96d 100644 --- a/components/signin/public/identity_manager/primary_account_mutator_unittest.cc +++ b/components/signin/public/identity_manager/primary_account_mutator_unittest.cc
@@ -51,10 +51,10 @@ // Helper IdentityManager::Observer that forwards some events to the // callback passed to the constructor. class ClearPrimaryAccountTestObserver - : public identity::IdentityManager::Observer { + : public signin::IdentityManager::Observer { public: ClearPrimaryAccountTestObserver( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, PrimaryAccountClearedCallback on_primary_account_cleared, RefreshTokenRemovedCallback on_refresh_token_removed) : on_primary_account_cleared_(std::move(on_primary_account_cleared)), @@ -65,7 +65,7 @@ scoped_observer_.Add(identity_manager); } - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnPrimaryAccountCleared(const CoreAccountInfo& account_info) override { on_primary_account_cleared_.Run(account_info); } @@ -78,7 +78,7 @@ private: PrimaryAccountClearedCallback on_primary_account_cleared_; RefreshTokenRemovedCallback on_refresh_token_removed_; - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> scoped_observer_; DISALLOW_COPY_AND_ASSIGN(ClearPrimaryAccountTestObserver); @@ -96,16 +96,16 @@ // take place, or whether an auth error should happen, useful for some tests. void RunClearPrimaryAccountTest( signin::AccountConsistencyMethod account_consistency_method, - identity::PrimaryAccountMutator::ClearAccountsAction account_action, + signin::PrimaryAccountMutator::ClearAccountsAction account_action, RemoveAccountExpectation account_expectation, AuthExpectation auth_expection = AuthExpectation::kAuthNormal) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment environment( + signin::IdentityTestEnvironment environment( /*test_url_loader_factory=*/nullptr, /*pref_service=*/nullptr, account_consistency_method); - identity::IdentityManager* identity_manager = environment.identity_manager(); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityManager* identity_manager = environment.identity_manager(); + signin::PrimaryAccountMutator* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); // Abort the test if the current platform does not support mutation of the @@ -130,7 +130,7 @@ if (auth_expection == AuthExpectation::kAuthError) { // Set primary account to have authentication error. SetRefreshTokenForPrimaryAccount(identity_manager); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager, account_info.account_id, GoogleServiceAuthError( GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS)); @@ -214,10 +214,10 @@ // Checks that setting the primary account works. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment environment; + signin::IdentityTestEnvironment environment; - identity::IdentityManager* identity_manager = environment.identity_manager(); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityManager* identity_manager = environment.identity_manager(); + signin::PrimaryAccountMutator* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); // Abort the test if the current platform does not support mutation of the @@ -240,10 +240,10 @@ // the identity service. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount_NoAccount) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment environment; + signin::IdentityTestEnvironment environment; - identity::IdentityManager* identity_manager = environment.identity_manager(); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityManager* identity_manager = environment.identity_manager(); + signin::PrimaryAccountMutator* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); // Abort the test if the current platform does not support mutation of the @@ -258,10 +258,10 @@ // Checks that setting the primary account fails if the account is unknown. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount_UnknownAccount) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment environment; + signin::IdentityTestEnvironment environment; - identity::IdentityManager* identity_manager = environment.identity_manager(); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityManager* identity_manager = environment.identity_manager(); + signin::PrimaryAccountMutator* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); // Abort the test if the current platform does not support mutation of the @@ -280,10 +280,10 @@ // primary account. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount_AlreadyHasPrimaryAccount) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment environment; + signin::IdentityTestEnvironment environment; - identity::IdentityManager* identity_manager = environment.identity_manager(); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityManager* identity_manager = environment.identity_manager(); + signin::PrimaryAccountMutator* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); // Abort the test if the current platform does not support mutation of the @@ -315,11 +315,11 @@ base::test::ScopedTaskEnvironment task_environment; sync_preferences::TestingPrefServiceSyncable pref_service; - identity::IdentityTestEnvironment environment( + signin::IdentityTestEnvironment environment( /*test_url_loader_factory=*/nullptr, &pref_service); - identity::IdentityManager* identity_manager = environment.identity_manager(); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityManager* identity_manager = environment.identity_manager(); + signin::PrimaryAccountMutator* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); // Abort the test if the current platform does not support mutation of the @@ -340,10 +340,10 @@ TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_NotSignedIn) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment environment; + signin::IdentityTestEnvironment environment; - identity::IdentityManager* identity_manager = environment.identity_manager(); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityManager* identity_manager = environment.identity_manager(); + signin::PrimaryAccountMutator* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); // Abort the test if the current platform does not support mutation of the @@ -354,7 +354,7 @@ // Trying to signout an account that hasn't signed in first should fail. EXPECT_FALSE(identity_manager->HasPrimaryAccount()); EXPECT_FALSE(primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); @@ -364,17 +364,17 @@ EXPECT_FALSE(identity_manager->HasPrimaryAccount()); EXPECT_FALSE(primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); } TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_Default) { base::test::ScopedTaskEnvironment task_environment; - identity::IdentityTestEnvironment environment; + signin::IdentityTestEnvironment environment; - identity::IdentityManager* identity_manager = environment.identity_manager(); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::IdentityManager* identity_manager = environment.identity_manager(); + signin::PrimaryAccountMutator* primary_account_mutator = identity_manager->GetPrimaryAccountMutator(); // Abort the test if the current platform does not support mutation of the @@ -401,7 +401,7 @@ primary_account_info.account_id); EXPECT_TRUE(primary_account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); @@ -422,7 +422,7 @@ kTestedAccountConsistencyMethods) { RunClearPrimaryAccountTest( account_consistency_method, - identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, RemoveAccountExpectation::kKeepAll); } } @@ -434,7 +434,7 @@ kTestedAccountConsistencyMethods) { RunClearPrimaryAccountTest( account_consistency_method, - identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, + signin::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, RemoveAccountExpectation::kRemoveAll); } } @@ -446,7 +446,7 @@ ClearPrimaryAccount_Default_DisabledConsistency) { RunClearPrimaryAccountTest( signin::AccountConsistencyMethod::kDisabled, - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, RemoveAccountExpectation::kRemoveAll); } @@ -457,7 +457,7 @@ ClearPrimaryAccount_Default_MirrorConsistency) { RunClearPrimaryAccountTest( signin::AccountConsistencyMethod::kMirror, - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, RemoveAccountExpectation::kRemoveAll); } @@ -467,7 +467,7 @@ TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_Default_DiceConsistency) { RunClearPrimaryAccountTest( signin::AccountConsistencyMethod::kDice, - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, RemoveAccountExpectation::kKeepAll); } @@ -478,6 +478,6 @@ ClearPrimaryAccount_Default_DiceConsistency_AuthError) { RunClearPrimaryAccountTest( signin::AccountConsistencyMethod::kDice, - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, RemoveAccountExpectation::kRemovePrimary, AuthExpectation::kAuthError); }
diff --git a/components/signin/public/identity_manager/test_identity_manager_observer.cc b/components/signin/public/identity_manager/test_identity_manager_observer.cc index f64f231..afa01cb 100644 --- a/components/signin/public/identity_manager/test_identity_manager_observer.cc +++ b/components/signin/public/identity_manager/test_identity_manager_observer.cc
@@ -8,7 +8,7 @@ #include <utility> -namespace identity { +namespace signin { TestIdentityManagerObserver::TestIdentityManagerObserver( IdentityManager* identity_manager) @@ -226,4 +226,4 @@ is_inside_batch_ = false; } -} // namespace identity +} // namespace signin
diff --git a/components/signin/public/identity_manager/test_identity_manager_observer.h b/components/signin/public/identity_manager/test_identity_manager_observer.h index 5f8feffa..506e246 100644 --- a/components/signin/public/identity_manager/test_identity_manager_observer.h +++ b/components/signin/public/identity_manager/test_identity_manager_observer.h
@@ -13,9 +13,9 @@ #include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/google_service_auth_error.h" -namespace identity { +namespace signin { -// Class that observes events from identity::IdentityManager. It allows setting +// Class that observes events from IdentityManager. It allows setting // |OnceClosure| callbacks to be executed for the observed events and retrieving // the potential results and/or errors returned after such events have occurred. class TestIdentityManagerObserver : IdentityManager::Observer { @@ -130,6 +130,6 @@ DISALLOW_COPY_AND_ASSIGN(TestIdentityManagerObserver); }; -} // namespace identity +} // namespace signin #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_TEST_IDENTITY_MANAGER_OBSERVER_H_
diff --git a/components/suggestions/suggestions_service_impl.cc b/components/suggestions/suggestions_service_impl.cc index 75978bc..943b73b3 100644 --- a/components/suggestions/suggestions_service_impl.cc +++ b/components/suggestions/suggestions_service_impl.cc
@@ -107,7 +107,7 @@ } // namespace SuggestionsServiceImpl::SuggestionsServiceImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, syncer::SyncService* sync_service, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, std::unique_ptr<SuggestionsStore> suggestions_store, @@ -342,17 +342,17 @@ return; identity::ScopeSet scopes{GaiaConstants::kChromeSyncOAuth2Scope}; - token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( "suggestions_service", identity_manager_, scopes, base::BindOnce(&SuggestionsServiceImpl::AccessTokenAvailable, base::Unretained(this), url), - identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); + signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable); } void SuggestionsServiceImpl::AccessTokenAvailable( const GURL& url, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { DCHECK(token_fetcher_); token_fetcher_.reset();
diff --git a/components/suggestions/suggestions_service_impl.h b/components/suggestions/suggestions_service_impl.h index d458088c..7c933537 100644 --- a/components/suggestions/suggestions_service_impl.h +++ b/components/suggestions/suggestions_service_impl.h
@@ -31,10 +31,10 @@ #include "net/url_request/url_fetcher_delegate.h" #include "url/gurl.h" -namespace identity { +namespace signin { class IdentityManager; class PrimaryAccountAccessTokenFetcher; -} // namespace identity +} // namespace signin namespace network { class SharedURLLoaderFactory; @@ -59,7 +59,7 @@ public syncer::SyncServiceObserver { public: SuggestionsServiceImpl( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, syncer::SyncService* sync_service, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, std::unique_ptr<SuggestionsStore> suggestions_store, @@ -140,7 +140,7 @@ // Called when an access token request completes (successfully or not). void AccessTokenAvailable(const GURL& url, GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // Issues a network request for suggestions (fetch, blacklist, or clear // blacklist, depending on |url|). @@ -174,7 +174,7 @@ base::ThreadChecker thread_checker_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; syncer::SyncService* sync_service_; ScopedObserver<syncer::SyncService, syncer::SyncServiceObserver> @@ -200,7 +200,7 @@ // Helper for fetching OAuth2 access tokens. This is non-null iff an access // token request is currently in progress. - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; // Contains the current suggestions fetch request. Will only have a value // while a request is pending, and will be reset by |OnURLFetchComplete| or
diff --git a/components/suggestions/suggestions_service_impl_unittest.cc b/components/suggestions/suggestions_service_impl_unittest.cc index 2eaaa7d7..459ee07 100644 --- a/components/suggestions/suggestions_service_impl_unittest.cc +++ b/components/suggestions/suggestions_service_impl_unittest.cc
@@ -185,7 +185,7 @@ return suggestions_service_.get(); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } @@ -197,7 +197,7 @@ base::test::ScopedTaskEnvironment::TimeSource::MOCK_TIME}; private: - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; syncer::TestSyncService test_sync_service_; network::TestURLLoaderFactory url_loader_factory_;
diff --git a/components/sync/driver/BUILD.gn b/components/sync/driver/BUILD.gn index 9a8fd4b..ecbe3ba 100644 --- a/components/sync/driver/BUILD.gn +++ b/components/sync/driver/BUILD.gn
@@ -112,7 +112,6 @@ "//components/invalidation/impl:feature_list", "//components/keyed_service/core", "//components/prefs", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//components/version_info", "//components/version_info:generate_version_info",
diff --git a/components/sync/driver/DEPS b/components/sync/driver/DEPS index 5bb686a3..fe63a79 100644 --- a/components/sync/driver/DEPS +++ b/components/sync/driver/DEPS
@@ -5,25 +5,7 @@ "+components/policy", "+components/pref_registry", "+components/prefs", - "+components/signin/core/browser", - # Use identity_manager.h instead of the below files; - # see https://groups.google.com/a/chromium.org/d/msg/chromium-dev/dgFLuxqZt1o/iEqkyoQQBwAJ for help and info. - "-components/signin/internal/identity_manager/account_fetcher_service.h", - "-components/signin/internal/identity_manager/account_info_fetcher.h", - "-components/signin/internal/identity_manager/account_tracker_service.h", - "-components/signin/internal/identity_manager/child_account_info_fetcher_android.h", - "-components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/gaia_cookie_manager_service.h", - "-components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_helper.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_token_fetcher.h", - "-components/signin/internal/identity_manager/primary_account_manager.h", - "-components/signin/internal/identity_manager/primary_account_policy_manager.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h", - "-components/signin/internal/identity_manager/ubertoken_fetcher_impl.h", "+components/signin/public", - "+components/sync/base", "+components/sync/engine", "+components/sync/engine_impl",
diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc index 3b69d71..e9504a4 100644 --- a/components/sync/driver/profile_sync_service.cc +++ b/components/sync/driver/profile_sync_service.cc
@@ -880,7 +880,7 @@ // Check for a cookie jar mismatch. if (identity_manager_) { - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = identity_manager_->GetAccountsInCookieJar(); if (accounts_in_cookie_jar_info.accounts_are_fresh) { OnAccountsInCookieUpdated(accounts_in_cookie_jar_info, @@ -964,7 +964,7 @@ // GetPrimaryAccountMutator() returns nullptr on ChromeOS only. DCHECK(account_mutator); account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SERVER_FORCED_DISABLE, signin_metrics::SignoutDelete::IGNORE_METRIC); } @@ -1478,7 +1478,7 @@ } void ProfileSyncService::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { OnAccountsInCookieUpdatedWithCallback( accounts_in_cookie_jar_info.signed_in_accounts, base::Closure());
diff --git a/components/sync/driver/profile_sync_service.h b/components/sync/driver/profile_sync_service.h index 88d12451..a5e71292e 100644 --- a/components/sync/driver/profile_sync_service.h +++ b/components/sync/driver/profile_sync_service.h
@@ -70,7 +70,7 @@ public SyncPrefObserver, public DataTypeManagerObserver, public UnrecoverableErrorHandler, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // If AUTO_START, sync will set IsFirstSetupComplete() automatically and sync // will begin syncing without the user needing to confirm sync settings. @@ -89,7 +89,7 @@ ~InitParams(); std::unique_ptr<SyncClient> sync_client; - identity::IdentityManager* identity_manager = nullptr; + signin::IdentityManager* identity_manager = nullptr; std::vector<invalidation::IdentityProvider*> invalidations_identity_providers; StartBehavior start_behavior = MANUAL_START; @@ -185,7 +185,7 @@ // IdentityManager::Observer implementation. void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; // Similar to above but with a callback that will be invoked on completion. @@ -371,7 +371,7 @@ // Encapsulates user signin - used to set/get the user's authenticated // email address and sign-out upon error. - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; // The user-configurable knobs. Non-null between Initialize() and Shutdown(). std::unique_ptr<SyncUserSettingsImpl> user_settings_;
diff --git a/components/sync/driver/profile_sync_service_bundle.h b/components/sync/driver/profile_sync_service_bundle.h index a4fd8b1..fbd6216 100644 --- a/components/sync/driver/profile_sync_service_bundle.h +++ b/components/sync/driver/profile_sync_service_bundle.h
@@ -50,11 +50,11 @@ return &pref_service_; } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return identity_test_env_.identity_manager(); } @@ -72,7 +72,7 @@ private: sync_preferences::TestingPrefServiceSyncable pref_service_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; testing::NiceMock<SyncApiComponentFactoryMock> component_factory_; std::unique_ptr<invalidation::ProfileIdentityProvider> identity_provider_; invalidation::FakeInvalidationService fake_invalidation_service_;
diff --git a/components/sync/driver/profile_sync_service_unittest.cc b/components/sync/driver/profile_sync_service_unittest.cc index edb3d4cb..ac4a334c 100644 --- a/components/sync/driver/profile_sync_service_unittest.cc +++ b/components/sync/driver/profile_sync_service_unittest.cc
@@ -263,11 +263,11 @@ return profile_sync_service_bundle_.identity_provider(); } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return profile_sync_service_bundle_.identity_manager(); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return profile_sync_service_bundle_.identity_test_env(); } @@ -535,7 +535,7 @@ // GetPrimaryAccountMutator() returns nullptr on ChromeOS only. DCHECK(account_mutator); account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC); // Wait for PSS to be notified that the primary account has gone away. @@ -799,7 +799,7 @@ DCHECK(account_mutator); account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC); EXPECT_TRUE(service()->GetAccessTokenForTest().empty());
diff --git a/components/sync/driver/sync_auth_manager.cc b/components/sync/driver/sync_auth_manager.cc index 1ed436c..bf070b1 100644 --- a/components/sync/driver/sync_auth_manager.cc +++ b/components/sync/driver/sync_auth_manager.cc
@@ -54,7 +54,7 @@ } // namespace SyncAuthManager::SyncAuthManager( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const AccountStateChangedCallback& account_state_changed, const CredentialsChangedCallback& credentials_changed) : identity_manager_(identity_manager), @@ -370,7 +370,7 @@ } void SyncAuthManager::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { UpdateSyncAccountIfNecessary(); } @@ -462,12 +462,12 @@ {GaiaConstants::kChromeSyncOAuth2Scope}, base::BindOnce(&SyncAuthManager::AccessTokenFetched, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kWaitUntilRefreshTokenAvailable); + signin::AccessTokenFetcher::Mode::kWaitUntilRefreshTokenAvailable); } void SyncAuthManager::AccessTokenFetched( GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { DCHECK(registered_for_auth_notifications_); DCHECK(ongoing_access_token_fetch_);
diff --git a/components/sync/driver/sync_auth_manager.h b/components/sync/driver/sync_auth_manager.h index 06f90da..2180618 100644 --- a/components/sync/driver/sync_auth_manager.h +++ b/components/sync/driver/sync_auth_manager.h
@@ -22,10 +22,10 @@ #include "google_apis/gaia/google_service_auth_error.h" #include "net/base/backoff_entry.h" -namespace identity { +namespace signin { class AccessTokenFetcher; struct AccessTokenInfo; -} +} // namespace signin namespace syncer { @@ -34,7 +34,7 @@ // SyncAuthManager tracks the account to be used for Sync and its authentication // state. Note that this account may or may not be the primary account (as per // IdentityManager::GetPrimaryAccountInfo() etc). -class SyncAuthManager : public identity::IdentityManager::Observer { +class SyncAuthManager : public signin::IdentityManager::Observer { public: // Called when the existence of an authenticated account changes. It's // guaranteed that this is only called for going from "no account" to "have @@ -48,7 +48,7 @@ // |identity_manager| may be null (this is the case if local Sync is enabled), // but if non-null, must outlive this object. - SyncAuthManager(identity::IdentityManager* identity_manager, + SyncAuthManager(signin::IdentityManager* identity_manager, const AccountStateChangedCallback& account_state_changed, const CredentialsChangedCallback& credentials_changed); ~SyncAuthManager() override; @@ -98,7 +98,7 @@ // cached access token, error from the server, etc). void ConnectionClosed(); - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnPrimaryAccountSet( const CoreAccountInfo& primary_account_info) override; void OnPrimaryAccountCleared( @@ -108,7 +108,7 @@ void OnRefreshTokenRemovedForAccount( const CoreAccountId& account_id) override; void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; // Test-only methods for inspecting/modifying internal state. @@ -145,11 +145,11 @@ // Callback for |ongoing_access_token_fetch_|. void AccessTokenFetched(GoogleServiceAuthError error, - identity::AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); void SetLastAuthError(const GoogleServiceAuthError& error); - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; const AccountStateChangedCallback account_state_changed_callback_; const CredentialsChangedCallback credentials_changed_callback_; @@ -181,7 +181,7 @@ // Pending request for an access token. Non-null iff there is a request // ongoing. - std::unique_ptr<identity::AccessTokenFetcher> ongoing_access_token_fetch_; + std::unique_ptr<signin::AccessTokenFetcher> ongoing_access_token_fetch_; // If RequestAccessToken fails with transient error then retry requesting // access token with exponential backoff.
diff --git a/components/sync/driver/sync_auth_manager_unittest.cc b/components/sync/driver/sync_auth_manager_unittest.cc index 50b8fb4..2d80450 100644 --- a/components/sync/driver/sync_auth_manager_unittest.cc +++ b/components/sync/driver/sync_auth_manager_unittest.cc
@@ -52,12 +52,12 @@ base::DoNothing()); } - identity::IdentityTestEnvironment* identity_env() { return &identity_env_; } + signin::IdentityTestEnvironment* identity_env() { return &identity_env_; } private: base::test::ScopedTaskEnvironment task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_env_; + signin::IdentityTestEnvironment identity_env_; }; TEST_F(SyncAuthManagerTest, ProvidesNothingInLocalSyncMode) { @@ -160,7 +160,7 @@ // Make the account primary. EXPECT_CALL(account_state_changed, Run()); - identity::PrimaryAccountMutator* primary_account_mutator = + signin::PrimaryAccountMutator* primary_account_mutator = identity_env()->identity_manager()->GetPrimaryAccountMutator(); primary_account_mutator->SetPrimaryAccount(account_info.account_id);
diff --git a/components/sync/driver/sync_auth_util.cc b/components/sync/driver/sync_auth_util.cc index d2e50e72..17584a5 100644 --- a/components/sync/driver/sync_auth_util.cc +++ b/components/sync/driver/sync_auth_util.cc
@@ -19,9 +19,8 @@ bool is_primary) : account_info(account_info), is_primary(is_primary) {} -SyncAccountInfo DetermineAccountToUse( - identity::IdentityManager* identity_manager, - bool allow_secondary_accounts) { +SyncAccountInfo DetermineAccountToUse(signin::IdentityManager* identity_manager, + bool allow_secondary_accounts) { // If there is a "primary account", i.e. the user explicitly chose to // sign-in to Chrome, then always use that account. if (identity_manager->HasPrimaryAccount()) {
diff --git a/components/sync/driver/sync_auth_util.h b/components/sync/driver/sync_auth_util.h index 6190dad..e88a42a 100644 --- a/components/sync/driver/sync_auth_util.h +++ b/components/sync/driver/sync_auth_util.h
@@ -9,9 +9,9 @@ class GoogleServiceAuthError; -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin namespace syncer { @@ -26,9 +26,8 @@ // Determines which account should be used for Sync and returns the // corresponding SyncAccountInfo. This is exposed so that autofill metrics // code can use it. -SyncAccountInfo DetermineAccountToUse( - identity::IdentityManager* identity_manager, - bool allow_secondary_accounts); +SyncAccountInfo DetermineAccountToUse(signin::IdentityManager* identity_manager, + bool allow_secondary_accounts); // Returns whether |auth_error| indicates the user has locally signed out of // content area, rejecting credentials.
diff --git a/components/sync/driver/sync_driver_switches.cc b/components/sync/driver/sync_driver_switches.cc index e9cd4ce..ab24f6a 100644 --- a/components/sync/driver/sync_driver_switches.cc +++ b/components/sync/driver/sync_driver_switches.cc
@@ -65,7 +65,7 @@ // Enable USS implementation of Bookmarks datatype. const base::Feature kSyncUSSBookmarks{"SyncUSSBookmarks", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; // Enable USS implementation of Passwords datatype. const base::Feature kSyncUSSPasswords{"SyncUSSPasswords",
diff --git a/components/sync/driver/sync_session_durations_metrics_recorder.cc b/components/sync/driver/sync_session_durations_metrics_recorder.cc index 641c953..130e960 100644 --- a/components/sync/driver/sync_session_durations_metrics_recorder.cc +++ b/components/sync/driver/sync_session_durations_metrics_recorder.cc
@@ -27,7 +27,7 @@ SyncSessionDurationsMetricsRecorder::SyncSessionDurationsMetricsRecorder( SyncService* sync_service, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : sync_service_(sync_service), identity_manager_(identity_manager), sync_observer_(this), @@ -44,7 +44,7 @@ // Check if we already know the signed in cookies. This will trigger a fetch // if we don't have them yet. - identity::AccountsInCookieJarInfo accounts_in_cookie_jar_info = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar_info = identity_manager_->GetAccountsInCookieJar(); if (accounts_in_cookie_jar_info.accounts_are_fresh) { OnAccountsInCookieUpdated(accounts_in_cookie_jar_info, @@ -93,7 +93,7 @@ } void SyncSessionDurationsMetricsRecorder::OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) { DVLOG(1) << "Cookie state change. accounts: " << accounts_in_cookie_jar_info.signed_in_accounts.size()
diff --git a/components/sync/driver/sync_session_durations_metrics_recorder.h b/components/sync/driver/sync_session_durations_metrics_recorder.h index ce1224f7..9bd195a 100644 --- a/components/sync/driver/sync_session_durations_metrics_recorder.h +++ b/components/sync/driver/sync_session_durations_metrics_recorder.h
@@ -21,12 +21,12 @@ // as fraction of their total browsing time. class SyncSessionDurationsMetricsRecorder : public syncer::SyncServiceObserver, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // Callers must ensure that the parameters outlive this object. SyncSessionDurationsMetricsRecorder( SyncService* sync_service, - identity::IdentityManager* identity_manager); + signin::IdentityManager* identity_manager); ~SyncSessionDurationsMetricsRecorder() override; // Informs this service that a session started at |session_start| time. @@ -46,7 +46,7 @@ const CoreAccountInfo& account_info, const GoogleServiceAuthError& error) override; void OnAccountsInCookieUpdated( - const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, + const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; private: @@ -71,11 +71,11 @@ FeatureState DetermineAccountStatus() const; SyncService* const sync_service_; - identity::IdentityManager* const identity_manager_; + signin::IdentityManager* const identity_manager_; ScopedObserver<syncer::SyncService, syncer::SyncServiceObserver> sync_observer_; - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; // Tracks the elapsed active session time while the browser is open. The timer
diff --git a/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc b/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc index 2b26126..1734766 100644 --- a/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc +++ b/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc
@@ -72,7 +72,7 @@ protected: base::test::ScopedTaskEnvironment task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; TestSyncService sync_service_; const base::TimeDelta session_time_;
diff --git a/components/test/BUILD.gn b/components/test/BUILD.gn index 1105e8a..e755c31 100644 --- a/components/test/BUILD.gn +++ b/components/test/BUILD.gn
@@ -16,7 +16,6 @@ deps = [ "//components/content_settings/core/common", "//components/gcm_driver:gcm_driver", - "//components/signin/core/browser", "//mojo/core/embedder", "//net", "//testing/gtest",
diff --git a/components/translate/ios/browser/language_detection_controller.h b/components/translate/ios/browser/language_detection_controller.h index 82ba785..0c681c0 100644 --- a/components/translate/ios/browser/language_detection_controller.h +++ b/components/translate/ios/browser/language_detection_controller.h
@@ -14,6 +14,7 @@ #include "base/memory/weak_ptr.h" #include "base/strings/string16.h" #include "components/prefs/pref_member.h" +#import "ios/web/public/web_state/web_state.h" #include "ios/web/public/web_state/web_state_observer.h" class GURL; @@ -30,7 +31,6 @@ namespace web { class NavigationContext; -class WebState; } namespace translate { @@ -79,6 +79,9 @@ // WebStateDestroyed has been called. web::WebState* web_state_ = nullptr; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + JsLanguageDetectionManager* js_manager_; BooleanPrefMember translate_enabled_; std::string content_language_header_;
diff --git a/components/translate/ios/browser/language_detection_controller.mm b/components/translate/ios/browser/language_detection_controller.mm index eb76d507..ac7b521 100644 --- a/components/translate/ios/browser/language_detection_controller.mm +++ b/components/translate/ios/browser/language_detection_controller.mm
@@ -47,7 +47,7 @@ translate_enabled_.Init(prefs::kOfferTranslateEnabled, prefs); web_state_->AddObserver(this); - web_state_->AddScriptCommandCallback( + subscription_ = web_state_->AddScriptCommandCallback( base::Bind(&LanguageDetectionController::OnTextCaptured, base::Unretained(this)), kCommandPrefix); @@ -55,7 +55,6 @@ LanguageDetectionController::~LanguageDetectionController() { if (web_state_) { - web_state_->RemoveScriptCommandCallback(kCommandPrefix); web_state_->RemoveObserver(this); web_state_ = nullptr; } @@ -186,7 +185,6 @@ void LanguageDetectionController::WebStateDestroyed(web::WebState* web_state) { DCHECK_EQ(web_state_, web_state); - web_state_->RemoveScriptCommandCallback(kCommandPrefix); web_state_->RemoveObserver(this); web_state_ = nullptr; }
diff --git a/components/translate/ios/browser/translate_controller.h b/components/translate/ios/browser/translate_controller.h index 43e1a00..94ab587a 100644 --- a/components/translate/ios/browser/translate_controller.h +++ b/components/translate/ios/browser/translate_controller.h
@@ -15,6 +15,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/translate/core/common/translate_errors.h" +#import "ios/web/public/web_state/web_state.h" #include "ios/web/public/web_state/web_state_observer.h" #include "services/network/public/cpp/simple_url_loader.h" @@ -27,7 +28,6 @@ namespace web { class NavigationContext; -class WebState; } // namespace web namespace translate { @@ -122,6 +122,9 @@ // Used to fetch additional scripts needed for translate. std::unique_ptr<network::SimpleURLLoader> script_fetcher_; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + Observer* observer_; base::scoped_nsobject<JsTranslateManager> js_manager_; base::WeakPtrFactory<TranslateController> weak_method_factory_;
diff --git a/components/translate/ios/browser/translate_controller.mm b/components/translate/ios/browser/translate_controller.mm index 8348084..fb226d30 100644 --- a/components/translate/ios/browser/translate_controller.mm +++ b/components/translate/ios/browser/translate_controller.mm
@@ -49,7 +49,7 @@ DCHECK(js_manager_); DCHECK(web_state_); web_state_->AddObserver(this); - web_state_->AddScriptCommandCallback( + subscription_ = web_state_->AddScriptCommandCallback( base::Bind( [](TranslateController* ptr, const base::DictionaryValue& command, const GURL& page_url, bool user_is_interacting, @@ -288,7 +288,6 @@ void TranslateController::WebStateDestroyed(web::WebState* web_state) { DCHECK_EQ(web_state_, web_state); - web_state_->RemoveScriptCommandCallback(kCommandPrefix); web_state_->RemoveObserver(this); web_state_ = nullptr;
diff --git a/components/unified_consent/BUILD.gn b/components/unified_consent/BUILD.gn index e0cafb05f..eeae8f03 100644 --- a/components/unified_consent/BUILD.gn +++ b/components/unified_consent/BUILD.gn
@@ -20,7 +20,7 @@ "//components/autofill/core/common", "//components/browser_sync", "//components/pref_registry", - "//components/signin/core/browser", + "//components/prefs", "//components/signin/public/identity_manager", "//components/sync", "//components/sync_preferences",
diff --git a/components/unified_consent/unified_consent_service.cc b/components/unified_consent/unified_consent_service.cc index 1523882..efe2ba43 100644 --- a/components/unified_consent/unified_consent_service.cc +++ b/components/unified_consent/unified_consent_service.cc
@@ -21,7 +21,7 @@ UnifiedConsentService::UnifiedConsentService( sync_preferences::PrefServiceSyncable* pref_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, syncer::SyncService* sync_service, const std::vector<std::string>& service_pref_names) : pref_service_(pref_service),
diff --git a/components/unified_consent/unified_consent_service.h b/components/unified_consent/unified_consent_service.h index ab386f22..76f19e2b 100644 --- a/components/unified_consent/unified_consent_service.h +++ b/components/unified_consent/unified_consent_service.h
@@ -54,14 +54,14 @@ // syncing down older changes. class UnifiedConsentService : public KeyedService, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public syncer::SyncServiceObserver, public sync_preferences::PrefServiceSyncableObserver { public: // Initializes the service. The |service_pref_names| vector is used to track // pref changes during the first sync setup. UnifiedConsentService(sync_preferences::PrefServiceSyncable* pref_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, syncer::SyncService* sync_service, const std::vector<std::string>& service_pref_names); ~UnifiedConsentService() override; @@ -109,7 +109,7 @@ void UpdateSettingsForMigration(); sync_preferences::PrefServiceSyncable* pref_service_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; syncer::SyncService* sync_service_; // Used for tracking the service pref states during the advanced sync opt-in.
diff --git a/components/unified_consent/unified_consent_service_unittest.cc b/components/unified_consent/unified_consent_service_unittest.cc index b5c2adf..1ff55483 100644 --- a/components/unified_consent/unified_consent_service_unittest.cc +++ b/components/unified_consent/unified_consent_service_unittest.cc
@@ -91,7 +91,7 @@ protected: base::test::ScopedTaskEnvironment task_environment_; sync_preferences::TestingPrefServiceSyncable pref_service_; - identity::IdentityTestEnvironment identity_test_environment_; + signin::IdentityTestEnvironment identity_test_environment_; TestSyncService sync_service_; std::unique_ptr<UnifiedConsentService> consent_service_; std::unique_ptr<ScopedUnifiedConsent> scoped_unified_consent_;
diff --git a/components/viz/service/BUILD.gn b/components/viz/service/BUILD.gn index 887be863..16ef26a 100644 --- a/components/viz/service/BUILD.gn +++ b/components/viz/service/BUILD.gn
@@ -310,6 +310,8 @@ "display_embedder/image_context.h", "display_embedder/skia_output_device.cc", "display_embedder/skia_output_device.h", + "display_embedder/skia_output_device_buffer_queue.cc", + "display_embedder/skia_output_device_buffer_queue.h", "display_embedder/skia_output_device_gl.cc", "display_embedder/skia_output_device_gl.h", "display_embedder/skia_output_device_offscreen.cc", @@ -402,6 +404,7 @@ "display/texture_deleter_unittest.cc", "display_embedder/buffer_queue_unittest.cc", "display_embedder/server_shared_bitmap_manager_unittest.cc", + "display_embedder/skia_output_device_buffer_queue_unittest.cc", "display_embedder/skia_output_surface_impl_unittest.cc", "display_embedder/software_output_surface_unittest.cc", "display_embedder/vsync_parameter_listener_unittest.cc",
diff --git a/components/viz/service/display/skia_output_surface.h b/components/viz/service/display/skia_output_surface.h index 325a4077..f0986c9 100644 --- a/components/viz/service/display/skia_output_surface.h +++ b/components/viz/service/display/skia_output_surface.h
@@ -75,6 +75,9 @@ // Swaps the current backbuffer to the screen. virtual void SkiaSwapBuffers(OutputSurfaceFrame frame) = 0; + // Schedule overlay planes to be displayed + virtual void ScheduleOverlays(OverlayCandidateList overlays) = 0; + // Begin painting a render pass. This method will create a // SkDeferredDisplayListRecorder and return a SkCanvas of it. The SkiaRenderer // will use this SkCanvas to paint the render pass.
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index d6fb6d1..a701949 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -687,6 +687,9 @@ if (use_swap_with_bounds_) swap_content_bounds_ = current_frame()->root_content_bounds; + + skia_output_surface_->ScheduleOverlays( + std::move(current_frame()->overlay_list)); } void SkiaRenderer::SwapBuffers(std::vector<ui::LatencyInfo> latency_info) {
diff --git a/components/viz/service/display_embedder/skia_output_device.cc b/components/viz/service/display_embedder/skia_output_device.cc index 4d10da1..f5c63081 100644 --- a/components/viz/service/display_embedder/skia_output_device.cc +++ b/components/viz/service/display_embedder/skia_output_device.cc
@@ -7,6 +7,7 @@ #include <utility> #include "third_party/skia/include/core/SkSurface.h" +#include "ui/gfx/gpu_fence.h" #include "ui/gfx/presentation_feedback.h" namespace viz { @@ -80,4 +81,12 @@ void SkiaOutputDevice::EnsureBackbuffer() {} void SkiaOutputDevice::DiscardBackbuffer() {} +gl::GLImage* SkiaOutputDevice::GetOverlayImage() { + return nullptr; +} + +std::unique_ptr<gfx::GpuFence> SkiaOutputDevice::SubmitOverlayGpuFence() { + return nullptr; +} + } // namespace viz
diff --git a/components/viz/service/display_embedder/skia_output_device.h b/components/viz/service/display_embedder/skia_output_device.h index 063cf16..2eceb24 100644 --- a/components/viz/service/display_embedder/skia_output_device.h +++ b/components/viz/service/display_embedder/skia_output_device.h
@@ -19,6 +19,7 @@ namespace gfx { class ColorSpace; +class GpuFence; class Rect; class Size; struct PresentationFeedback; @@ -75,6 +76,9 @@ BufferPresentedCallback feedback, std::vector<ui::LatencyInfo> latency_info); + virtual gl::GLImage* GetOverlayImage(); + virtual std::unique_ptr<gfx::GpuFence> SubmitOverlayGpuFence(); + // Set the rectangle that will be drawn into on the surface. virtual void SetDrawRectangle(const gfx::Rect& draw_rectangle);
diff --git a/components/viz/service/display_embedder/skia_output_device_buffer_queue.cc b/components/viz/service/display_embedder/skia_output_device_buffer_queue.cc new file mode 100644 index 0000000..367b8c3 --- /dev/null +++ b/components/viz/service/display_embedder/skia_output_device_buffer_queue.cc
@@ -0,0 +1,294 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/service/display_embedder/skia_output_device_buffer_queue.h" + +#include "components/viz/service/display_embedder/skia_output_surface_dependency.h" +#include "gpu/command_buffer/common/capabilities.h" +#include "gpu/command_buffer/common/shared_image_usage.h" +#include "gpu/command_buffer/service/feature_info.h" +#include "gpu/command_buffer/service/shared_context_state.h" +#include "gpu/command_buffer/service/shared_image_representation.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/core/SkSurfaceProps.h" +#include "ui/gl/color_space_utils.h" +#include "ui/gl/gl_fence.h" +#include "ui/gl/gl_surface.h" + +namespace viz { + +static constexpr uint32_t kSharedImageUsage = + gpu::SHARED_IMAGE_USAGE_SCANOUT | gpu::SHARED_IMAGE_USAGE_DISPLAY | + gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT; + +SkiaOutputDeviceBufferQueue::SkiaOutputDeviceBufferQueue( + scoped_refptr<gl::GLSurface> gl_surface, + SkiaOutputSurfaceDependency* deps, + const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback, + uint32_t shared_image_usage) + : SkiaOutputDevice(false /*need_swap_semaphore */, + did_swap_buffer_complete_callback), + dependency_(deps), + gl_surface_(gl_surface), + shared_image_factory_(deps->GetGpuPreferences(), + deps->GetGpuDriverBugWorkarounds(), + deps->GetGpuFeatureInfo(), + deps->GetSharedContextState().get(), + deps->GetMailboxManager(), + deps->GetSharedImageManager(), + nullptr, + nullptr, + true), + shared_image_usage_(shared_image_usage) { + shared_image_representation_factory_ = + std::make_unique<gpu::SharedImageRepresentationFactory>( + deps->GetSharedImageManager(), nullptr); + + // TODO(vasilyt): Need to figure out why partial swap isn't working + capabilities_.supports_post_sub_buffer = false; +} + +SkiaOutputDeviceBufferQueue::SkiaOutputDeviceBufferQueue( + scoped_refptr<gl::GLSurface> gl_surface, + SkiaOutputSurfaceDependency* deps, + const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback) + : SkiaOutputDeviceBufferQueue(gl_surface, + deps, + did_swap_buffer_complete_callback, + kSharedImageUsage) {} + +SkiaOutputDeviceBufferQueue::~SkiaOutputDeviceBufferQueue() { + FreeAllSurfaces(); +} + +SkiaOutputDeviceBufferQueue::Image* +SkiaOutputDeviceBufferQueue::GetCurrentImage() { + if (!current_image_) + current_image_ = GetNextImage(); + + return current_image_.get(); +} + +std::unique_ptr<SkiaOutputDeviceBufferQueue::Image> +SkiaOutputDeviceBufferQueue::GetNextImage() { + if (!available_images_.empty()) { + std::unique_ptr<Image> image = std::move(available_images_.back()); + available_images_.pop_back(); + return image; + } + + auto image = std::make_unique<Image>( + &shared_image_factory_, shared_image_representation_factory_.get()); + + if (image->Initialize(image_size_, color_space_, ResourceFormat::RGBA_8888, + dependency_, shared_image_usage_)) { + return image; + } + + return nullptr; +} + +void SkiaOutputDeviceBufferQueue::PageFlipComplete() { + DCHECK(!in_flight_images_.empty()); + + if (in_flight_images_.front()) { + if (displayed_image_) + available_images_.push_back(std::move(displayed_image_)); + displayed_image_ = std::move(in_flight_images_.front()); + // If the GpuFence was created for ScheduleOverlayPlane we can release it + // now + if (displayed_image_) + displayed_image_->ResetFence(); + } + + in_flight_images_.pop_front(); +} + +void SkiaOutputDeviceBufferQueue::FreeAllSurfaces() { + displayed_image_.reset(); + current_image_.reset(); + // This is intentionally not emptied since the swap buffers acks are still + // expected to arrive. + for (auto& image : in_flight_images_) + image = nullptr; + + available_images_.clear(); +} + +gl::GLImage* SkiaOutputDeviceBufferQueue::GetOverlayImage() { + if (current_image_) { + return current_image_->GetImage(); + } + return nullptr; +} + +std::unique_ptr<gfx::GpuFence> +SkiaOutputDeviceBufferQueue::SubmitOverlayGpuFence() { + if (current_image_) { + return current_image_->CreateFence(); + } + return nullptr; +} + +void SkiaOutputDeviceBufferQueue::SwapBuffers( + BufferPresentedCallback feedback, + std::vector<ui::LatencyInfo> latency_info) { + in_flight_images_.push_back(std::move(current_image_)); + + StartSwapBuffers({}); + + if (gl_surface_->SupportsAsyncSwap()) { + auto callback = base::BindOnce( + &SkiaOutputDeviceBufferQueue::DoFinishSwapBuffers, + weak_ptr_factory_.GetWeakPtr(), image_size_, std::move(latency_info)); + gl_surface_->SwapBuffersAsync(std::move(callback), std::move(feedback)); + } else { + DoFinishSwapBuffers(image_size_, std::move(latency_info), + gl_surface_->SwapBuffers(std::move(feedback)), nullptr); + } +} + +void SkiaOutputDeviceBufferQueue::PostSubBuffer( + const gfx::Rect& rect, + BufferPresentedCallback feedback, + std::vector<ui::LatencyInfo> latency_info) { + in_flight_images_.push_back(std::move(current_image_)); + StartSwapBuffers({}); + + if (gl_surface_->SupportsAsyncSwap()) { + auto callback = base::BindOnce( + &SkiaOutputDeviceBufferQueue::DoFinishSwapBuffers, + weak_ptr_factory_.GetWeakPtr(), image_size_, std::move(latency_info)); + gl_surface_->PostSubBufferAsync(rect.x(), rect.y(), rect.width(), + rect.height(), std::move(callback), + std::move(feedback)); + + } else { + DoFinishSwapBuffers( + image_size_, std::move(latency_info), + gl_surface_->PostSubBuffer(rect.x(), rect.y(), rect.width(), + rect.height(), std::move(feedback)), + nullptr); + } +} + +void SkiaOutputDeviceBufferQueue::DoFinishSwapBuffers( + const gfx::Size& size, + std::vector<ui::LatencyInfo> latency_info, + gfx::SwapResult result, + std::unique_ptr<gfx::GpuFence> gpu_fence) { + DCHECK(!gpu_fence); + + PageFlipComplete(); + FinishSwapBuffers(result, size, latency_info); +} + +void SkiaOutputDeviceBufferQueue::Reshape(const gfx::Size& size, + float device_scale_factor, + const gfx::ColorSpace& color_space, + bool has_alpha, + gfx::OverlayTransform transform) { + gl::GLSurface::ColorSpace surface_color_space = + gl::ColorSpaceUtils::GetGLSurfaceColorSpace(color_space); + if (!gl_surface_->Resize(size, device_scale_factor, surface_color_space, + has_alpha)) { + LOG(FATAL) << "Failed to resize."; + // TODO(vasilyt): Handle the failure. + } + + color_space_ = color_space; + image_size_ = size; + FreeAllSurfaces(); +} + +SkSurface* SkiaOutputDeviceBufferQueue::BeginPaint() { + auto* image = GetCurrentImage(); + return image->BeginWriteSkia().get(); +} +void SkiaOutputDeviceBufferQueue::EndPaint( + const GrBackendSemaphore& semaphore) { + auto* image = GetCurrentImage(); + image->EndWriteSkia(); +} + +sk_sp<SkSurface> SkiaOutputDeviceBufferQueue::Image::BeginWriteSkia() { + std::vector<GrBackendSemaphore> begin_semaphores; + DCHECK(end_semaphores_.empty()); + DCHECK(!sk_surface_); + + SkSurfaceProps surface_props{0, kUnknown_SkPixelGeometry}; + + // TODO(vasilyt): Props and MSAA + sk_surface_ = skia_representation_->BeginWriteAccess( + 0, surface_props, &begin_semaphores, &end_semaphores_); + if (!begin_semaphores.empty()) { + sk_surface_->wait(begin_semaphores.size(), begin_semaphores.data()); + } + + return sk_surface_; +} + +void SkiaOutputDeviceBufferQueue::Image::EndWriteSkia() { + GrFlushInfo flush_info = { + .fFlags = kNone_GrFlushFlags, + .fNumSemaphores = end_semaphores_.size(), + .fSignalSemaphores = end_semaphores_.data(), + }; + sk_surface_->flush(SkSurface::BackendSurfaceAccess::kPresent, flush_info); + + skia_representation_->EndWriteAccess(std::move(sk_surface_)); + + end_semaphores_.clear(); +} + +gl::GLImage* SkiaOutputDeviceBufferQueue::Image::GetImage() const { + auto* texture = gl_representation_->GetTexture(); + return texture->GetLevelImage(texture->target(), 0); +} + +bool SkiaOutputDeviceBufferQueue::Image::Initialize( + const gfx::Size& size, + const gfx::ColorSpace& color_space, + ResourceFormat format, + SkiaOutputSurfaceDependency* deps, + uint32_t shared_image_usage) { + mailbox = gpu::Mailbox::GenerateForSharedImage(); + if (factory_->CreateSharedImage(mailbox, format, size, color_space, + shared_image_usage)) { + skia_representation_ = representation_factory_->ProduceSkia( + mailbox, deps->GetSharedContextState()); + gl_representation_ = representation_factory_->ProduceGLTexture(mailbox); + + return true; + } + + mailbox.SetZero(); + return false; +} + +SkiaOutputDeviceBufferQueue::Image::Image( + gpu::SharedImageFactory* factory, + gpu::SharedImageRepresentationFactory* representation_factory) + : factory_(factory), representation_factory_(representation_factory) {} + +SkiaOutputDeviceBufferQueue::Image::~Image() { + skia_representation_.reset(); + gl_representation_.reset(); + + if (!mailbox.IsZero()) + factory_->DestroySharedImage(mailbox); +} + +std::unique_ptr<gfx::GpuFence> +SkiaOutputDeviceBufferQueue::Image::CreateFence() { + if (!fence_) + fence_ = gl::GLFence::CreateForGpuFence(); + return fence_->GetGpuFence(); +} + +void SkiaOutputDeviceBufferQueue::Image::ResetFence() { + fence_.reset(); +} + +} // namespace viz
diff --git a/components/viz/service/display_embedder/skia_output_device_buffer_queue.h b/components/viz/service/display_embedder/skia_output_device_buffer_queue.h new file mode 100644 index 0000000..27dcea2 --- /dev/null +++ b/components/viz/service/display_embedder/skia_output_device_buffer_queue.h
@@ -0,0 +1,133 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_BUFFER_QUEUE_H_ +#define COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_BUFFER_QUEUE_H_ + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "components/viz/service/display_embedder/skia_output_device.h" +#include "components/viz/service/viz_service_export.h" +#include "gpu/command_buffer/service/shared_image_factory.h" + +namespace gpu { +class SharedImageRepresentationSkia; +} // namespace gpu + +namespace gl { +class GLFence; +class GLSurface; +} // namespace gl + +namespace viz { + +class SkiaOutputSurfaceDependency; + +class VIZ_SERVICE_EXPORT SkiaOutputDeviceBufferQueue final + : public SkiaOutputDevice { + public: + SkiaOutputDeviceBufferQueue( + scoped_refptr<gl::GLSurface> gl_surface, + SkiaOutputSurfaceDependency* deps, + const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback); + SkiaOutputDeviceBufferQueue( + scoped_refptr<gl::GLSurface> gl_surface, + SkiaOutputSurfaceDependency* deps, + const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback, + uint32_t shared_image_usage); + ~SkiaOutputDeviceBufferQueue() override; + + void SwapBuffers(BufferPresentedCallback feedback, + std::vector<ui::LatencyInfo> latency_info) override; + void PostSubBuffer(const gfx::Rect& rect, + BufferPresentedCallback feedback, + std::vector<ui::LatencyInfo> latency_info) override; + void Reshape(const gfx::Size& size, + float device_scale_factor, + const gfx::ColorSpace& color_space, + bool has_alpha, + gfx::OverlayTransform transform) override; + SkSurface* BeginPaint() override; + void EndPaint(const GrBackendSemaphore& semaphore) override; + bool supports_alpha() { return true; } + + gl::GLImage* GetOverlayImage() override; + // Creates and submits gpu fence + std::unique_ptr<gfx::GpuFence> SubmitOverlayGpuFence() override; + + private: + friend class SkiaOutputDeviceBufferQueueTest; + + class VIZ_SERVICE_EXPORT Image { + public: + Image(gpu::SharedImageFactory* factory, + gpu::SharedImageRepresentationFactory* representation_factory); + ~Image(); + + bool Initialize(const gfx::Size& size, + const gfx::ColorSpace& color_space, + ResourceFormat format, + SkiaOutputSurfaceDependency* deps, + uint32_t shared_image_usage); + + sk_sp<SkSurface> BeginWriteSkia(); + void EndWriteSkia(); + gl::GLImage* GetImage() const; + std::unique_ptr<gfx::GpuFence> CreateFence(); + void ResetFence(); + + private: + gpu::Mailbox mailbox; + std::unique_ptr<gpu::SharedImageRepresentationSkia> skia_representation_; + std::unique_ptr<gpu::SharedImageRepresentationGLTexture> gl_representation_; + std::vector<GrBackendSemaphore> end_semaphores_; + sk_sp<SkSurface> sk_surface_; + std::unique_ptr<gl::GLFence> fence_; + + gpu::SharedImageFactory* factory_; + gpu::SharedImageRepresentationFactory* representation_factory_; + }; + + Image* GetCurrentImage(); + std::unique_ptr<Image> GetNextImage(); + void PageFlipComplete(); + void FreeAllSurfaces(); + // Used as callback for SwapBuffersAsync and PostSubBufferAsync to finish + // operation + void DoFinishSwapBuffers(const gfx::Size& size, + std::vector<ui::LatencyInfo> latency_info, + gfx::SwapResult result, + std::unique_ptr<gfx::GpuFence>); + + SkiaOutputSurfaceDependency* const dependency_; + scoped_refptr<gl::GLSurface> gl_surface_; + // Format of images + gfx::ColorSpace color_space_; + gfx::Size image_size_; + + // This image is currently used by Skia as RenderTarget. This may be nullptr + // if no drawing in progress or if allocation failed at bind. + std::unique_ptr<Image> current_image_; + // The image currently on the screen, if any. + std::unique_ptr<Image> displayed_image_; + // These are free for use, and are not nullptr. + std::vector<std::unique_ptr<Image>> available_images_; + // These have been scheduled to display but are not displayed yet. + // Entries of this deque may be nullptr, if they represent frames that have + // been destroyed. + base::circular_deque<std::unique_ptr<Image>> in_flight_images_; + + // Shared Image factories + gpu::SharedImageFactory shared_image_factory_; + std::unique_ptr<gpu::SharedImageRepresentationFactory> + shared_image_representation_factory_; + uint32_t shared_image_usage_; + + base::WeakPtrFactory<SkiaOutputDeviceBufferQueue> weak_ptr_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(SkiaOutputDeviceBufferQueue); +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_BUFFER_QUEUE_H_
diff --git a/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc b/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc new file mode 100644 index 0000000..1a516d66 --- /dev/null +++ b/components/viz/service/display_embedder/skia_output_device_buffer_queue_unittest.cc
@@ -0,0 +1,425 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/service/display_embedder/skia_output_device_buffer_queue.h" + +#include <stddef.h> +#include <stdint.h> + +#include <set> +#include <utility> + +#include "base/bind_helpers.h" +#include "base/memory/ptr_util.h" +#include "base/test/bind_test_util.h" +#include "build/build_config.h" +#include "gpu/command_buffer/service/scheduler.h" + +#include "components/viz/service/display_embedder/skia_output_surface_dependency_impl.h" +#include "components/viz/service/gl/gpu_service_impl.h" +#include "components/viz/test/test_gpu_service_holder.h" +#include "gpu/command_buffer/common/shared_image_usage.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/display/types/display_snapshot.h" +#include "ui/gl/gl_surface_stub.h" + +using ::testing::_; +using ::testing::Expectation; +using ::testing::Ne; +using ::testing::Return; + +namespace { + +// These MACRO and TestOnGpu class make it easier to write tests that runs on +// GPU Thread +// Use TEST_F_GPU instead of TEST_F in the same manner and in your subclass +// of TestOnGpu implement SetUpOnMain/SetUpOnGpu and +// TearDownOnMain/TearDownOnGpu instead of SetUp and TearDown respectively. +// +// NOTE: Most likely you need to implement TearDownOnGpu instead of relying on +// destructor to ensure that necessary cleanup happens on GPU Thread. + +// TODO(vasilyt): Extract this for others to use? + +#define GTEST_TEST_GPU_(test_suite_name, test_name, parent_class, parent_id) \ + class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ + : public parent_class { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ + \ + private: \ + virtual void TestBodyOnGpu(); \ + static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ + test_name)); \ + }; \ + \ + ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ + test_name)::test_info_ = \ + ::testing::internal::MakeAndRegisterTestInfo( \ + #test_suite_name, #test_name, nullptr, nullptr, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \ + ::testing::internal::SuiteApiResolver< \ + parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \ + ::testing::internal::SuiteApiResolver< \ + parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \ + new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \ + test_suite_name, test_name)>); \ + void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBodyOnGpu() + +#define TEST_F_GPU(test_fixture, test_name) \ + GTEST_TEST_GPU_(test_fixture, test_name, test_fixture, \ + ::testing::internal::GetTypeId<test_fixture>()) + +class TestOnGpu : public ::testing::Test { + protected: + TestOnGpu() + : wait_(base::WaitableEvent::ResetPolicy::AUTOMATIC, + base::WaitableEvent::InitialState::NOT_SIGNALED) {} + + void TestBody() override { + auto callback = + base::BindLambdaForTesting([&]() { this->TestBodyOnGpu(); }); + ScheduleGpuTask(std::move(callback)); + } + + void SetUp() override { + gpu_service_holder_ = viz::TestGpuServiceHolder::GetInstance(); + SetUpOnMain(); + + auto setup = base::BindLambdaForTesting([&]() { this->SetUpOnGpu(); }); + ScheduleGpuTask(setup); + } + + void TearDown() override { + auto teardown = + base::BindLambdaForTesting([&]() { this->TearDownOnGpu(); }); + ScheduleGpuTask(teardown); + + TearDownOnMain(); + } + + void CallOnGpuAndUnblockMain(base::OnceClosure callback) { + DCHECK(!wait_.IsSignaled()); + std::move(callback).Run(); + wait_.Signal(); + } + + void ScheduleGpuTask(base::OnceClosure callback) { + auto wrap = base::BindOnce(&TestOnGpu::CallOnGpuAndUnblockMain, + base::Unretained(this), std::move(callback)); + + auto* gpu_service_impl = gpu_service_holder_->gpu_service(); + gpu_service_impl->scheduler()->ScheduleTask(gpu::Scheduler::Task( + gpu_service_impl->skia_output_surface_sequence_id(), std::move(wrap), + std::vector<gpu::SyncToken>())); + + wait_.Wait(); + } + + virtual void SetUpOnMain() {} + virtual void SetUpOnGpu() {} + virtual void TearDownOnMain() {} + virtual void TearDownOnGpu() {} + virtual void TestBodyOnGpu() {} + + viz::TestGpuServiceHolder* gpu_service_holder_; + base::WaitableEvent wait_; +}; + +// Here starts SkiaOutputDeviceBufferQueue test related code + +class MockGLSurfaceAsync : public gl::GLSurfaceStub { + public: + bool SupportsAsyncSwap() override { return true; } + + void SwapBuffersAsync(SwapCompletionCallback completion_callback, + PresentationCallback presentation_callback) override { + DCHECK(!callback_); + callback_ = std::move(completion_callback); + } + + void SwapComplete() { + std::move(callback_).Run(gfx::SwapResult::SWAP_ACK, nullptr); + } + + protected: + ~MockGLSurfaceAsync() override {} + SwapCompletionCallback callback_; +}; + +} // namespace + +namespace viz { + +class SkiaOutputDeviceBufferQueueTest : public TestOnGpu { + public: + SkiaOutputDeviceBufferQueueTest() {} + + void SetUpOnMain() override { + gpu::SurfaceHandle surface_handle_ = gpu::kNullSurfaceHandle; + dependency_ = std::make_unique<SkiaOutputSurfaceDependencyImpl>( + gpu_service_holder_->gpu_service(), surface_handle_); + } + + void SetUpOnGpu() override { + gl_surface_ = base::MakeRefCounted<MockGLSurfaceAsync>(); + + auto present_callback = + base::DoNothing::Repeatedly<gpu::SwapBuffersCompleteParams, + const gfx::Size&>(); + + uint32_t shared_image_usage = + gpu::SHARED_IMAGE_USAGE_DISPLAY | + gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT; + + std::unique_ptr<SkiaOutputDeviceBufferQueue> onscreen_device = + std::make_unique<SkiaOutputDeviceBufferQueue>( + gl_surface_, dependency_.get(), present_callback, + shared_image_usage); + + output_device_ = std::move(onscreen_device); + } + + void TearDownOnGpu() override { output_device_.reset(); } + + using Image = SkiaOutputDeviceBufferQueue::Image; + + Image* current_image() { return output_device_->current_image_.get(); } + + const std::vector<std::unique_ptr<Image>>& available_images() { + return output_device_->available_images_; + } + + Image* displayed_image() { return output_device_->displayed_image_.get(); } + + base::circular_deque<std::unique_ptr<Image>>& in_flight_images() { + return output_device_->in_flight_images_; + } + + int CountBuffers() { + int n = available_images().size() + in_flight_images().size(); + + if (displayed_image()) + n++; + if (current_image()) + n++; + return n; + } + + void CheckUnique() { + std::set<Image*> images; + for (const auto& image : available_images()) + images.insert(image.get()); + for (const auto& image : in_flight_images()) + images.insert(image.get()); + + if (displayed_image()) + images.insert(displayed_image()); + + if (current_image()) + images.insert(current_image()); + + EXPECT_EQ(images.size(), (size_t)CountBuffers()); + } + + Image* GetCurrentImage() { return output_device_->GetCurrentImage(); } + + void SwapBuffers() { + auto present_callback = + base::DoNothing::Once<const gfx::PresentationFeedback&>(); + + output_device_->SwapBuffers(std::move(present_callback), + std::vector<ui::LatencyInfo>()); + } + + void PageFlipComplete() { gl_surface_->SwapComplete(); } + + protected: + std::unique_ptr<SkiaOutputSurfaceDependency> dependency_; + scoped_refptr<MockGLSurfaceAsync> gl_surface_; + std::unique_ptr<SkiaOutputDeviceBufferQueue> output_device_; +}; + +namespace { + +const gfx::Size screen_size = gfx::Size(30, 30); + +TEST_F_GPU(SkiaOutputDeviceBufferQueueTest, MultipleGetCurrentBufferCalls) { + // Check that multiple bind calls do not create or change surfaces. + + output_device_->Reshape(screen_size, 1.0f, gfx::ColorSpace(), false, + gfx::OVERLAY_TRANSFORM_NONE); + EXPECT_NE(GetCurrentImage(), nullptr); + EXPECT_EQ(1, CountBuffers()); + auto* fb = current_image(); + EXPECT_NE(GetCurrentImage(), nullptr); + EXPECT_EQ(1, CountBuffers()); + EXPECT_EQ(fb, current_image()); +} + +TEST_F_GPU(SkiaOutputDeviceBufferQueueTest, CheckDoubleBuffering) { + // Check buffer flow through double buffering path. + output_device_->Reshape(screen_size, 1.0f, gfx::ColorSpace(), false, + gfx::OVERLAY_TRANSFORM_NONE); + EXPECT_EQ(0, CountBuffers()); + + EXPECT_NE(GetCurrentImage(), nullptr); + EXPECT_EQ(1, CountBuffers()); + EXPECT_NE(current_image(), nullptr); + EXPECT_FALSE(displayed_image()); + SwapBuffers(); + EXPECT_EQ(1U, in_flight_images().size()); + PageFlipComplete(); + EXPECT_EQ(0U, in_flight_images().size()); + EXPECT_TRUE(displayed_image()); + EXPECT_NE(GetCurrentImage(), nullptr); + EXPECT_EQ(2, CountBuffers()); + CheckUnique(); + EXPECT_NE(current_image(), nullptr); + EXPECT_EQ(0U, in_flight_images().size()); + EXPECT_TRUE(displayed_image()); + SwapBuffers(); + CheckUnique(); + EXPECT_EQ(1U, in_flight_images().size()); + EXPECT_TRUE(displayed_image()); + PageFlipComplete(); + CheckUnique(); + EXPECT_EQ(0U, in_flight_images().size()); + EXPECT_EQ(1U, available_images().size()); + EXPECT_TRUE(displayed_image()); + EXPECT_NE(GetCurrentImage(), nullptr); + EXPECT_EQ(2, CountBuffers()); + CheckUnique(); + EXPECT_TRUE(available_images().empty()); +} + +TEST_F_GPU(SkiaOutputDeviceBufferQueueTest, CheckTripleBuffering) { + // Check buffer flow through triple buffering path. + output_device_->Reshape(screen_size, 1.0f, gfx::ColorSpace(), false, + gfx::OVERLAY_TRANSFORM_NONE); + + // This bit is the same sequence tested in the doublebuffering case. + EXPECT_NE(GetCurrentImage(), nullptr); + EXPECT_FALSE(displayed_image()); + SwapBuffers(); + PageFlipComplete(); + EXPECT_NE(GetCurrentImage(), nullptr); + SwapBuffers(); + + EXPECT_EQ(2, CountBuffers()); + CheckUnique(); + EXPECT_EQ(1U, in_flight_images().size()); + EXPECT_TRUE(displayed_image()); + EXPECT_NE(GetCurrentImage(), nullptr); + EXPECT_EQ(3, CountBuffers()); + CheckUnique(); + EXPECT_NE(current_image(), nullptr); + EXPECT_EQ(1U, in_flight_images().size()); + EXPECT_TRUE(displayed_image()); + PageFlipComplete(); + EXPECT_EQ(3, CountBuffers()); + CheckUnique(); + EXPECT_NE(current_image(), nullptr); + EXPECT_EQ(0U, in_flight_images().size()); + EXPECT_TRUE(displayed_image()); + EXPECT_EQ(1U, available_images().size()); +} + +TEST_F_GPU(SkiaOutputDeviceBufferQueueTest, CheckEmptySwap) { + // Check empty swap flow, in which the damage is empty and BindFramebuffer + // might not be called. + output_device_->Reshape(screen_size, 1.0f, gfx::ColorSpace(), false, + gfx::OVERLAY_TRANSFORM_NONE); + + EXPECT_EQ(0, CountBuffers()); + auto* image = GetCurrentImage(); + EXPECT_NE(image, nullptr); + EXPECT_EQ(1, CountBuffers()); + EXPECT_NE(current_image(), nullptr); + EXPECT_FALSE(displayed_image()); + + SwapBuffers(); + // Make sure we won't be drawing to the texture we just sent for scanout. + auto* new_image = GetCurrentImage(); + EXPECT_NE(new_image, nullptr); + EXPECT_NE(image, new_image); + + EXPECT_EQ(1U, in_flight_images().size()); + PageFlipComplete(); + + // Test swapbuffers without calling BeginPaint/EndPaint (i.e without + // GetCurrentImage) + SwapBuffers(); + EXPECT_EQ(1U, in_flight_images().size()); + PageFlipComplete(); + EXPECT_EQ(0U, in_flight_images().size()); + + EXPECT_EQ(current_image(), nullptr); + SwapBuffers(); + EXPECT_EQ(1U, in_flight_images().size()); + PageFlipComplete(); + EXPECT_EQ(0U, in_flight_images().size()); +} + +TEST_F_GPU(SkiaOutputDeviceBufferQueueTest, CheckCorrectBufferOrdering) { + output_device_->Reshape(screen_size, 1.0f, gfx::ColorSpace(), false, + gfx::OVERLAY_TRANSFORM_NONE); + const size_t kSwapCount = 5; + + for (size_t i = 0; i < kSwapCount; ++i) { + EXPECT_NE(GetCurrentImage(), nullptr); + SwapBuffers(); + EXPECT_NE(GetCurrentImage(), nullptr); + PageFlipComplete(); + } + + // Note: this must be three, not kSwapCount + EXPECT_EQ(3, CountBuffers()); + + for (size_t i = 0; i < kSwapCount; ++i) { + EXPECT_NE(GetCurrentImage(), nullptr); + SwapBuffers(); + EXPECT_EQ(1U, in_flight_images().size()); + auto* next_image = in_flight_images().front().get(); + PageFlipComplete(); + EXPECT_EQ(displayed_image(), next_image); + } +} + +TEST_F_GPU(SkiaOutputDeviceBufferQueueTest, ReshapeWithInFlightSurfaces) { + output_device_->Reshape(screen_size, 1.0f, gfx::ColorSpace(), false, + gfx::OVERLAY_TRANSFORM_NONE); + + const size_t kSwapCount = 5; + + for (size_t i = 0; i < kSwapCount; ++i) { + EXPECT_NE(GetCurrentImage(), nullptr); + SwapBuffers(); + EXPECT_NE(GetCurrentImage(), nullptr); + PageFlipComplete(); + } + + SwapBuffers(); + + output_device_->Reshape(screen_size, 1.0f, gfx::ColorSpace(), false, + gfx::OVERLAY_TRANSFORM_NONE); + EXPECT_EQ(1u, in_flight_images().size()); + + PageFlipComplete(); + EXPECT_FALSE(displayed_image()); + + // The dummy surfacess left should be discarded. + EXPECT_EQ(0u, available_images().size()); + + // Test swap after reshape + EXPECT_NE(GetCurrentImage(), nullptr); + SwapBuffers(); + PageFlipComplete(); + EXPECT_NE(displayed_image(), nullptr); +} + +} // namespace +} // namespace viz
diff --git a/components/viz/service/display_embedder/skia_output_device_gl.cc b/components/viz/service/display_embedder/skia_output_device_gl.cc index 86013a8..55098e81 100644 --- a/components/viz/service/display_embedder/skia_output_device_gl.cc +++ b/components/viz/service/display_embedder/skia_output_device_gl.cc
@@ -7,7 +7,6 @@ #include <utility> #include "base/bind_helpers.h" -#include "components/viz/service/display_embedder/skia_output_surface_dependency.h" #include "gpu/command_buffer/common/swap_buffers_complete_params.h" #include "gpu/command_buffer/service/feature_info.h" #include "gpu/command_buffer/service/gl_utils.h" @@ -24,15 +23,13 @@ namespace viz { SkiaOutputDeviceGL::SkiaOutputDeviceGL( - SkiaOutputSurfaceDependency* deps, + scoped_refptr<gl::GLSurface> gl_surface, scoped_refptr<gpu::gles2::FeatureInfo> feature_info, const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback) : SkiaOutputDevice(false /*need_swap_semaphore */, did_swap_buffer_complete_callback), - dependency_(deps), - feature_info_(feature_info) { - gl_surface_ = dependency_->CreateGLSurface(weak_ptr_factory_.GetWeakPtr()); -} + feature_info_(feature_info), + gl_surface_(gl_surface) {} void SkiaOutputDeviceGL::Initialize(GrContext* gr_context, gl::GLContext* gl_context) { @@ -179,8 +176,7 @@ void SkiaOutputDeviceGL::DidCreateAcceleratedSurfaceChildWindow( gpu::SurfaceHandle parent_window, gpu::SurfaceHandle child_window) { - dependency_->DidCreateAcceleratedSurfaceChildWindow(parent_window, - child_window); + NOTREACHED(); } #endif
diff --git a/components/viz/service/display_embedder/skia_output_device_gl.h b/components/viz/service/display_embedder/skia_output_device_gl.h index 701f25d..0f11856 100644 --- a/components/viz/service/display_embedder/skia_output_device_gl.h +++ b/components/viz/service/display_embedder/skia_output_device_gl.h
@@ -34,13 +34,11 @@ namespace viz { -class SkiaOutputSurfaceDependency; - class SkiaOutputDeviceGL final : public SkiaOutputDevice, public gpu::ImageTransportSurfaceDelegate { public: SkiaOutputDeviceGL( - SkiaOutputSurfaceDependency* deps, + scoped_refptr<gl::GLSurface> gl_surface, scoped_refptr<gpu::gles2::FeatureInfo> feature_info, const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback); ~SkiaOutputDeviceGL() override; @@ -82,7 +80,6 @@ GpuVSyncCallback GetGpuVSyncCallback() override; private: - SkiaOutputSurfaceDependency* const dependency_; scoped_refptr<gpu::gles2::FeatureInfo> feature_info_; gpu::GpuPreferences gpu_preferences_;
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.cc b/components/viz/service/display_embedder/skia_output_surface_impl.cc index 2bcb8003..7bb6eb2 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl.cc
@@ -357,6 +357,16 @@ ScheduleGpuTask(std::move(callback), std::vector<gpu::SyncToken>()); } +void SkiaOutputSurfaceImpl::ScheduleOverlays(OverlayCandidateList overlays) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + // impl_on_gpu_ is released on the GPU thread by a posted task from + // SkiaOutputSurfaceImpl::dtor. So it is safe to use base::Unretained. + auto callback = + base::BindOnce(&SkiaOutputSurfaceImplOnGpu::ScheduleOverlays, + base::Unretained(impl_on_gpu_.get()), std::move(overlays)); + ScheduleGpuTask(std::move(callback), std::vector<gpu::SyncToken>()); +} + SkCanvas* SkiaOutputSurfaceImpl::BeginPaintRenderPass( const RenderPassId& id, const gfx::Size& surface_size, @@ -558,6 +568,7 @@ *result = false; } else { capabilities_ = impl_on_gpu_->capabilities(); + is_displayed_as_overlay_ = impl_on_gpu_->IsDisplayedAsOverlay(); *result = true; } } @@ -681,7 +692,7 @@ } bool SkiaOutputSurfaceImpl::IsDisplayedAsOverlayPlane() const { - return false; + return is_displayed_as_overlay_; } unsigned SkiaOutputSurfaceImpl::GetOverlayTextureId() const {
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.h b/components/viz/service/display_embedder/skia_output_surface_impl.h index 39de6a6..5ee4875 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl.h
@@ -90,6 +90,8 @@ sk_sp<SkColorSpace> dst_color_space, bool has_alpha) override; void SkiaSwapBuffers(OutputSurfaceFrame frame) override; + void ScheduleOverlays(OverlayCandidateList overlays) override; + SkCanvas* BeginPaintRenderPass(const RenderPassId& id, const gfx::Size& surface_size, ResourceFormat format, @@ -160,6 +162,7 @@ std::unique_ptr<SkiaOutputSurfaceDependency> dependency_; const bool is_using_vulkan_; UpdateVSyncParametersCallback update_vsync_parameters_callback_; + bool is_displayed_as_overlay_ = false; std::unique_ptr<base::WaitableEvent> initialize_waitable_event_; SkSurfaceCharacterization characterization_;
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc index 9aae36d..197edda8 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc
@@ -6,6 +6,7 @@ #include "base/atomic_sequence_num.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/optional.h" @@ -22,6 +23,7 @@ #include "components/viz/service/display_embedder/direct_context_provider.h" #include "components/viz/service/display_embedder/image_context.h" #include "components/viz/service/display_embedder/skia_output_device.h" +#include "components/viz/service/display_embedder/skia_output_device_buffer_queue.h" #include "components/viz/service/display_embedder/skia_output_device_gl.h" #include "components/viz/service/display_embedder/skia_output_device_offscreen.h" #include "components/viz/service/display_embedder/skia_output_surface_dependency.h" @@ -40,12 +42,12 @@ #include "gpu/config/gpu_preferences.h" #include "gpu/ipc/common/gpu_client_ids.h" #include "gpu/ipc/common/gpu_surface_lookup.h" -#include "gpu/ipc/service/image_transport_surface.h" #include "gpu/vulkan/buildflags.h" #include "skia/ext/image_operations.h" #include "third_party/skia/include/core/SkPixelRef.h" #include "third_party/skia/include/private/SkDeferredDisplayList.h" #include "ui/gfx/color_space.h" +#include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_context.h" @@ -592,9 +594,13 @@ // This ensures any outstanding callbacks for promise images are performed. gr_context()->flush(); } - copier_ = nullptr; - texture_deleter_ = nullptr; - context_provider_ = nullptr; + + if (copier_) { + copier_ = nullptr; + texture_deleter_ = nullptr; + context_provider_ = nullptr; + MakeCurrent(false /* need_fbo0 */); + } sync_point_client_state_->Destroy(); } @@ -645,15 +651,15 @@ DCHECK(ddl); DCHECK(!scoped_output_device_paint_); + if (!MakeCurrent(true /* need_fbo0 */)) + return; + // We do not reset scoped_output_device_paint_ after drawing the ddl until // SwapBuffers() is called, because we may need access to output_sk_surface() // for CopyOutput(). scoped_output_device_paint_.emplace(output_device_.get()); DCHECK(output_sk_surface()); - if (!MakeCurrent(true /* need_fbo0 */)) - return; - dependency_->ScheduleGrContextCleanup(); PullTextureUpdates(std::move(sync_tokens)); @@ -727,6 +733,36 @@ ReleaseFenceSyncAndPushTextureUpdates(sync_fence_release); } +void SkiaOutputSurfaceImplOnGpu::ScheduleOverlays( + const OverlayCandidateList& overlays) { + if (overlays.empty()) + return; + + DCHECK(!is_using_vulkan()); + + if (!MakeCurrent(!dependency_->IsOffscreen() /* need_fbo0 */)) + return; + + for (const auto& overlay_candidate : overlays) { + gl::GLImage* image = nullptr; + std::unique_ptr<gfx::GpuFence> gpu_fence; + if (overlay_candidate.use_output_surface_for_resource) { + image = output_device_->GetOverlayImage(); + gpu_fence = output_device_->SubmitOverlayGpuFence(); + } else { + NOTIMPLEMENTED_LOG_ONCE(); + } + + if (image) { + gl_surface_->ScheduleOverlayPlane( + overlay_candidate.plane_z_order, overlay_candidate.transform, image, + ToNearestRect(overlay_candidate.display_rect), + overlay_candidate.uv_rect, !overlay_candidate.is_opaque, + std::move(gpu_fence)); + } + } +} + void SkiaOutputSurfaceImplOnGpu::SwapBuffers(OutputSurfaceFrame frame) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(scoped_output_device_paint_); @@ -1256,20 +1292,6 @@ } bool SkiaOutputSurfaceImplOnGpu::InitializeForGL() { - std::unique_ptr<SkiaOutputDeviceGL> onscreen_device; - if (!dependency_->IsOffscreen()) { - onscreen_device = std::make_unique<SkiaOutputDeviceGL>( - dependency_, feature_info_, did_swap_buffer_complete_callback_); - gl_surface_ = onscreen_device->gl_surface(); - } else { - gl_surface_ = dependency_->CreateGLSurface(nullptr); - } - - if (!gl_surface_) - return false; - - DCHECK_EQ(gl_surface_->IsOffscreen(), dependency_->IsOffscreen()); - context_state_ = dependency_->GetSharedContextState(); if (!context_state_) { DLOG(ERROR) << "Failed to create GrContext"; @@ -1281,23 +1303,47 @@ api_ = current_gl->Api; gl_version_info_ = context->GetVersionInfo(); - if (onscreen_device) { - if (!MakeCurrent(true /* need_fbo0 */)) { - gl_surface_ = nullptr; - context_state_ = nullptr; - DLOG(ERROR) << "Failed to make current during initialization."; + if (dependency_->IsOffscreen()) { + gl_surface_ = dependency_->CreateGLSurface(nullptr); + if (!gl_surface_) return false; - } - onscreen_device->Initialize(gr_context(), context); - supports_alpha_ = onscreen_device->supports_alpha(); - output_device_ = std::move(onscreen_device); - } else { + output_device_ = std::make_unique<SkiaOutputDeviceOffscreen>( gr_context(), true /* flipped */, renderer_settings_.requires_alpha_channel, did_swap_buffer_complete_callback_); supports_alpha_ = renderer_settings_.requires_alpha_channel; + } else { + gl_surface_ = dependency_->CreateGLSurface(weak_ptr_factory_.GetWeakPtr()); + + if (!gl_surface_) + return false; + + if (MakeCurrent(true /* need_fbo0 */)) { + if (gl_surface_->IsSurfaceless()) { + std::unique_ptr<SkiaOutputDeviceBufferQueue> onscreen_device = + std::make_unique<SkiaOutputDeviceBufferQueue>( + gl_surface_, dependency_, did_swap_buffer_complete_callback_); + supports_alpha_ = onscreen_device->supports_alpha(); + output_device_ = std::move(onscreen_device); + + } else { + std::unique_ptr<SkiaOutputDeviceGL> onscreen_device = + std::make_unique<SkiaOutputDeviceGL>( + gl_surface_, feature_info_, did_swap_buffer_complete_callback_); + + onscreen_device->Initialize(gr_context(), context); + supports_alpha_ = onscreen_device->supports_alpha(); + output_device_ = std::move(onscreen_device); + } + } else { + gl_surface_ = nullptr; + context_state_ = nullptr; + LOG(FATAL) << "Failed to make current during initialization."; + return false; + } } + DCHECK_EQ(gl_surface_->IsOffscreen(), dependency_->IsOffscreen()); return true; } @@ -1419,4 +1465,41 @@ sync_point_client_state_->ReleaseFenceSync(sync_fence_release); } +bool SkiaOutputSurfaceImplOnGpu::IsDisplayedAsOverlay() { + return gl_surface_ ? gl_surface_->IsSurfaceless() : false; +} + +#if defined(OS_WIN) +void SkiaOutputSurfaceImplOnGpu::DidCreateAcceleratedSurfaceChildWindow( + gpu::SurfaceHandle parent_window, + gpu::SurfaceHandle child_window) { + dependency_->DidCreateAcceleratedSurfaceChildWindow(parent_window, + child_window); +} +#endif + +const gpu::gles2::FeatureInfo* SkiaOutputSurfaceImplOnGpu::GetFeatureInfo() + const { + return feature_info_.get(); +} + +const gpu::GpuPreferences& SkiaOutputSurfaceImplOnGpu::GetGpuPreferences() + const { + return gpu_preferences_; +} + +GpuVSyncCallback SkiaOutputSurfaceImplOnGpu::GetGpuVSyncCallback() { + return base::DoNothing::Repeatedly<base::TimeTicks, base::TimeDelta>(); +} + +void SkiaOutputSurfaceImplOnGpu::DidSwapBuffersComplete( + gpu::SwapBuffersCompleteParams params) { + NOTIMPLEMENTED_LOG_ONCE(); +} + +void SkiaOutputSurfaceImplOnGpu::BufferPresented( + const gfx::PresentationFeedback& feedback) { + NOTIMPLEMENTED_LOG_ONCE(); +} + } // namespace viz
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h index 06e7c5e..e288d86f 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h
@@ -69,7 +69,7 @@ // The SkiaOutputSurface implementation running on the GPU thread. This class // should be created, used and destroyed on the GPU thread. -class SkiaOutputSurfaceImplOnGpu { +class SkiaOutputSurfaceImplOnGpu : public gpu::ImageTransportSurfaceDelegate { public: using DidSwapBufferCompleteCallback = base::RepeatingCallback<void(gpu::SwapBuffersCompleteParams, @@ -92,7 +92,7 @@ const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback, const BufferPresentedCallback& buffer_presented_callback, const ContextLostCallback& context_lost_callback); - ~SkiaOutputSurfaceImplOnGpu(); + ~SkiaOutputSurfaceImplOnGpu() override; gpu::CommandBufferId command_buffer_id() const { return sync_point_client_state_->command_buffer_id(); @@ -119,6 +119,7 @@ std::vector<gpu::SyncToken> sync_tokens, uint64_t sync_fence_release, base::OnceClosure on_finished); + void ScheduleOverlays(const OverlayCandidateList& overlays); void SwapBuffers(OutputSurfaceFrame frame); void EnsureBackbuffer() { output_device_->EnsureBackbuffer(); } void DiscardBackbuffer() { output_device_->DiscardBackbuffer(); } @@ -154,6 +155,20 @@ void SetCapabilitiesForTesting( const OutputSurface::Capabilities& capabilities); + bool IsDisplayedAsOverlay(); + + // gpu::ImageTransportSurfaceDelegate implementation: +#if defined(OS_WIN) + void DidCreateAcceleratedSurfaceChildWindow( + gpu::SurfaceHandle parent_window, + gpu::SurfaceHandle child_window) override; +#endif + const gpu::gles2::FeatureInfo* GetFeatureInfo() const override; + const gpu::GpuPreferences& GetGpuPreferences() const override; + void DidSwapBuffersComplete(gpu::SwapBuffersCompleteParams params) override; + void BufferPresented(const gfx::PresentationFeedback& feedback) override; + GpuVSyncCallback GetGpuVSyncCallback() override; + private: class ScopedPromiseImageAccess;
diff --git a/components/viz/test/fake_skia_output_surface.cc b/components/viz/test/fake_skia_output_surface.cc index 873f4997..d94dc85a 100644 --- a/components/viz/test/fake_skia_output_surface.cc +++ b/components/viz/test/fake_skia_output_surface.cc
@@ -83,6 +83,11 @@ NOTIMPLEMENTED(); } +void FakeSkiaOutputSurface::ScheduleOverlays(OverlayCandidateList overlays) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + NOTIMPLEMENTED(); +} + uint32_t FakeSkiaOutputSurface::GetFramebufferCopyTextureFormat() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return GL_RGB;
diff --git a/components/viz/test/fake_skia_output_surface.h b/components/viz/test/fake_skia_output_surface.h index e334b8d..12fee6f 100644 --- a/components/viz/test/fake_skia_output_surface.h +++ b/components/viz/test/fake_skia_output_surface.h
@@ -49,6 +49,7 @@ bool has_alpha, bool use_stencil) override; void SwapBuffers(OutputSurfaceFrame frame) override; + void ScheduleOverlays(OverlayCandidateList overlays) override; uint32_t GetFramebufferCopyTextureFormat() override; bool IsDisplayedAsOverlayPlane() const override; unsigned GetOverlayTextureId() const override;
diff --git a/content/browser/back_forward_cache_browsertest.cc b/content/browser/back_forward_cache_browsertest.cc index 73ff0690..ed80522 100644 --- a/content/browser/back_forward_cache_browsertest.cc +++ b/content/browser/back_forward_cache_browsertest.cc
@@ -72,8 +72,8 @@ // Navigate from A to B and go back. IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, Basic) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -105,8 +105,8 @@ // Navigate from A to B and go back. IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, BasicDocumentInitiated) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -140,8 +140,8 @@ IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, NavigateBackForwardRepeatedly) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -202,8 +202,8 @@ return; ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A and open a popup. EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -258,9 +258,9 @@ // Navigate from A(B) to C and go back. IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, BasicIframe) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL( + const GURL url_a(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); - GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html")); + const GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html")); // 1) Navigate to A(B). EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -294,8 +294,8 @@ // Ensure flushing the BackForwardCache works properly. IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, BackForwardCacheFlush) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -328,8 +328,8 @@ // document from the BackForwardCache. IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, VisibleURL) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Go to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -349,8 +349,8 @@ // Test documents are evicted from the BackForwardCache at some point. IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, CacheEviction) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), url_a)); // BackForwardCache size is 0. RenderFrameHostImpl* rfh_a = current_frame_host(); @@ -377,9 +377,9 @@ // Test case: a1(b2) -> c3 -> a1(b2) IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, SubframeSurviveCache1) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL( + const GURL url_a(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); - GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html")); + const GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html")); std::vector<RenderFrameDeletedObserver*> rfh_observer; @@ -416,9 +416,9 @@ // Test case: a1(b2) -> b3 -> a1(b2). IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, SubframeSurviveCache2) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL( + const GURL url_a(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); std::vector<RenderFrameDeletedObserver*> rfh_observer; @@ -456,9 +456,9 @@ // Test case: a1(b2) -> b3(a4) -> a1(b2) -> b3(a4) IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, SubframeSurviveCache3) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL( + const GURL url_a(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); - GURL url_b(embedded_test_server()->GetURL( + const GURL url_b(embedded_test_server()->GetURL( "b.com", "/cross_site_iframe_factory.html?b(a)")); std::vector<RenderFrameDeletedObserver*> rfh_observer; @@ -511,10 +511,10 @@ // Test case: a1(b2) -> b3 -> a4 -> b5 -> a1(b2). IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, SubframeSurviveCache4) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_ab(embedded_test_server()->GetURL( + const GURL url_ab(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); std::vector<RenderFrameDeletedObserver*> rfh_observer; @@ -567,19 +567,33 @@ IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, DisallowedFeatureOnPage) { ASSERT_TRUE(embedded_test_server()->Start()); - // Navigate to a page that has an unsupported feature for bfcache. - NavigateToURL( - shell(), - embedded_test_server()->GetURL( - "a.com", "/back_forward_cache/page_with_dedicated_worker.html")); - RenderFrameDeletedObserver delete_rfh_a(current_frame_host()); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL( + "b.com", "/back_forward_cache/page_with_dedicated_worker.html")); - // Navigate away. - NavigateToURL(shell(), - embedded_test_server()->GetURL("b.com", "/title1.html")); + // Navigate to page A which is cacheable. + NavigateToURL(shell(), url_a); + EXPECT_EQ(url_a, web_contents()->GetVisibleURL()); + RenderFrameHostImpl* rfh_a = current_frame_host(); + RenderFrameDeletedObserver delete_rfh_a(rfh_a); - // The page with the unsupported feature should be deleted (not cached). - delete_rfh_a.WaitUntilDeleted(); + // Navigate to page B which has an unsupported feature for bfcache. + NavigateToURL(shell(), url_b); + EXPECT_EQ(url_b, web_contents()->GetVisibleURL()); + RenderFrameHostImpl* rfh_b = current_frame_host(); + RenderFrameDeletedObserver delete_rfh_b(rfh_b); + + // Page A should now be cached. + EXPECT_FALSE(delete_rfh_a.deleted()); + EXPECT_TRUE(rfh_a->is_in_back_forward_cache()); + + // Navigate back to page A. + web_contents()->GetController().GoBack(); + EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); + EXPECT_EQ(url_a, web_contents()->GetVisibleURL()); + + // Page B with the unsupported feature should have been deleted (not cached). + delete_rfh_b.WaitUntilDeleted(); } // Check that unload event handlers are not dispatched when the page goes @@ -587,8 +601,8 @@ IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, ConfirmUnloadEventNotFired) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); - GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a));
diff --git a/content/browser/compositor/DEPS b/content/browser/compositor/DEPS index f8b67982..e032424 100644 --- a/content/browser/compositor/DEPS +++ b/content/browser/compositor/DEPS
@@ -16,8 +16,5 @@ ], "reflector_impl_unittest\.cc": [ "+ui/ozone/public", - ], - "viz_process_transport_factory\.cc": [ - "+ui/ozone/public", ] }
diff --git a/content/browser/compositor/viz_process_transport_factory.cc b/content/browser/compositor/viz_process_transport_factory.cc index f0c3e0d..5bb9bc2 100644 --- a/content/browser/compositor/viz_process_transport_factory.cc +++ b/content/browser/compositor/viz_process_transport_factory.cc
@@ -44,10 +44,6 @@ #include "ui/gfx/win/rendering_window_manager.h" #endif -#if defined(USE_OZONE) -#include "ui/ozone/public/ozone_platform.h" -#endif - namespace content { namespace { @@ -194,14 +190,8 @@ // GPU process access is disabled. Start a new thread to run the display // compositor in-process and connect HostFrameSinkManager to it. - base::MessageLoop::Type message_loop_type = base::MessageLoop::TYPE_DEFAULT; -#if defined(USE_OZONE) - message_loop_type = ui::OzonePlatform::GetInstance() - ->GetPlatformProperties() - .message_loop_type_for_gpu; -#endif - viz_compositor_thread_ = - std::make_unique<viz::VizCompositorThreadRunner>(message_loop_type); + viz_compositor_thread_ = std::make_unique<viz::VizCompositorThreadRunner>( + base::MessageLoop::TYPE_DEFAULT); viz::mojom::FrameSinkManagerParamsPtr params = viz::mojom::FrameSinkManagerParams::New();
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index e0d5b840..0774bc2 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -2921,7 +2921,8 @@ TextSurroundingSelectionCallback callback, int max_length) { DCHECK(!callback.is_null()); - frame_->GetTextSurroundingSelection(max_length, std::move(callback)); + GetSurroundingText()->GetTextSurroundingSelection(max_length, + std::move(callback)); } void RenderFrameHostImpl::AllowBindings(int bindings_flags) { @@ -5490,6 +5491,14 @@ return find_in_page_; } +const mojo::AssociatedRemote<blink::mojom::SurroundingText>& +RenderFrameHostImpl::GetSurroundingText() { + if (!surrounding_text_ || !surrounding_text_.is_bound() || + !surrounding_text_.is_connected()) + GetRemoteAssociatedInterfaces()->GetInterface(&surrounding_text_); + return surrounding_text_; +} + void RenderFrameHostImpl::ResetLoadingState() { if (is_loading()) { // When pending deletion, just set the loading state to not loading.
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index d0f858a..fca613e 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -78,6 +78,7 @@ #include "third_party/blink/public/mojom/frame/document_interface_broker.mojom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/navigation_initiator.mojom.h" +#include "third_party/blink/public/mojom/frame/surrounding_text.mojom.h" #include "third_party/blink/public/mojom/idle/idle_manager.mojom.h" #include "third_party/blink/public/mojom/image_downloader/image_downloader.mojom.h" #include "third_party/blink/public/mojom/presentation/presentation.mojom.h" @@ -747,6 +748,10 @@ // Returns remote to renderer side FindInPage associated with this frame. const mojo::AssociatedRemote<blink::mojom::FindInPage>& GetFindInPage(); + // Returns remote to renderer side SurroundingText associated with this frame. + const mojo::AssociatedRemote<blink::mojom::SurroundingText>& + GetSurroundingText(); + // Resets the loading state. Following this call, the RenderFrameHost will be // in a non-loading state. void ResetLoadingState(); @@ -1904,6 +1909,9 @@ // Holder of Mojo connection with FindInPage service in Blink. mojo::AssociatedRemote<blink::mojom::FindInPage> find_in_page_; + // Holder of Mojo connection with the SurroundingText service in Blink. + mojo::AssociatedRemote<blink::mojom::SurroundingText> surrounding_text_; + // Holds a NavigationRequest when it's about to commit, ie. after // OnCrossDocumentCommitProcessed has returned a positive answer for this // NavigationRequest but before receiving DidCommitProvisionalLoad. This
diff --git a/content/browser/gpu/gpu_data_manager_impl_private.cc b/content/browser/gpu/gpu_data_manager_impl_private.cc index e36f2344..0380136 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private.cc +++ b/content/browser/gpu/gpu_data_manager_impl_private.cc
@@ -371,10 +371,10 @@ if (GpuAccessAllowed(nullptr)) return true; -#if defined(USE_X11) || defined(OS_MACOSX) +#if defined(USE_X11) || defined(OS_MACOSX) || defined(OS_FUCHSIA) // If GPU access is disabled with OOP-D we run the display compositor in: // Browser process: Windows - // GPU process: Linux and Mac + // GPU process: Linux, Mac and Fuchsia // N/A: Android and Chrome OS (GPU access can't be disabled) if (features::IsVizDisplayCompositorEnabled()) return true;
diff --git a/content/common/frame.mojom b/content/common/frame.mojom index 4a8fb9a7..a2fe2db 100644 --- a/content/common/frame.mojom +++ b/content/common/frame.mojom
@@ -64,12 +64,6 @@ // Set the lifecycle state. SetLifecycleState(blink.mojom.FrameLifecycleState state); - // Retrieves the text surrounding the current selection for the frame up to - // the length specified by |max_length|, along with its start and end offsets. - GetTextSurroundingSelection(uint32 max_length) - => (mojo_base.mojom.String16 content, uint32 start_offset, - uint32 end_offset); - // Samsung Galaxy Note-specific "smart clip" stylus text getter. // Extracts the data at the given rect. [EnableIf=is_android]
diff --git a/content/renderer/compositor/layer_tree_view.cc b/content/renderer/compositor/layer_tree_view.cc index 4daec12..6ba2e4d 100644 --- a/content/renderer/compositor/layer_tree_view.cc +++ b/content/renderer/compositor/layer_tree_view.cc
@@ -188,10 +188,6 @@ layer_tree_host_->SetNeedsAnimate(); } -void LayerTreeView::ForceRecalculateRasterScales() { - layer_tree_host_->SetNeedsRecalculateRasterScales(); -} - void LayerTreeView::SetHaveScrollEventHandlers(bool has_handlers) { layer_tree_host_->SetHaveScrollEventHandlers(has_handlers); }
diff --git a/content/renderer/compositor/layer_tree_view.h b/content/renderer/compositor/layer_tree_view.h index bf0a67f..764bc34 100644 --- a/content/renderer/compositor/layer_tree_view.h +++ b/content/renderer/compositor/layer_tree_view.h
@@ -127,7 +127,6 @@ // blink::WebLayerTreeView implementation. viz::FrameSinkId GetFrameSinkId() override; void SetNonBlinkManagedRootLayer(scoped_refptr<cc::Layer> layer); - void ForceRecalculateRasterScales() override; void SetHaveScrollEventHandlers(bool) override; bool HaveScrollEventHandlers() const override; int LayerTreeId() const override;
diff --git a/content/renderer/media/webrtc/mock_data_channel_impl.cc b/content/renderer/media/webrtc/mock_data_channel_impl.cc index 6f4e886c1..1d3547f5 100644 --- a/content/renderer/media/webrtc/mock_data_channel_impl.cc +++ b/content/renderer/media/webrtc/mock_data_channel_impl.cc
@@ -34,18 +34,6 @@ bool MockDataChannel::ordered() const { return config_.ordered; } -uint16_t MockDataChannel::maxRetransmitTime() const { - // TODO(https://bugs.chromium.org/854385): Restore when change landed. - // return config_.maxRetransmitTime; - return -1; -} - -uint16_t MockDataChannel::maxRetransmits() const { - // TODO(https://bugs.chromium.org/854385): Restore when change landed. - // return config_.maxRetransmits; - return -1; -} - std::string MockDataChannel::protocol() const { return config_.protocol; } bool MockDataChannel::negotiated() const { return config_.negotiated; }
diff --git a/content/renderer/media/webrtc/mock_data_channel_impl.h b/content/renderer/media/webrtc/mock_data_channel_impl.h index 13a8ad2..6fbf726b 100644 --- a/content/renderer/media/webrtc/mock_data_channel_impl.h +++ b/content/renderer/media/webrtc/mock_data_channel_impl.h
@@ -24,8 +24,6 @@ std::string label() const override; bool reliable() const override; bool ordered() const override; - uint16_t maxRetransmitTime() const override; - uint16_t maxRetransmits() const override; std::string protocol() const override; bool negotiated() const override; int id() const override;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 6984a44..ecfe49c3 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -215,7 +215,6 @@ #include "third_party/blink/public/web/web_security_policy.h" #include "third_party/blink/public/web/web_serialized_script_value.h" #include "third_party/blink/public/web/web_settings.h" -#include "third_party/blink/public/web/web_surrounding_text.h" #include "third_party/blink/public/web/web_user_gesture_indicator.h" #include "third_party/blink/public/web/web_view.h" #include "third_party/blink/public/web/web_widget.h" @@ -2788,24 +2787,6 @@ frame_->SetLifecycleState(state); } -void RenderFrameImpl::GetTextSurroundingSelection( - uint32_t max_length, - GetTextSurroundingSelectionCallback callback) { - blink::WebSurroundingText surrounding_text(frame_, max_length); - - if (surrounding_text.IsEmpty()) { - // |surrounding_text| might not be correctly initialized, for example if - // |frame_->SelectionRange().IsNull()|, in other words, if there was no - // selection. - std::move(callback).Run(base::string16(), 0, 0); - return; - } - - std::move(callback).Run(surrounding_text.TextContent().Utf16(), - surrounding_text.StartOffsetInTextContent(), - surrounding_text.EndOffsetInTextContent()); -} - void RenderFrameImpl::VisibilityChanged( blink::mojom::FrameVisibility visibility) { GetFrameHost()->VisibilityChanged(visibility);
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 92ab2b7..bd621228e 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -529,9 +529,6 @@ void ResumeBlockedRequests() override; void CancelBlockedRequests() override; void SetLifecycleState(blink::mojom::FrameLifecycleState state) override; - void GetTextSurroundingSelection( - uint32_t max_length, - GetTextSurroundingSelectionCallback callback) override; #if defined(OS_ANDROID) void ExtractSmartClipData(
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index fdd6d3a65..370773c 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -3395,6 +3395,10 @@ target_offset, use_anchor, new_page_scale, duration); } +void RenderWidget::ForceRecalculateRasterScales() { + layer_tree_view_->layer_tree_host()->SetNeedsRecalculateRasterScales(); +} + void RenderWidget::RequestDecode(const cc::PaintImage& image, base::OnceCallback<void(bool)> callback) { layer_tree_view_->layer_tree_host()->QueueImageDecode(image,
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index 9f608d5..75b8ef6 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -455,6 +455,7 @@ bool use_anchor, float new_page_scale, double duration_sec) override; + void ForceRecalculateRasterScales() override; void RequestDecode(const cc::PaintImage& image, base::OnceCallback<void(bool)> callback) override; void NotifySwapTime(ReportTimeCallback callback) override;
diff --git a/content/shell/test_runner/test_runner.cc b/content/shell/test_runner/test_runner.cc index b7dd07c..d933c90 100644 --- a/content/shell/test_runner/test_runner.cc +++ b/content/shell/test_runner/test_runner.cc
@@ -55,7 +55,6 @@ #include "third_party/blink/public/web/web_security_policy.h" #include "third_party/blink/public/web/web_serialized_script_value.h" #include "third_party/blink/public/web/web_settings.h" -#include "third_party/blink/public/web/web_surrounding_text.h" #include "third_party/blink/public/web/web_view.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h"
diff --git a/content/shell/test_runner/test_runner_for_specific_view.cc b/content/shell/test_runner/test_runner_for_specific_view.cc index 62e606f..18c27e8 100644 --- a/content/shell/test_runner/test_runner_for_specific_view.cc +++ b/content/shell/test_runner/test_runner_for_specific_view.cc
@@ -55,7 +55,6 @@ #include "third_party/blink/public/web/web_security_policy.h" #include "third_party/blink/public/web/web_serialized_script_value.h" #include "third_party/blink/public/web/web_settings.h" -#include "third_party/blink/public/web/web_surrounding_text.h" #include "third_party/blink/public/web/web_view.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h"
diff --git a/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt index d7283bf..39cdb0a 100644 --- a/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt +++ b/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt
@@ -417,6 +417,7 @@ crbug.com/733599 [ android no-angle ] conformance/textures/video/tex-2d-luminance-luminance-unsigned_byte.html [ RetryOnFailure ] crbug.com/834933 [ android android-chromium no-angle ] conformance/textures/video/tex-2d-rgb-rgb-unsigned_byte.html [ RetryOnFailure ] crbug.com/834933 [ android android-chromium ] conformance/textures/video/tex-2d-rgba-rgba-unsigned_byte.html [ RetryOnFailure ] +crbug.com/891456 [ android ] conformance/textures/image_bitmap_from_video/tex-2d-rgba-rgba-unsigned_short_5_5_5_1.html [ RetryOnFailure ] # This crashes in Android WebView on the Nexus 6, preventing the # suite from running further. Rather than add multiple @@ -526,7 +527,6 @@ crbug.com/891456 [ android nvidia ] conformance/textures/image_bitmap_from_video/tex-2d-luminance_alpha-luminance_alpha-unsigned_byte.html [ RetryOnFailure ] crbug.com/891456 [ android nvidia ] conformance/textures/image_bitmap_from_video/tex-2d-rgb-rgb-unsigned_short_5_6_5.html [ RetryOnFailure ] crbug.com/891456 [ android nvidia ] conformance/textures/image_bitmap_from_video/tex-2d-rgba-rgba-unsigned_byte.html [ RetryOnFailure ] -crbug.com/891456 [ android nvidia ] conformance/textures/image_bitmap_from_video/tex-2d-rgba-rgba-unsigned_short_5_5_5_1.html [ RetryOnFailure ] # Flaky timeout on android_n5x_swarming_rel and # android-marshmallow-arm64-rel. @@ -538,6 +538,7 @@ crbug.com/981579 [ android android-chromium opengles ] conformance/textures/video/tex-2d-rgb-rgb-unsigned_byte.html [ Failure ] crbug.com/906724 [ android opengles ] conformance/textures/video/tex-2d-luminance_alpha-luminance_alpha-unsigned_byte.html [ Failure ] crbug.com/906724 [ android opengles ] conformance/textures/video/tex-2d-luminance-luminance-unsigned_byte.html [ Failure ] +crbug.com/986808 [ android opengles ] conformance/textures/misc/texture-corner-case-videos.html [ Failure ] # Misc failures crbug.com/angleproject/2988 [ android opengles ] conformance/context/context-size-change.html [ Failure ]
diff --git a/extensions/browser/updater/extension_downloader.cc b/extensions/browser/updater/extension_downloader.cc index 0f76b1c..79fe4b38 100644 --- a/extensions/browser/updater/extension_downloader.cc +++ b/extensions/browser/updater/extension_downloader.cc
@@ -320,7 +320,7 @@ } void ExtensionDownloader::SetIdentityManager( - identity::IdentityManager* identity_manager) { + signin::IdentityManager* identity_manager) { identity_manager_ = identity_manager; } @@ -1005,11 +1005,11 @@ // It is safe to use Unretained(this) here given that the callback // will not be invoked if this object is deleted. access_token_fetcher_ = - std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( + std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( kTokenServiceConsumerId, identity_manager_, webstore_scopes, base::BindOnce(&ExtensionDownloader::OnAccessTokenFetchComplete, base::Unretained(this)), - identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); + signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); return; } extension_loader_resource_request_->headers.SetHeader( @@ -1236,7 +1236,7 @@ void ExtensionDownloader::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) {
diff --git a/extensions/browser/updater/extension_downloader.h b/extensions/browser/updater/extension_downloader.h index 7d191d9..c447403 100644 --- a/extensions/browser/updater/extension_downloader.h +++ b/extensions/browser/updater/extension_downloader.h
@@ -29,11 +29,11 @@ enum class VerifierFormat; } -namespace identity { +namespace signin { class PrimaryAccountAccessTokenFetcher; class IdentityManager; struct AccessTokenInfo; -} // namespace identity +} // namespace signin namespace net { class URLRequestStatus; @@ -135,7 +135,7 @@ // Sets the IdentityManager instance to be used for OAuth2 authentication on // protected Webstore downloads. The IdentityManager instance must be valid to // use for the lifetime of this object. - void SetIdentityManager(identity::IdentityManager* identity_manager); + void SetIdentityManager(signin::IdentityManager* identity_manager); void set_brand_code(const std::string& brand_code) { brand_code_ = brand_code; @@ -340,7 +340,7 @@ int response_code); void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); ManifestFetchData* CreateManifestFetchData( const GURL& update_url, @@ -402,14 +402,14 @@ // May be used to fetch access tokens for protected download requests. May be // null. If non-null, guaranteed to outlive this object. - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // A Webstore download-scoped access token for the |identity_provider_|'s // active account, if any. std::string access_token_; // A pending access token fetcher. - std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> access_token_fetcher_; // Brand code to include with manifest fetch queries if sending ping data.
diff --git a/google_apis/BUILD.gn b/google_apis/BUILD.gn index 407837e..75152af 100644 --- a/google_apis/BUILD.gn +++ b/google_apis/BUILD.gn
@@ -118,10 +118,6 @@ "gaia/oauth2_id_token_decoder.h", "gaia/oauth2_mint_token_flow.cc", "gaia/oauth2_mint_token_flow.h", - "gaia/oauth2_token_service.cc", - "gaia/oauth2_token_service.h", - "gaia/oauth2_token_service_delegate.cc", - "gaia/oauth2_token_service_delegate.h", "gaia/oauth2_token_service_observer.h", "gaia/oauth_multilogin_result.cc", "gaia/oauth_multilogin_result.h", @@ -179,8 +175,6 @@ "gaia/fake_gaia.h", "gaia/fake_oauth2_access_token_manager.cc", "gaia/fake_oauth2_access_token_manager.h", - "gaia/fake_oauth2_token_service_delegate.cc", - "gaia/fake_oauth2_token_service_delegate.h", "gaia/oauth2_access_token_manager_test_util.cc", "gaia/oauth2_access_token_manager_test_util.h", ] @@ -218,7 +212,6 @@ "gaia/oauth2_api_call_flow_unittest.cc", "gaia/oauth2_id_token_decoder_unittest.cc", "gaia/oauth2_mint_token_flow_unittest.cc", - "gaia/oauth2_token_service_delegate_unittest.cc", "gaia/oauth_multilogin_result_unittest.cc", "gaia/oauth_request_signer_unittest.cc", "google_api_keys_unittest.cc",
diff --git a/google_apis/drive/auth_service.cc b/google_apis/drive/auth_service.cc index 067c155a..b2fbfda 100644 --- a/google_apis/drive/auth_service.cc +++ b/google_apis/drive/auth_service.cc
@@ -39,7 +39,7 @@ // OAuth2 authorization token retrieval request. class AuthRequest { public: - AuthRequest(identity::IdentityManager* identity_manager, + AuthRequest(signin::IdentityManager* identity_manager, const CoreAccountId& account_id, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const AuthStatusCallback& callback, @@ -48,17 +48,17 @@ private: void OnAccessTokenFetchComplete(GoogleServiceAuthError error, - identity::AccessTokenInfo token_info); + signin::AccessTokenInfo token_info); AuthStatusCallback callback_; - std::unique_ptr<identity::AccessTokenFetcher> access_token_fetcher_; + std::unique_ptr<signin::AccessTokenFetcher> access_token_fetcher_; base::ThreadChecker thread_checker_; DISALLOW_COPY_AND_ASSIGN(AuthRequest); }; AuthRequest::AuthRequest( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const CoreAccountId& account_id, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const AuthStatusCallback& callback, @@ -72,14 +72,14 @@ identity::ScopeSet(scopes.begin(), scopes.end()), base::BindOnce(&AuthRequest::OnAccessTokenFetchComplete, base::Unretained(this)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); } AuthRequest::~AuthRequest() {} void AuthRequest::OnAccessTokenFetchComplete( GoogleServiceAuthError error, - identity::AccessTokenInfo token_info) { + signin::AccessTokenInfo token_info) { DCHECK(thread_checker_.CalledOnValidThread()); if (error.state() == GoogleServiceAuthError::NONE) { @@ -111,7 +111,7 @@ } // namespace AuthService::AuthService( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, const CoreAccountId& account_id, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::vector<std::string>& scopes)
diff --git a/google_apis/drive/auth_service.h b/google_apis/drive/auth_service.h index 9a4f451..1a2fc93 100644 --- a/google_apis/drive/auth_service.h +++ b/google_apis/drive/auth_service.h
@@ -29,13 +29,13 @@ // (IdentityManager) and provides OAuth2 token refresh infrastructure. // All public functions must be called on UI thread. class AuthService : public AuthServiceInterface, - public identity::IdentityManager::Observer { + public signin::IdentityManager::Observer { public: // |url_loader_factory| is used to perform authentication with // SimpleURLLoader. // // |scopes| specifies OAuth2 scopes. - AuthService(identity::IdentityManager* identity_manager, + AuthService(signin::IdentityManager* identity_manager, const CoreAccountId& account_id, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::vector<std::string>& scopes); @@ -67,7 +67,7 @@ DriveApiErrorCode error, const std::string& access_token); - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; CoreAccountId account_id_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; bool has_refresh_token_;
diff --git a/google_apis/gaia/gaia_constants.cc b/google_apis/gaia/gaia_constants.cc index 9bf3c1ad..812f352 100644 --- a/google_apis/gaia/gaia_constants.cc +++ b/google_apis/gaia/gaia_constants.cc
@@ -82,4 +82,6 @@ // Canonical email of the account to sign in. const char kClientOAuthEmailKey[] = "email"; +// Used as an Invalid refresh token. +const char kInvalidRefreshToken[] = "invalid_refresh_token"; } // namespace GaiaConstants
diff --git a/google_apis/gaia/gaia_constants.h b/google_apis/gaia/gaia_constants.h index f6388d89..f7d87c0 100644 --- a/google_apis/gaia/gaia_constants.h +++ b/google_apis/gaia/gaia_constants.h
@@ -47,6 +47,8 @@ // Used by wallet sign in helper. extern const char kClientOAuthEmailKey[]; +// Refresh token that is guaranteed to be invalid. +extern const char kInvalidRefreshToken[]; } // namespace GaiaConstants #endif // GOOGLE_APIS_GAIA_GAIA_CONSTANTS_H_
diff --git a/google_apis/gaia/oauth2_token_service.cc b/google_apis/gaia/oauth2_token_service.cc deleted file mode 100644 index c5312bda..0000000 --- a/google_apis/gaia/oauth2_token_service.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "google_apis/gaia/oauth2_token_service.h" - -#include "google_apis/gaia/oauth2_token_service_delegate.h" - -OAuth2TokenService::OAuth2TokenService( - std::unique_ptr<OAuth2TokenServiceDelegate> delegate) - : delegate_(std::move(delegate)) { - DCHECK(delegate_); -} - -OAuth2TokenService::~OAuth2TokenService() = default; - -OAuth2TokenServiceDelegate* OAuth2TokenService::GetDelegate() { - return delegate_.get(); -} - -const OAuth2TokenServiceDelegate* OAuth2TokenService::GetDelegate() const { - return delegate_.get(); -}
diff --git a/google_apis/gaia/oauth2_token_service.h b/google_apis/gaia/oauth2_token_service.h deleted file mode 100644 index 4d1592c..0000000 --- a/google_apis/gaia/oauth2_token_service.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_H_ -#define GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" - -class OAuth2TokenServiceDelegate; - -// Abstract base class for a service that fetches and caches OAuth2 access -// tokens. Concrete subclasses should implement GetRefreshToken to return -// the appropriate refresh token. Derived services might maintain refresh tokens -// for multiple accounts. -// -// All calls are expected from the UI thread. -// -// To use this service, call StartRequest() with a given set of scopes and a -// consumer of the request results. The consumer is required to outlive the -// request. The request can be deleted. The consumer may be called back -// asynchronously with the fetch results. -// -// - If the consumer is not called back before the request is deleted, it will -// never be called back. -// Note in this case, the actual network requests are not canceled and the -// cache will be populated with the fetched results; it is just the consumer -// callback that is aborted. -// -// - Otherwise the consumer will be called back with the request and the fetch -// results. -// -// The caller of StartRequest() owns the returned request and is responsible to -// delete the request even once the callback has been invoked. -class OAuth2TokenService { - public: - explicit OAuth2TokenService( - std::unique_ptr<OAuth2TokenServiceDelegate> delegate); - ~OAuth2TokenService(); - - OAuth2TokenServiceDelegate* GetDelegate(); - const OAuth2TokenServiceDelegate* GetDelegate() const; - - private: - // TODO(https://crbug.com/967598): Completely merge this class into - // ProfileOAuth2TokenService. - friend class ProfileOAuth2TokenService; - friend class OAuth2TokenServiceDelegate; - - std::unique_ptr<OAuth2TokenServiceDelegate> delegate_; - - DISALLOW_COPY_AND_ASSIGN(OAuth2TokenService); -}; - -#endif // GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_H_
diff --git a/gpu/command_buffer/service/shared_image_factory.cc b/gpu/command_buffer/service/shared_image_factory.cc index 648a3cb..8b4402c 100644 --- a/gpu/command_buffer/service/shared_image_factory.cc +++ b/gpu/command_buffer/service/shared_image_factory.cc
@@ -293,6 +293,13 @@ bool using_interop_factory = share_between_threads || share_between_gl_vulkan || using_dawn || share_between_gl_metal; + + // TODO(vasilyt): Android required AHB for overlays + // What about other platforms? +#if defined(OS_ANDROID) + using_interop_factory |= usage & SHARED_IMAGE_USAGE_SCANOUT; +#endif + // wrapped_sk_image_factory_ is only used for OOPR and supports // a limited number of flags (e.g. no SHARED_IMAGE_USAGE_SCANOUT). constexpr auto kWrappedSkImageUsage = SHARED_IMAGE_USAGE_RASTER |
diff --git a/headless/BUILD.gn b/headless/BUILD.gn index 8c202dd0..b747274 100644 --- a/headless/BUILD.gn +++ b/headless/BUILD.gn
@@ -300,6 +300,7 @@ deps = [ ":gen_devtools_client_api", ":protocol_sources", + ":version_header", "//base:base_static", "//content/public/common", "//content/public/common:service_names",
diff --git a/infra/config/cr-buildbucket.cfg b/infra/config/cr-buildbucket.cfg index 0bf0d82..9825f6fb 100644 --- a/infra/config/cr-buildbucket.cfg +++ b/infra/config/cr-buildbucket.cfg
@@ -1351,6 +1351,7 @@ builders { name: "chromeos-amd64-generic-asan-rel" mixins: "chromeos-ci" + mixins: "linux-xenial" mixins: "builderless" } @@ -1379,6 +1380,7 @@ builders { name: "chromeos-arm-generic-rel" mixins: "chromeos-ci" + mixins: "linux-xenial" mixins: "builderless" } @@ -1606,6 +1608,7 @@ mixins: "fyi-ci" mixins: "linux" mixins: "builderless" + mixins: "linux-xenial" } builders { @@ -4073,6 +4076,7 @@ builders { mixins: "builderless" mixins: "linux-try" + mixins: "linux-xenial" name: "linux-blink-heap-concurrent-marking-tsan-rel" } builders {
diff --git a/ios/build/bots/chromium.fyi/ios13-beta-simulator.json b/ios/build/bots/chromium.fyi/ios13-beta-simulator.json index 479d1523..209d6b3 100644 --- a/ios/build/bots/chromium.fyi/ios13-beta-simulator.json +++ b/ios/build/bots/chromium.fyi/ios13-beta-simulator.json
@@ -115,6 +115,7 @@ } }, { + "xcode parallelization": false, "include": "eg_cq_tests.json", "device type": "iPhone X", "os": "13.0", @@ -128,6 +129,7 @@ } }, { + "xcode parallelization": false, "include": "eg_cq_tests.json", "device type": "iPad Pro (12.9-inch)", "os": "13.0", @@ -141,6 +143,7 @@ } }, { + "xcode parallelization": false, "include": "eg_tests.json", "device type": "iPhone X", "os": "13.0", @@ -154,6 +157,7 @@ } }, { + "xcode parallelization": false, "include": "eg_tests.json", "device type": "iPad Air (3rd generation)", "os": "13.0",
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 1faa653c..407ae1a 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -2642,7 +2642,7 @@ ios::ChromeBrowserState* browserState = [self currentBrowserState]; if (browserState->IsOffTheRecord()) return nil; - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browserState); std::string username = identity_manager->GetPrimaryAccountInfo().email; return username.empty() ? nil : base::SysUTF8ToNSString(username);
diff --git a/ios/chrome/app/resources/LaunchScreen.xib b/ios/chrome/app/resources/LaunchScreen.xib index c25ae05..3008ab66 100644 --- a/ios/chrome/app/resources/LaunchScreen.xib +++ b/ios/chrome/app/resources/LaunchScreen.xib
@@ -1,10 +1,9 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="9531" systemVersion="15C50" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES"> +<?xml version="1.0" encoding="UTF-8"?> +<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14845" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES"> + <device id="retina6_1" orientation="portrait" appearance="light"/> <dependencies> - <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/> - <capability name="Aspect ratio constraints" minToolsVersion="5.1"/> - <capability name="Constraints to layout margins" minToolsVersion="6.0"/> - <capability name="Constraints with non-1.0 multipliers" minToolsVersion="5.1"/> + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14799.2"/> + <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/> @@ -15,11 +14,11 @@ <viewControllerLayoutGuide type="bottom" id="TrJ-rv-PCn"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="tRS-Cx-RH3"> - <rect key="frame" x="0.0" y="0.0" width="600" height="600"/> + <rect key="frame" x="0.0" y="0.0" width="414" height="896"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="launchscreen_app_logo" translatesAutoresizingMaskIntoConstraints="NO" id="K7H-Iv-QNk"> - <rect key="frame" x="204" y="204" width="192" height="192"/> + <rect key="frame" x="128" y="369" width="158" height="158"/> <constraints> <constraint firstAttribute="width" relation="lessThanOrEqual" constant="192" id="Ybu-iB-Ad4"/> <constraint firstAttribute="height" relation="lessThanOrEqual" constant="192" id="gGV-z8-zNx"/> @@ -27,14 +26,14 @@ </constraints> </imageView> <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="launchscreen_brand_name" translatesAutoresizingMaskIntoConstraints="NO" id="bAU-qs-X5w"> - <rect key="frame" x="247" y="545" width="107" height="35"/> + <rect key="frame" x="153.5" y="807" width="107" height="35"/> <constraints> <constraint firstAttribute="width" constant="107" id="0Mf-i7-mvo"/> <constraint firstAttribute="height" constant="35" id="7Gs-G7-OR2"/> </constraints> </imageView> </subviews> - <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/> + <color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/> <constraints> <constraint firstItem="K7H-Iv-QNk" firstAttribute="width" secondItem="tRS-Cx-RH3" secondAttribute="width" multiplier="0.381966" id="3hJ-Yo-1Tg"/> <constraint firstItem="K7H-Iv-QNk" firstAttribute="height" secondItem="tRS-Cx-RH3" secondAttribute="height" multiplier="0.381966" id="962-tL-cOd"/>
diff --git a/ios/chrome/browser/BUILD.gn b/ios/chrome/browser/BUILD.gn index de3b096..18089d120 100644 --- a/ios/chrome/browser/BUILD.gn +++ b/ios/chrome/browser/BUILD.gn
@@ -96,7 +96,6 @@ "//components/search_provider_logos", "//components/security_state/core", "//components/send_tab_to_self", - "//components/signin/core/browser", "//components/strings", "//components/sync", "//components/translate/core/browser",
diff --git a/ios/chrome/browser/DEPS b/ios/chrome/browser/DEPS index 43b0094..408716d 100644 --- a/ios/chrome/browser/DEPS +++ b/ios/chrome/browser/DEPS
@@ -72,24 +72,7 @@ "+components/services/unzip", "+components/sessions", "+components/signin/core/browser", - # Use identity_manager.h instead of the below files; - # see https://groups.google.com/a/chromium.org/d/msg/chromium-dev/dgFLuxqZt1o/iEqkyoQQBwAJ for help and info. - "-components/signin/internal/identity_manager/account_fetcher_service.h", - "-components/signin/internal/identity_manager/account_info_fetcher.h", - "-components/signin/internal/identity_manager/account_tracker_service.h", - "-components/signin/internal/identity_manager/child_account_info_fetcher_android.h", - "-components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/gaia_cookie_manager_service.h", - "-components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_helper.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_token_fetcher.h", - "-components/signin/internal/identity_manager/primary_account_manager.h", - "-components/signin/internal/identity_manager/primary_account_policy_manager.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h", - "-components/signin/internal/identity_manager/ubertoken_fetcher_impl.h", "+components/signin/public", - "+components/signin/ios/browser", "+components/ssl_errors", "+components/suggestions",
diff --git a/ios/chrome/browser/autocomplete/BUILD.gn b/ios/chrome/browser/autocomplete/BUILD.gn index 073fe828..233583d 100644 --- a/ios/chrome/browser/autocomplete/BUILD.gn +++ b/ios/chrome/browser/autocomplete/BUILD.gn
@@ -27,7 +27,6 @@ "//components/language/core/browser", "//components/omnibox/browser", "//components/prefs", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//components/sync", "//components/unified_consent",
diff --git a/ios/chrome/browser/autocomplete/autocomplete_provider_client_impl.mm b/ios/chrome/browser/autocomplete/autocomplete_provider_client_impl.mm index 5ef2dbe..af453a26 100644 --- a/ios/chrome/browser/autocomplete/autocomplete_provider_client_impl.mm +++ b/ios/chrome/browser/autocomplete/autocomplete_provider_client_impl.mm
@@ -184,7 +184,7 @@ } bool AutocompleteProviderClientImpl::IsAuthenticated() const { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browser_state_); return identity_manager != nullptr && identity_manager->HasPrimaryAccount(); }
diff --git a/ios/chrome/browser/autofill/BUILD.gn b/ios/chrome/browser/autofill/BUILD.gn index eaa0eb8..c69f901 100644 --- a/ios/chrome/browser/autofill/BUILD.gn +++ b/ios/chrome/browser/autofill/BUILD.gn
@@ -115,7 +115,6 @@ "//components/infobars/core", "//components/pref_registry", "//components/prefs", - "//components/signin/core/browser", "//ios/chrome/app/strings", "//ios/chrome/browser", "//ios/chrome/browser/browser_state",
diff --git a/ios/chrome/browser/autofill/autofill_controller_unittest.mm b/ios/chrome/browser/autofill/autofill_controller_unittest.mm index 51cc3bd..7773944 100644 --- a/ios/chrome/browser/autofill/autofill_controller_unittest.mm +++ b/ios/chrome/browser/autofill/autofill_controller_unittest.mm
@@ -42,7 +42,6 @@ #include "ios/chrome/browser/webdata_services/web_data_service_factory.h" #import "ios/web/public/deprecated/crw_js_injection_receiver.h" #include "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/navigation/navigation_item.h" #import "ios/web/public/navigation/navigation_manager.h" @@ -323,7 +322,8 @@ NSString* html, size_t expected_number_of_forms) { LoadHtml(html); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state()); + web::WebFrame* main_frame = + web_state()->GetWebFramesManager()->GetMainWebFrame(); AutofillManager* autofill_manager = AutofillDriverIOS::FromWebStateAndWebFrame(web_state(), main_frame) ->autofill_manager(); @@ -344,7 +344,8 @@ // registered as a FormStructure by the AutofillManager. TEST_F(AutofillControllerTest, ReadForm) { ASSERT_TRUE(LoadHtmlAndWaitForFormFetched(kProfileFormHtml, 1)); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state()); + web::WebFrame* main_frame = + web_state()->GetWebFramesManager()->GetMainWebFrame(); AutofillManager* autofill_manager = AutofillDriverIOS::FromWebStateAndWebFrame(web_state(), main_frame) ->autofill_manager(); @@ -364,7 +365,8 @@ // name is correctly set. TEST_F(AutofillControllerTest, ReadFormName) { ASSERT_TRUE(LoadHtmlAndWaitForFormFetched(kMinimalFormWithNameHtml, 1)); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state()); + web::WebFrame* main_frame = + web_state()->GetWebFramesManager()->GetMainWebFrame(); AutofillManager* autofill_manager = AutofillDriverIOS::FromWebStateAndWebFrame(web_state(), main_frame) ->autofill_manager();
diff --git a/ios/chrome/browser/autofill/automation/automation_egtest.mm b/ios/chrome/browser/autofill/automation/automation_egtest.mm index 7a2cb4f..8383acf 100644 --- a/ios/chrome/browser/autofill/automation/automation_egtest.mm +++ b/ios/chrome/browser/autofill/automation/automation_egtest.mm
@@ -23,7 +23,6 @@ #import "ios/chrome/test/app/tab_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/earl_grey/web_view_actions.h" #import "ios/web/public/test/earl_grey/web_view_matchers.h" @@ -182,7 +181,8 @@ // Save the profile and credit card generated to the personal data manager. web::WebState* web_state = chrome_test_util::GetCurrentWebState(); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state); + web::WebFrame* main_frame = + web_state->GetWebFramesManager()->GetMainWebFrame(); autofill::AutofillManager* autofill_manager = autofill::AutofillDriverIOS::FromWebStateAndWebFrame(web_state, main_frame)
diff --git a/ios/chrome/browser/autofill/form_structure_browsertest.mm b/ios/chrome/browser/autofill/form_structure_browsertest.mm index 5b1d2f3f..81aa898c 100644 --- a/ios/chrome/browser/autofill/form_structure_browsertest.mm +++ b/ios/chrome/browser/autofill/form_structure_browsertest.mm
@@ -30,7 +30,6 @@ #include "ios/chrome/browser/web/chrome_web_client.h" #import "ios/chrome/browser/web/chrome_web_test.h" #include "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/web_state/web_state.h" @@ -173,7 +172,7 @@ std::string* output) { ASSERT_TRUE(LoadHtmlWithoutSubresources(input)); base::ThreadPoolInstance::Get()->FlushForTesting(); - web::WebFrame* frame = web::GetMainWebFrame(web_state()); + web::WebFrame* frame = web_state()->GetWebFramesManager()->GetMainWebFrame(); AutofillManager* autofill_manager = AutofillDriverIOS::FromWebStateAndWebFrame(web_state(), frame) ->autofill_manager();
diff --git a/ios/chrome/browser/autofill/form_suggestion_controller.mm b/ios/chrome/browser/autofill/form_suggestion_controller.mm index 9d90146..0489bda7 100644 --- a/ios/chrome/browser/autofill/form_suggestion_controller.mm +++ b/ios/chrome/browser/autofill/form_suggestion_controller.mm
@@ -131,8 +131,7 @@ base::mac::ObjCCast<JsSuggestionManager>( [webState->GetJSInjectionReceiver() instanceOfClass:[JsSuggestionManager class]]); - [jsSuggestionManager - setWebFramesManager:web::WebFramesManager::FromWebState(webState)]; + [jsSuggestionManager setWebFramesManager:webState->GetWebFramesManager()]; return [self initWithWebState:webState providers:providers JsSuggestionManager:jsSuggestionManager];
diff --git a/ios/chrome/browser/autofill/js_autofill_manager_unittest.mm b/ios/chrome/browser/autofill/js_autofill_manager_unittest.mm index ee2e9da2..ab28a5621 100644 --- a/ios/chrome/browser/autofill/js_autofill_manager_unittest.mm +++ b/ios/chrome/browser/autofill/js_autofill_manager_unittest.mm
@@ -14,7 +14,7 @@ #include "ios/chrome/browser/web/chrome_web_client.h" #import "ios/chrome/browser/web/chrome_web_test.h" #import "ios/web/public/deprecated/crw_js_injection_receiver.h" -#include "ios/web/public/js_messaging/web_frame_util.h" +#import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/js_test_util.h" #import "ios/web/public/web_state/web_state.h" #import "testing/gtest_mac.h" @@ -75,6 +75,11 @@ manager_ = [[JsAutofillManager alloc] initWithReceiver:web_state()->GetJSInjectionReceiver()]; } + + web::WebFrame* main_web_frame() { + return web_state()->GetWebFramesManager()->GetMainWebFrame(); + } + // Testable autofill manager. JsAutofillManager* manager_; }; @@ -153,14 +158,13 @@ __block BOOL block_was_called = NO; __block NSString* result; - [manager_ - fetchFormsWithMinimumRequiredFieldsCount: - autofill::MinRequiredFieldsForHeuristics() - inFrame:web::GetMainWebFrame(web_state()) - completionHandler:^(NSString* actualResult) { - block_was_called = YES; - result = [actualResult copy]; - }]; + [manager_ fetchFormsWithMinimumRequiredFieldsCount: + autofill::MinRequiredFieldsForHeuristics() + inFrame:main_web_frame() + completionHandler:^(NSString* actualResult) { + block_was_called = YES; + result = [actualResult copy]; + }]; base::test::ios::WaitUntilCondition(^bool() { return block_was_called; }); @@ -245,14 +249,13 @@ __block BOOL block_was_called = NO; __block NSString* result; - [manager_ - fetchFormsWithMinimumRequiredFieldsCount: - autofill::MinRequiredFieldsForHeuristics() - inFrame:web::GetMainWebFrame(web_state()) - completionHandler:^(NSString* actualResult) { - block_was_called = YES; - result = [actualResult copy]; - }]; + [manager_ fetchFormsWithMinimumRequiredFieldsCount: + autofill::MinRequiredFieldsForHeuristics() + inFrame:main_web_frame() + completionHandler:^(NSString* actualResult) { + block_was_called = YES; + result = [actualResult copy]; + }]; base::test::ios::WaitUntilCondition(^bool() { return block_was_called; }); @@ -283,14 +286,13 @@ __block BOOL block_was_called = NO; __block NSString* result; - [manager_ - fetchFormsWithMinimumRequiredFieldsCount: - autofill::MinRequiredFieldsForHeuristics() - inFrame:web::GetMainWebFrame(web_state()) - completionHandler:^(NSString* actualResult) { - block_was_called = YES; - result = [actualResult copy]; - }]; + [manager_ fetchFormsWithMinimumRequiredFieldsCount: + autofill::MinRequiredFieldsForHeuristics() + inFrame:main_web_frame() + completionHandler:^(NSString* actualResult) { + block_was_called = YES; + result = [actualResult copy]; + }]; base::test::ios::WaitUntilCondition(^bool() { return block_was_called; }); @@ -318,14 +320,13 @@ __block BOOL block_was_called = NO; __block NSString* result; - [manager_ - fetchFormsWithMinimumRequiredFieldsCount: - autofill::MinRequiredFieldsForHeuristics() - inFrame:web::GetMainWebFrame(web_state()) - completionHandler:^(NSString* actualResult) { - block_was_called = YES; - result = [actualResult copy]; - }]; + [manager_ fetchFormsWithMinimumRequiredFieldsCount: + autofill::MinRequiredFieldsForHeuristics() + inFrame:main_web_frame() + completionHandler:^(NSString* actualResult) { + block_was_called = YES; + result = [actualResult copy]; + }]; base::test::ios::WaitUntilCondition(^bool() { return block_was_called; }); @@ -355,11 +356,12 @@ data->SetString("identifier", "email"); data->SetString("value", "newemail@com"); __block BOOL block_was_called = NO; - [manager_ fillActiveFormField:std::move(data) - inFrame:web::GetMainWebFrame(web_state()) - completionHandler:^{ - block_was_called = YES; - }]; + [manager_ + fillActiveFormField:std::move(data) + inFrame:web_state()->GetWebFramesManager()->GetMainWebFrame() + completionHandler:^{ + block_was_called = YES; + }]; EXPECT_TRUE(base::test::ios::WaitUntilConditionOrTimeout( base::test::ios::kWaitForActionTimeout, ^bool() { return block_was_called; @@ -383,14 +385,13 @@ __block BOOL block_was_called = NO; __block NSString* result; - [manager_ - fetchFormsWithMinimumRequiredFieldsCount: - autofill::MinRequiredFieldsForHeuristics() - inFrame:web::GetMainWebFrame(web_state()) - completionHandler:^(NSString* actualResult) { - block_was_called = YES; - result = [actualResult copy]; - }]; + [manager_ fetchFormsWithMinimumRequiredFieldsCount: + autofill::MinRequiredFieldsForHeuristics() + inFrame:main_web_frame() + completionHandler:^(NSString* actualResult) { + block_was_called = YES; + result = [actualResult copy]; + }]; base::test::ios::WaitUntilCondition(^bool() { return block_was_called; }); @@ -454,14 +455,13 @@ __block BOOL block_was_called = NO; __block NSString* result; - [manager_ - fetchFormsWithMinimumRequiredFieldsCount: - autofill::MinRequiredFieldsForHeuristics() - inFrame:web::GetMainWebFrame(web_state()) - completionHandler:^(NSString* actualResult) { - block_was_called = YES; - result = [actualResult copy]; - }]; + [manager_ fetchFormsWithMinimumRequiredFieldsCount: + autofill::MinRequiredFieldsForHeuristics() + inFrame:main_web_frame() + completionHandler:^(NSString* actualResult) { + block_was_called = YES; + result = [actualResult copy]; + }]; base::test::ios::WaitUntilCondition(^bool() { return block_was_called; });
diff --git a/ios/chrome/browser/autofill/js_suggestion_manager_unittest.mm b/ios/chrome/browser/autofill/js_suggestion_manager_unittest.mm index fdb1fe8..93841d5 100644 --- a/ios/chrome/browser/autofill/js_suggestion_manager_unittest.mm +++ b/ios/chrome/browser/autofill/js_suggestion_manager_unittest.mm
@@ -54,13 +54,11 @@ ChromeWebTest::SetUp(); manager_ = [[JsSuggestionManager alloc] initWithReceiver:web_state()->GetJSInjectionReceiver()]; - [manager_ - setWebFramesManager:web::WebFramesManager::FromWebState(web_state())]; + [manager_ setWebFramesManager:web_state()->GetWebFramesManager()]; } NSString* JsSuggestionManagerTest::GetFrameIdForMainFrame() { - web::WebFramesManager* manager = - web::WebFramesManager::FromWebState(web_state()); + web::WebFramesManager* manager = web_state()->GetWebFramesManager(); return base::SysUTF8ToNSString(manager->GetMainWebFrame()->GetFrameId()); }
diff --git a/ios/chrome/browser/browser_state/BUILD.gn b/ios/chrome/browser/browser_state/BUILD.gn index a3102a3..9836169e 100644 --- a/ios/chrome/browser/browser_state/BUILD.gn +++ b/ios/chrome/browser/browser_state/BUILD.gn
@@ -23,7 +23,6 @@ "//components/keyed_service/ios", "//components/prefs", "//components/search_engines", - "//components/signin/core/browser", "//components/sync_preferences", "//components/variations/net", "//components/webdata_services", @@ -79,7 +78,6 @@ "//components/prefs", "//components/proxy_config", "//components/proxy_config/ios", - "//components/signin/core/browser", "//components/signin/ios/browser:active_state_manager", "//components/signin/public/identity_manager", "//components/sync_preferences",
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc b/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc index 989e6f93..7f6ef58 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc +++ b/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc
@@ -219,7 +219,7 @@ if (browser_state->GetStatePath().DirName() != cache->GetUserDataDir()) return; - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browser_state); CoreAccountInfo account_info = identity_manager->GetPrimaryAccountInfo(); base::string16 username = base::UTF8ToUTF16(account_info.email);
diff --git a/ios/chrome/browser/browsing_data/BUILD.gn b/ios/chrome/browser/browsing_data/BUILD.gn index 3a4bc0d..1722a71 100644 --- a/ios/chrome/browser/browsing_data/BUILD.gn +++ b/ios/chrome/browser/browsing_data/BUILD.gn
@@ -50,7 +50,6 @@ "//components/password_manager/core/browser", "//components/prefs", "//components/sessions", - "//components/signin/core/browser", "//components/signin/ios/browser", "//components/translate/core/browser:browser", "//ios/chrome/browser",
diff --git a/ios/chrome/browser/google/google_logo_service.h b/ios/chrome/browser/google/google_logo_service.h index a4eb6d98..b2210cd 100644 --- a/ios/chrome/browser/google/google_logo_service.h +++ b/ios/chrome/browser/google/google_logo_service.h
@@ -24,7 +24,7 @@ public: GoogleLogoService( TemplateURLService* template_url_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~GoogleLogoService() override;
diff --git a/ios/chrome/browser/google/google_logo_service.mm b/ios/chrome/browser/google/google_logo_service.mm index 58d6fe69..7c0b132 100644 --- a/ios/chrome/browser/google/google_logo_service.mm +++ b/ios/chrome/browser/google/google_logo_service.mm
@@ -36,7 +36,7 @@ GoogleLogoService::GoogleLogoService( TemplateURLService* template_url_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : LogoServiceImpl( DoodleDirectory(),
diff --git a/ios/chrome/browser/metrics/ios_profile_session_durations_service.h b/ios/chrome/browser/metrics/ios_profile_session_durations_service.h index eb276647..f4d1f09 100644 --- a/ios/chrome/browser/metrics/ios_profile_session_durations_service.h +++ b/ios/chrome/browser/metrics/ios_profile_session_durations_service.h
@@ -9,7 +9,7 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/sync/driver/sync_session_durations_metrics_recorder.h" -namespace identity { +namespace signin { class IdentityManager; } namespace syncer { @@ -23,9 +23,8 @@ // Callers must ensure that the parameters outlive this object. // If |sync_service| and |identity_manager| are null, then this object does // not monitor profile session durations. - IOSProfileSessionDurationsService( - syncer::SyncService* sync_service, - identity::IdentityManager* identity_manager); + IOSProfileSessionDurationsService(syncer::SyncService* sync_service, + signin::IdentityManager* identity_manager); ~IOSProfileSessionDurationsService() override; // KeyedService:
diff --git a/ios/chrome/browser/metrics/ios_profile_session_durations_service.mm b/ios/chrome/browser/metrics/ios_profile_session_durations_service.mm index 60c93a97..dcbdd9c 100644 --- a/ios/chrome/browser/metrics/ios_profile_session_durations_service.mm +++ b/ios/chrome/browser/metrics/ios_profile_session_durations_service.mm
@@ -10,7 +10,7 @@ IOSProfileSessionDurationsService::IOSProfileSessionDurationsService( syncer::SyncService* sync_service, - identity::IdentityManager* identity_manager) + signin::IdentityManager* identity_manager) : KeyedService() { if (!sync_service && !identity_manager) { // |sync_service| and |identity_maanger| may be null for testing.
diff --git a/ios/chrome/browser/metrics/ios_profile_session_durations_service_factory.mm b/ios/chrome/browser/metrics/ios_profile_session_durations_service_factory.mm index 1d9ec34..ade5f13 100644 --- a/ios/chrome/browser/metrics/ios_profile_session_durations_service_factory.mm +++ b/ios/chrome/browser/metrics/ios_profile_session_durations_service_factory.mm
@@ -52,7 +52,7 @@ ios::ChromeBrowserState::FromBrowserState(context); syncer::SyncService* sync_service = ProfileSyncServiceFactory::GetForBrowserState(browser_state); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browser_state); return std::make_unique<IOSProfileSessionDurationsService>(sync_service, identity_manager);
diff --git a/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.cc b/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.cc index 6c03c22d..f754379 100644 --- a/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.cc +++ b/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.cc
@@ -100,7 +100,7 @@ base::DefaultClock::GetInstance()); // Create the ContentSuggestionsService. - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(chrome_browser_state); HistoryService* history_service = ios::HistoryServiceFactory::GetForBrowserState( @@ -122,7 +122,7 @@ ios::ChromeBrowserState* chrome_browser_state = ios::ChromeBrowserState::FromBrowserState(browser_state); PrefService* prefs = chrome_browser_state->GetPrefs(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(chrome_browser_state); scoped_refptr<net::URLRequestContextGetter> request_context = browser_state->GetRequestContext();
diff --git a/ios/chrome/browser/passwords/BUILD.gn b/ios/chrome/browser/passwords/BUILD.gn index e77cdd1..98b80b4 100644 --- a/ios/chrome/browser/passwords/BUILD.gn +++ b/ios/chrome/browser/passwords/BUILD.gn
@@ -59,7 +59,6 @@ "//components/password_manager/ios", "//components/prefs", "//components/security_state/core", - "//components/signin/core/browser", "//components/strings", "//components/sync", "//components/translate/core/browser:browser",
diff --git a/ios/chrome/browser/passwords/credential_manager.h b/ios/chrome/browser/passwords/credential_manager.h index d98ab90..d5db2a0c 100644 --- a/ios/chrome/browser/passwords/credential_manager.h +++ b/ios/chrome/browser/passwords/credential_manager.h
@@ -6,10 +6,10 @@ #define IOS_CHROME_BROWSER_PASSWORDS_CREDENTIAL_MANAGER_H_ #include "components/password_manager/core/browser/credential_manager_impl.h" +#import "ios/web/public/web_state/web_state.h" namespace web { class WebFrame; -class WebState; } // Owned by PasswordController. It is responsible for registering and handling @@ -49,6 +49,9 @@ // Passed as callback to CredentialManagerImpl::Store. void SendStoreResponse(int promise_id); + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + password_manager::CredentialManagerImpl impl_; web::WebState* web_state_;
diff --git a/ios/chrome/browser/passwords/credential_manager.mm b/ios/chrome/browser/passwords/credential_manager.mm index 06e4b51..edeb3b44 100644 --- a/ios/chrome/browser/passwords/credential_manager.mm +++ b/ios/chrome/browser/passwords/credential_manager.mm
@@ -33,15 +33,13 @@ password_manager::PasswordManagerClient* client, web::WebState* web_state) : impl_(client), web_state_(web_state) { - web_state_->AddScriptCommandCallback( + subscription_ = web_state_->AddScriptCommandCallback( base::Bind(&CredentialManager::HandleScriptCommand, base::Unretained(this)), kCommandPrefix); } -CredentialManager::~CredentialManager() { - web_state_->RemoveScriptCommandCallback(kCommandPrefix); -} +CredentialManager::~CredentialManager() {} void CredentialManager::HandleScriptCommand(const base::DictionaryValue& json, const GURL& origin_url,
diff --git a/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm b/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm index cf3e51a..88a207b 100644 --- a/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm +++ b/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm
@@ -53,7 +53,7 @@ return ProfileSyncServiceFactory::GetForBrowserStateIfExists(browser_state); } -const identity::IdentityManager* GetIdentityManager( +const signin::IdentityManager* GetIdentityManager( ios::ChromeBrowserState* browser_state) { return IdentityManagerFactory::GetForBrowserState(browser_state); }
diff --git a/ios/chrome/browser/passwords/password_controller.mm b/ios/chrome/browser/passwords/password_controller.mm index 4ecc3bb..fddf59e6 100644 --- a/ios/chrome/browser/passwords/password_controller.mm +++ b/ios/chrome/browser/passwords/password_controller.mm
@@ -63,7 +63,6 @@ #import "ios/web/common/origin_util.h" #import "ios/web/public/deprecated/crw_js_injection_receiver.h" #include "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #include "ios/web/public/url_scheme_util.h" #import "ios/web/public/web_state/web_state.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/ios/chrome/browser/payments/BUILD.gn b/ios/chrome/browser/payments/BUILD.gn index b6aedec6..e5fa2cc 100644 --- a/ios/chrome/browser/payments/BUILD.gn +++ b/ios/chrome/browser/payments/BUILD.gn
@@ -40,7 +40,6 @@ "//components/payments/mojom", "//components/prefs", "//components/security_state/core", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//components/strings:components_strings_grit", "//ios/chrome/browser", @@ -117,7 +116,6 @@ "//components/payments/core", "//components/payments/core:test_support", "//components/prefs", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//ios/chrome/browser/browser_state:test_support", "//ios/web",
diff --git a/ios/chrome/browser/payments/payment_request.mm b/ios/chrome/browser/payments/payment_request.mm index 03edef6..bf852bb7 100644 --- a/ios/chrome/browser/payments/payment_request.mm +++ b/ios/chrome/browser/payments/payment_request.mm
@@ -175,7 +175,7 @@ } std::string PaymentRequest::GetAuthenticatedEmail() const { - const identity::IdentityManager* identity_manager = + const signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserStateIfExists(browser_state_); if (identity_manager && identity_manager->HasPrimaryAccount()) return identity_manager->GetPrimaryAccountInfo().email;
diff --git a/ios/chrome/browser/prefs/BUILD.gn b/ios/chrome/browser/prefs/BUILD.gn index fa10ba8..b997018 100644 --- a/ios/chrome/browser/prefs/BUILD.gn +++ b/ios/chrome/browser/prefs/BUILD.gn
@@ -52,7 +52,6 @@ "//components/rappor", "//components/search_engines", "//components/sessions", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//components/strings", "//components/sync",
diff --git a/ios/chrome/browser/prefs/browser_prefs.mm b/ios/chrome/browser/prefs/browser_prefs.mm index 7dd017b..1e7ef8c 100644 --- a/ios/chrome/browser/prefs/browser_prefs.mm +++ b/ios/chrome/browser/prefs/browser_prefs.mm
@@ -75,7 +75,7 @@ BrowserStateInfoCache::RegisterPrefs(registry); flags_ui::PrefServiceFlagsStorage::RegisterPrefs(registry); gcm::GCMChannelStatusSyncer::RegisterPrefs(registry); - identity::IdentityManager::RegisterLocalStatePrefs(registry); + signin::IdentityManager::RegisterLocalStatePrefs(registry); IOSChromeMetricsServiceClient::RegisterPrefs(registry); network_time::NetworkTimeTracker::RegisterPrefs(registry); ios::NotificationPromo::RegisterPrefs(registry);
diff --git a/ios/chrome/browser/search_engines/search_engine_js_unittest.mm b/ios/chrome/browser/search_engines/search_engine_js_unittest.mm index b67a9aff..60906562 100644 --- a/ios/chrome/browser/search_engines/search_engine_js_unittest.mm +++ b/ios/chrome/browser/search_engines/search_engine_js_unittest.mm
@@ -61,14 +61,13 @@ void SetUp() override { WebTestWithWebState::SetUp(); - web_state()->AddScriptCommandCallback( + subscription_ = web_state()->AddScriptCommandCallback( base::BindRepeating(&SearchEngineJsTest::OnMessageFromJavaScript, base::Unretained(this)), kCommandPrefix); } void TearDown() override { - web_state()->RemoveScriptCommandCallback(kCommandPrefix); WebTestWithWebState::TearDown(); } @@ -83,6 +82,9 @@ base::Value message_; bool message_received_ = false; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + DISALLOW_COPY_AND_ASSIGN(SearchEngineJsTest); };
diff --git a/ios/chrome/browser/search_engines/search_engine_tab_helper.h b/ios/chrome/browser/search_engines/search_engine_tab_helper.h index 94fc623..f279c18 100644 --- a/ios/chrome/browser/search_engines/search_engine_tab_helper.h +++ b/ios/chrome/browser/search_engines/search_engine_tab_helper.h
@@ -85,6 +85,9 @@ // will be set to empty GURL again. GURL searchable_url_; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + WEB_STATE_USER_DATA_KEY_DECL(); DISALLOW_COPY_AND_ASSIGN(SearchEngineTabHelper);
diff --git a/ios/chrome/browser/search_engines/search_engine_tab_helper.mm b/ios/chrome/browser/search_engines/search_engine_tab_helper.mm index 2b5d19bf..74962f97 100644 --- a/ios/chrome/browser/search_engines/search_engine_tab_helper.mm +++ b/ios/chrome/browser/search_engines/search_engine_tab_helper.mm
@@ -77,7 +77,7 @@ SearchEngineTabHelper::SearchEngineTabHelper(web::WebState* web_state) : web_state_(web_state) { web_state->AddObserver(this); - web_state->AddScriptCommandCallback( + subscription_ = web_state->AddScriptCommandCallback( base::BindRepeating(&SearchEngineTabHelper::OnJsMessage, base::Unretained(this)), kCommandPrefix); @@ -87,7 +87,6 @@ } void SearchEngineTabHelper::WebStateDestroyed(web::WebState* web_state) { - web_state->RemoveScriptCommandCallback(kCommandPrefix); web_state->RemoveObserver(this); web_state_ = nullptr; favicon_driver_observer_.RemoveAll();
diff --git a/ios/chrome/browser/signin/BUILD.gn b/ios/chrome/browser/signin/BUILD.gn index cf1c3b2..61bff4e 100644 --- a/ios/chrome/browser/signin/BUILD.gn +++ b/ios/chrome/browser/signin/BUILD.gn
@@ -63,7 +63,6 @@ "//components/pref_registry", "//components/prefs", "//components/signin/core/browser", - "//components/signin/internal/identity_manager", # TODO(crbug.com/974198): remove once closed "//components/signin/ios/browser", "//components/signin/ios/browser:active_state_manager", "//components/signin/public/identity_manager", @@ -118,8 +117,7 @@ "//base", "//components/image_fetcher/core:test_support", "//components/keyed_service/core", - "//components/signin/core/browser", - "//components/signin/ios/browser", + "//components/signin/public/base", "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//ios/chrome/browser/browser_state", @@ -147,8 +145,6 @@ "//base", "//components/pref_registry", "//components/prefs", - "//components/signin/core/browser", - "//components/signin/ios/browser", "//components/signin/public/base:test_support", "//components/signin/public/identity_manager", "//components/signin/public/identity_manager:test_support",
diff --git a/ios/chrome/browser/signin/DEPS b/ios/chrome/browser/signin/DEPS index 19de416..a5ba9e61 100644 --- a/ios/chrome/browser/signin/DEPS +++ b/ios/chrome/browser/signin/DEPS
@@ -1,21 +1,4 @@ specific_include_rules = { - # IdentityManagerFactory creates IdentityManager instances from internal - # dependencies. TODO(crbug.com/974198): Internalize this building and - # eliminate the need for these inclusions. - "identity_manager_factory.cc": [ - "+components/signin/internal/identity_manager/account_fetcher_service.h", - "+components/signin/internal/identity_manager/account_tracker_service.h", - "+components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h", - "+components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h", - "+components/signin/internal/identity_manager/diagnostics_provider_impl.h", - "+components/signin/internal/identity_manager/gaia_cookie_manager_service.h", - "+components/signin/internal/identity_manager/primary_account_mutator_impl.h", - "+components/signin/internal/identity_manager/primary_account_manager.h", - "+components/signin/internal/identity_manager/primary_account_policy_manager_impl.h", - "+components/signin/internal/identity_manager/profile_oauth2_token_service.h", - "+components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_ios.h", - ], - # The dependence on the Identity Service implementation should be used *only* # for Identity Service creation. "identity_service_creator.cc": [
diff --git a/ios/chrome/browser/signin/authentication_service.h b/ios/chrome/browser/signin/authentication_service.h index 566595e9..2628a49 100644 --- a/ios/chrome/browser/signin/authentication_service.h +++ b/ios/chrome/browser/signin/authentication_service.h
@@ -30,12 +30,12 @@ // AuthenticationService is the Chrome interface to the iOS shared // authentication library. class AuthenticationService : public KeyedService, - public identity::IdentityManager::Observer, + public signin::IdentityManager::Observer, public ios::ChromeIdentityService::Observer { public: AuthenticationService(PrefService* pref_service, SyncSetupService* sync_setup_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, syncer::SyncService* sync_service); ~AuthenticationService() override; @@ -176,7 +176,7 @@ // authenticated identity was removed. void ComputeHaveAccountsChanged(bool should_prompt); - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnEndBatchOfRefreshTokenStateChanges() override; // ChromeIdentityServiceObserver implementation. @@ -193,7 +193,7 @@ // Pointer to the KeyedServices used by AuthenticationService. PrefService* pref_service_ = nullptr; SyncSetupService* sync_setup_service_ = nullptr; - identity::IdentityManager* identity_manager_ = nullptr; + signin::IdentityManager* identity_manager_ = nullptr; syncer::SyncService* sync_service_ = nullptr; // Whether Initialized has been called. @@ -215,7 +215,7 @@ ios::ChromeIdentityService::Observer> identity_service_observer_; - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; base::WeakPtrFactory<AuthenticationService> weak_pointer_factory_;
diff --git a/ios/chrome/browser/signin/authentication_service.mm b/ios/chrome/browser/signin/authentication_service.mm index 21b89f7..b6a4d02 100644 --- a/ios/chrome/browser/signin/authentication_service.mm +++ b/ios/chrome/browser/signin/authentication_service.mm
@@ -55,9 +55,8 @@ constexpr char kFakeAccountIdForRemovedAccount[] = "0000000000000"; // Returns the account id associated with |identity|. -std::string ChromeIdentityToAccountID( - identity::IdentityManager* identity_manager, - ChromeIdentity* identity) { +std::string ChromeIdentityToAccountID(signin::IdentityManager* identity_manager, + ChromeIdentity* identity) { std::string gaia_id = base::SysNSStringToUTF8([identity gaiaID]); auto maybe_account = identity_manager->FindAccountInfoForAccountWithRefreshTokenByGaiaId( @@ -72,7 +71,7 @@ AuthenticationService::AuthenticationService( PrefService* pref_service, SyncSetupService* sync_setup_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, syncer::SyncService* sync_service) : pref_service_(pref_service), sync_setup_service_(sync_setup_service), @@ -166,7 +165,7 @@ swap(cached_mdm_infos_, cached_mdm_infos); if (!cached_mdm_infos.empty()) { - identity::DeviceAccountsSynchronizer* device_accounts_synchronizer = + signin::DeviceAccountsSynchronizer* device_accounts_synchronizer = identity_manager_->GetDeviceAccountsSynchronizer(); for (const auto& cached_mdm_info : cached_mdm_infos) { device_accounts_synchronizer->ReloadAccountFromSystem( @@ -224,11 +223,10 @@ void AuthenticationService::MigrateAccountsStoredInPrefsIfNeeded() { if (identity_manager_->GetAccountIdMigrationState() == - identity::IdentityManager::AccountIdMigrationState:: - MIGRATION_NOT_STARTED) { + signin::IdentityManager::AccountIdMigrationState::MIGRATION_NOT_STARTED) { return; } - DCHECK_EQ(identity::IdentityManager::AccountIdMigrationState::MIGRATION_DONE, + DCHECK_EQ(signin::IdentityManager::AccountIdMigrationState::MIGRATION_DONE, identity_manager_->GetAccountIdMigrationState()); if (pref_service_->GetBoolean(prefs::kSigninLastAccountsMigrated)) { // Already migrated. @@ -362,7 +360,7 @@ // GetPrimaryAccountMutator() returns nullptr on ChromeOS only. DCHECK(account_mutator); account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signout_source, signin_metrics::SignoutDelete::IGNORE_METRIC); breakpad_helper::SetCurrentlySignedIn(false); cached_mdm_infos_.clear();
diff --git a/ios/chrome/browser/signin/authentication_service_fake.h b/ios/chrome/browser/signin/authentication_service_fake.h index 73247a0..f6cf90e 100644 --- a/ios/chrome/browser/signin/authentication_service_fake.h +++ b/ios/chrome/browser/signin/authentication_service_fake.h
@@ -10,7 +10,7 @@ #import "ios/chrome/browser/signin/authentication_service.h" #import "ios/public/provider/chrome/browser/signin/chrome_identity.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -42,7 +42,7 @@ private: AuthenticationServiceFake(PrefService* pref_service, SyncSetupService* sync_setup_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, syncer::SyncService* sync_service); __strong ChromeIdentity* authenticated_identity_;
diff --git a/ios/chrome/browser/signin/authentication_service_fake.mm b/ios/chrome/browser/signin/authentication_service_fake.mm index 58ee9b3..cdf7324 100644 --- a/ios/chrome/browser/signin/authentication_service_fake.mm +++ b/ios/chrome/browser/signin/authentication_service_fake.mm
@@ -23,7 +23,7 @@ AuthenticationServiceFake::AuthenticationServiceFake( PrefService* pref_service, SyncSetupService* sync_setup_service, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, syncer::SyncService* sync_service) : AuthenticationService(pref_service, sync_setup_service,
diff --git a/ios/chrome/browser/signin/authentication_service_unittest.mm b/ios/chrome/browser/signin/authentication_service_unittest.mm index 646c27c..563f8b5 100644 --- a/ios/chrome/browser/signin/authentication_service_unittest.mm +++ b/ios/chrome/browser/signin/authentication_service_unittest.mm
@@ -151,7 +151,7 @@ browser_state_.get()); } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return IdentityManagerFactory::GetForBrowserState(browser_state_.get()); } @@ -330,16 +330,16 @@ ASSERT_EQ(2u, accounts.size()); switch (identity_manager()->GetAccountIdMigrationState()) { - case identity::IdentityManager::MIGRATION_NOT_STARTED: + case signin::IdentityManager::MIGRATION_NOT_STARTED: EXPECT_EQ("foo2@foo.com", accounts[0]); EXPECT_EQ("foo@foo.com", accounts[1]); break; - case identity::IdentityManager::MIGRATION_IN_PROGRESS: - case identity::IdentityManager::MIGRATION_DONE: + case signin::IdentityManager::MIGRATION_IN_PROGRESS: + case signin::IdentityManager::MIGRATION_DONE: EXPECT_EQ("foo2ID", accounts[0]); EXPECT_EQ("fooID", accounts[1]); break; - case identity::IdentityManager::NUM_MIGRATION_STATES: + case signin::IdentityManager::NUM_MIGRATION_STATES: FAIL() << "NUM_MIGRATION_STATES is not a real migration state."; break; } @@ -363,16 +363,16 @@ ASSERT_EQ(2u, accounts.size()); switch (identity_manager()->GetAccountIdMigrationState()) { - case identity::IdentityManager::MIGRATION_NOT_STARTED: + case signin::IdentityManager::MIGRATION_NOT_STARTED: EXPECT_EQ("foo2@foo.com", accounts[0].account_id); EXPECT_EQ("foo@foo.com", accounts[1].account_id); break; - case identity::IdentityManager::MIGRATION_IN_PROGRESS: - case identity::IdentityManager::MIGRATION_DONE: + case signin::IdentityManager::MIGRATION_IN_PROGRESS: + case signin::IdentityManager::MIGRATION_DONE: EXPECT_EQ("foo2ID", accounts[0].account_id); EXPECT_EQ("fooID", accounts[1].account_id); break; - case identity::IdentityManager::NUM_MIGRATION_STATES: + case signin::IdentityManager::NUM_MIGRATION_STATES: FAIL() << "NUM_MIGRATION_STATES is not a real migration state."; break; } @@ -388,18 +388,18 @@ std::sort(accounts.begin(), accounts.end(), account_compare_func); ASSERT_EQ(3u, accounts.size()); switch (identity_manager()->GetAccountIdMigrationState()) { - case identity::IdentityManager::MIGRATION_NOT_STARTED: + case signin::IdentityManager::MIGRATION_NOT_STARTED: EXPECT_EQ("foo2@foo.com", accounts[0].account_id); EXPECT_EQ("foo3@foo.com", accounts[1].account_id); EXPECT_EQ("foo@foo.com", accounts[2].account_id); break; - case identity::IdentityManager::MIGRATION_IN_PROGRESS: - case identity::IdentityManager::MIGRATION_DONE: + case signin::IdentityManager::MIGRATION_IN_PROGRESS: + case signin::IdentityManager::MIGRATION_DONE: EXPECT_EQ("foo2ID", accounts[0].account_id); EXPECT_EQ("foo3ID", accounts[1].account_id); EXPECT_EQ("fooID", accounts[2].account_id); break; - case identity::IdentityManager::NUM_MIGRATION_STATES: + case signin::IdentityManager::NUM_MIGRATION_STATES: FAIL() << "NUM_MIGRATION_STATES is not a real migration state."; break; } @@ -475,7 +475,7 @@ TEST_F(AuthenticationServiceTest, MigrateAccountsStoredInPref) { if (identity_manager()->GetAccountIdMigrationState() == - identity::IdentityManager::MIGRATION_NOT_STARTED) { + signin::IdentityManager::MIGRATION_NOT_STARTED) { // The account tracker is not migratable. Skip the test as the accounts // cannot be migrated. return; @@ -484,7 +484,7 @@ // Force the migration state to MIGRATION_NOT_STARTED before signing in. browser_state_->GetPrefs()->SetInteger( prefs::kAccountIdMigrationState, - identity::IdentityManager::MIGRATION_NOT_STARTED); + signin::IdentityManager::MIGRATION_NOT_STARTED); browser_state_->GetPrefs()->SetBoolean(prefs::kSigninLastAccountsMigrated, false); @@ -498,8 +498,7 @@ // Migrate the accounts. browser_state_->GetPrefs()->SetInteger( - prefs::kAccountIdMigrationState, - identity::IdentityManager::MIGRATION_DONE); + prefs::kAccountIdMigrationState, signin::IdentityManager::MIGRATION_DONE); // Reload all credentials to find account info with the refresh token. // If it tries to find refresh token with gaia ID after @@ -535,14 +534,14 @@ SetCachedMDMInfo(identity(0), user_info); GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager(), base::SysNSStringToUTF8([identity(0) gaiaID]), error); // MDM error for |identity_| is being cleared and the error state of refresh // token will be updated. { bool notification_received = false; - identity::TestIdentityManagerObserver observer(identity_manager()); + signin::TestIdentityManagerObserver observer(identity_manager()); observer.SetOnErrorStateOfRefreshTokenUpdatedCallback( base::BindLambdaForTesting([&]() { notification_received = true; })); @@ -557,7 +556,7 @@ // MDM error has already been cleared, no notification will be sent. { bool notification_received = false; - identity::TestIdentityManagerObserver observer(identity_manager()); + signin::TestIdentityManagerObserver observer(identity_manager()); observer.SetOnErrorStateOfRefreshTokenUpdatedCallback( base::BindLambdaForTesting([&]() { notification_received = true; })); @@ -588,7 +587,7 @@ authentication_service()->SignIn(identity(0)); GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager(), base::SysNSStringToUTF8([identity(0) gaiaID]), error); NSDictionary* user_info1 = @{ @"foo" : @1 }; @@ -624,7 +623,7 @@ authentication_service()->SignIn(identity(0)); GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager(), base::SysNSStringToUTF8([identity(0) gaiaID]), error); NSDictionary* user_info1 = @{ @"foo" : @1 }; @@ -682,7 +681,7 @@ authentication_service()->SignIn(identity(0)); GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager(), base::SysNSStringToUTF8([identity(0) gaiaID]), error); NSDictionary* user_info = [NSDictionary dictionary];
diff --git a/ios/chrome/browser/signin/identity_manager_factory.cc b/ios/chrome/browser/signin/identity_manager_factory.cc index faa8314..9021ebe 100644 --- a/ios/chrome/browser/signin/identity_manager_factory.cc +++ b/ios/chrome/browser/signin/identity_manager_factory.cc
@@ -23,7 +23,7 @@ void IdentityManagerFactory::RegisterBrowserStatePrefs( user_prefs::PrefRegistrySyncable* registry) { - identity::IdentityManager::RegisterProfilePrefs(registry); + signin::IdentityManager::RegisterProfilePrefs(registry); } IdentityManagerFactory::IdentityManagerFactory() @@ -36,16 +36,16 @@ IdentityManagerFactory::~IdentityManagerFactory() {} // static -identity::IdentityManager* IdentityManagerFactory::GetForBrowserState( +signin::IdentityManager* IdentityManagerFactory::GetForBrowserState( ios::ChromeBrowserState* browser_state) { - return static_cast<identity::IdentityManager*>( + return static_cast<signin::IdentityManager*>( GetInstance()->GetServiceForBrowserState(browser_state, true)); } // static -identity::IdentityManager* IdentityManagerFactory::GetForBrowserStateIfExists( +signin::IdentityManager* IdentityManagerFactory::GetForBrowserStateIfExists( ios::ChromeBrowserState* browser_state) { - return static_cast<identity::IdentityManager*>( + return static_cast<signin::IdentityManager*>( GetInstance()->GetServiceForBrowserState(browser_state, false)); } @@ -70,7 +70,7 @@ ios::ChromeBrowserState* browser_state = ios::ChromeBrowserState::FromBrowserState(context); - identity::IdentityManagerBuildParams params; + signin::IdentityManagerBuildParams params; params.account_consistency = signin::AccountConsistencyMethod::kMirror; params.device_accounts_provider = std::make_unique<DeviceAccountsProviderImpl>(); @@ -80,8 +80,8 @@ params.profile_path = base::FilePath(); params.signin_client = SigninClientFactory::GetForBrowserState(browser_state); - std::unique_ptr<identity::IdentityManager> identity_manager = - identity::BuildIdentityManager(¶ms); + std::unique_ptr<signin::IdentityManager> identity_manager = + signin::BuildIdentityManager(¶ms); for (auto& observer : observer_list_) observer.IdentityManagerCreated(identity_manager.get()); @@ -90,7 +90,7 @@ } void IdentityManagerFactory::BrowserStateShutdown(web::BrowserState* context) { - auto* identity_manager = static_cast<identity::IdentityManager*>( + auto* identity_manager = static_cast<signin::IdentityManager*>( GetServiceForBrowserState(context, false)); if (identity_manager) { for (auto& observer : observer_list_)
diff --git a/ios/chrome/browser/signin/identity_manager_factory.h b/ios/chrome/browser/signin/identity_manager_factory.h index 9952877..d064a67 100644 --- a/ios/chrome/browser/signin/identity_manager_factory.h +++ b/ios/chrome/browser/signin/identity_manager_factory.h
@@ -12,7 +12,7 @@ class IdentityManagerFactoryObserver; -namespace identity { +namespace signin { class IdentityManager; } @@ -24,9 +24,9 @@ // BrowserStates. class IdentityManagerFactory : public BrowserStateKeyedServiceFactory { public: - static identity::IdentityManager* GetForBrowserState( + static signin::IdentityManager* GetForBrowserState( ios::ChromeBrowserState* browser_state); - static identity::IdentityManager* GetForBrowserStateIfExists( + static signin::IdentityManager* GetForBrowserStateIfExists( ios::ChromeBrowserState* browser_state); // Returns an instance of the IdentityManagerFactory singleton.
diff --git a/ios/chrome/browser/signin/identity_manager_factory_observer.h b/ios/chrome/browser/signin/identity_manager_factory_observer.h index 1d5d7ec..98d175d9 100644 --- a/ios/chrome/browser/signin/identity_manager_factory_observer.h +++ b/ios/chrome/browser/signin/identity_manager_factory_observer.h
@@ -8,7 +8,7 @@ #include "base/macros.h" #include "base/observer_list_types.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -19,11 +19,11 @@ ~IdentityManagerFactoryObserver() override {} // Called when an IdentityManager instance is created. - virtual void IdentityManagerCreated(identity::IdentityManager* manager) {} + virtual void IdentityManagerCreated(signin::IdentityManager* manager) {} // Called when a IdentityManager instance is being shut down. Observers // of |manager| should remove themselves at this point. - virtual void IdentityManagerShutdown(identity::IdentityManager* manager) {} + virtual void IdentityManagerShutdown(signin::IdentityManager* manager) {} private: DISALLOW_COPY_AND_ASSIGN(IdentityManagerFactoryObserver);
diff --git a/ios/chrome/browser/signin/identity_service_creator.cc b/ios/chrome/browser/signin/identity_service_creator.cc index ba478cc..f75ce470 100644 --- a/ios/chrome/browser/signin/identity_service_creator.cc +++ b/ios/chrome/browser/signin/identity_service_creator.cc
@@ -12,7 +12,7 @@ std::unique_ptr<service_manager::Service> CreateIdentityService( ios::ChromeBrowserState* browser_state, service_manager::mojom::ServiceRequest request) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browser_state); return std::make_unique<identity::IdentityService>(identity_manager, std::move(request));
diff --git a/ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.cc b/ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.cc index a01e528a..2488199 100644 --- a/ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.cc +++ b/ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.cc
@@ -45,13 +45,13 @@ return accounts_status; } -std::vector<identity::IdentityManager*> +std::vector<signin::IdentityManager*> IOSChromeSigninStatusMetricsProviderDelegate:: GetIdentityManagersForAllAccounts() { - std::vector<identity::IdentityManager*> managers; + std::vector<signin::IdentityManager*> managers; for (ios::ChromeBrowserState* browser_state : GetLoadedChromeBrowserStates()) { - identity::IdentityManager* manager = + signin::IdentityManager* manager = IdentityManagerFactory::GetForBrowserStateIfExists(browser_state); if (manager) { managers.push_back(manager); @@ -62,12 +62,12 @@ } void IOSChromeSigninStatusMetricsProviderDelegate::IdentityManagerCreated( - identity::IdentityManager* manager) { + signin::IdentityManager* manager) { owner()->OnIdentityManagerCreated(manager); } void IOSChromeSigninStatusMetricsProviderDelegate::IdentityManagerShutdown( - identity::IdentityManager* manager) { + signin::IdentityManager* manager) { owner()->OnIdentityManagerShutdown(manager); }
diff --git a/ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.h b/ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.h index 37d4a98..905a189 100644 --- a/ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.h +++ b/ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.h
@@ -26,12 +26,12 @@ // SigninStatusMetricsProviderDelegate implementation. void Initialize() override; AccountsStatus GetStatusOfAllAccounts() override; - std::vector<identity::IdentityManager*> GetIdentityManagersForAllAccounts() + std::vector<signin::IdentityManager*> GetIdentityManagersForAllAccounts() override; // IdentityManagerFactoryObserver implementation. - void IdentityManagerCreated(identity::IdentityManager* manager) override; - void IdentityManagerShutdown(identity::IdentityManager* manager) override; + void IdentityManagerCreated(signin::IdentityManager* manager) override; + void IdentityManagerShutdown(signin::IdentityManager* manager) override; // Returns the loaded ChromeBrowserState instances. std::vector<ios::ChromeBrowserState*> GetLoadedChromeBrowserStates();
diff --git a/ios/chrome/browser/signin/signin_browser_state_info_updater.h b/ios/chrome/browser/signin/signin_browser_state_info_updater.h index 1571a5c..4552915 100644 --- a/ios/chrome/browser/signin/signin_browser_state_info_updater.h +++ b/ios/chrome/browser/signin/signin_browser_state_info_updater.h
@@ -15,12 +15,11 @@ // This class listens to various signin events and updates the signin-related // fields of BrowserStateInfoCache. -class SigninBrowserStateInfoUpdater - : public KeyedService, - public SigninErrorController::Observer, - public identity::IdentityManager::Observer { +class SigninBrowserStateInfoUpdater : public KeyedService, + public SigninErrorController::Observer, + public signin::IdentityManager::Observer { public: - SigninBrowserStateInfoUpdater(identity::IdentityManager* identity_manager, + SigninBrowserStateInfoUpdater(signin::IdentityManager* identity_manager, SigninErrorController* signin_error_controller, const base::FilePath& browser_state_path); @@ -42,10 +41,10 @@ void OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) override; - identity::IdentityManager* identity_manager_ = nullptr; + signin::IdentityManager* identity_manager_ = nullptr; SigninErrorController* signin_error_controller_ = nullptr; const base::FilePath browser_state_path_; - ScopedObserver<identity::IdentityManager, SigninBrowserStateInfoUpdater> + ScopedObserver<signin::IdentityManager, SigninBrowserStateInfoUpdater> identity_manager_observer_; ScopedObserver<SigninErrorController, SigninBrowserStateInfoUpdater> signin_error_controller_observer_;
diff --git a/ios/chrome/browser/signin/signin_browser_state_info_updater.mm b/ios/chrome/browser/signin/signin_browser_state_info_updater.mm index 1935bbd..dd3c97a1 100644 --- a/ios/chrome/browser/signin/signin_browser_state_info_updater.mm +++ b/ios/chrome/browser/signin/signin_browser_state_info_updater.mm
@@ -18,7 +18,7 @@ #include "ios/chrome/browser/browser_state/chrome_browser_state_manager.h" SigninBrowserStateInfoUpdater::SigninBrowserStateInfoUpdater( - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, SigninErrorController* signin_error_controller, const base::FilePath& browser_state_path) : identity_manager_(identity_manager),
diff --git a/ios/chrome/browser/signin/signin_browser_state_info_updater_unittest.mm b/ios/chrome/browser/signin/signin_browser_state_info_updater_unittest.mm index 1e803ea7..b20ea7f 100644 --- a/ios/chrome/browser/signin/signin_browser_state_info_updater_unittest.mm +++ b/ios/chrome/browser/signin/signin_browser_state_info_updater_unittest.mm
@@ -67,7 +67,7 @@ /*username=*/base::string16()); } - identity::IdentityTestEnvironment* identity_test_env() { + signin::IdentityTestEnvironment* identity_test_env() { return &identity_test_env_; } @@ -91,7 +91,7 @@ web::TestWebThreadBundle thread_bundle_; IOSChromeScopedTestingChromeBrowserStateManager scoped_browser_state_manager_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; SigninErrorController signin_error_controller_; SigninBrowserStateInfoUpdater signin_browser_state_info_updater_; };
diff --git a/ios/chrome/browser/suggestions/suggestions_service_factory.mm b/ios/chrome/browser/suggestions/suggestions_service_factory.mm index 9d107e10..d6be8c1c0 100644 --- a/ios/chrome/browser/suggestions/suggestions_service_factory.mm +++ b/ios/chrome/browser/suggestions/suggestions_service_factory.mm
@@ -59,7 +59,7 @@ web::BrowserState* context) const { ios::ChromeBrowserState* browser_state = ios::ChromeBrowserState::FromBrowserState(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browser_state); syncer::SyncService* sync_service = ProfileSyncServiceFactory::GetForBrowserState(browser_state);
diff --git a/ios/chrome/browser/sync/BUILD.gn b/ios/chrome/browser/sync/BUILD.gn index 3324031..7a7f797 100644 --- a/ios/chrome/browser/sync/BUILD.gn +++ b/ios/chrome/browser/sync/BUILD.gn
@@ -52,7 +52,7 @@ "//components/search_engines", "//components/send_tab_to_self", "//components/sessions", - "//components/signin/core/browser", + "//components/signin/public/base", "//components/sync", "//components/sync_device_info", "//components/sync_preferences",
diff --git a/ios/chrome/browser/system_flags.mm b/ios/chrome/browser/system_flags.mm index a9b452e..7bb4d91e 100644 --- a/ios/chrome/browser/system_flags.mm +++ b/ios/chrome/browser/system_flags.mm
@@ -20,7 +20,6 @@ #include "base/strings/sys_string_conversions.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/password_manager/core/common/password_manager_features.h" -#include "components/signin/public/base/signin_switches.h" #include "components/variations/variations_associated_data.h" #include "ios/chrome/browser/browsing_data/browsing_data_features.h" #include "ios/chrome/browser/chrome_switches.h"
diff --git a/ios/chrome/browser/translate/js_language_detection_manager_unittest.mm b/ios/chrome/browser/translate/js_language_detection_manager_unittest.mm index 272ccb7..33bd4d8 100644 --- a/ios/chrome/browser/translate/js_language_detection_manager_unittest.mm +++ b/ios/chrome/browser/translate/js_language_detection_manager_unittest.mm
@@ -264,10 +264,10 @@ auto callback = base::Bind( &JsLanguageDetectionManagerDetectLanguageTest::CommandReceived, base::Unretained(this)); - web_state()->AddScriptCommandCallback(callback, "languageDetection"); + subscription_ = + web_state()->AddScriptCommandCallback(callback, "languageDetection"); } void TearDown() override { - web_state()->RemoveScriptCommandCallback("languageDetection"); JsLanguageDetectionManagerTest::TearDown(); } // Called when "languageDetection" command is received. @@ -281,6 +281,9 @@ protected: // Received "languageDetection" commands. std::vector<std::unique_ptr<base::DictionaryValue>> commands_received_; + + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; }; // Tests if |__gCrWeb.languageDetection.detectLanguage| correctly informs the
diff --git a/ios/chrome/browser/ui/alert_view_controller/alert_view_controller.mm b/ios/chrome/browser/ui/alert_view_controller/alert_view_controller.mm index f941af9..9aaad54 100644 --- a/ios/chrome/browser/ui/alert_view_controller/alert_view_controller.mm +++ b/ios/chrome/browser/ui/alert_view_controller/alert_view_controller.mm
@@ -281,15 +281,16 @@ // fields. UIView* stackHolder = [[UIView alloc] init]; stackHolder.layer.cornerRadius = kTextFieldCornerRadius; - if (@available(iOS 13, *)) { + stackHolder.layer.borderColor = UIColor.cr_separatorColor.CGColor; #if defined(__IPHONE_13_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0) + if (@available(iOS 13, *)) { + // Use performAsCurrentTraitCollection to get the correct CGColor for the + // given dynamic color and current userInterfaceStyle. [self.traitCollection performAsCurrentTraitCollection:^{ stackHolder.layer.borderColor = UIColor.cr_separatorColor.CGColor; }]; -#endif - } else { - stackHolder.layer.borderColor = UIColor.cr_separatorColor.CGColor; } +#endif stackHolder.layer.borderWidth = 1.0 / [UIScreen mainScreen].scale; stackHolder.clipsToBounds = YES; stackHolder.backgroundColor = UIColor.cr_secondarySystemBackgroundColor;
diff --git a/ios/chrome/browser/ui/authentication/BUILD.gn b/ios/chrome/browser/ui/authentication/BUILD.gn index 2b86394..27e9d8a9 100644 --- a/ios/chrome/browser/ui/authentication/BUILD.gn +++ b/ios/chrome/browser/ui/authentication/BUILD.gn
@@ -38,8 +38,7 @@ "//components/google/core/browser", "//components/infobars/core", "//components/prefs", - "//components/signin/core/browser", - "//components/signin/ios/browser", + "//components/signin/public/base", "//components/signin/public/identity_manager", "//components/signin/public/identity_manager/objc", "//components/strings", @@ -114,7 +113,7 @@ "//components/consent_auditor", "//components/consent_auditor:test_support", "//components/pref_registry", - "//components/signin/core/browser:browser", + "//components/signin/public/base", "//components/signin/public/identity_manager", "//components/sync_preferences", "//components/sync_preferences:test_support", @@ -161,8 +160,6 @@ deps = [ ":authentication", "unified_consent", - "//components/signin/core/browser", - "//components/signin/public/base", "//components/signin/public/identity_manager", "//components/unified_consent", "//ios/chrome/app/strings:ios_strings_grit",
diff --git a/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm b/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm index bc4f47a..4817761f 100644 --- a/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm +++ b/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm
@@ -256,7 +256,7 @@ if (AuthenticationServiceFactory::GetForBrowserState(browserState) ->IsAuthenticatedIdentityManaged()) { - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browserState); base::Optional<AccountInfo> primary_account_info = identity_manager->FindExtendedAccountInfoForAccount(
diff --git a/ios/chrome/browser/ui/authentication/cells/BUILD.gn b/ios/chrome/browser/ui/authentication/cells/BUILD.gn index d42ce9a..b3a7f0d 100644 --- a/ios/chrome/browser/ui/authentication/cells/BUILD.gn +++ b/ios/chrome/browser/ui/authentication/cells/BUILD.gn
@@ -24,7 +24,6 @@ ] deps = [ "//base", - "//components/signin/core/browser", "//components/unified_consent", "//ios/chrome/app/strings", "//ios/chrome/browser", @@ -59,7 +58,6 @@ "//components/consent_auditor", "//components/consent_auditor:test_support", "//components/pref_registry", - "//components/signin/core/browser:browser", "//components/sync_preferences", "//components/sync_preferences:test_support", "//components/unified_consent",
diff --git a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h index 8ddd260..531cbf66 100644 --- a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h +++ b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h
@@ -7,8 +7,6 @@ #import <UIKit/UIKit.h> -#include "components/signin/public/base/signin_metrics.h" - @protocol SigninPromoViewDelegate; typedef NS_ENUM(NSInteger, SigninPromoViewMode) {
diff --git a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.mm b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.mm index df194c5f..10114d2 100644 --- a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.mm +++ b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.mm
@@ -6,6 +6,7 @@ #include "base/logging.h" #include "base/mac/foundation_util.h" +#include "components/signin/public/base/signin_metrics.h" #import "ios/chrome/browser/ui/authentication/cells/signin_promo_view_delegate.h" #import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h"
diff --git a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.h b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.h index 18a38849..3f0c19b 100644 --- a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.h +++ b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.h
@@ -11,7 +11,6 @@ #include "base/auto_reset.h" #include "base/timer/timer.h" -#include "components/signin/public/base/signin_metrics.h" #import "ios/chrome/browser/signin/constants.h" #include "ios/chrome/browser/ui/authentication/signin_confirmation_view_controller.h" @@ -23,6 +22,11 @@ class ChromeBrowserState; } // namespace ios +namespace signin_metrics { +enum class AccessPoint; +enum class PromoAction; +} + using TimerGeneratorBlock = std::unique_ptr<base::OneShotTimer> (^)(); @protocol ChromeSigninViewControllerDelegate<NSObject>
diff --git a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller_unittest.mm b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller_unittest.mm index 9bd81cf..0fa472e 100644 --- a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller_unittest.mm
@@ -371,7 +371,7 @@ UIWindow* window_; ChromeSigninViewController* vc_; consent_auditor::FakeConsentAuditor* fake_consent_auditor_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; base::MockOneShotTimer* mock_timer_ptr_ = nullptr; FakeChromeSigninViewControllerDelegate* vc_delegate_; };
diff --git a/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm b/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm index 76aef036..d8ced07f 100644 --- a/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm +++ b/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm
@@ -113,7 +113,7 @@ NSMutableDictionary<NSString*, CollectionViewItem*>* mutableIdentityMap = [[NSMutableDictionary alloc] init]; - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(_browserState); for (const auto& account : identityManager->GetAccountsWithRefreshTokens()) { ChromeIdentity* identity = ios::GetChromeBrowserProvider() @@ -180,7 +180,7 @@ @interface SignedInAccountsViewController () < IdentityManagerObserverBridgeDelegate> { ios::ChromeBrowserState* _browserState; // Weak. - std::unique_ptr<identity::IdentityManagerObserverBridge> + std::unique_ptr<signin::IdentityManagerObserverBridge> _identityManagerObserver; MDCDialogTransitionController* _transitionController; @@ -217,7 +217,7 @@ _browserState = browserState; _dispatcher = dispatcher; _identityManagerObserver = - std::make_unique<identity::IdentityManagerObserverBridge>( + std::make_unique<signin::IdentityManagerObserverBridge>( IdentityManagerFactory::GetForBrowserState(_browserState), self); _transitionController = [[MDCDialogTransitionController alloc] init]; self.modalPresentationStyle = UIModalPresentationCustom; @@ -246,7 +246,7 @@ CGFloat width = std::min( kDialogMaxWidth, self.presentingViewController.view.bounds.size.width - 2 * kMDCMinHorizontalPadding); - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(_browserState); int shownAccounts = std::min(kMaxShownAccounts, @@ -389,7 +389,7 @@ #pragma mark IdentityManagerObserverBridgeDelegate - (void)onEndBatchOfRefreshTokenStateChanges { - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(_browserState); if (identityManager->GetAccountsWithRefreshTokens().empty()) { [self dismissWithCompletion:nil];
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h index 3742de9f..0d57d9e9 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h
@@ -15,6 +15,10 @@ @class SigninPromoViewConfigurator; @protocol SigninPromoViewConsumer; +namespace signin_metrics { +enum class AccessPoint; +} + namespace ios { class ChromeBrowserState;
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm index 8cb9220..20373a2 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator_unittest.mm
@@ -6,6 +6,7 @@ #include "base/run_loop.h" #import "base/test/ios/wait_util.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/unified_consent/feature.h" #import "ios/chrome/browser/ui/authentication/cells/signin_promo_view.h" #import "ios/chrome/browser/ui/authentication/cells/signin_promo_view_configurator.h"
diff --git a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h index 8498897f..9702e16 100644 --- a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h +++ b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h
@@ -49,7 +49,7 @@ AutocompleteHistoryManager* GetAutocompleteHistoryManager() override; PrefService* GetPrefs() override; syncer::SyncService* GetSyncService() override; - identity::IdentityManager* GetIdentityManager() override; + signin::IdentityManager* GetIdentityManager() override; FormDataImporter* GetFormDataImporter() override; payments::PaymentsClient* GetPaymentsClient() override; StrikeDatabase* GetStrikeDatabase() override; @@ -126,7 +126,7 @@ ios::ChromeBrowserState* browser_state_; web::WebState* web_state_; __weak id<AutofillClientIOSBridge> bridge_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; std::unique_ptr<payments::PaymentsClient> payments_client_; std::unique_ptr<FormDataImporter> form_data_importer_; scoped_refptr<AutofillWebDataService> autofill_web_data_service_;
diff --git a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm index ef7d42a..39d3da7d 100644 --- a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm +++ b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm
@@ -124,7 +124,7 @@ return sync_service_; } -identity::IdentityManager* ChromeAutofillClientIOS::GetIdentityManager() { +signin::IdentityManager* ChromeAutofillClientIOS::GetIdentityManager() { return identity_manager_; }
diff --git a/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.mm b/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.mm index 8b93e34..4ad983d 100644 --- a/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.mm +++ b/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.mm
@@ -143,7 +143,7 @@ _JSSuggestionManager = base::mac::ObjCCastStrict<JsSuggestionManager>( [injectionReceiver instanceOfClass:[JsSuggestionManager class]]); [_JSSuggestionManager - setWebFramesManager:web::WebFramesManager::FromWebState(webState)]; + setWebFramesManager:webState->GetWebFramesManager()]; FormSuggestionTabHelper* tabHelper = FormSuggestionTabHelper::FromWebState(webState); if (tabHelper) { @@ -441,7 +441,7 @@ self.JSSuggestionManager = base::mac::ObjCCastStrict<JsSuggestionManager>( [injectionReceiver instanceOfClass:[JsSuggestionManager class]]); [self.JSSuggestionManager - setWebFramesManager:web::WebFramesManager::FromWebState(webState)]; + setWebFramesManager:webState->GetWebFramesManager()]; FormSuggestionTabHelper* tabHelper = FormSuggestionTabHelper::FromWebState(webState); if (tabHelper) {
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn b/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn index f831ed7..b45c715 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn +++ b/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn
@@ -57,6 +57,7 @@ "//ios/chrome/browser/ui/table_view:table_view", "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web_state_list:web_state_list", + "//ios/chrome/common/colors", "//ios/web/public", "//ios/web/public/deprecated", "//ios/web/public/js_messaging",
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/action_cell.mm b/ios/chrome/browser/ui/autofill/manual_fill/action_cell.mm index 152a784e..9d4acde 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/action_cell.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/action_cell.mm
@@ -7,6 +7,7 @@ #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_button.h" #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_utils.h" #import "ios/chrome/browser/ui/list_model/list_model.h" +#import "ios/chrome/common/colors/UIColor+cr_semantic_colors.h" #import "ios/chrome/common/ui_util/constraints_ui_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -97,7 +98,7 @@ self.titleButton.accessibilityIdentifier = accessibilityID; self.titleButton.enabled = enabled; if (!enabled) { - [self.titleButton setTitleColor:UIColor.lightGrayColor + [self.titleButton setTitleColor:UIColor.cr_secondaryLabelColor forState:UIControlStateNormal]; } self.action = action;
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/all_password_coordinator.mm b/ios/chrome/browser/ui/autofill/manual_fill/all_password_coordinator.mm index 9e284f0..8c38485 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/all_password_coordinator.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/all_password_coordinator.mm
@@ -99,7 +99,6 @@ TableViewNavigationController* navigationController = [[TableViewNavigationController alloc] initWithTable:self.passwordViewController]; - navigationController.navigationBar.barTintColor = UIColor.whiteColor; navigationController.transitioningDelegate = self; [navigationController setModalPresentationStyle:UIModalPresentationCustom];
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/card_coordinator.mm b/ios/chrome/browser/ui/autofill/manual_fill/card_coordinator.mm index 53d5e4b..7c43e6f5 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/card_coordinator.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/card_coordinator.mm
@@ -19,7 +19,6 @@ #include "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/browser/web_state_list/web_state_list.h" #include "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/web_state/web_state.h" #if !defined(__has_feature) || !__has_feature(objc_arc)
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator.mm b/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator.mm index 3b80151..b15d471e 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator.mm
@@ -15,6 +15,7 @@ #import "ios/chrome/browser/ui/table_view/chrome_table_view_controller.h" #import "ios/chrome/browser/ui/table_view/table_view_navigation_controller.h" #include "ios/chrome/browser/ui/util/ui_util.h" +#import "ios/chrome/common/colors/UIColor+cr_semantic_colors.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -70,7 +71,8 @@ popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp | UIPopoverArrowDirectionDown; popoverPresentationController.delegate = self; - popoverPresentationController.backgroundColor = UIColor.whiteColor; + popoverPresentationController.backgroundColor = + UIColor.cr_systemBackgroundColor; } #pragma mark - ChromeCoordinator
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/fallback_view_controller.mm b/ios/chrome/browser/ui/autofill/manual_fill/fallback_view_controller.mm index 28bd47f..ce7e4653 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/fallback_view_controller.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/fallback_view_controller.mm
@@ -9,6 +9,7 @@ #import "ios/chrome/browser/ui/table_view/chrome_table_view_styler.h" #include "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/UIColor+cr_semantic_colors.h" #import "ios/chrome/common/colors/semantic_color_names.h" #include "ios/chrome/grit/ios_strings.h" #include "ui/base/l10n/l10n_util_mac.h" @@ -78,7 +79,7 @@ - (void)viewDidLoad { // Super's |viewDidLoad| uses |styler.tableViewBackgroundColor| so it needs to // be set before. - self.styler.tableViewBackgroundColor = [UIColor whiteColor]; + self.styler.tableViewBackgroundColor = UIColor.cr_systemBackgroundColor; [super viewDidLoad];
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester.mm b/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester.mm index 1240b22..b4ef7bec 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester.mm
@@ -12,7 +12,7 @@ #include "ios/chrome/browser/ui/payments/full_card_requester.h" #import "ios/chrome/browser/web_state_list/web_state_list.h" #include "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" +#import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/web_state/web_state.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -59,7 +59,7 @@ withBaseViewController:(UIViewController*)viewController { // Payment Request is only enabled in main frame. web::WebState* webState = self.webStateList->GetActiveWebState(); - web::WebFrame* mainFrame = web::GetMainWebFrame(webState); + web::WebFrame* mainFrame = webState->GetWebFramesManager()->GetMainWebFrame(); autofill::AutofillManager* autofillManager = autofill::AutofillDriverIOS::FromWebStateAndWebFrame(webState, mainFrame) ->autofill_manager();
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.mm index d702efb..4806680 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.mm
@@ -231,7 +231,7 @@ } - (UIColor*)activeTintColor { - return [UIColor.blackColor colorWithAlphaComponent:0.5]; + return [UIColor colorWithWhite:0.5 alpha:1.0]; } - (void)animateKeyboardButtonHidden:(BOOL)hidden {
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_address_cell.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_address_cell.mm index e7c9a8b..e0d9118 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_address_cell.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_address_cell.mm
@@ -8,6 +8,7 @@ #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_utils.h" #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_content_delegate.h" #import "ios/chrome/browser/ui/list_model/list_model.h" +#import "ios/chrome/common/colors/UIColor+cr_semantic_colors.h" #import "ios/chrome/common/ui_util/constraints_ui_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -153,7 +154,7 @@ attributedString = [[NSMutableAttributedString alloc] initWithString:blackText attributes:@{ - NSForegroundColorAttributeName : UIColor.blackColor, + NSForegroundColorAttributeName : UIColor.cr_labelColor, NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline] }]; @@ -161,7 +162,7 @@ NSString* formattedGrayText = [NSString stringWithFormat:@" –– %@", grayText]; NSDictionary* attributes = @{ - NSForegroundColorAttributeName : UIColor.lightGrayColor, + NSForegroundColorAttributeName : UIColor.cr_secondaryLabelColor, NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody] };
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_cell.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_cell.mm index aa642de..9d2c27d 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_cell.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_cell.mm
@@ -148,7 +148,7 @@ [[NSMutableAttributedString alloc] initWithString:cardName attributes:@{ - NSForegroundColorAttributeName : UIColor.blackColor, + NSForegroundColorAttributeName : UIColor.cr_labelColor, NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline] }];
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_button.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_button.mm index f8457a1..902e785 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_button.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_button.mm
@@ -5,6 +5,7 @@ #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_button.h" #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_cell_utils.h" +#import "ios/chrome/common/colors/UIColor+cr_semantic_colors.h" #import "ios/chrome/common/colors/semantic_color_names.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -44,7 +45,7 @@ - (void)setHighlighted:(BOOL)highlighted { [super setHighlighted:highlighted]; CGFloat alpha = highlighted ? 0.07 : 0; - self.backgroundColor = [UIColor colorWithWhite:0 alpha:alpha]; + self.backgroundColor = [UIColor.cr_labelColor colorWithAlphaComponent:alpha]; } #pragma mark - Private
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_injection_handler.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_injection_handler.mm index 6f30bbd..f2f729e 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_injection_handler.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_injection_handler.mm
@@ -156,7 +156,7 @@ [self.injectionReceiver instanceOfClass:[JsSuggestionManager class]]); web::WebState* webState = self.webStateList->GetActiveWebState(); if (webState) { - [manager setWebFramesManager:web::WebFramesManager::FromWebState(webState)]; + [manager setWebFramesManager:webState->GetWebFramesManager()]; } return manager; }
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.mm index 606c5ec8..dca6822c 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.mm
@@ -168,7 +168,7 @@ [[NSMutableAttributedString alloc] initWithString:credential.siteName ? credential.siteName : @"" attributes:@{ - NSForegroundColorAttributeName : UIColor.blackColor, + NSForegroundColorAttributeName : UIColor.cr_labelColor, NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline] }]; @@ -177,7 +177,7 @@ NSString* hostString = [NSString stringWithFormat:@" –– %@", credential.host]; NSDictionary* attributes = @{ - NSForegroundColorAttributeName : UIColor.lightGrayColor, + NSForegroundColorAttributeName : UIColor.cr_secondaryLabelColor, NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody] }; @@ -199,7 +199,7 @@ NSString* titleString = l10n_util::GetNSString(IDS_IOS_MANUAL_FALLBACK_NO_USERNAME); [self.usernameButton setTitle:titleString forState:UIControlStateNormal]; - [self.usernameButton setTitleColor:UIColor.lightGrayColor + [self.usernameButton setTitleColor:UIColor.cr_secondaryLabelColor forState:UIControlStateNormal]; self.usernameButton.enabled = NO; }
diff --git a/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm b/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm index 4c1dffb..9e7bcf47 100644 --- a/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm +++ b/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm
@@ -26,7 +26,6 @@ #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/http_server/http_server.h" #import "ios/web/public/web_state/web_state.h" @@ -94,7 +93,8 @@ static CreditCardSaveManager* credit_card_save_manager() { web::WebState* web_state = chrome_test_util::GetCurrentWebState(); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state); + web::WebFrame* main_frame = + web_state->GetWebFramesManager()->GetMainWebFrame(); DCHECK(web_state); return AutofillDriverIOS::FromWebStateAndWebFrame(web_state, main_frame) ->autofill_manager() @@ -105,7 +105,8 @@ static payments::PaymentsClient* payments_client() { web::WebState* web_state = chrome_test_util::GetCurrentWebState(); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state); + web::WebFrame* main_frame = + web_state->GetWebFramesManager()->GetMainWebFrame(); DCHECK(web_state); return AutofillDriverIOS::FromWebStateAndWebFrame(web_state, main_frame) ->autofill_manager()
diff --git a/ios/chrome/browser/ui/bookmarks/BUILD.gn b/ios/chrome/browser/ui/bookmarks/BUILD.gn index 795202f..e99a849 100644 --- a/ios/chrome/browser/ui/bookmarks/BUILD.gn +++ b/ios/chrome/browser/ui/bookmarks/BUILD.gn
@@ -60,7 +60,6 @@ "//components/pref_registry", "//components/prefs", "//components/query_parser", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//components/signin/public/identity_manager/objc", "//components/strings",
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm b/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm index 7d97b784..0ebe73b 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm
@@ -23,7 +23,7 @@ IdentityManagerObserverBridgeDelegate> { bool _isIncognito; ios::ChromeBrowserState* _browserState; - std::unique_ptr<identity::IdentityManagerObserverBridge> + std::unique_ptr<signin::IdentityManagerObserverBridge> _identityManagerObserverBridge; } @@ -52,7 +52,7 @@ if (!_isIncognito) { _browserState = browserState; _identityManagerObserverBridge.reset( - new identity::IdentityManagerObserverBridge( + new signin::IdentityManagerObserverBridge( IdentityManagerFactory::GetForBrowserState(_browserState), self)); _signinPromoViewMediator = [[SigninPromoViewMediator alloc] initWithBrowserState:_browserState @@ -93,7 +93,7 @@ shouldDisplaySigninPromoViewWithAccessPoint: signin_metrics::AccessPoint::ACCESS_POINT_BOOKMARK_MANAGER browserState:_browserState]) { - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(_browserState); self.shouldShowSigninPromo = !identityManager->HasPrimaryAccount(); }
diff --git a/ios/chrome/browser/ui/bookmarks/synced_bookmarks_bridge.h b/ios/chrome/browser/ui/bookmarks/synced_bookmarks_bridge.h index 815e4dc..e6f9bb3d 100644 --- a/ios/chrome/browser/ui/bookmarks/synced_bookmarks_bridge.h +++ b/ios/chrome/browser/ui/bookmarks/synced_bookmarks_bridge.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #import "ios/chrome/browser/sync/sync_observer_bridge.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -33,7 +33,7 @@ bool IsPerformingInitialSync(); private: - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; ios::ChromeBrowserState* browser_state_; DISALLOW_COPY_AND_ASSIGN(SyncedBookmarksObserverBridge);
diff --git a/ios/chrome/browser/ui/commands/BUILD.gn b/ios/chrome/browser/ui/commands/BUILD.gn index 3ff0450..c08a3b1 100644 --- a/ios/chrome/browser/ui/commands/BUILD.gn +++ b/ios/chrome/browser/ui/commands/BUILD.gn
@@ -4,6 +4,7 @@ source_set("commands") { configs += [ "//build/config/compiler:enable_arc" ] + sources = [ "activity_service_commands.h", "application_commands.h", @@ -30,15 +31,19 @@ "snackbar_commands.h", "toolbar_commands.h", ] + deps = [ - "//base", - "//components/browsing_data/core", - "//components/signin/core/browser", - "//ios/chrome/browser/browsing_data:browsing_data_remove_mask", "//ios/web", "//net", "//url", ] + + public_deps = [ + "//base", + "//components/browsing_data/core", + "//components/signin/public/base", + "//ios/chrome/browser/browsing_data:browsing_data_remove_mask", + ] } source_set("unit_tests") {
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h index 779dc03..51f652b 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h
@@ -11,7 +11,7 @@ #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_commands.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller_delegate.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -47,7 +47,7 @@ templateURLService:(nonnull TemplateURLService*)templateURLService urlLoadingService:(nonnull UrlLoadingService*)urlLoadingService authService:(nonnull AuthenticationService*)authService - identityManager:(nonnull identity::IdentityManager*)identityManager + identityManager:(nonnull signin::IdentityManager*)identityManager logoVendor:(nonnull id<LogoVendor>)logoVendor NS_DESIGNATED_INITIALIZER;
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm index 5abc37c..9ef5f41 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm
@@ -82,7 +82,7 @@ // Listen for default search engine changes. std::unique_ptr<SearchEngineObserverBridge> _searchEngineObserver; // Observes changes in identity and updates the Identity Disc. - std::unique_ptr<identity::IdentityManagerObserverBridge> + std::unique_ptr<signin::IdentityManagerObserverBridge> _identityObserverBridge; // Used to load URLs. UrlLoadingService* _urlLoadingService; @@ -110,7 +110,7 @@ templateURLService:(TemplateURLService*)templateURLService urlLoadingService:(UrlLoadingService*)urlLoadingService authService:(AuthenticationService*)authService - identityManager:(identity::IdentityManager*)identityManager + identityManager:(signin::IdentityManager*)identityManager logoVendor:(id<LogoVendor>)logoVendor { self = [super init]; if (self) { @@ -121,7 +121,7 @@ _urlLoadingService = urlLoadingService; _authService = authService; _identityObserverBridge.reset( - new identity::IdentityManagerObserverBridge(identityManager, self)); + new signin::IdentityManagerObserverBridge(identityManager, self)); // Listen for default search engine changes. _searchEngineObserver = std::make_unique<SearchEngineObserverBridge>( self, self.templateURLService);
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm index 5f487128..1354d83 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm
@@ -138,7 +138,7 @@ FakeWebStateListDelegate web_state_list_delegate_; TestUrlLoadingService* url_loader_; AuthenticationServiceFake* auth_service_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; private: std::unique_ptr<web::TestWebState> test_web_state_;
diff --git a/ios/chrome/browser/ui/first_run/BUILD.gn b/ios/chrome/browser/ui/first_run/BUILD.gn index 1998ff1..ea2f17ea 100644 --- a/ios/chrome/browser/ui/first_run/BUILD.gn +++ b/ios/chrome/browser/ui/first_run/BUILD.gn
@@ -26,7 +26,6 @@ "//base:i18n", "//components/metrics", "//components/prefs", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//components/unified_consent", "//ios/chrome/app/strings",
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.h b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.h index 1b91b1e..a2ed0a3a 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.h +++ b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.h
@@ -44,6 +44,10 @@ // |display| is NO. Will animate change if |animated| is YES. - (void)displayBadge:(BOOL)display animated:(BOOL)animated; +// Toggles |enabled| state of the trailing button and updates accessibility +// appropriately. +- (void)enableTrailingButton:(BOOL)enabled; + // The tappable button representing the location bar. @property(nonatomic, strong) UIButton* locationButton; // The label displaying the current location URL.
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm index c49d18a8..81ab612 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm
@@ -334,6 +334,11 @@ [self.leadingButton displayBadge:display animated:animated]; } +- (void)enableTrailingButton:(BOOL)enabled { + self.trailingButton.enabled = enabled; + [self updateAccessibility]; +} + #pragma mark - UIResponder // This is needed for UIMenu @@ -380,6 +385,12 @@ self.locationButton.accessibilityValue = [NSString stringWithFormat:@"%@", self.locationLabel.text]; } + + if (self.trailingButton.enabled) { + [self.accessibleElements addObject:self.trailingButton]; + } else { + [self.accessibleElements removeObject:self.trailingButton]; + } } // Returns the font size for the location label.
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm b/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm index 82c9404..c010f1a 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm
@@ -255,7 +255,7 @@ - (void)setShareButtonEnabled:(BOOL)enabled { _shareButtonEnabled = enabled; if (self.trailingButtonState == kShareButton) { - self.locationBarSteadyView.trailingButton.enabled = enabled; + [self.locationBarSteadyView enableTrailingButton:enabled]; } } @@ -399,8 +399,7 @@ forState:UIControlStateNormal]; self.locationBarSteadyView.trailingButton.accessibilityLabel = l10n_util::GetNSString(IDS_IOS_TOOLS_MENU_SHARE); - self.locationBarSteadyView.trailingButton.enabled = - self.shareButtonEnabled; + [self.locationBarSteadyView enableTrailingButton:self.shareButtonEnabled]; break; }; case kVoiceSearchButton: { @@ -419,7 +418,7 @@ forState:UIControlStateNormal]; self.locationBarSteadyView.trailingButton.accessibilityLabel = l10n_util::GetNSString(IDS_IOS_TOOLS_MENU_VOICE_SEARCH); - self.locationBarSteadyView.trailingButton.enabled = YES; + [self.locationBarSteadyView enableTrailingButton:YES]; } } }
diff --git a/ios/chrome/browser/ui/payments/BUILD.gn b/ios/chrome/browser/ui/payments/BUILD.gn index 35ba4fc..8718dbc 100644 --- a/ios/chrome/browser/ui/payments/BUILD.gn +++ b/ios/chrome/browser/ui/payments/BUILD.gn
@@ -68,7 +68,7 @@ "//components/omnibox/browser", "//components/payments/core", "//components/payments/mojom", - "//components/signin/core/browser", + "//components/prefs", "//components/strings", "//components/url_formatter", "//ios/chrome/app/strings", @@ -223,7 +223,6 @@ "//components/payments/core:test_support", "//components/payments/mojom", "//components/prefs:prefs", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//components/signin/public/identity_manager:test_support", "//components/strings",
diff --git a/ios/chrome/browser/ui/payments/full_card_requester_unittest.mm b/ios/chrome/browser/ui/payments/full_card_requester_unittest.mm index 7d569b9..44f637e 100644 --- a/ios/chrome/browser/ui/payments/full_card_requester_unittest.mm +++ b/ios/chrome/browser/ui/payments/full_card_requester_unittest.mm
@@ -20,9 +20,9 @@ #import "ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h" #import "ios/chrome/test/scoped_key_window.h" #import "ios/web/public/deprecated/crw_test_js_injection_receiver.h" -#import "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #include "ios/web/public/test/fakes/fake_web_frame.h" +#import "ios/web/public/test/fakes/fake_web_frames_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" #include "third_party/ocmock/gtest_support.h" @@ -71,9 +71,14 @@ [[CRWTestJSInjectionReceiver alloc] init]; web_state()->SetJSInjectionReceiver(injectionReceiver); - web_state()->CreateWebFramesManager(); - auto main_frame = std::make_unique<web::FakeWebFrame>("main", true, GURL()); - web_state()->AddWebFrame(std::move(main_frame)); + auto frames_manager = std::make_unique<web::FakeWebFramesManager>(); + auto main_frame = std::make_unique<web::FakeWebFrame>( + /*frame_id=*/"main", /*is_main_frame=*/true, + /*security_origin=*/GURL()); + frames_manager->AddWebFrame(std::move(main_frame)); + web_state()->SetWebFramesManager(std::move(frames_manager)); + web_state()->OnWebFrameDidBecomeAvailable( + web_state()->GetWebFramesManager()->GetMainWebFrame()); autofill_agent_ = [[AutofillAgent alloc] initWithPrefService:browser_state()->GetPrefs() @@ -112,7 +117,8 @@ FullCardRequester full_card_requester(base_view_controller, browser_state()); EXPECT_EQ(nil, base_view_controller.presentedViewController); - web::WebFrame* main_frame = web::GetMainWebFrame(web_state()); + web::WebFrame* main_frame = + web_state()->GetWebFramesManager()->GetMainWebFrame(); autofill::AutofillManager* autofill_manager = autofill::AutofillDriverIOS::FromWebStateAndWebFrame(web_state(), main_frame)
diff --git a/ios/chrome/browser/ui/payments/payment_request_manager.mm b/ios/chrome/browser/ui/payments/payment_request_manager.mm index 5087bddf..879056b 100644 --- a/ios/chrome/browser/ui/payments/payment_request_manager.mm +++ b/ios/chrome/browser/ui/payments/payment_request_manager.mm
@@ -61,7 +61,6 @@ #include "ios/web/public/deprecated/url_verification_constants.h" #include "ios/web/public/favicon/favicon_status.h" #include "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/navigation/navigation_context.h" #include "ios/web/public/navigation/navigation_item.h" @@ -136,6 +135,9 @@ // Storage for data to return in the payment response, until we're ready to // send an actual PaymentResponse. PendingPaymentResponse _pendingPaymentResponse; + + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> _subscription; } // YES if Payment Request is enabled on the active web state. @@ -309,7 +311,6 @@ _paymentRequestJsManager = nil; _activeWebState->RemoveObserver(_activeWebStateObserver.get()); - _activeWebState->RemoveScriptCommandCallback(kCommandPrefix); _activeWebStateObserver.reset(); _activeWebState = nullptr; } @@ -320,7 +321,7 @@ _paymentRequestJsManager = nil; _activeWebState->RemoveObserver(_activeWebStateObserver.get()); - _activeWebState->RemoveScriptCommandCallback(kCommandPrefix); + _subscription.reset(); _activeWebState = nullptr; } @@ -338,7 +339,8 @@ } }); _activeWebState->AddObserver(_activeWebStateObserver.get()); - _activeWebState->AddScriptCommandCallback(callback, kCommandPrefix); + _subscription = + _activeWebState->AddScriptCommandCallback(callback, kCommandPrefix); _paymentRequestJsManager = base::mac::ObjCCastStrict<JSPaymentRequestManager>( @@ -679,7 +681,8 @@ BOOL connectionSecure = _activeWebState->GetLastCommittedURL().SchemeIs(url::kHttpsScheme); // Payment Request is only enabled in main frame. - web::WebFrame* main_frame = web::GetMainWebFrame(_activeWebState); + web::WebFrame* main_frame = + _activeWebState->GetWebFramesManager()->GetMainWebFrame(); autofill::AutofillManager* autofillManager = autofill::AutofillDriverIOS::FromWebStateAndWebFrame(_activeWebState, main_frame)
diff --git a/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm b/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm index 812b70d..4dd321f4 100644 --- a/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm +++ b/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm
@@ -107,7 +107,7 @@ PaymentRequestMediator* mediator() { return mediator_; } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return IdentityManagerFactory::GetForBrowserState(browser_state()); }
diff --git a/ios/chrome/browser/ui/promos/BUILD.gn b/ios/chrome/browser/ui/promos/BUILD.gn index b6ea157..b88404a 100644 --- a/ios/chrome/browser/ui/promos/BUILD.gn +++ b/ios/chrome/browser/ui/promos/BUILD.gn
@@ -11,7 +11,7 @@ ] deps = [ "//base", - "//components/signin/core/browser", + "//components/signin/public/base", "//components/unified_consent", "//components/version_info", "//ios/chrome/app:tests_hook",
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm index c95418c..7060ea1 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm
@@ -157,7 +157,7 @@ // GetPrimaryAccountMutator() returns nullptr on ChromeOS only. DCHECK(account_mutator); account_mutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC); } @@ -203,7 +203,7 @@ web::TestWebThreadBundle thread_bundle_; GoogleServiceAuthError no_error_; IOSChromeScopedTestingLocalState local_state_; - identity::IdentityTestEnvironment identity_test_env_; + signin::IdentityTestEnvironment identity_test_env_; syncer::FakeModelTypeControllerDelegate fake_controller_delegate_; testing::NiceMock<OpenTabsUIDelegateMock> open_tabs_ui_delegate_;
diff --git a/ios/chrome/browser/ui/recent_tabs/synced_sessions_bridge.h b/ios/chrome/browser/ui/recent_tabs/synced_sessions_bridge.h index 67726ed..68a2c101 100644 --- a/ios/chrome/browser/ui/recent_tabs/synced_sessions_bridge.h +++ b/ios/chrome/browser/ui/recent_tabs/synced_sessions_bridge.h
@@ -17,7 +17,7 @@ class ChromeBrowserState; } -namespace identity { +namespace signin { class IdentityManager; } @@ -30,13 +30,12 @@ // Bridge class that will notify the panel when the remote sessions content // change. -class SyncedSessionsObserverBridge - : public identity::IdentityManager::Observer { +class SyncedSessionsObserverBridge : public signin::IdentityManager::Observer { public: SyncedSessionsObserverBridge(id<SyncedSessionsObserver> owner, ios::ChromeBrowserState* browserState); ~SyncedSessionsObserverBridge() override; - // identity::IdentityManager::Observer implementation. + // signin::IdentityManager::Observer implementation. void OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) override; @@ -47,8 +46,8 @@ void OnForeignSessionChanged(); __weak id<SyncedSessionsObserver> owner_ = nil; - identity::IdentityManager* identity_manager_ = nullptr; - ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + signin::IdentityManager* identity_manager_ = nullptr; + ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; std::unique_ptr<base::CallbackList<void()>::Subscription> foreign_session_updated_subscription_;
diff --git a/ios/chrome/browser/ui/recent_tabs/synced_sessions_bridge.mm b/ios/chrome/browser/ui/recent_tabs/synced_sessions_bridge.mm index 82c3bfa..7dcf5357 100644 --- a/ios/chrome/browser/ui/recent_tabs/synced_sessions_bridge.mm +++ b/ios/chrome/browser/ui/recent_tabs/synced_sessions_bridge.mm
@@ -39,7 +39,7 @@ SyncedSessionsObserverBridge::~SyncedSessionsObserverBridge() {} -#pragma mark - identity::IdentityManager::Observer +#pragma mark - signin::IdentityManager::Observer void SyncedSessionsObserverBridge::OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) {
diff --git a/ios/chrome/browser/ui/settings/BUILD.gn b/ios/chrome/browser/ui/settings/BUILD.gn index e3f18e7..d0f90ada 100644 --- a/ios/chrome/browser/ui/settings/BUILD.gn +++ b/ios/chrome/browser/ui/settings/BUILD.gn
@@ -115,7 +115,6 @@ "//components/prefs/ios", "//components/resources", "//components/search_engines", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//components/signin/public/identity_manager/objc", "//components/strings",
diff --git a/ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_manager.mm b/ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_manager.mm index 9fbea8d..251193b1 100644 --- a/ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_manager.mm +++ b/ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_manager.mm
@@ -354,7 +354,7 @@ // Add footers about user's account data. - (void)addSyncProfileItemsToModel:(ListModel*)model { // Google Account footer. - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(self.browserState); if (identityManager->HasPrimaryAccount()) { // TODO(crbug.com/650424): Footer items must currently go into a separate @@ -805,7 +805,7 @@ "History.ClearBrowsingData.HistoryNoticeShownInFooterWhenUpdated", _shouldShowNoticeAboutOtherFormsOfBrowsingHistory); - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(_browserState); if (!identityManager->HasPrimaryAccount()) { return;
diff --git a/ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.mm b/ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.mm index 17d5368..31cd45e 100644 --- a/ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.mm
@@ -86,7 +86,7 @@ ios::ChromeBrowserState* _browserState; // weak BOOL _closeSettingsOnAddAccount; std::unique_ptr<SyncObserverBridge> _syncObserver; - std::unique_ptr<identity::IdentityManagerObserverBridge> + std::unique_ptr<signin::IdentityManagerObserverBridge> _identityManagerObserver; // Modal alert for sign out. AlertCoordinator* _alertCoordinator; @@ -140,7 +140,7 @@ _syncObserver.reset(new SyncObserverBridge(self, syncService)); } _identityManagerObserver = - std::make_unique<identity::IdentityManagerObserverBridge>( + std::make_unique<signin::IdentityManagerObserverBridge>( IdentityManagerFactory::GetForBrowserState(_browserState), self); [[NSNotificationCenter defaultCenter] addObserver:self @@ -219,7 +219,7 @@ [model addSectionWithIdentifier:SectionIdentifierAccounts]; [model setHeader:[self header] forSectionWithIdentifier:SectionIdentifierAccounts]; - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(_browserState); for (const auto& account : identityManager->GetAccountsWithRefreshTokens()) { ChromeIdentity* identity = ios::GetChromeBrowserProvider() @@ -526,7 +526,7 @@ NSString* continueButtonTitle = l10n_util::GetNSString(IDS_IOS_DISCONNECT_DIALOG_CONTINUE_BUTTON_MOBILE); if ([self authService] -> IsAuthenticatedIdentityManaged()) { - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(_browserState); base::Optional<AccountInfo> accountInfo = identityManager->FindExtendedAccountInfoForAccount(
diff --git a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.h b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.h index eabd0aa..5b52197 100644 --- a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.h +++ b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.h
@@ -23,9 +23,9 @@ class SyncService; } // namespace syncer -namespace identity { +namespace signin { class IdentityManager; -} // namespace identity +} // namespace signin // Mediator for the Google services settings. @interface GoogleServicesSettingsMediator @@ -44,7 +44,7 @@ // Sync service. @property(nonatomic, assign) syncer::SyncService* syncService; // Identity manager; -@property(nonatomic, assign) identity::IdentityManager* identityManager; +@property(nonatomic, assign) signin::IdentityManager* identityManager; // Designated initializer. All the paramters should not be null. // |userPrefService|: preference service from the browser state.
diff --git a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm index d47902ba..73c57ea 100644 --- a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm +++ b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm
@@ -93,7 +93,7 @@ // Sync observer. std::unique_ptr<SyncObserverBridge> _syncObserver; // Identity manager observer. - std::unique_ptr<identity::IdentityManagerObserverBridge> + std::unique_ptr<signin::IdentityManagerObserverBridge> _identityManagerObserverBridge; // Chrome identity observer. std::unique_ptr<ChromeIdentityServiceObserverBridge> _identityServiceObserver; @@ -632,7 +632,7 @@ [self loadSyncSection]; [self loadNonPersonalizedSection]; _identityManagerObserverBridge.reset( - new identity::IdentityManagerObserverBridge(self.identityManager, self)); + new signin::IdentityManagerObserverBridge(self.identityManager, self)); DCHECK(self.syncService); _syncObserver.reset(new SyncObserverBridge(self, self.syncService)); _identityServiceObserver.reset(new ChromeIdentityServiceObserverBridge(self));
diff --git a/ios/chrome/browser/ui/settings/settings_table_view_controller.mm b/ios/chrome/browser/ui/settings/settings_table_view_controller.mm index a5a7699..752bf6ef 100644 --- a/ios/chrome/browser/ui/settings/settings_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_table_view_controller.mm
@@ -174,7 +174,7 @@ ios::ChromeBrowserState* _browserState; // weak // Bridge for TemplateURLServiceObserver. std::unique_ptr<SearchEngineObserverBridge> _searchEngineObserverBridge; - std::unique_ptr<identity::IdentityManagerObserverBridge> + std::unique_ptr<signin::IdentityManagerObserverBridge> _identityObserverBridge; std::unique_ptr<SyncObserverBridge> _syncObserverBridge; // Whether the impression of the Signin button has already been recorded. @@ -257,13 +257,13 @@ _searchEngineObserverBridge.reset(new SearchEngineObserverBridge( self, ios::TemplateURLServiceFactory::GetForBrowserState(_browserState))); - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = IdentityManagerFactory::GetForBrowserState(_browserState); // It is expected that |identityManager| should never be nil except in // tests. In that case, the tests should be fixed. DCHECK(identityManager); _identityObserverBridge.reset( - new identity::IdentityManagerObserverBridge(identityManager, self)); + new signin::IdentityManagerObserverBridge(identityManager, self)); syncer::SyncService* syncService = ProfileSyncServiceFactory::GetForBrowserState(_browserState); _syncObserverBridge.reset(new SyncObserverBridge(self, syncService));
diff --git a/ios/chrome/browser/ui/settings/sync/sync_encryption_passphrase_table_view_controller.mm b/ios/chrome/browser/ui/settings/sync/sync_encryption_passphrase_table_view_controller.mm index ef4a355f..111213c 100644 --- a/ios/chrome/browser/ui/settings/sync/sync_encryption_passphrase_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/sync/sync_encryption_passphrase_table_view_controller.mm
@@ -60,7 +60,7 @@ NSString* savedTitle_; UIBarButtonItem* savedLeftButton_; std::unique_ptr<SyncObserverBridge> syncObserver_; - std::unique_ptr<identity::IdentityManagerObserverBridge> + std::unique_ptr<signin::IdentityManagerObserverBridge> identityManagerObserver_; UITextField* passphrase_; } @@ -109,7 +109,7 @@ _footerMessage = l10n_util::GetNSString(IDS_IOS_SYNC_PASSPHRASE_RECOVER); identityManagerObserver_ = - std::make_unique<identity::IdentityManagerObserverBridge>( + std::make_unique<signin::IdentityManagerObserverBridge>( IdentityManagerFactory::GetForBrowserState(browserState_), self); } return self;
diff --git a/ios/chrome/browser/ui/settings/sync/sync_settings_table_view_controller.mm b/ios/chrome/browser/ui/settings/sync/sync_settings_table_view_controller.mm index f775f55..a00d2839 100644 --- a/ios/chrome/browser/ui/settings/sync/sync_settings_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/sync/sync_settings_table_view_controller.mm
@@ -101,7 +101,7 @@ ios::ChromeBrowserState* _browserState; // Weak. SyncSetupService* _syncSetupService; // Weak. std::unique_ptr<SyncObserverBridge> _syncObserver; - std::unique_ptr<identity::IdentityManagerObserverBridge> + std::unique_ptr<signin::IdentityManagerObserverBridge> _identityManagerObserver; AuthenticationFlow* _authenticationFlow; // Whether switching sync account is allowed on the screen. @@ -228,7 +228,7 @@ syncer::SyncService* syncService = ProfileSyncServiceFactory::GetForBrowserState(_browserState); _syncObserver.reset(new SyncObserverBridge(self, syncService)); - _identityManagerObserver.reset(new identity::IdentityManagerObserverBridge( + _identityManagerObserver.reset(new signin::IdentityManagerObserverBridge( IdentityManagerFactory::GetForBrowserState(_browserState), self)); _avatarCache = [[ResizedAvatarCache alloc] init]; _identityServiceObserver.reset( @@ -1019,7 +1019,7 @@ [self updateTableView]; } -#pragma mark identity::IdentityManagerObserverBridgeDelegate +#pragma mark signin::IdentityManagerObserverBridgeDelegate - (void)onEndBatchOfRefreshTokenStateChanges { if (_authenticationOperationInProgress) {
diff --git a/ios/chrome/browser/ui/settings/sync/utils/BUILD.gn b/ios/chrome/browser/ui/settings/sync/utils/BUILD.gn index dfd0400..84aadc5 100644 --- a/ios/chrome/browser/ui/settings/sync/utils/BUILD.gn +++ b/ios/chrome/browser/ui/settings/sync/utils/BUILD.gn
@@ -17,7 +17,6 @@ "//base", "//components/browser_sync", "//components/infobars/core", - "//components/signin/core/browser", "//components/strings", "//components/sync", "//components/unified_consent",
diff --git a/ios/chrome/browser/ui/signin_interaction/BUILD.gn b/ios/chrome/browser/ui/signin_interaction/BUILD.gn index 3a4236e..3766d69 100644 --- a/ios/chrome/browser/ui/signin_interaction/BUILD.gn +++ b/ios/chrome/browser/ui/signin_interaction/BUILD.gn
@@ -15,7 +15,6 @@ "//base", "//components//unified_consent", "//components/prefs", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//ios/chrome/browser", "//ios/chrome/browser/browser_state",
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm index c1e1d2b..3b9b835d 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm
@@ -657,27 +657,8 @@ styler.tableViewBackgroundColor = UIColorFromRGB(kGridBackgroundColor); styler.cellHighlightColor = [UIColor colorWithWhite:0 alpha:kGridDarkThemeCellHighlightColorAlpha]; - // For iOS 13, setting the overrideUserInterfaceStyle to dark forces the use - // of dark mode colors for all the colors in this view. However, this - // override is not available on pre-iOS 13 devices, so the dark mode colors - // must be provided manually. - if (@available(iOS 13, *)) { -#if defined(__IPHONE_13_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0) - self.remoteTabsViewController.overrideUserInterfaceStyle = - UIUserInterfaceStyleDark; -#endif - } else { - styler.cellTitleColor = UIColorFromRGB(kGridDarkThemeCellTitleColor); - styler.headerFooterTitleColor = - UIColorFromRGB(kGridDarkThemeCellTitleColor); - styler.cellDetailColor = UIColorFromRGB(kGridDarkThemeCellDetailColor, - kGridDarkThemeCellDetailAlpha); - styler.headerFooterDetailColor = UIColorFromRGB( - kGridDarkThemeCellDetailColor, kGridDarkThemeCellDetailAlpha); - styler.tintColor = UIColorFromRGB(kGridDarkThemeCellTintColor); - styler.solidButtonTextColor = - UIColorFromRGB(kGridDarkThemeCellSolidButtonTextColor); - } + // To make using the compile guards easier, use a separate method. + [self setupRemoteTabsViewControllerForDarkModeWithStyler:styler]; self.remoteTabsViewController.styler = styler; UIView* contentView = self.scrollContentView; @@ -702,6 +683,32 @@ [NSLayoutConstraint activateConstraints:constraints]; } +// The iOS 13 compile guards are much easier to use in a separate function that +// can be returned from. +- (void)setupRemoteTabsViewControllerForDarkModeWithStyler: + (ChromeTableViewStyler*)styler { + // For iOS 13, setting the overrideUserInterfaceStyle to dark forces the use + // of dark mode colors for all the colors in this view. However, this + // override is not available on pre-iOS 13 devices, so the dark mode colors + // must be provided manually. +#if defined(__IPHONE_13_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0) + if (@available(iOS 13, *)) { + self.remoteTabsViewController.overrideUserInterfaceStyle = + UIUserInterfaceStyleDark; + return; + } +#endif + styler.cellTitleColor = UIColorFromRGB(kGridDarkThemeCellTitleColor); + styler.headerFooterTitleColor = UIColorFromRGB(kGridDarkThemeCellTitleColor); + styler.cellDetailColor = UIColorFromRGB(kGridDarkThemeCellDetailColor, + kGridDarkThemeCellDetailAlpha); + styler.headerFooterDetailColor = UIColorFromRGB( + kGridDarkThemeCellDetailColor, kGridDarkThemeCellDetailAlpha); + styler.tintColor = UIColorFromRGB(kGridDarkThemeCellTintColor); + styler.solidButtonTextColor = + UIColorFromRGB(kGridDarkThemeCellSolidButtonTextColor); +} + // Adds the top toolbar and sets constraints. - (void)setupTopToolbar { TabGridTopToolbar* topToolbar = [[TabGridTopToolbar alloc] init];
diff --git a/ios/chrome/browser/ui/webui/BUILD.gn b/ios/chrome/browser/ui/webui/BUILD.gn index 6cbeed9..447abb7 100644 --- a/ios/chrome/browser/ui/webui/BUILD.gn +++ b/ios/chrome/browser/ui/webui/BUILD.gn
@@ -91,9 +91,7 @@ ] deps = [ ":webui", - "//base", "//components/resources", - "//components/signin/core/browser", "//components/signin/public/identity_manager", "//ios/chrome/app/resources:ios_resources", "//ios/chrome/browser", @@ -104,9 +102,14 @@ "//ios/chrome/browser/ui/webui/net_export", "//ios/chrome/browser/ui/webui/sync_internals", "//ios/chrome/browser/ui/webui/translate_internals", - "//ios/web/public/webui", "//url", ] + + public_deps = [ + "//base", + "//components/signin/core/browser", + "//ios/web/public/webui", + ] } source_set("eg_tests") {
diff --git a/ios/chrome/browser/ui/webui/inspect/inspect_ui.mm b/ios/chrome/browser/ui/webui/inspect/inspect_ui.mm index 02088f7..0021db1 100644 --- a/ios/chrome/browser/ui/webui/inspect/inspect_ui.mm +++ b/ios/chrome/browser/ui/webui/inspect/inspect_ui.mm
@@ -186,7 +186,7 @@ web::WebFrame* sender_frame, const JavaScriptConsoleMessage& message) { web::WebFrame* inspect_ui_main_frame = - web::GetMainWebFrame(web_ui()->GetWebState()); + web_ui()->GetWebState()->GetWebFramesManager()->GetMainWebFrame(); if (!inspect_ui_main_frame) { // Disable logging and drop this message because the main frame no longer // exists. @@ -195,7 +195,8 @@ } std::vector<base::Value> params; - web::WebFrame* main_web_frame = web::GetMainWebFrame(web_state); + web::WebFrame* main_web_frame = + web_state->GetWebFramesManager()->GetMainWebFrame(); params.push_back(base::Value(main_web_frame->GetFrameId())); params.push_back(base::Value(sender_frame->GetFrameId())); params.push_back(base::Value(message.url.spec())); @@ -245,7 +246,10 @@ std::vector<base::Value> params; params.push_back(base::Value(web::GetMainWebFrameId(web_state))); - web::GetMainWebFrame(web_ui()->GetWebState()) + web_ui() + ->GetWebState() + ->GetWebFramesManager() + ->GetMainWebFrame() ->CallJavaScriptFunction("inspectWebUI.tabClosed", params); }
diff --git a/ios/chrome/browser/ui/webui/signin_internals_ui_ios.cc b/ios/chrome/browser/ui/webui/signin_internals_ui_ios.cc index eabc948..eeb26fa 100644 --- a/ios/chrome/browser/ui/webui/signin_internals_ui_ios.cc +++ b/ios/chrome/browser/ui/webui/signin_internals_ui_ios.cc
@@ -6,7 +6,6 @@ #include "base/hash/hash.h" #include "components/grit/components_resources.h" -#include "components/signin/core/browser/about_signin_internals.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" @@ -75,9 +74,9 @@ std::vector<const base::Value*> args{&status}; web_ui()->CallJavascriptFunction( "chrome.signin.getSigninInfo.handleReply", args); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browser_state); - identity::AccountsInCookieJarInfo accounts_in_cookie_jar = + signin::AccountsInCookieJarInfo accounts_in_cookie_jar = identity_manager->GetAccountsInCookieJar(); if (accounts_in_cookie_jar.accounts_are_fresh) { about_signin_internals->OnAccountsInCookieUpdated(
diff --git a/ios/chrome/browser/ui/webui/sync_internals/BUILD.gn b/ios/chrome/browser/ui/webui/sync_internals/BUILD.gn index e9028ad..1fb9f69 100644 --- a/ios/chrome/browser/ui/webui/sync_internals/BUILD.gn +++ b/ios/chrome/browser/ui/webui/sync_internals/BUILD.gn
@@ -13,7 +13,6 @@ "//base", "//components/browser_sync", "//components/resources", - "//components/signin/core/browser", "//components/sync", "//ios/chrome/browser", "//ios/chrome/browser/browser_state",
diff --git a/ios/chrome/browser/unified_consent/BUILD.gn b/ios/chrome/browser/unified_consent/BUILD.gn index 24d644c..ad5cdb6 100644 --- a/ios/chrome/browser/unified_consent/BUILD.gn +++ b/ios/chrome/browser/unified_consent/BUILD.gn
@@ -12,7 +12,6 @@ "//components/browser_sync", "//components/keyed_service/ios", "//components/metrics", - "//components/signin/core/browser", "//components/sync", "//components/sync_preferences", "//components/unified_consent",
diff --git a/ios/chrome/browser/unified_consent/unified_consent_service_factory.cc b/ios/chrome/browser/unified_consent/unified_consent_service_factory.cc index a0ffad4..1a38663 100644 --- a/ios/chrome/browser/unified_consent/unified_consent_service_factory.cc +++ b/ios/chrome/browser/unified_consent/unified_consent_service_factory.cc
@@ -59,7 +59,7 @@ sync_preferences::PrefServiceSyncable* user_pref_service = browser_state->GetSyncablePrefs(); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForBrowserState(browser_state); syncer::SyncService* sync_service = ProfileSyncServiceFactory::GetForBrowserState(browser_state);
diff --git a/ios/chrome/browser/web/image_fetch_js_unittest.mm b/ios/chrome/browser/web/image_fetch_js_unittest.mm index e5d3739..2140573 100644 --- a/ios/chrome/browser/web/image_fetch_js_unittest.mm +++ b/ios/chrome/browser/web/image_fetch_js_unittest.mm
@@ -85,17 +85,12 @@ WebTestWithWebState::SetUp(); server_.RegisterDefaultHandler(base::BindRepeating(HandleRequest)); ASSERT_TRUE(server_.Start()); - web_state()->AddScriptCommandCallback( + subscription_ = web_state()->AddScriptCommandCallback( base::BindRepeating(&ImageFetchJsTest::OnMessageFromJavaScript, base::Unretained(this)), kCommandPrefix); } - void TearDown() override { - web_state()->RemoveScriptCommandCallback(kCommandPrefix); - WebTestWithWebState::TearDown(); - } - void OnMessageFromJavaScript(const base::DictionaryValue& message, const GURL& page_url, bool user_is_interacting, @@ -104,6 +99,9 @@ message_ = message.Clone(); } + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + net::EmbeddedTestServer server_; base::Value message_; bool message_received_ = false;
diff --git a/ios/chrome/browser/web/image_fetch_tab_helper.h b/ios/chrome/browser/web/image_fetch_tab_helper.h index 22ed08b..dd08784 100644 --- a/ios/chrome/browser/web/image_fetch_tab_helper.h +++ b/ios/chrome/browser/web/image_fetch_tab_helper.h
@@ -103,6 +103,9 @@ // |OnImageDataReceived| and used to invoke the corresponding callback. int call_id_ = 0; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + base::WeakPtrFactory<ImageFetchTabHelper> weak_ptr_factory_; WEB_STATE_USER_DATA_KEY_DECL();
diff --git a/ios/chrome/browser/web/image_fetch_tab_helper.mm b/ios/chrome/browser/web/image_fetch_tab_helper.mm index 6d4e849..5e64dd8 100644 --- a/ios/chrome/browser/web/image_fetch_tab_helper.mm +++ b/ios/chrome/browser/web/image_fetch_tab_helper.mm
@@ -67,7 +67,7 @@ web_state->AddObserver(this); // BindRepeating cannot work on WeakPtr and function with return value, use // lambda as mediator. - web_state->AddScriptCommandCallback( + subscription_ = web_state->AddScriptCommandCallback( base::BindRepeating(&ImageFetchTabHelper::OnJsMessage, weak_ptr_factory_.GetWeakPtr()), kCommandPrefix); @@ -87,7 +87,6 @@ } void ImageFetchTabHelper::WebStateDestroyed(web::WebState* web_state) { - web_state->RemoveScriptCommandCallback(kCommandPrefix); for (auto&& pair : js_callbacks_) std::move(pair.second).Run(nullptr); web_state->RemoveObserver(this);
diff --git a/ios/chrome/browser/web/java_script_console/java_script_console_tab_helper.h b/ios/chrome/browser/web/java_script_console/java_script_console_tab_helper.h index 25d443b..26663b2 100644 --- a/ios/chrome/browser/web/java_script_console/java_script_console_tab_helper.h +++ b/ios/chrome/browser/web/java_script_console/java_script_console_tab_helper.h
@@ -42,6 +42,9 @@ // The delegate associated with the receiver. JavaScriptConsoleTabHelperDelegate* delegate_ = nullptr; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + // The WebState this instance is observing. Will be null after // WebStateDestroyed has been called. web::WebState* web_state_ = nullptr;
diff --git a/ios/chrome/browser/web/java_script_console/java_script_console_tab_helper.mm b/ios/chrome/browser/web/java_script_console/java_script_console_tab_helper.mm index dbb37d7..0f4facdd 100644 --- a/ios/chrome/browser/web/java_script_console/java_script_console_tab_helper.mm +++ b/ios/chrome/browser/web/java_script_console/java_script_console_tab_helper.mm
@@ -24,7 +24,7 @@ JavaScriptConsoleTabHelper::JavaScriptConsoleTabHelper(web::WebState* web_state) : web_state_(web_state) { web_state->AddObserver(this); - web_state->AddScriptCommandCallback( + subscription_ = web_state->AddScriptCommandCallback( base::BindRepeating( &JavaScriptConsoleTabHelper::OnJavaScriptConsoleMessage, base::Unretained(this)), @@ -62,7 +62,6 @@ } void JavaScriptConsoleTabHelper::WebStateDestroyed(web::WebState* web_state) { - web_state->RemoveScriptCommandCallback(kCommandPrefix); web_state->RemoveObserver(this); web_state_ = nullptr; } @@ -75,7 +74,6 @@ JavaScriptConsoleTabHelper::~JavaScriptConsoleTabHelper() { if (web_state_) { web_state_->RemoveObserver(this); - web_state_->RemoveScriptCommandCallback(kCommandPrefix); web_state_ = nullptr; } }
diff --git a/ios/chrome/browser/web/print_tab_helper.h b/ios/chrome/browser/web/print_tab_helper.h index 828da6080..3ba9138 100644 --- a/ios/chrome/browser/web/print_tab_helper.h +++ b/ios/chrome/browser/web/print_tab_helper.h
@@ -41,6 +41,9 @@ __weak id<WebStatePrinter> printer_; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + WEB_STATE_USER_DATA_KEY_DECL(); DISALLOW_COPY_AND_ASSIGN(PrintTabHelper);
diff --git a/ios/chrome/browser/web/print_tab_helper.mm b/ios/chrome/browser/web/print_tab_helper.mm index 3579bd8..6c580e1 100644 --- a/ios/chrome/browser/web/print_tab_helper.mm +++ b/ios/chrome/browser/web/print_tab_helper.mm
@@ -23,7 +23,7 @@ PrintTabHelper::PrintTabHelper(web::WebState* web_state) { web_state->AddObserver(this); - web_state->AddScriptCommandCallback( + subscription_ = web_state->AddScriptCommandCallback( base::Bind(&PrintTabHelper::OnPrintCommand, base::Unretained(this), base::Unretained(web_state)), kPrintCommandPrefix); @@ -37,7 +37,6 @@ void PrintTabHelper::WebStateDestroyed(web::WebState* web_state) { // Stops handling print requests from the web page. - web_state->RemoveScriptCommandCallback(kPrintCommandPrefix); web_state->RemoveObserver(this); }
diff --git a/ios/chrome/browser/webdata_services/BUILD.gn b/ios/chrome/browser/webdata_services/BUILD.gn index fffd82d..b75897d 100644 --- a/ios/chrome/browser/webdata_services/BUILD.gn +++ b/ios/chrome/browser/webdata_services/BUILD.gn
@@ -13,7 +13,6 @@ "//components/keyed_service/core", "//components/keyed_service/ios", "//components/search_engines", - "//components/signin/core/browser", "//components/signin/public/webdata", "//components/webdata_services", "//ios/chrome/browser",
diff --git a/ios/chrome/test/DEPS b/ios/chrome/test/DEPS index 0c03455d..ae791ab 100644 --- a/ios/chrome/test/DEPS +++ b/ios/chrome/test/DEPS
@@ -10,25 +10,7 @@ "+components/metrics", "+components/network_time", "+components/prefs", - "+components/signin/core/browser", "+components/signin/public/base", - # Use identity_manager.h instead of the below files; - # see https://groups.google.com/a/chromium.org/d/msg/chromium-dev/dgFLuxqZt1o/iEqkyoQQBwAJ for help and info. - "-components/signin/internal/identity_manager/account_fetcher_service.h", - "-components/signin/internal/identity_manager/account_info_fetcher.h", - "-components/signin/internal/identity_manager/account_tracker_service.h", - "-components/signin/internal/identity_manager/child_account_info_fetcher_android.h", - "-components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/gaia_cookie_manager_service.h", - "-components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_helper.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_token_fetcher.h", - "-components/signin/internal/identity_manager/primary_account_manager.h", - "-components/signin/internal/identity_manager/primary_account_policy_manager.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h", - "-components/signin/internal/identity_manager/ubertoken_fetcher_impl.h", - "+components/sync", "+components/sync_device_info", "+components/translate",
diff --git a/ios/chrome/test/app/BUILD.gn b/ios/chrome/test/app/BUILD.gn index b95e731..18d9d454 100644 --- a/ios/chrome/test/app/BUILD.gn +++ b/ios/chrome/test/app/BUILD.gn
@@ -44,7 +44,7 @@ "//components/keyed_service/core", "//components/metrics", "//components/prefs", - "//components/signin/core/browser", + "//components/signin/public/base", "//components/sync/test/fake_server", "//components/sync_device_info", "//google_apis",
diff --git a/ios/chrome/test/earl_grey/BUILD.gn b/ios/chrome/test/earl_grey/BUILD.gn index 2819f7c..79ec786 100644 --- a/ios/chrome/test/earl_grey/BUILD.gn +++ b/ios/chrome/test/earl_grey/BUILD.gn
@@ -219,8 +219,8 @@ deps = [ "//base", "//base/test:test_support", + "//components/content_settings/core/browser", "//components/payments/core:core", - "//components/signin/core/browser", "//components/strings", "//components/sync/base", "//components/translate/core/browser", @@ -322,8 +322,8 @@ deps = [ "//base", "//base/test:test_support", + "//components/content_settings/core/browser", "//components/payments/core:core", - "//components/signin/core/browser", "//components/strings", "//components/sync/base", "//components/translate/core/browser",
diff --git a/ios/chrome/test/wpt/cwt_webdriver_app_interface.mm b/ios/chrome/test/wpt/cwt_webdriver_app_interface.mm index c01b0fd7..f13a567 100644 --- a/ios/chrome/test/wpt/cwt_webdriver_app_interface.mm +++ b/ios/chrome/test/wpt/cwt_webdriver_app_interface.mm
@@ -192,12 +192,14 @@ }); __block BOOL webStateFound = NO; + __block std::unique_ptr<web::WebState::ScriptCommandSubscription> + subscription; grey_dispatch_sync_on_main_thread(^{ web::WebState* webState = GetWebStateWithId(tabID); if (!webState) return; webStateFound = YES; - webState->AddScriptCommandCallback(callback, command); + subscription = webState->AddScriptCommandCallback(callback, command); webState->ExecuteJavaScript( base::UTF8ToUTF16(scriptFunctionWithCompletionHandler)); }); @@ -213,12 +215,6 @@ return scriptExecutionComplete; }); - grey_dispatch_sync_on_main_thread(^{ - web::WebState* webState = GetWebStateWithId(tabID); - if (webState) - webState->RemoveScriptCommandCallback(command); - }); - if (!success) return nil;
diff --git a/ios/public/provider/chrome/browser/DEPS b/ios/public/provider/chrome/browser/DEPS index 9bdde63..9d4bc261 100644 --- a/ios/public/provider/chrome/browser/DEPS +++ b/ios/public/provider/chrome/browser/DEPS
@@ -2,7 +2,6 @@ "+components/autofill/core/browser", "+components/favicon_base", "+components/metrics", - "+components/signin/ios/browser", "+components/sync_sessions", "+google_apis/gaia", "+ios/web/public",
diff --git a/ios/web/favicon/favicon_manager.h b/ios/web/favicon/favicon_manager.h index 6958ae1f..710bebc 100644 --- a/ios/web/favicon/favicon_manager.h +++ b/ios/web/favicon/favicon_manager.h
@@ -7,10 +7,10 @@ #include "base/macros.h" #include "base/values.h" +#import "ios/web/web_state/web_state_impl.h" class GURL; namespace web { -class WebStateImpl; class WebFrame; // Handles "favicon.favicons" message from injected JavaScript and notifies @@ -28,6 +28,9 @@ WebStateImpl* web_state_impl_ = nullptr; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + DISALLOW_COPY_AND_ASSIGN(FaviconManager); };
diff --git a/ios/web/favicon/favicon_manager.mm b/ios/web/favicon/favicon_manager.mm index 6fb9d76..6e68537 100644 --- a/ios/web/favicon/favicon_manager.mm +++ b/ios/web/favicon/favicon_manager.mm
@@ -5,7 +5,6 @@ #import "ios/web/favicon/favicon_manager.h" #import "ios/web/favicon/favicon_util.h" -#import "ios/web/web_state/web_state_impl.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -19,14 +18,12 @@ FaviconManager::FaviconManager(WebStateImpl* web_state) : web_state_impl_(web_state) { - web_state_impl_->AddScriptCommandCallback( + subscription_ = web_state_impl_->AddScriptCommandCallback( base::BindRepeating(&FaviconManager::OnJsMessage, base::Unretained(this)), kCommandPrefix); } -FaviconManager::~FaviconManager() { - web_state_impl_->RemoveScriptCommandCallback(kCommandPrefix); -} +FaviconManager::~FaviconManager() {} void FaviconManager::OnJsMessage(const base::DictionaryValue& message, const GURL& page_url,
diff --git a/ios/web/find_in_page/find_in_page_manager_impl.mm b/ios/web/find_in_page/find_in_page_manager_impl.mm index d9a4d6b..3e8b46b 100644 --- a/ios/web/find_in_page/find_in_page_manager_impl.mm +++ b/ios/web/find_in_page/find_in_page_manager_impl.mm
@@ -106,7 +106,8 @@ } void FindInPageManagerImpl::StartSearch(NSString* query) { - std::set<WebFrame*> all_frames = GetAllWebFrames(web_state_); + std::set<WebFrame*> all_frames = + web_state_->GetWebFramesManager()->GetAllWebFrames(); last_find_request_.Reset(query, all_frames.size()); if (all_frames.size() == 0) { // No frames to search in. @@ -148,7 +149,7 @@ /*new_pending_frame_call_count=*/0); std::vector<base::Value> params; - for (WebFrame* frame : GetAllWebFrames(web_state_)) { + for (WebFrame* frame : web_state_->GetWebFramesManager()->GetAllWebFrames()) { frame->CallJavaScriptFunction(kFindInPageStop, params); } if (delegate_) {
diff --git a/ios/web/find_in_page/find_in_page_manager_inttest.mm b/ios/web/find_in_page/find_in_page_manager_inttest.mm index cc6b832..64005e2b 100644 --- a/ios/web/find_in_page/find_in_page_manager_inttest.mm +++ b/ios/web/find_in_page/find_in_page_manager_inttest.mm
@@ -5,7 +5,7 @@ #import "base/test/ios/wait_util.h" #include "ios/testing/embedded_test_server_handlers.h" #import "ios/web/public/find_in_page/find_in_page_manager.h" -#include "ios/web/public/js_messaging/web_frame_util.h" +#import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/fakes/fake_find_in_page_manager_delegate.h" #import "ios/web/public/test/navigation_test_util.h" #import "ios/web/public/test/web_test_with_web_state.h" @@ -76,7 +76,7 @@ net::EscapeQueryParamValue(kFindInPageIFrameUrl, /*use_plus=*/true); test::LoadUrl(web_state(), test_server_.GetURL(url_spec)); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ - return GetAllWebFrames(web_state()).size() == 2; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 2; })); GetFindInPageManager()->Find(@"Main frame text", @@ -97,7 +97,7 @@ net::EscapeQueryParamValue(kFindInPageIFrameUrl, /*use_plus=*/true); test::LoadUrl(web_state(), test_server_.GetURL(url_spec)); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ - return GetAllWebFrames(web_state()).size() == 2; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 2; })); GetFindInPageManager()->Find(@"frame", FindInPageOptions::FindInPageSearch); @@ -117,7 +117,7 @@ net::EscapeQueryParamValue(kFindInPageIFrameUrl, /*use_plus=*/true); test::LoadUrl(web_state(), test_server_.GetURL(url_spec)); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ - return GetAllWebFrames(web_state()).size() == 2; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 2; })); GetFindInPageManager()->Find(@"foobar", FindInPageOptions::FindInPageSearch); @@ -137,7 +137,7 @@ net::EscapeQueryParamValue(kFindInPageIFrameUrl, /*use_plus=*/true); test::LoadUrl(web_state(), test_server_.GetURL(url_spec)); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ - return GetAllWebFrames(web_state()).size() == 2; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 2; })); GetFindInPageManager()->Find(@"frame", FindInPageOptions::FindInPageSearch); @@ -166,7 +166,7 @@ net::EscapeQueryParamValue(kFindInPageIFrameUrl, /*use_plus=*/true); test::LoadUrl(web_state(), test_server_.GetURL(url_spec)); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ - return GetAllWebFrames(web_state()).size() == 2; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 2; })); GetFindInPageManager()->Find(@"frame", FindInPageOptions::FindInPageSearch); @@ -194,7 +194,7 @@ net::EscapeQueryParamValue(kFindInPageIFrameUrl, /*use_plus=*/true); test::LoadUrl(web_state(), test_server_.GetURL(url_spec)); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ - return GetAllWebFrames(web_state()).size() == 2; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 2; })); GetFindInPageManager()->Find(@"iframe", FindInPageOptions::FindInPageSearch); @@ -219,7 +219,7 @@ net::EscapeQueryParamValue(kFindInPageIFrameUrl, /*use_plus=*/true); test::LoadUrl(web_state(), test_server_.GetURL(url_spec)); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ - return GetAllWebFrames(web_state()).size() == 2; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 2; })); GetFindInPageManager()->Find(@"iframe", FindInPageOptions::FindInPageSearch);
diff --git a/ios/web/find_in_page/find_in_page_manger_impl_unittest.mm b/ios/web/find_in_page/find_in_page_manger_impl_unittest.mm index 87da5b7..c44a280 100644 --- a/ios/web/find_in_page/find_in_page_manger_impl_unittest.mm +++ b/ios/web/find_in_page/find_in_page_manger_impl_unittest.mm
@@ -8,10 +8,10 @@ #import "base/test/ios/wait_util.h" #include "base/values.h" #import "ios/web/find_in_page/find_in_page_constants.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/fakes/fake_find_in_page_manager_delegate.h" #include "ios/web/public/test/fakes/fake_web_frame.h" +#import "ios/web/public/test/fakes/fake_web_frames_manager.h" #import "ios/web/public/test/fakes/test_web_state.h" #include "ios/web/public/test/web_test.h" #include "testing/gtest/include/gtest/gtest.h" @@ -37,9 +37,11 @@ // FindInPageManagerDelegate is correct depending on what web frames return. class FindInPageManagerImplTest : public WebTest { protected: - FindInPageManagerImplTest() - : test_web_state_(std::make_unique<TestWebState>()) { - test_web_state_->CreateWebFramesManager(); + FindInPageManagerImplTest() { + test_web_state_ = std::make_unique<TestWebState>(); + auto frames_manager = std::make_unique<FakeWebFramesManager>(); + fake_web_frames_manager_ = frames_manager.get(); + test_web_state_->SetWebFramesManager(std::move(frames_manager)); FindInPageManagerImpl::CreateForWebState(test_web_state_.get()); GetFindInPageManager()->SetDelegate(&fake_delegate_); } @@ -79,7 +81,20 @@ return frame; } + void AddWebFrame(std::unique_ptr<WebFrame> frame) { + WebFrame* frame_ptr = frame.get(); + fake_web_frames_manager_->AddWebFrame(std::move(frame)); + test_web_state_->OnWebFrameDidBecomeAvailable(frame_ptr); + } + + void RemoveWebFrame(const std::string& frame_id) { + WebFrame* frame_ptr = fake_web_frames_manager_->GetFrameWithId(frame_id); + test_web_state_->OnWebFrameWillBecomeUnavailable(frame_ptr); + fake_web_frames_manager_->RemoveWebFrame(frame_id); + } + std::unique_ptr<TestWebState> test_web_state_; + FakeWebFramesManager* fake_web_frames_manager_; FakeFindInPageManagerDelegate fake_delegate_; }; @@ -92,8 +107,8 @@ auto frame_with_two_matches = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -121,8 +136,8 @@ auto frame_with_one_match = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(1.0), kOneMatchFrameId); FakeWebFrame* frame_with_one_match_ptr = frame_with_one_match.get(); - test_web_state_->AddWebFrame(std::move(frame_with_null_result)); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_null_result)); + AddWebFrame(std::move(frame_with_one_match)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -148,11 +163,11 @@ auto frame_with_two_matches = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); - test_web_state_->RemoveWebFrame(kOneMatchFrameId); + RemoveWebFrame(kOneMatchFrameId); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^bool { @@ -174,11 +189,11 @@ TEST_F(FindInPageManagerImplTest, DestroyWebStateDuringFind) { auto frame_with_one_match = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(1.0), kOneMatchFrameId); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_one_match)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); - test_web_state_ = nullptr; + test_web_state_.reset(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(fake_delegate_.state()); } @@ -191,12 +206,12 @@ FakeWebFrame* frame_with_one_match_ptr = frame_with_one_match.get(); auto frame_with_two_matches = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); - test_web_state_->RemoveWebFrame(kTwoMatchesFrameId); + RemoveWebFrame(kTwoMatchesFrameId); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^bool { base::RunLoop().RunUntilIdle(); return fake_delegate_.state(); @@ -218,11 +233,11 @@ frame_with_two_matches->AddJsResultForFunctionCall( std::make_unique<base::Value>(2.0), kFindInPagePump); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_two_matches)); auto frame_with_one_match = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(1.0), kOneMatchFrameId); FakeWebFrame* frame_with_one_match_ptr = frame_with_one_match.get(); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_one_match)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -248,7 +263,7 @@ auto frame_with_one_match = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(1.0), kOneMatchFrameId); FakeWebFrame* frame_with_one_match_ptr = frame_with_one_match.get(); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_one_match)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -262,7 +277,7 @@ auto frame_cannot_call_func = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(1.0), kOneMatchFrameId); frame_cannot_call_func->set_can_call_function(false); - test_web_state_->AddWebFrame(std::move(frame_cannot_call_func)); + AddWebFrame(std::move(frame_cannot_call_func)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -292,7 +307,7 @@ auto frame_with_zero_matches = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(0.0), "frame_with_zero_matches"); FakeWebFrame* frame_with_zero_matches_ptr = frame_with_zero_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_zero_matches)); + AddWebFrame(std::move(frame_with_zero_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -314,7 +329,7 @@ auto frame_with_two_matches = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -336,7 +351,7 @@ auto frame_with_two_matches = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -371,8 +386,8 @@ auto frame_with_two_matches = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -423,8 +438,8 @@ auto frame_with_two_matches = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -477,8 +492,8 @@ auto frame_with_two_matches = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -509,7 +524,7 @@ TEST_F(FindInPageManagerImplTest, FindDidNotRepondToNextOrPrevIfNoSearch) { auto frame_with_three_matches = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(3.0), "frame_with_three_matches"); - test_web_state_->AddWebFrame(std::move(frame_with_three_matches)); + AddWebFrame(std::move(frame_with_three_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageNext); base::RunLoop().RunUntilIdle(); @@ -533,8 +548,8 @@ auto frame_with_two_matches = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); FakeWebFrame* frame_with_two_matches_ptr = frame_with_two_matches.get(); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -546,7 +561,7 @@ EXPECT_EQ("__gCrWeb.findInPage.selectAndScrollToVisibleMatch(0);", frame_with_one_match_ptr->GetJavaScriptCallHistory()[1]); - test_web_state_->RemoveWebFrame(kOneMatchFrameId); + RemoveWebFrame(kOneMatchFrameId); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageNext); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^bool { @@ -561,9 +576,9 @@ TEST_F(FindInPageManagerImplTest, FindDidNotRepondAfterFrameRemoved) { auto frame_with_one_match = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(1.0), kOneMatchFrameId); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_one_match)); - test_web_state_->RemoveWebFrame(kOneMatchFrameId); + RemoveWebFrame(kOneMatchFrameId); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(fake_delegate_.state()); @@ -575,7 +590,7 @@ TEST_F(FindInPageManagerImplTest, FindInPageUpdateMatchCountAfterFrameRemoved) { auto frame_with_one_match = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(1.0), kOneMatchFrameId); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_one_match)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); @@ -584,7 +599,7 @@ return fake_delegate_.state(); })); - test_web_state_->RemoveWebFrame(kOneMatchFrameId); + RemoveWebFrame(kOneMatchFrameId); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^bool { base::RunLoop().RunUntilIdle(); return fake_delegate_.state()->match_count == 0; @@ -599,8 +614,8 @@ std::make_unique<base::Value>(0.0), kZeroMatchesFrameId); auto frame_with_two_matches = CreateChildWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), kTwoMatchesFrameId); - test_web_state_->AddWebFrame(std::move(frame_with_zero_matches)); - test_web_state_->AddWebFrame(std::move(frame_with_two_matches)); + AddWebFrame(std::move(frame_with_zero_matches)); + AddWebFrame(std::move(frame_with_two_matches)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^bool { @@ -609,7 +624,7 @@ })); fake_delegate_.Reset(); - test_web_state_->RemoveWebFrame(kZeroMatchesFrameId); + RemoveWebFrame(kZeroMatchesFrameId); EXPECT_FALSE(fake_delegate_.state()); } @@ -631,7 +646,7 @@ TEST_F(FindInPageManagerImplTest, FindInPageCanStopFind) { auto frame_with_one_match = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(1.0), kOneMatchFrameId); - test_web_state_->AddWebFrame(std::move(frame_with_one_match)); + AddWebFrame(std::move(frame_with_one_match)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^bool { @@ -655,7 +670,7 @@ auto frame_with_hidden_match = CreateMainWebFrameWithJsResultForFind( std::make_unique<base::Value>(2.0), "frame_with_hidden_match"); FakeWebFrame* frame_with_hidden_match_ptr = frame_with_hidden_match.get(); - test_web_state_->AddWebFrame(std::move(frame_with_hidden_match)); + AddWebFrame(std::move(frame_with_hidden_match)); GetFindInPageManager()->Find(@"foo", FindInPageOptions::FindInPageSearch); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^bool {
diff --git a/ios/web/js_messaging/BUILD.gn b/ios/web/js_messaging/BUILD.gn index 4367260..7038bba 100644 --- a/ios/web/js_messaging/BUILD.gn +++ b/ios/web/js_messaging/BUILD.gn
@@ -13,7 +13,6 @@ "//ios/web/public", "//ios/web/public/deprecated", "//ios/web/public/js_messaging", - "//ios/web/web_state:web_state_impl_header", "//ios/web/web_view:util", "//url", ]
diff --git a/ios/web/js_messaging/web_frame_impl.h b/ios/web/js_messaging/web_frame_impl.h index a064798..5b22504 100644 --- a/ios/web/js_messaging/web_frame_impl.h +++ b/ios/web/js_messaging/web_frame_impl.h
@@ -15,13 +15,12 @@ #include "base/memory/weak_ptr.h" #include "base/values.h" #include "crypto/symmetric_key.h" +#import "ios/web/public/web_state/web_state.h" #include "ios/web/public/web_state/web_state_observer.h" #include "url/gurl.h" namespace web { -class WebState; - class WebFrameImpl : public WebFrame, public web::WebStateObserver { public: // Creates a new WebFrame. |initial_message_id| will be used as the message ID @@ -139,6 +138,8 @@ GURL security_origin_; // The associated web state. web::WebState* web_state_ = nullptr; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; base::WeakPtrFactory<WebFrameImpl> weak_ptr_factory_;
diff --git a/ios/web/js_messaging/web_frame_impl.mm b/ios/web/js_messaging/web_frame_impl.mm index 82b4fa8..0b0cdf7 100644 --- a/ios/web/js_messaging/web_frame_impl.mm +++ b/ios/web/js_messaging/web_frame_impl.mm
@@ -17,7 +17,6 @@ #include "crypto/aead.h" #include "crypto/random.h" #include "ios/web/public/thread/web_task_traits.h" -#import "ios/web/public/web_state/web_state.h" #include "url/gurl.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -42,7 +41,7 @@ DCHECK(web_state); web_state->AddObserver(this); - web_state->AddScriptCommandCallback( + subscription_ = web_state->AddScriptCommandCallback( base::BindRepeating(&WebFrameImpl::OnJavaScriptReply, base::Unretained(this), base::Unretained(web_state)), GetScriptCommandPrefix()); @@ -269,7 +268,6 @@ void WebFrameImpl::DetachFromWebState() { if (web_state_) { - web_state_->RemoveScriptCommandCallback(GetScriptCommandPrefix()); web_state_->RemoveObserver(this); web_state_ = nullptr; }
diff --git a/ios/web/js_messaging/web_frame_impl_inttest.mm b/ios/web/js_messaging/web_frame_impl_inttest.mm index ba15499..39fe8f7 100644 --- a/ios/web/js_messaging/web_frame_impl_inttest.mm +++ b/ios/web/js_messaging/web_frame_impl_inttest.mm
@@ -7,12 +7,12 @@ #include "base/bind.h" #include "base/ios/ios_util.h" #import "base/test/ios/wait_util.h" -#include "ios/web/js_messaging/web_frames_manager_impl.h" -#include "ios/web/public/js_messaging/web_frame_util.h" +#import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/fakes/test_web_client.h" #import "ios/web/public/test/js_test_util.h" #import "ios/web/public/test/web_js_test.h" #import "ios/web/public/test/web_test_with_web_state.h" +#import "ios/web/public/web_state/web_state.h" #include "testing/gtest/include/gtest/gtest.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -26,8 +26,7 @@ // Returns the first WebFrame found which is not the main frame in the given // |web_state|. Does not wait and returns null if such a frame is not found. web::WebFrame* GetChildWebFrameForWebState(web::WebState* web_state) { - __block web::WebFramesManagerImpl* manager = - web::WebFramesManagerImpl::FromWebState(web_state); + __block web::WebFramesManager* manager = web_state->GetWebFramesManager(); web::WebFrame* iframe = nullptr; for (web::WebFrame* frame : manager->GetAllWebFrames()) { if (!frame->IsMainFrame()) { @@ -49,7 +48,7 @@ TEST_F(WebFrameImplIntTest, CallJavaScriptFunctionOnMainFrame) { ASSERT_TRUE(LoadHtml("<p>")); - WebFrame* main_frame = GetMainWebFrame(web_state()); + WebFrame* main_frame = web_state()->GetWebFramesManager()->GetMainWebFrame(); ASSERT_TRUE(main_frame); NSTimeInterval js_timeout = kWaitForJSCompletionTimeout; @@ -73,8 +72,7 @@ TEST_F(WebFrameImplIntTest, CallJavaScriptFunctionOnIframe) { ASSERT_TRUE(LoadHtml("<p><iframe srcdoc='<p>'/>")); - __block WebFramesManagerImpl* manager = - WebFramesManagerImpl::FromWebState(web_state()); + __block WebFramesManager* manager = web_state()->GetWebFramesManager(); ASSERT_TRUE(WaitUntilConditionOrTimeout( base::test::ios::kWaitForJSCompletionTimeout, ^bool { return manager->GetAllWebFrames().size() == 2; @@ -108,7 +106,7 @@ " while(true) {}" "};"); - WebFrame* main_frame = GetMainWebFrame(web_state()); + WebFrame* main_frame = web_state()->GetWebFramesManager()->GetMainWebFrame(); ASSERT_TRUE(main_frame); __block bool called = false; @@ -135,7 +133,7 @@ TEST_F(WebFrameImplIntTest, PreventMessageReplay) { ASSERT_TRUE(LoadHtml("<p>")); - WebFrame* main_frame = GetMainWebFrame(web_state()); + WebFrame* main_frame = web_state()->GetWebFramesManager()->GetMainWebFrame(); ASSERT_TRUE(main_frame); // Inject function into main frame to intercept encrypted message targeted for @@ -208,21 +206,20 @@ bool /* user_is_interacting */, WebFrame* sender_frame) { command_received = true; EXPECT_TRUE(sender_frame->IsMainFrame()); - EXPECT_EQ(GetMainWebFrame(web_state()), sender_frame); + EXPECT_EQ(web_state()->GetWebFramesManager()->GetMainWebFrame(), + sender_frame); }); - web_state()->AddScriptCommandCallback(callback, "senderFrameTestCommand"); - __block WebFramesManagerImpl* manager = - WebFramesManagerImpl::FromWebState(web_state()); + auto subscription = + web_state()->AddScriptCommandCallback(callback, "senderFrameTestCommand"); EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return manager->GetAllWebFrames().size() == 1; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 1; })); ExecuteJavaScript(@"__gCrWeb.message.invokeOnHost({'command':" @"'senderFrameTestCommand.mainframe'});"); EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ return command_received; })); - web_state()->RemoveScriptCommandCallback("senderFrameTestCommand"); } // Tests that an iframe WebFrame is passed to the callback when sending a @@ -240,11 +237,10 @@ EXPECT_EQ(GetChildWebFrameForWebState(web_state()), sender_frame); }); - web_state()->AddScriptCommandCallback(callback, "senderFrameTestCommand"); - __block WebFramesManagerImpl* manager = - WebFramesManagerImpl::FromWebState(web_state()); + auto subscription = + web_state()->AddScriptCommandCallback(callback, "senderFrameTestCommand"); EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return manager->GetAllWebFrames().size() == 2; + return web_state()->GetWebFramesManager()->GetAllWebFrames().size() == 2; })); ExecuteJavaScript( @"window.frames[0].__gCrWeb.message.invokeOnHost({'command':'" @@ -252,6 +248,5 @@ EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ return command_received; })); - web_state()->RemoveScriptCommandCallback("senderFrameTestCommand"); } }
diff --git a/ios/web/js_messaging/web_frame_util.mm b/ios/web/js_messaging/web_frame_util.mm index 74c1bf51..81fff4b 100644 --- a/ios/web/js_messaging/web_frame_util.mm +++ b/ios/web/js_messaging/web_frame_util.mm
@@ -14,14 +14,9 @@ #endif namespace web { -WebFrame* GetMainWebFrame(WebState* web_state) { - WebFramesManager* manager = WebFramesManager::FromWebState(web_state); - DCHECK(manager); - return manager->GetMainWebFrame(); -} std::string GetMainWebFrameId(WebState* web_state) { - WebFrame* main_frame = GetMainWebFrame(web_state); + WebFrame* main_frame = web_state->GetWebFramesManager()->GetMainWebFrame(); if (!main_frame) { return std::string(); } @@ -29,20 +24,13 @@ } WebFrame* GetWebFrameWithId(WebState* web_state, const std::string& frame_id) { - if (frame_id.size() == 0) + if (frame_id.empty()) return nullptr; - WebFramesManager* manager = WebFramesManager::FromWebState(web_state); - DCHECK(manager); - return manager->GetFrameWithId(frame_id); + return web_state->GetWebFramesManager()->GetFrameWithId(frame_id); } std::string GetWebFrameId(WebFrame* frame) { return frame ? frame->GetFrameId() : std::string(); } -std::set<WebFrame*> GetAllWebFrames(WebState* web_state) { - WebFramesManager* manager = WebFramesManager::FromWebState(web_state); - return manager->GetAllWebFrames(); -} - } // namespace web
diff --git a/ios/web/js_messaging/web_frame_util_unittest.mm b/ios/web/js_messaging/web_frame_util_unittest.mm index 8a805c2..d635abb9 100644 --- a/ios/web/js_messaging/web_frame_util_unittest.mm +++ b/ios/web/js_messaging/web_frame_util_unittest.mm
@@ -6,6 +6,7 @@ #include "base/test/gtest_util.h" #include "ios/web/public/test/fakes/fake_web_frame.h" +#import "ios/web/public/test/fakes/fake_web_frames_manager.h" #import "ios/web/public/test/fakes/test_web_state.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" @@ -16,96 +17,102 @@ namespace web { -typedef PlatformTest WebFrameUtilTest; +class WebFrameUtilTest : public PlatformTest { + public: + WebFrameUtilTest() { + auto frames_manager = std::make_unique<FakeWebFramesManager>(); + fake_web_frames_manager_ = frames_manager.get(); + test_web_state_.SetWebFramesManager(std::move(frames_manager)); + } + + protected: + TestWebState test_web_state_; + FakeWebFramesManager* fake_web_frames_manager_; +}; // Tests the GetMainWebFrame function. TEST_F(WebFrameUtilTest, GetMainWebFrame) { - TestWebState test_web_state; - test_web_state.CreateWebFramesManager(); // Still no main frame. - EXPECT_EQ(nullptr, GetMainWebFrame(&test_web_state)); + EXPECT_EQ(nullptr, test_web_state_.GetWebFramesManager()->GetMainWebFrame()); auto iframe = std::make_unique<FakeWebFrame>("iframe", false, GURL::EmptyGURL()); - test_web_state.AddWebFrame(std::move(iframe)); + fake_web_frames_manager_->AddWebFrame(std::move(iframe)); // Still no main frame. - EXPECT_EQ(nullptr, GetMainWebFrame(&test_web_state)); + EXPECT_EQ(nullptr, test_web_state_.GetWebFramesManager()->GetMainWebFrame()); auto main_frame = std::make_unique<FakeWebFrame>("main_frame", true, GURL::EmptyGURL()); FakeWebFrame* main_frame_ptr = main_frame.get(); - test_web_state.AddWebFrame(std::move(main_frame)); + fake_web_frames_manager_->AddWebFrame(std::move(main_frame)); // Now there is a main frame. - EXPECT_EQ(main_frame_ptr, GetMainWebFrame(&test_web_state)); + EXPECT_EQ(main_frame_ptr, + test_web_state_.GetWebFramesManager()->GetMainWebFrame()); - test_web_state.RemoveWebFrame(main_frame_ptr->GetFrameId()); + fake_web_frames_manager_->RemoveWebFrame(main_frame_ptr->GetFrameId()); // Now there is no main frame. - EXPECT_EQ(nullptr, GetMainWebFrame(&test_web_state)); + EXPECT_EQ(nullptr, test_web_state_.GetWebFramesManager()->GetMainWebFrame()); } // Tests the GetMainWebFrameId function. TEST_F(WebFrameUtilTest, GetMainWebFrameId) { - TestWebState test_web_state; - test_web_state.CreateWebFramesManager(); // Still no main frame. - EXPECT_TRUE(GetMainWebFrameId(&test_web_state).empty()); + EXPECT_TRUE(GetMainWebFrameId(&test_web_state_).empty()); auto iframe = std::make_unique<FakeWebFrame>("iframe", false, GURL::EmptyGURL()); - test_web_state.AddWebFrame(std::move(iframe)); + fake_web_frames_manager_->AddWebFrame(std::move(iframe)); // Still no main frame. - EXPECT_TRUE(GetMainWebFrameId(&test_web_state).empty()); + EXPECT_TRUE(GetMainWebFrameId(&test_web_state_).empty()); auto main_frame = std::make_unique<FakeWebFrame>("main_frame", true, GURL::EmptyGURL()); FakeWebFrame* main_frame_ptr = main_frame.get(); - test_web_state.AddWebFrame(std::move(main_frame)); + fake_web_frames_manager_->AddWebFrame(std::move(main_frame)); // Now there is a main frame. - EXPECT_EQ("main_frame", GetMainWebFrameId(&test_web_state)); + EXPECT_EQ("main_frame", GetMainWebFrameId(&test_web_state_)); - test_web_state.RemoveWebFrame(main_frame_ptr->GetFrameId()); + fake_web_frames_manager_->RemoveWebFrame(main_frame_ptr->GetFrameId()); // Now there is no main frame. - EXPECT_TRUE(GetMainWebFrameId(&test_web_state).empty()); + EXPECT_TRUE(GetMainWebFrameId(&test_web_state_).empty()); } // Tests the GetWebFrameWithId function. TEST_F(WebFrameUtilTest, GetWebFrameWithId) { - TestWebState test_web_state; - test_web_state.CreateWebFramesManager(); // Still no main frame. - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "iframe")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "main_frame")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "unused")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "iframe")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "main_frame")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "unused")); auto iframe = std::make_unique<FakeWebFrame>("iframe", false, GURL::EmptyGURL()); FakeWebFrame* iframe_ptr = iframe.get(); - test_web_state.AddWebFrame(std::move(iframe)); + fake_web_frames_manager_->AddWebFrame(std::move(iframe)); // There is an iframe. - EXPECT_EQ(iframe_ptr, GetWebFrameWithId(&test_web_state, "iframe")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "main_frame")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "unused")); + EXPECT_EQ(iframe_ptr, GetWebFrameWithId(&test_web_state_, "iframe")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "main_frame")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "unused")); auto main_frame = std::make_unique<FakeWebFrame>("main_frame", true, GURL::EmptyGURL()); FakeWebFrame* main_frame_ptr = main_frame.get(); - test_web_state.AddWebFrame(std::move(main_frame)); + fake_web_frames_manager_->AddWebFrame(std::move(main_frame)); // Now there is a main frame. - EXPECT_EQ(iframe_ptr, GetWebFrameWithId(&test_web_state, "iframe")); - EXPECT_EQ(main_frame_ptr, GetWebFrameWithId(&test_web_state, "main_frame")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "unused")); + EXPECT_EQ(iframe_ptr, GetWebFrameWithId(&test_web_state_, "iframe")); + EXPECT_EQ(main_frame_ptr, GetWebFrameWithId(&test_web_state_, "main_frame")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "unused")); - test_web_state.RemoveWebFrame(main_frame_ptr->GetFrameId()); + fake_web_frames_manager_->RemoveWebFrame(main_frame_ptr->GetFrameId()); // Now there is only an iframe. - EXPECT_EQ(iframe_ptr, GetWebFrameWithId(&test_web_state, "iframe")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "main_frame")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "unused")); + EXPECT_EQ(iframe_ptr, GetWebFrameWithId(&test_web_state_, "iframe")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "main_frame")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "unused")); // Now there nothing left. - test_web_state.RemoveWebFrame(iframe_ptr->GetFrameId()); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "iframe")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "main_frame")); - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "unused")); + fake_web_frames_manager_->RemoveWebFrame(iframe_ptr->GetFrameId()); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "iframe")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "main_frame")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "unused")); // Test that GetWebFrameWithId returns nullptr for the empty string. - EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state, "")); + EXPECT_EQ(nullptr, GetWebFrameWithId(&test_web_state_, "")); } // Tests the GetWebFrameId GetWebFrameId function. @@ -117,19 +124,18 @@ // Tests the GetAllWebFrames function. TEST_F(WebFrameUtilTest, GetAllWebFrames) { - TestWebState test_web_state; - test_web_state.CreateWebFramesManager(); - - EXPECT_EQ(0U, GetAllWebFrames(&test_web_state).size()); + EXPECT_EQ(0U, + test_web_state_.GetWebFramesManager()->GetAllWebFrames().size()); auto main_frame = std::make_unique<FakeWebFrame>("main_frame", true, GURL::EmptyGURL()); FakeWebFrame* main_frame_ptr = main_frame.get(); - test_web_state.AddWebFrame(std::move(main_frame)); + fake_web_frames_manager_->AddWebFrame(std::move(main_frame)); auto iframe = std::make_unique<FakeWebFrame>("iframe", false, GURL::EmptyGURL()); FakeWebFrame* iframe_ptr = iframe.get(); - test_web_state.AddWebFrame(std::move(iframe)); - std::set<WebFrame*> all_frames = GetAllWebFrames(&test_web_state); + fake_web_frames_manager_->AddWebFrame(std::move(iframe)); + std::set<WebFrame*> all_frames = + test_web_state_.GetWebFramesManager()->GetAllWebFrames(); // Both frames should be returned EXPECT_NE(all_frames.end(), all_frames.find(main_frame_ptr)); EXPECT_NE(all_frames.end(), all_frames.find(iframe_ptr));
diff --git a/ios/web/js_messaging/web_frame_web_state_observer_inttest.mm b/ios/web/js_messaging/web_frame_web_state_observer_inttest.mm index dedb1e86..701baed 100644 --- a/ios/web/js_messaging/web_frame_web_state_observer_inttest.mm +++ b/ios/web/js_messaging/web_frame_web_state_observer_inttest.mm
@@ -7,9 +7,8 @@ #include "base/ios/ios_util.h" #include "base/test/scoped_feature_list.h" #include "ios/web/common/features.h" -#include "ios/web/js_messaging/web_frames_manager_impl.h" #import "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" +#import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/web_state/web_state.h" #import "ios/web/public/web_state/web_state_observer.h" #include "testing/gmock/include/gmock/gmock.h" @@ -52,15 +51,14 @@ // Verifies that the web frame passed to the observer is the main frame. ACTION_P(VerifyMainWebFrame, web_state) { EXPECT_EQ(web_state, arg0); - EXPECT_EQ(web::GetMainWebFrame(web_state), arg1); + EXPECT_EQ(web_state->GetWebFramesManager()->GetMainWebFrame(), arg1); } // Verifies that the web frame passed to the observer is a child frame. ACTION_P(VerifyChildWebFrame, web_state) { EXPECT_EQ(web_state, arg0); - web::WebFramesManagerImpl* manager = - web::WebFramesManagerImpl::FromWebState(web_state); + web::WebFramesManager* manager = web_state->GetWebFramesManager(); auto frames = manager->GetAllWebFrames(); EXPECT_TRUE(frames.end() != std::find(frames.begin(), frames.end(), arg1)); EXPECT_NE(manager->GetMainWebFrame(), arg1);
diff --git a/ios/web/js_messaging/web_frames_manager_impl.h b/ios/web/js_messaging/web_frames_manager_impl.h index a48b7bf..207a2d8 100644 --- a/ios/web/js_messaging/web_frames_manager_impl.h +++ b/ios/web/js_messaging/web_frames_manager_impl.h
@@ -8,20 +8,33 @@ #import "ios/web/public/js_messaging/web_frames_manager.h" #import <WebKit/WebKit.h> +#include <map> @class CRWWKScriptMessageRouter; namespace web { - +class WebState; class WebFrame; +// Delegate for WebFramesManager to publish frame events and get WebState. +class WebFramesManagerDelegate { + public: + virtual ~WebFramesManagerDelegate() {} + + // Will be invoked only once for each web frame in the page, when the frame is + // loaded and a WebFrame is added to the WebFramesManager. + virtual void OnWebFrameAvailable(WebFrame* frame) = 0; + // Will be invoked only once for each web frame in the page, when the frame is + // unloaed and before the WebFrame is removed from the WebFramesManager. + virtual void OnWebFrameUnavailable(WebFrame* frame) = 0; + + virtual WebState* GetWebState() = 0; +}; + class WebFramesManagerImpl : public WebFramesManager { public: + explicit WebFramesManagerImpl(WebFramesManagerDelegate& delegate); ~WebFramesManagerImpl() override; - explicit WebFramesManagerImpl(web::WebState* web_state); - - static void CreateForWebState(WebState* web_state); - static WebFramesManagerImpl* FromWebState(WebState* web_state); // Adds |frame| to the list of web frames associated with WebState. // The frame must not be already in the frame manager (the frame manager must @@ -52,8 +65,6 @@ CRWWKScriptMessageRouter* message_router); private: - friend class web::WebStateUserData<WebFramesManagerImpl>; - // Handles FrameBecameAvailable JS message and creates new WebFrame based on // frame info from the message (e.g. ID, encryption key, message counter, // etc.). @@ -68,7 +79,11 @@ // Reference to the current main web frame. WebFrame* main_web_frame_ = nullptr; - WebState* web_state_ = nullptr; + + // Reference to the delegate. + WebFramesManagerDelegate& delegate_; + + DISALLOW_COPY_AND_ASSIGN(WebFramesManagerImpl); }; } // namespace web
diff --git a/ios/web/js_messaging/web_frames_manager_impl.mm b/ios/web/js_messaging/web_frames_manager_impl.mm index 1c4a60e..b0d747f 100644 --- a/ios/web/js_messaging/web_frames_manager_impl.mm +++ b/ios/web/js_messaging/web_frames_manager_impl.mm
@@ -10,7 +10,7 @@ #include "crypto/symmetric_key.h" #import "ios/web/js_messaging/crw_wk_script_message_router.h" #include "ios/web/js_messaging/web_frame_impl.h" -#import "ios/web/web_state/web_state_impl.h" +#import "ios/web/public/web_state/web_state.h" #import "ios/web/web_view/wk_security_origin_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -26,27 +26,13 @@ namespace web { -// static -void WebFramesManagerImpl::CreateForWebState(WebState* web_state) { - DCHECK(web_state); - if (!FromWebState(web_state)) - web_state->SetUserData( - UserDataKey(), base::WrapUnique(new WebFramesManagerImpl(web_state))); -} - -// static -WebFramesManagerImpl* WebFramesManagerImpl::FromWebState(WebState* web_state) { - return static_cast<WebFramesManagerImpl*>( - WebFramesManager::FromWebState(web_state)); -} +WebFramesManagerImpl::WebFramesManagerImpl(WebFramesManagerDelegate& delegate) + : delegate_(delegate) {} WebFramesManagerImpl::~WebFramesManagerImpl() { RemoveAllWebFrames(); } -WebFramesManagerImpl::WebFramesManagerImpl(web::WebState* web_state) - : web_state_(web_state) {} - void WebFramesManagerImpl::AddFrame(std::unique_ptr<WebFrame> frame) { DCHECK(frame); DCHECK(!frame->GetFrameId().empty()); @@ -106,7 +92,7 @@ } void WebFramesManagerImpl::RegisterExistingFrames() { - web_state_->ExecuteJavaScript( + delegate_.GetWebState()->ExecuteJavaScript( base::UTF8ToUTF16("__gCrWeb.message.getExistingFrames();")); } @@ -138,7 +124,7 @@ webView:new_web_view]; [message_router setScriptMessageHandler:^(WKScriptMessage* message) { - DCHECK(!web_state_->IsBeingDestroyed()); + DCHECK(!delegate_.GetWebState()->IsBeingDestroyed()); this->OnFrameBecameUnavailable(message); } name:kFrameBecameUnavailableMessageName @@ -147,7 +133,7 @@ } void WebFramesManagerImpl::OnFrameBecameAvailable(WKScriptMessage* message) { - DCHECK(!web_state_->IsBeingDestroyed()); + DCHECK(!delegate_.GetWebState()->IsBeingDestroyed()); // Validate all expected message components because any frame could falsify // this message. if (![message.body isKindOfClass:[NSDictionary class]] || @@ -173,7 +159,7 @@ auto new_frame = std::make_unique<web::WebFrameImpl>( frame_id, message.frameInfo.mainFrame, message_frame_origin, - web_state_); + delegate_.GetWebState()); if (frame_key) { new_frame->SetEncryptionKey(std::move(frame_key)); } @@ -186,13 +172,12 @@ } AddFrame(std::move(new_frame)); - static_cast<WebStateImpl*>(web_state_) - ->OnWebFrameAvailable(GetFrameWithId(frame_id)); + delegate_.OnWebFrameAvailable(GetFrameWithId(frame_id)); } } void WebFramesManagerImpl::OnFrameBecameUnavailable(WKScriptMessage* message) { - DCHECK(!web_state_->IsBeingDestroyed()); + DCHECK(!delegate_.GetWebState()->IsBeingDestroyed()); if (![message.body isKindOfClass:[NSString class]]) { // WebController is being destroyed or message is invalid. return; @@ -200,10 +185,9 @@ std::string frame_id = base::SysNSStringToUTF8(message.body); WebFrame* frame = GetFrameWithId(frame_id); if (frame) { - static_cast<WebStateImpl*>(web_state_)->OnWebFrameUnavailable(frame); + delegate_.OnWebFrameUnavailable(frame); RemoveFrameWithId(frame_id); } } -WEB_STATE_USER_DATA_KEY_IMPL(WebFramesManager) } // namespace
diff --git a/ios/web/js_messaging/web_frames_manager_impl_unittest.mm b/ios/web/js_messaging/web_frames_manager_impl_unittest.mm index 2485ba98..fd58ce1 100644 --- a/ios/web/js_messaging/web_frames_manager_impl_unittest.mm +++ b/ios/web/js_messaging/web_frames_manager_impl_unittest.mm
@@ -37,15 +37,18 @@ namespace web { -class WebFramesManagerImplTest : public PlatformTest { +class WebFramesManagerImplTest : public PlatformTest, + public WebFramesManagerDelegate { protected: - WebFramesManagerImplTest() { - WebFramesManagerImpl::CreateForWebState(&test_web_state_); - frames_manager_ = WebFramesManagerImpl::FromWebState(&test_web_state_); - } + WebFramesManagerImplTest() : frames_manager_(*this) {} + + // WebFramesManagerDelegate. + void OnWebFrameAvailable(WebFrame* frame) override {} + void OnWebFrameUnavailable(WebFrame* frame) override {} + WebState* GetWebState() override { return &test_web_state_; } TestWebState test_web_state_; - WebFramesManagerImpl* frames_manager_ = nullptr; + WebFramesManagerImpl frames_manager_; }; // Tests that the WebFrame for the main frame is returned. @@ -55,17 +58,17 @@ "web_frame", /*is_main_frame=*/true, security_origin, &test_web_state_); WebFrameImpl* web_frame_ptr = web_frame.get(); - frames_manager_->AddFrame(std::move(web_frame)); + frames_manager_.AddFrame(std::move(web_frame)); - EXPECT_EQ(web_frame_ptr, frames_manager_->GetMainWebFrame()); - auto frames = frames_manager_->GetAllWebFrames(); + EXPECT_EQ(web_frame_ptr, frames_manager_.GetMainWebFrame()); + auto frames = frames_manager_.GetAllWebFrames(); EXPECT_EQ(1ul, frames.size()); EXPECT_TRUE(ContainsWebFrame(frames, web_frame_ptr)); } // Tests that the WebFrame returns null if no main frame is known. TEST_F(WebFramesManagerImplTest, NoMainWebFrame) { - EXPECT_EQ(nullptr, frames_manager_->GetMainWebFrame()); + EXPECT_EQ(nullptr, frames_manager_.GetMainWebFrame()); GURL security_origin; const std::string web_frame_frame_id = "web_frame"; @@ -73,11 +76,11 @@ std::make_unique<WebFrameImpl>(web_frame_frame_id, /*is_main_frame=*/true, security_origin, &test_web_state_); - frames_manager_->AddFrame(std::move(web_frame)); - frames_manager_->RemoveFrameWithId(web_frame_frame_id); + frames_manager_.AddFrame(std::move(web_frame)); + frames_manager_.RemoveFrameWithId(web_frame_frame_id); - EXPECT_EQ(nullptr, frames_manager_->GetMainWebFrame()); - EXPECT_EQ(0ul, frames_manager_->GetAllWebFrames().size()); + EXPECT_EQ(nullptr, frames_manager_.GetMainWebFrame()); + EXPECT_EQ(0ul, frames_manager_.GetAllWebFrames().size()); } // Tests that the WebFramesManagerImpl returns a list of all current WebFrame @@ -88,15 +91,15 @@ "main_web_frame", /*is_main_frame=*/true, security_origin, &test_web_state_); WebFrameImpl* main_web_frame_ptr = main_web_frame.get(); - frames_manager_->AddFrame(std::move(main_web_frame)); + frames_manager_.AddFrame(std::move(main_web_frame)); auto child_web_frame = std::make_unique<WebFrameImpl>( "child_web_frame", /*is_main_frame=*/false, security_origin, &test_web_state_); WebFrameImpl* child_web_frame_ptr = child_web_frame.get(); - frames_manager_->AddFrame(std::move(child_web_frame)); + frames_manager_.AddFrame(std::move(child_web_frame)); - auto frames = frames_manager_->GetAllWebFrames(); + auto frames = frames_manager_.GetAllWebFrames(); EXPECT_EQ(2ul, frames.size()); EXPECT_TRUE(ContainsWebFrame(frames, main_web_frame_ptr)); EXPECT_TRUE(ContainsWebFrame(frames, child_web_frame_ptr)); @@ -109,23 +112,23 @@ "main_web_frame", /*is_main_frame=*/true, security_origin, &test_web_state_); WebFrameImpl* main_web_frame_ptr = main_web_frame.get(); - frames_manager_->AddFrame(std::move(main_web_frame)); + frames_manager_.AddFrame(std::move(main_web_frame)); const std::string child_web_frame_1_frame_id = "child_web_frame_1_frame_id"; auto child_web_frame_1 = std::make_unique<WebFrameImpl>( child_web_frame_1_frame_id, /*is_main_frame=*/false, security_origin, &test_web_state_); - frames_manager_->AddFrame(std::move(child_web_frame_1)); + frames_manager_.AddFrame(std::move(child_web_frame_1)); auto child_web_frame_2 = std::make_unique<WebFrameImpl>( "child_web_frame_2", /*is_main_frame=*/false, security_origin, &test_web_state_); WebFrameImpl* child_web_frame_2_ptr = child_web_frame_2.get(); - frames_manager_->AddFrame(std::move(child_web_frame_2)); + frames_manager_.AddFrame(std::move(child_web_frame_2)); - frames_manager_->RemoveFrameWithId(child_web_frame_1_frame_id); + frames_manager_.RemoveFrameWithId(child_web_frame_1_frame_id); - auto frames = frames_manager_->GetAllWebFrames(); + auto frames = frames_manager_.GetAllWebFrames(); EXPECT_EQ(2ul, frames.size()); EXPECT_TRUE(ContainsWebFrame(frames, main_web_frame_ptr)); EXPECT_TRUE(ContainsWebFrame(frames, child_web_frame_2_ptr)); @@ -134,17 +137,17 @@ // Tests that all frames are removed after a call to |RemoveAllFrames|. TEST_F(WebFramesManagerImplTest, RemoveAllFrames) { GURL security_origin; - frames_manager_->AddFrame(std::make_unique<WebFrameImpl>( + frames_manager_.AddFrame(std::make_unique<WebFrameImpl>( "main_web_frame", /*is_main_frame=*/true, security_origin, &test_web_state_)); - frames_manager_->AddFrame(std::make_unique<WebFrameImpl>( + frames_manager_.AddFrame(std::make_unique<WebFrameImpl>( "web_frame", /*is_main_frame=*/false, security_origin, &test_web_state_)); - ASSERT_EQ(2ul, frames_manager_->GetAllWebFrames().size()); - frames_manager_->RemoveAllWebFrames(); - EXPECT_EQ(nullptr, frames_manager_->GetMainWebFrame()); - EXPECT_EQ(0ul, frames_manager_->GetAllWebFrames().size()); + ASSERT_EQ(2ul, frames_manager_.GetAllWebFrames().size()); + frames_manager_.RemoveAllWebFrames(); + EXPECT_EQ(nullptr, frames_manager_.GetMainWebFrame()); + EXPECT_EQ(0ul, frames_manager_.GetAllWebFrames().size()); } // Tests that the WebFramesManagerImpl correctly ignores attempted removal of an @@ -157,15 +160,15 @@ /*is_main_frame=*/true, security_origin, &test_web_state_); WebFrameImpl* main_web_frame_ptr = main_web_frame.get(); - frames_manager_->AddFrame(std::move(main_web_frame)); - auto frames = frames_manager_->GetAllWebFrames(); + frames_manager_.AddFrame(std::move(main_web_frame)); + auto frames = frames_manager_.GetAllWebFrames(); EXPECT_EQ(1ul, frames.size()); EXPECT_TRUE(ContainsWebFrame(frames, main_web_frame_ptr)); - frames_manager_->RemoveFrameWithId(main_web_frame_frame_id); - EXPECT_EQ(0ul, frames_manager_->GetAllWebFrames().size()); - frames_manager_->RemoveFrameWithId(main_web_frame_frame_id); - EXPECT_EQ(0ul, frames_manager_->GetAllWebFrames().size()); + frames_manager_.RemoveFrameWithId(main_web_frame_frame_id); + EXPECT_EQ(0ul, frames_manager_.GetAllWebFrames().size()); + frames_manager_.RemoveFrameWithId(main_web_frame_frame_id); + EXPECT_EQ(0ul, frames_manager_.GetAllWebFrames().size()); } // Tests that a WebFrame is correctly returned by its frame id. @@ -177,10 +180,10 @@ web_frame_frame_id, /*is_main_frame=*/false, security_origin, &test_web_state_); WebFrameImpl* web_frame_ptr = web_frame.get(); - frames_manager_->AddFrame(std::move(web_frame)); + frames_manager_.AddFrame(std::move(web_frame)); - EXPECT_EQ(web_frame_ptr, frames_manager_->GetFrameWithId(web_frame_frame_id)); - EXPECT_EQ(nullptr, frames_manager_->GetFrameWithId("invalid_id")); + EXPECT_EQ(web_frame_ptr, frames_manager_.GetFrameWithId(web_frame_frame_id)); + EXPECT_EQ(nullptr, frames_manager_.GetFrameWithId("invalid_id")); } // Tests that WebFramesManagerImpl will unregister callbacks for previous @@ -236,7 +239,7 @@ // Test begin! // Tell the manager to change from nil to |web_view_1|. - frames_manager_->OnWebViewUpdated(nil, web_view_1, router); + frames_manager_.OnWebViewUpdated(nil, web_view_1, router); // Send the "FrameBecameAvailable" to |router|. [(id<WKScriptMessageHandler>)router @@ -244,8 +247,8 @@ didReceiveScriptMessage:available_message]; // Check that the WebFrame for main frame is created. - ASSERT_EQ(1UL, frames_manager_->GetAllWebFrames().size()); - WebFrame* main_frame = frames_manager_->GetMainWebFrame(); + ASSERT_EQ(1UL, frames_manager_.GetAllWebFrames().size()); + WebFrame* main_frame = frames_manager_.GetMainWebFrame(); ASSERT_TRUE(main_frame); EXPECT_EQ(kFrameId, main_frame->GetFrameId()); EXPECT_TRUE(main_frame->IsMainFrame()); @@ -257,11 +260,11 @@ didReceiveScriptMessage:unavailable_message]; // Check that the WebFrame for main frame is removed. - ASSERT_EQ(0UL, frames_manager_->GetAllWebFrames().size()); - ASSERT_FALSE(frames_manager_->GetMainWebFrame()); + ASSERT_EQ(0UL, frames_manager_.GetAllWebFrames().size()); + ASSERT_FALSE(frames_manager_.GetMainWebFrame()); // Tell the manager to change from |web_view_1| to |web_view_2|. - frames_manager_->OnWebViewUpdated(web_view_1, web_view_2, router); + frames_manager_.OnWebViewUpdated(web_view_1, web_view_2, router); // Send the "FrameBecameAvailable" of |web_view_1| to |router| again. [(id<WKScriptMessageHandler>)router @@ -270,8 +273,8 @@ // Check that WebFramesManagerImpl doesn't reply JS messages from previous // WKWebView. - ASSERT_EQ(0UL, frames_manager_->GetAllWebFrames().size()); - ASSERT_FALSE(frames_manager_->GetMainWebFrame()); + ASSERT_EQ(0UL, frames_manager_.GetAllWebFrames().size()); + ASSERT_FALSE(frames_manager_.GetMainWebFrame()); } } // namespace web
diff --git a/ios/web/js_messaging/web_frames_manager_inttest.mm b/ios/web/js_messaging/web_frames_manager_inttest.mm index 7de1ea5..08a7416 100644 --- a/ios/web/js_messaging/web_frames_manager_inttest.mm +++ b/ios/web/js_messaging/web_frames_manager_inttest.mm
@@ -5,8 +5,8 @@ #include "base/ios/ios_util.h" #include "base/test/scoped_feature_list.h" #include "ios/web/common/features.h" -#include "ios/web/js_messaging/web_frames_manager_impl.h" #include "ios/web/public/js_messaging/web_frame.h" +#import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/navigation/navigation_manager.h" #import "ios/web/public/test/web_view_content_test_util.h" #import "ios/web/public/test/web_view_interaction_test_util.h" @@ -88,8 +88,7 @@ // Tests that the WebFramesManager correctly adds a WebFrame for a webpage. TEST_P(WebFramesManagerTest, SingleWebFrame) { - WebFramesManagerImpl* frames_manager = - WebFramesManagerImpl::FromWebState(web_state()); + WebFramesManager* frames_manager = web_state()->GetWebFramesManager(); GURL url = test_server_->GetURL("/echo"); ASSERT_TRUE(LoadUrl(url)); @@ -106,8 +105,7 @@ // Tests that the WebFramesManager correctly adds a unique WebFrame after a // webpage navigates back. TEST_P(WebFramesManagerTest, SingleWebFrameBack) { - WebFramesManagerImpl* frames_manager = - WebFramesManagerImpl::FromWebState(web_state()); + WebFramesManager* frames_manager = web_state()->GetWebFramesManager(); // Load first page. GURL url = test_server_->GetURL("/echo"); @@ -143,8 +141,7 @@ // Tests that the WebFramesManager correctly adds a unique WebFrame after a // webpage navigates back from a clicked link. TEST_P(WebFramesManagerTest, SingleWebFrameLinkNavigationBackForward) { - WebFramesManagerImpl* frames_manager = - WebFramesManagerImpl::FromWebState(web_state()); + WebFramesManager* frames_manager = web_state()->GetWebFramesManager(); // Load page with links. GURL url = test_server_->GetURL(kLinksPageURL); @@ -193,8 +190,7 @@ // Tests that the WebFramesManager correctly adds a unique WebFrame after a // webpage navigates back from a clicked same page link. TEST_P(WebFramesManagerTest, SingleWebFrameSamePageNavigationBackForward) { - WebFramesManagerImpl* frames_manager = - WebFramesManagerImpl::FromWebState(web_state()); + WebFramesManager* frames_manager = web_state()->GetWebFramesManager(); GURL url = test_server_->GetURL(kLinksPageURL); ASSERT_TRUE(LoadUrl(url));
diff --git a/ios/web/navigation/crw_js_navigation_handler.mm b/ios/web/navigation/crw_js_navigation_handler.mm index c8a658a6..2fe09dc5 100644 --- a/ios/web/navigation/crw_js_navigation_handler.mm +++ b/ios/web/navigation/crw_js_navigation_handler.mm
@@ -36,7 +36,10 @@ } // namespace -@interface CRWJSNavigationHandler () +@interface CRWJSNavigationHandler () { + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> _subscription; +} @property(nonatomic, weak) id<CRWJSNavigationHandlerDelegate> delegate; @@ -92,7 +95,7 @@ } }; - self.webStateImpl->AddScriptCommandCallback( + _subscription = self.webStateImpl->AddScriptCommandCallback( base::BindRepeating(navigationStateCallback), kCommandPrefix); } return self; @@ -100,7 +103,6 @@ - (void)close { self.beingDestroyed = YES; - self.webStateImpl->RemoveScriptCommandCallback(kCommandPrefix); } - (NSString*)javaScriptToReplaceWebViewURL:(const GURL&)URL
diff --git a/ios/web/navigation/crw_wk_navigation_handler.mm b/ios/web/navigation/crw_wk_navigation_handler.mm index 2de7b8c..2589f00 100644 --- a/ios/web/navigation/crw_wk_navigation_handler.mm +++ b/ios/web/navigation/crw_wk_navigation_handler.mm
@@ -830,8 +830,7 @@ // not notify web view delegate about received response, so web controller // does not get a chance to properly update MIME type. [self.JSInjector injectWindowID]; - web::WebFramesManagerImpl::FromWebState(self.webStateImpl) - ->RegisterExistingFrames(); + self.webStateImpl->GetWebFramesManagerImpl().RegisterExistingFrames(); } } @@ -1968,12 +1967,12 @@ // Clears the frames list. - (void)removeAllWebFrames { - web::WebFramesManagerImpl* framesManager = - web::WebFramesManagerImpl::FromWebState(self.webStateImpl); - for (auto* frame : framesManager->GetAllWebFrames()) { + web::WebFramesManagerImpl& framesManager = + self.webStateImpl->GetWebFramesManagerImpl(); + for (auto* frame : framesManager.GetAllWebFrames()) { self.webStateImpl->OnWebFrameUnavailable(frame); } - framesManager->RemoveAllWebFrames(); + framesManager.RemoveAllWebFrames(); } // Resets any state that is associated with a specific document object (e.g.,
diff --git a/ios/web/public/js_messaging/web_frame_util.h b/ios/web/public/js_messaging/web_frame_util.h index 628a7f9..c182bbb 100644 --- a/ios/web/public/js_messaging/web_frame_util.h +++ b/ios/web/public/js_messaging/web_frame_util.h
@@ -12,10 +12,6 @@ class WebFrame; class WebState; -// Returns the main WebFrame in |web_state|. -// Returns nullptr if |web_state| does not have a main frame. -WebFrame* GetMainWebFrame(WebState* web_state); - // Returns the ID of the main WebFrame in |web_state|. // Returns "" if |web_state| does not have a main frame. std::string GetMainWebFrameId(WebState* web_state); @@ -27,9 +23,6 @@ // Returns the ID of |frame|. Returns std::string() if |frame| is nullptr. std::string GetWebFrameId(WebFrame* frame); -// Returns all web frames in |web_state|. -std::set<WebFrame*> GetAllWebFrames(WebState* web_state); - } // namespace web #endif // IOS_WEB_PUBLIC_JS_MESSAGING_WEB_FRAME_UTIL_H_
diff --git a/ios/web/public/js_messaging/web_frames_manager.h b/ios/web/public/js_messaging/web_frames_manager.h index 3174452..33482382 100644 --- a/ios/web/public/js_messaging/web_frames_manager.h +++ b/ios/web/public/js_messaging/web_frames_manager.h
@@ -9,7 +9,6 @@ #include <string> #include "base/macros.h" -#import "ios/web/public/web_state/web_state_user_data.h" namespace web { @@ -17,13 +16,15 @@ // Stores and provides access to all WebFrame objects associated with a // particular WebState. -// NOTE: Code that store references to WebFrames must observe WebState, in -// particular |WebFrameDidBecomeUnavailable| event, and clear all reference -// when the frame becomes unavailable ad the pointer to the WebFrame becomes -// invalid. -// For example, a navigation will invalidate the WebFrame object for that frame. -class WebFramesManager : public web::WebStateUserData<WebFramesManager> { +// NOTE: Code that store references to WebFrames must clear them in +// WebStateObserver::WebFrameWillBecomeUnavailable, which is emitted when +// WebFrames in current page become invalid and will be removed from +// WebFramesManager (e.g. A new navigation is committed or failed, the web +// process crashed, etc.). +class WebFramesManager { public: + virtual ~WebFramesManager() {} + // Returns a list of all the web frames associated with WebState. // NOTE: Due to the asynchronous nature of renderer, this list may be // outdated. @@ -39,10 +40,6 @@ // not back a real frame in the web page. virtual WebFrame* GetFrameWithId(const std::string& frame_id) = 0; - ~WebFramesManager() override {} - - WEB_STATE_USER_DATA_KEY_DECL(); - protected: WebFramesManager() {}
diff --git a/ios/web/public/test/earl_grey/web_view_actions.mm b/ios/web/public/test/earl_grey/web_view_actions.mm index 94236a5..6d18ac2 100644 --- a/ios/web/public/test/earl_grey/web_view_actions.mm +++ b/ios/web/public/test/earl_grey/web_view_actions.mm
@@ -41,12 +41,11 @@ // Generic verification injector. Injects one-time mousedown verification into // |web_state| that will set the boolean pointed to by |verified| to true when // |web_state|'s webview registers the mousedown event. -// RemoveVerifierWithPrefix should be called after this to ensure -// future tests can add verifiers with the same prefix. -bool AddVerifierToElementWithPrefix(web::WebState* web_state, - ElementSelector* selector, - const std::string& prefix, - bool* verified) { +std::unique_ptr<web::WebState::ScriptCommandSubscription> +AddVerifierToElementWithPrefix(web::WebState* web_state, + ElementSelector* selector, + const std::string& prefix, + bool* verified) { const char kCallbackCommand[] = "verified"; const std::string kCallbackInvocation = prefix + '.' + kCallbackCommand; @@ -92,7 +91,7 @@ }); if (!success) - return false; + return nullptr; // The callback doesn't care about any of the parameters, just whether it is // called or not. @@ -102,16 +101,7 @@ *verified = true; }); - static_cast<web::WebStateImpl*>(web_state)->AddScriptCommandCallback(callback, - prefix); - return true; -} - -// Removes the injected callback. -void RemoveVerifierWithPrefix(web::WebState* web_state, - const std::string& prefix) { - static_cast<web::WebStateImpl*>(web_state)->RemoveScriptCommandCallback( - prefix); + return web_state->AddScriptCommandCallback(callback, prefix); } // Returns a no element found error. @@ -178,15 +168,10 @@ // reference. __block bool verified = false; - // Ensure that RemoveVerifierWithPrefix() is run regardless of how - // the block exits. - base::ScopedClosureRunner cleanup( - base::BindOnce(&RemoveVerifierWithPrefix, state, prefix)); - // Inject the verifier. - bool verifier_added = + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription = AddVerifierToElementWithPrefix(state, selector, prefix, &verified); - if (!verifier_added) { + if (!subscription) { NSString* description = [NSString stringWithFormat:@"It wasn't possible to add the verification " @"javascript for element %@",
diff --git a/ios/web/public/test/fakes/BUILD.gn b/ios/web/public/test/fakes/BUILD.gn index 56538eba..431cc072 100644 --- a/ios/web/public/test/fakes/BUILD.gn +++ b/ios/web/public/test/fakes/BUILD.gn
@@ -47,6 +47,8 @@ "fake_navigation_context.mm", "fake_web_frame.cc", "fake_web_frame.h", + "fake_web_frames_manager.h", + "fake_web_frames_manager.mm", "fake_web_state_policy_decider.h", "fake_web_state_policy_decider.mm", "test_browser_state.cc",
diff --git a/ios/web/public/test/fakes/fake_web_frames_manager.h b/ios/web/public/test/fakes/fake_web_frames_manager.h new file mode 100644 index 0000000..1f731a7a --- /dev/null +++ b/ios/web/public/test/fakes/fake_web_frames_manager.h
@@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_WEB_PUBLIC_TEST_FAKES_FAKE_WEB_FRAMES_MANAGER_H_ +#define IOS_WEB_PUBLIC_TEST_FAKES_FAKE_WEB_FRAMES_MANAGER_H_ + +#import "ios/web/public/js_messaging/web_frames_manager.h" + +#include <map> + +namespace web { +class WebFrame; + +// A minimal implementation of web::WebFramesManager. Common usage pattern: +// 1. Create TestWebState; +// 2. Create FakeWebFramesManager; +// 3. Call TestWebState::SetWebFramesManager with FakeWebFramesManager; +// 4. Manipulate WebFrames: +// a. Call FakeWebFramesManager::AddWebFrame then +// TestWebState::OnWebFrameDidBecomeAvailable; +// b. Call TestWebState::OnWebFrameWillBecomeUnavailable then +// FakeWebFramesManager::RemoveWebFrame. +class FakeWebFramesManager : public WebFramesManager { + public: + FakeWebFramesManager(); + ~FakeWebFramesManager() override; + + std::set<WebFrame*> GetAllWebFrames() override; + WebFrame* GetMainWebFrame() override; + WebFrame* GetFrameWithId(const std::string& frame_id) override; + + void AddWebFrame(std::unique_ptr<web::WebFrame> frame); + void RemoveWebFrame(const std::string& frame_id); + + protected: + // List of pointers to all web frames associated with WebState. + std::map<std::string, std::unique_ptr<WebFrame>> web_frames_; + // Reference to the current main web frame. + WebFrame* main_web_frame_ = nullptr; +}; + +} // namespace web + +#endif // IOS_WEB_PUBLIC_TEST_FAKES_FAKE_WEB_FRAMES_MANAGER_H_
diff --git a/ios/web/public/test/fakes/fake_web_frames_manager.mm b/ios/web/public/test/fakes/fake_web_frames_manager.mm new file mode 100644 index 0000000..f14684f --- /dev/null +++ b/ios/web/public/test/fakes/fake_web_frames_manager.mm
@@ -0,0 +1,61 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/web/public/test/fakes/fake_web_frames_manager.h" + +#include "ios/web/public/js_messaging/web_frame.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace web { + +FakeWebFramesManager::FakeWebFramesManager() {} +FakeWebFramesManager::~FakeWebFramesManager() {} + +std::set<WebFrame*> FakeWebFramesManager::GetAllWebFrames() { + std::set<WebFrame*> frames; + for (const auto& it : web_frames_) { + frames.insert(it.second.get()); + } + return frames; +} + +WebFrame* FakeWebFramesManager::GetMainWebFrame() { + return main_web_frame_; +} + +WebFrame* FakeWebFramesManager::GetFrameWithId(const std::string& frame_id) { + auto web_frames_it = web_frames_.find(frame_id); + return web_frames_it == web_frames_.end() ? nullptr + : web_frames_it->second.get(); +} + +void FakeWebFramesManager::AddWebFrame(std::unique_ptr<WebFrame> frame) { + DCHECK(frame); + if (frame->IsMainFrame()) { + main_web_frame_ = frame.get(); + } + web_frames_[frame->GetFrameId()] = std::move(frame); +} + +void FakeWebFramesManager::RemoveWebFrame(const std::string& frame_id) { + // If the removed frame is a main frame, it should be the current one. + if (web_frames_.count(frame_id) == 0) { + return; + } + if (main_web_frame_ && main_web_frame_->GetFrameId() == frame_id) { + main_web_frame_ = nullptr; + } + // The web::WebFrame destructor can call some callbacks that will try to + // access the frame via GetFrameWithId. This can lead to a reentrancy issue + // on |web_frames_|. + // To avoid this issue, keep the frame alive during the map operation and + // destroy it after. + auto keep_frame_alive = std::move(web_frames_[frame_id]); + web_frames_.erase(frame_id); +} + +} // namespace web
diff --git a/ios/web/public/test/fakes/test_web_state.h b/ios/web/public/test/fakes/test_web_state.h index 7c1fdc5..205bbae 100644 --- a/ios/web/public/test/fakes/test_web_state.h +++ b/ios/web/public/test/fakes/test_web_state.h
@@ -44,6 +44,8 @@ void Stop() override {} const NavigationManager* GetNavigationManager() const override; NavigationManager* GetNavigationManager() override; + const WebFramesManager* GetWebFramesManager() const override; + WebFramesManager* GetWebFramesManager() override; const SessionCertificatePolicyCache* GetSessionCertificatePolicyCache() const override; SessionCertificatePolicyCache* GetSessionCertificatePolicyCache() override; @@ -66,10 +68,9 @@ const GURL& GetVisibleURL() const override; const GURL& GetLastCommittedURL() const override; GURL GetCurrentURL(URLVerificationTrustLevel* trust_level) const override; - void AddScriptCommandCallback(const ScriptCommandCallback& callback, - const std::string& command_prefix) override {} - void RemoveScriptCommandCallback(const std::string& command_prefix) override { - } + std::unique_ptr<ScriptCommandSubscription> AddScriptCommandCallback( + const ScriptCommandCallback& callback, + const std::string& command_prefix) override; CRWWebViewProxyType GetWebViewProxy() const override; bool IsShowingWebInterstitial() const override; WebInterstitial* GetWebInterstitial() const override; @@ -98,14 +99,13 @@ void SetTrustLevel(URLVerificationTrustLevel trust_level); void SetNavigationManager( std::unique_ptr<NavigationManager> navigation_manager); + void SetWebFramesManager( + std::unique_ptr<WebFramesManager> web_frames_manager); void SetView(UIView* view); void SetIsCrashed(bool value); void SetIsEvicted(bool value); void SetWebViewProxy(CRWWebViewProxyType web_view_proxy); void ClearLastExecutedJavascript(); - void CreateWebFramesManager(); - void AddWebFrame(std::unique_ptr<web::WebFrame> frame); - void RemoveWebFrame(std::string frame_id); void SetCanTakeSnapshot(bool can_take_snapshot); // Getters for test data. @@ -127,6 +127,8 @@ void OnRenderProcessGone(); void OnBackForwardStateChanged(); void OnVisibleSecurityStateChanged(); + void OnWebFrameDidBecomeAvailable(WebFrame* frame); + void OnWebFrameWillBecomeUnavailable(WebFrame* frame); private: BrowserState* browser_state_; @@ -145,9 +147,11 @@ bool content_is_html_; std::string mime_type_; std::unique_ptr<NavigationManager> navigation_manager_; + std::unique_ptr<WebFramesManager> web_frames_manager_; UIView* view_; CRWWebViewProxyType web_view_proxy_; NSData* last_loaded_data_; + base::CallbackList<ScriptCommandCallbackSignature> callback_list_; // A list of observers notified when page state changes. Weak references. base::ObserverList<WebStateObserver, true>::Unchecked observers_;
diff --git a/ios/web/public/test/fakes/test_web_state.mm b/ios/web/public/test/fakes/test_web_state.mm index 3cf86a8..ce4360de 100644 --- a/ios/web/public/test/fakes/test_web_state.mm +++ b/ios/web/public/test/fakes/test_web_state.mm
@@ -102,6 +102,14 @@ return navigation_manager_.get(); } +const WebFramesManager* TestWebState::GetWebFramesManager() const { + return web_frames_manager_.get(); +} + +WebFramesManager* TestWebState::GetWebFramesManager() { + return web_frames_manager_.get(); +} + const SessionCertificatePolicyCache* TestWebState::GetSessionCertificatePolicyCache() const { return nullptr; @@ -127,6 +135,11 @@ navigation_manager_ = std::move(navigation_manager); } +void TestWebState::SetWebFramesManager( + std::unique_ptr<WebFramesManager> web_frames_manager) { + web_frames_manager_ = std::move(web_frames_manager); +} + void TestWebState::SetView(UIView* view) { view_ = view; } @@ -192,6 +205,12 @@ return url_; } +std::unique_ptr<WebState::ScriptCommandSubscription> +TestWebState::AddScriptCommandCallback(const ScriptCommandCallback& callback, + const std::string& command_prefix) { + return callback_list_.Add(callback); +} + bool TestWebState::IsShowingWebInterstitial() const { return false; } @@ -293,6 +312,18 @@ } } +void TestWebState::OnWebFrameDidBecomeAvailable(WebFrame* frame) { + for (auto& observer : observers_) { + observer.WebFrameDidBecomeAvailable(this, frame); + } +} + +void TestWebState::OnWebFrameWillBecomeUnavailable(WebFrame* frame) { + for (auto& observer : observers_) { + observer.WebFrameWillBecomeUnavailable(this, frame); + } +} + bool TestWebState::ShouldAllowRequest( NSURLRequest* request, const WebStatePolicyDecider::RequestInfo& request_info) { @@ -336,37 +367,6 @@ last_executed_javascript_.clear(); } -void TestWebState::CreateWebFramesManager() { - DCHECK(!web::WebFramesManagerImpl::FromWebState(this)); - web::WebFramesManagerImpl::CreateForWebState(this); -} - -void TestWebState::AddWebFrame(std::unique_ptr<web::WebFrame> frame) { - DCHECK(frame); - web::WebFramesManagerImpl* manager = - web::WebFramesManagerImpl::FromWebState(this); - DCHECK(manager) << "Create a frame manager before adding a frame."; - std::string frame_id = frame->GetFrameId(); - DCHECK(!manager->GetFrameWithId(frame_id)); - manager->AddFrame(std::move(frame)); - WebFrame* frame_ptr = manager->GetFrameWithId(frame_id); - for (auto& observer : observers_) { - observer.WebFrameDidBecomeAvailable(this, frame_ptr); - } -} - -void TestWebState::RemoveWebFrame(std::string frame_id) { - web::WebFramesManagerImpl* manager = - web::WebFramesManagerImpl::FromWebState(this); - DCHECK(manager) << "Create a frame manager before adding a frame."; - DCHECK(manager->GetFrameWithId(frame_id)); - WebFrame* frame_ptr = manager->GetFrameWithId(frame_id); - for (auto& observer : observers_) { - observer.WebFrameWillBecomeUnavailable(this, frame_ptr); - } - manager->RemoveFrameWithId(frame_id); -} - void TestWebState::SetCanTakeSnapshot(bool can_take_snapshot) { can_take_snapshot_ = can_take_snapshot; }
diff --git a/ios/web/public/web_state/web_state.h b/ios/web/public/web_state/web_state.h index f6641ea..f4b25bdd 100644 --- a/ios/web/public/web_state/web_state.h +++ b/ios/web/public/web_state/web_state.h
@@ -13,6 +13,7 @@ #include <vector> #include "base/callback_forward.h" +#include "base/callback_list.h" #include "base/memory/weak_ptr.h" #include "base/supports_user_data.h" #include "ios/web/public/deprecated/url_verification_constants.h" @@ -49,6 +50,7 @@ class NavigationManager; class SessionCertificatePolicyCache; class WebFrame; +class WebFramesManager; class WebInterstitial; class WebStateDelegate; class WebStateInterfaceProvider; @@ -152,6 +154,11 @@ virtual const NavigationManager* GetNavigationManager() const = 0; virtual NavigationManager* GetNavigationManager() = 0; + // Gets the WebFramesManager associated with this WebState. Can never return + // null. + virtual const WebFramesManager* GetWebFramesManager() const = 0; + virtual WebFramesManager* GetWebFramesManager() = 0; + // Gets the SessionCertificatePolicyCache for this WebState. Can never return // null. virtual const SessionCertificatePolicyCache* @@ -253,20 +260,24 @@ // frame, |user_is_interacting| indicates if the user is interacting with the // page. // TODO(crbug.com/881813): remove |page_url|. - typedef base::RepeatingCallback<void(const base::DictionaryValue& message, - const GURL& page_url, - bool user_is_interacting, - web::WebFrame* sender_frame)> - ScriptCommandCallback; - - // Registers a callback that will be called when a command matching - // |command_prefix| is received. - virtual void AddScriptCommandCallback(const ScriptCommandCallback& callback, - const std::string& command_prefix) = 0; - - // Removes the callback associated with |command_prefix|. - virtual void RemoveScriptCommandCallback( - const std::string& command_prefix) = 0; + using ScriptCommandCallbackSignature = + void(const base::DictionaryValue& message, + const GURL& page_url, + bool user_is_interacting, + web::WebFrame* sender_frame); + using ScriptCommandCallback = + base::RepeatingCallback<ScriptCommandCallbackSignature>; + using ScriptCommandSubscription = + base::CallbackList<ScriptCommandCallbackSignature>::Subscription; + // Registers |callback| for JS message whose 'command' matches + // |command_prefix|. The returned ScriptCommandSubscription should be stored + // by the caller. When the description object is destroyed, it will unregister + // |callback| if this WebState is still alive, and do nothing if this WebState + // is already destroyed. Therefore if the caller want to stop receiving JS + // messages it can just destroy the subscription object. + virtual std::unique_ptr<ScriptCommandSubscription> AddScriptCommandCallback( + const ScriptCommandCallback& callback, + const std::string& command_prefix) WARN_UNUSED_RESULT = 0; // Returns the current CRWWebViewProxy object. virtual CRWWebViewProxyType GetWebViewProxy() const = 0;
diff --git a/ios/web/web_state/BUILD.gn b/ios/web/web_state/BUILD.gn index be14a04..8d0dfa9 100644 --- a/ios/web/web_state/BUILD.gn +++ b/ios/web/web_state/BUILD.gn
@@ -51,6 +51,7 @@ source_set("web_state_impl_header") { deps = [ "//base", + "//ios/web/js_messaging", "//ios/web/navigation:core", "//ios/web/public", "//ios/web/public/js_messaging",
diff --git a/ios/web/web_state/js/find_in_page_js_unittest.mm b/ios/web/web_state/js/find_in_page_js_unittest.mm index 4b5369b..27f04f13 100644 --- a/ios/web/web_state/js/find_in_page_js_unittest.mm +++ b/ios/web/web_state/js/find_in_page_js_unittest.mm
@@ -10,11 +10,11 @@ #import "base/test/ios/wait_util.h" #import "ios/web/find_in_page/find_in_page_constants.h" #import "ios/web/public/js_messaging/web_frame.h" -#import "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/web_test_with_web_state.h" #import "ios/web/public/web_state/ui/crw_web_view_proxy.h" #import "ios/web/public/web_state/ui/crw_web_view_scroll_view_proxy.h" +#import "ios/web/public/web_state/web_state.h" #include "testing/gtest_mac.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -42,11 +42,13 @@ class FindInPageJsTest : public WebTestWithWebState { protected: // Returns WebFramesManager instance. - WebFramesManager* frames_manager() { - return WebFramesManager::FromWebState(web_state()); + std::set<WebFrame*> all_web_frames() { + return web_state()->GetWebFramesManager()->GetAllWebFrames(); } // Returns main frame for |web_state_|. - WebFrame* main_web_frame() { return GetMainWebFrame(web_state()); } + WebFrame* main_web_frame() { + return web_state()->GetWebFramesManager()->GetMainWebFrame(); + } }; // Tests that FindInPage searches in main frame containing a match and responds @@ -56,7 +58,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; @@ -85,7 +87,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; std::vector<base::Value> params; @@ -114,9 +116,9 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 2; + return all_web_frames().size() == 2; })); - std::set<WebFrame*> all_frames = frames_manager()->GetAllWebFrames(); + std::set<WebFrame*> all_frames = all_web_frames(); __block bool message_received = false; WebFrame* child_frame = nullptr; for (auto* frame : all_frames) { @@ -149,7 +151,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; std::vector<base::Value> params; @@ -176,7 +178,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; std::vector<base::Value> params; @@ -202,7 +204,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; @@ -247,7 +249,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; @@ -313,7 +315,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; @@ -358,7 +360,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; std::vector<base::Value> params; @@ -391,7 +393,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; @@ -441,7 +443,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); // Do a search to ensure match highlighting is cleared properly. @@ -500,7 +502,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; std::vector<base::Value> params; @@ -551,7 +553,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; std::vector<base::Value> params; @@ -604,7 +606,7 @@ const base::TimeDelta kCallJavascriptFunctionTimeout = base::TimeDelta::FromSeconds(kWaitForJSCompletionTimeout); ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return frames_manager()->GetAllWebFrames().size() == 1; + return all_web_frames().size() == 1; })); __block bool message_received = false; std::vector<base::Value> params;
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 71c472f6..d15ba18 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -309,7 +309,6 @@ _certVerificationController = [[CRWCertVerificationController alloc] initWithBrowserState:browserState]; web::BrowsingDataRemover::FromBrowserState(browserState)->AddObserver(self); - web::WebFramesManagerImpl::CreateForWebState(_webStateImpl); web::FindInPageManagerImpl::CreateForWebState(_webStateImpl); _faviconManager = std::make_unique<web::FaviconManager>(_webStateImpl); _jsWindowErrorManager = @@ -421,8 +420,8 @@ CRWWKScriptMessageRouter* messageRouter = [self webViewConfigurationProvider].GetScriptMessageRouter(); - web::WebFramesManagerImpl::FromWebState(self.webStateImpl) - ->OnWebViewUpdated(_webView, webView, messageRouter); + self.webStateImpl->GetWebFramesManagerImpl().OnWebViewUpdated( + _webView, webView, messageRouter); if (_webView) { // TODO(crbug.com/956516): Use removeScriptMessageHandlerForName:webView: @@ -598,8 +597,6 @@ [self.UIHandler close]; [self.JSNavigationHandler close]; [self.requestController close]; - _faviconManager.reset(); - _jsWindowErrorManager.reset(); self.swipeRecognizerProvider = nil; [self.legacyNativeController close]; [self.requestController close];
diff --git a/ios/web/web_state/ui/js_window_error_manager.h b/ios/web/web_state/ui/js_window_error_manager.h index f7e5583..ee57e24 100644 --- a/ios/web/web_state/ui/js_window_error_manager.h +++ b/ios/web/web_state/ui/js_window_error_manager.h
@@ -5,14 +5,16 @@ #ifndef IOS_WEB_WEB_STATE_UI_JS_WINDOW_ERROR_MANAGER_H_ #define IOS_WEB_WEB_STATE_UI_JS_WINDOW_ERROR_MANAGER_H_ +#include <memory> + #include "base/macros.h" +#import "ios/web/public/web_state/web_state.h" namespace base { class DictionaryValue; } class GURL; namespace web { -class WebState; class WebFrame; // Handles "window.error" message from injected JavaScript and DLOG it. @@ -29,6 +31,9 @@ WebState* web_state_impl_ = nullptr; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + DISALLOW_COPY_AND_ASSIGN(JsWindowErrorManager); };
diff --git a/ios/web/web_state/ui/js_window_error_manager.mm b/ios/web/web_state/ui/js_window_error_manager.mm index d5f9579..c16a7825 100644 --- a/ios/web/web_state/ui/js_window_error_manager.mm +++ b/ios/web/web_state/ui/js_window_error_manager.mm
@@ -20,15 +20,13 @@ JsWindowErrorManager::JsWindowErrorManager(WebState* web_state) : web_state_impl_(web_state) { - web_state_impl_->AddScriptCommandCallback( + subscription_ = web_state_impl_->AddScriptCommandCallback( base::BindRepeating(&JsWindowErrorManager::OnJsMessage, base::Unretained(this)), kCommandPrefix); } -JsWindowErrorManager::~JsWindowErrorManager() { - web_state_impl_->RemoveScriptCommandCallback(kCommandPrefix); -} +JsWindowErrorManager::~JsWindowErrorManager() {} void JsWindowErrorManager::OnJsMessage(const base::DictionaryValue& message, const GURL& page_url,
diff --git a/ios/web/web_state/web_state_impl.h b/ios/web/web_state/web_state_impl.h index 38cdbddc..32397fb0 100644 --- a/ios/web/web_state/web_state_impl.h +++ b/ios/web/web_state/web_state_impl.h
@@ -19,6 +19,7 @@ #include "base/observer_list.h" #include "base/strings/string16.h" #include "base/values.h" +#import "ios/web/js_messaging/web_frames_manager_impl.h" #import "ios/web/navigation/navigation_manager_delegate.h" #import "ios/web/navigation/navigation_manager_impl.h" #import "ios/web/public/java_script_dialog_callback.h" @@ -65,7 +66,9 @@ // - SessionWindows are transient owners, passing ownership into WebControllers // during session restore, and discarding owned copies of WebStateImpls after // writing them out for session saves. -class WebStateImpl : public WebState, public NavigationManagerDelegate { +class WebStateImpl : public WebState, + public NavigationManagerDelegate, + public WebFramesManagerDelegate { public: // Constructor for WebStateImpls created for new sessions. explicit WebStateImpl(const CreateParams& params); @@ -113,6 +116,10 @@ const NavigationManagerImpl& GetNavigationManagerImpl() const; NavigationManagerImpl& GetNavigationManagerImpl(); + // Returns the associated WebFramesManagerImpl. + const WebFramesManagerImpl& GetWebFramesManagerImpl() const; + WebFramesManagerImpl& GetWebFramesManagerImpl(); + // Returns the SessionCertificatePolicyCacheImpl for this WebStateImpl. const SessionCertificatePolicyCacheImpl& GetSessionCertificatePolicyCacheImpl() const; @@ -167,10 +174,9 @@ void CommitPreviewingViewController( UIViewController* previewing_view_controller); - // Called when a new frame is available in the web_state. - void OnWebFrameAvailable(web::WebFrame* frame); - // Called when a frame is removed in the web_state - void OnWebFrameUnavailable(web::WebFrame* frame); + // WebFramesManagerDelegate. + void OnWebFrameAvailable(web::WebFrame* frame) override; + void OnWebFrameUnavailable(web::WebFrame* frame) override; // WebState: WebStateDelegate* GetDelegate() override; @@ -186,6 +192,8 @@ void Stop() override; const NavigationManager* GetNavigationManager() const override; NavigationManager* GetNavigationManager() override; + const WebFramesManager* GetWebFramesManager() const override; + WebFramesManager* GetWebFramesManager() override; const SessionCertificatePolicyCache* GetSessionCertificatePolicyCache() const override; SessionCertificatePolicyCache* GetSessionCertificatePolicyCache() override; @@ -210,9 +218,9 @@ GURL GetCurrentURL(URLVerificationTrustLevel* trust_level) const override; bool IsShowingWebInterstitial() const override; WebInterstitial* GetWebInterstitial() const override; - void AddScriptCommandCallback(const ScriptCommandCallback& callback, - const std::string& command_prefix) override; - void RemoveScriptCommandCallback(const std::string& command_prefix) override; + std::unique_ptr<ScriptCommandSubscription> AddScriptCommandCallback( + const ScriptCommandCallback& callback, + const std::string& command_prefix) override; id<CRWWebViewProxy> GetWebViewProxy() const override; WebStateInterfaceProvider* GetWebStateInterfaceProvider() override; void DidChangeVisibleSecurityState() override; @@ -332,6 +340,9 @@ // The NavigationManagerImpl that stores session info for this WebStateImpl. std::unique_ptr<NavigationManagerImpl> navigation_manager_; + // The associated WebFramesManagerImpl. + WebFramesManagerImpl web_frames_manager_; + // The SessionCertificatePolicyCacheImpl that stores the certificate policy // information for this WebStateImpl. std::unique_ptr<SessionCertificatePolicyCacheImpl> certificate_policy_cache_; @@ -365,7 +376,8 @@ base::string16 empty_string16_; // Callbacks associated to command prefixes. - std::map<std::string, ScriptCommandCallback> script_command_callbacks_; + std::map<std::string, base::CallbackList<ScriptCommandCallbackSignature>> + script_command_callbacks_; // Whether this WebState has an opener. See // WebState::CreateParams::created_with_opener_ for more details.
diff --git a/ios/web/web_state/web_state_impl.mm b/ios/web/web_state/web_state_impl.mm index 4829b7b..cb7dd161 100644 --- a/ios/web/web_state/web_state_impl.mm +++ b/ios/web/web_state/web_state_impl.mm
@@ -87,6 +87,7 @@ is_loading_(false), is_being_destroyed_(false), web_controller_(nil), + web_frames_manager_(*this), interstitial_(nullptr), created_with_opener_(params.created_with_opener), weak_factory_(this) { @@ -126,7 +127,6 @@ observer.WebStateDestroyed(); for (auto& observer : policy_deciders_) observer.ResetWebState(); - DCHECK(script_command_callbacks_.empty()); SetDelegate(nullptr); } @@ -213,7 +213,7 @@ if (it == script_command_callbacks_.end()) return; - it->second.Run(value, page_url, user_is_interacting, sender_frame); + it->second.Notify(value, page_url, user_is_interacting, sender_frame); } void WebStateImpl::SetIsLoading(bool is_loading) { @@ -279,12 +279,20 @@ observer.FaviconUrlUpdated(this, candidates); } +const NavigationManagerImpl& WebStateImpl::GetNavigationManagerImpl() const { + return *navigation_manager_; +} + NavigationManagerImpl& WebStateImpl::GetNavigationManagerImpl() { return *navigation_manager_; } -const NavigationManagerImpl& WebStateImpl::GetNavigationManagerImpl() const { - return *navigation_manager_; +const WebFramesManagerImpl& WebStateImpl::GetWebFramesManagerImpl() const { + return web_frames_manager_; +} + +WebFramesManagerImpl& WebStateImpl::GetWebFramesManagerImpl() { + return web_frames_manager_; } const SessionCertificatePolicyCacheImpl& @@ -618,6 +626,14 @@ return &GetNavigationManagerImpl(); } +const WebFramesManager* WebStateImpl::GetWebFramesManager() const { + return &web_frames_manager_; +} + +WebFramesManager* WebStateImpl::GetWebFramesManager() { + return &web_frames_manager_; +} + const SessionCertificatePolicyCache* WebStateImpl::GetSessionCertificatePolicyCache() const { return &GetSessionCertificatePolicyCacheImpl(); @@ -744,21 +760,14 @@ return result; } -void WebStateImpl::AddScriptCommandCallback( - const ScriptCommandCallback& callback, - const std::string& command_prefix) { +std::unique_ptr<WebState::ScriptCommandSubscription> +WebStateImpl::AddScriptCommandCallback(const ScriptCommandCallback& callback, + const std::string& command_prefix) { DCHECK(!command_prefix.empty()); DCHECK(command_prefix.find_first_of('.') == std::string::npos); - DCHECK(script_command_callbacks_.find(command_prefix) == - script_command_callbacks_.end()); - script_command_callbacks_[command_prefix] = callback; -} - -void WebStateImpl::RemoveScriptCommandCallback( - const std::string& command_prefix) { - DCHECK(script_command_callbacks_.find(command_prefix) != - script_command_callbacks_.end()); - script_command_callbacks_.erase(command_prefix); + DCHECK(script_command_callbacks_.count(command_prefix) == 0 || + script_command_callbacks_[command_prefix].empty()); + return script_command_callbacks_[command_prefix].Add(callback); } id<CRWWebViewProxy> WebStateImpl::GetWebViewProxy() const {
diff --git a/ios/web/web_state/web_state_impl_unittest.mm b/ios/web/web_state/web_state_impl_unittest.mm index fd2e04d..0cb4303 100644 --- a/ios/web/web_state/web_state_impl_unittest.mm +++ b/ios/web/web_state/web_state_impl_unittest.mm
@@ -747,7 +747,7 @@ const GURL kUrl1("http://foo"); bool is_called_1 = false; web::FakeWebFrame main_frame("main", true, GURL()); - web_state_->AddScriptCommandCallback( + auto subscription_1 = web_state_->AddScriptCommandCallback( base::BindRepeating(&HandleScriptCommand, &is_called_1, &value_1, kUrl1, /*expected_user_is_interacting*/ false, &main_frame), kPrefix1); @@ -758,7 +758,7 @@ value_2.SetString("c", "d"); const GURL kUrl2("http://bar"); bool is_called_2 = false; - web_state_->AddScriptCommandCallback( + auto subscription_2 = web_state_->AddScriptCommandCallback( base::BindRepeating(&HandleScriptCommand, &is_called_2, &value_2, kUrl2, /*expected_user_is_interacting*/ false, &main_frame), kPrefix2); @@ -770,7 +770,7 @@ const GURL kUrl3("http://iframe"); bool is_called_3 = false; web::FakeWebFrame subframe("subframe", false, GURL()); - web_state_->AddScriptCommandCallback( + auto subscription_3 = web_state_->AddScriptCommandCallback( base::BindRepeating(&HandleScriptCommand, &is_called_3, &value_3, kUrl3, /*expected_user_is_interacting*/ false, &subframe), kPrefix3); @@ -812,7 +812,7 @@ is_called_3 = false; // Remove the callback and check it is no longer called. - web_state_->RemoveScriptCommandCallback(kPrefix1); + subscription_1.reset(); web_state_->OnScriptCommandReceived(kCommand1, value_1, kUrl1, /*user_is_interacting*/ false, /*sender_frame*/ &main_frame); @@ -827,9 +827,6 @@ EXPECT_FALSE(is_called_1); EXPECT_TRUE(is_called_2); EXPECT_FALSE(is_called_3); - - web_state_->RemoveScriptCommandCallback(kPrefix2); - web_state_->RemoveScriptCommandCallback(kPrefix3); } // Tests that WebState::CreateParams::created_with_opener is translated to
diff --git a/ios/web/web_state/web_state_unittest.mm b/ios/web/web_state/web_state_unittest.mm index ff61f6b..a2003439 100644 --- a/ios/web/web_state/web_state_unittest.mm +++ b/ios/web/web_state/web_state_unittest.mm
@@ -170,7 +170,7 @@ /*interacted*/ bool, /*is_main_frame*/ web::WebFrame*) { message_received = true; }); - web_state()->AddScriptCommandCallback(callback, "test"); + auto subscription = web_state()->AddScriptCommandCallback(callback, "test"); // Load the page which overrides window.webkit object and wait until the // test message is received. @@ -183,7 +183,6 @@ WaitForCondition(^{ return message_received; }); - web_state()->RemoveScriptCommandCallback("test"); } // Tests that reload with web::ReloadType::NORMAL is no-op when navigation @@ -268,7 +267,7 @@ message_from_main_frame = sender_frame->IsMainFrame(); message_value = value.Clone(); }); - web_state()->AddScriptCommandCallback(callback, "test"); + auto subscription = web_state()->AddScriptCommandCallback(callback, "test"); ASSERT_TRUE(LoadHtml( "<script>" @@ -278,7 +277,6 @@ WaitForCondition(^{ return message_received; }); - web_state()->RemoveScriptCommandCallback("test"); EXPECT_TRUE(message_from_main_frame); EXPECT_TRUE(message_value.is_dict()); EXPECT_EQ(message_value.DictSize(), size_t(1)); @@ -302,7 +300,7 @@ message_from_main_frame = sender_frame->IsMainFrame(); message_value = value.Clone(); }); - web_state()->AddScriptCommandCallback(callback, "test"); + auto subscription = web_state()->AddScriptCommandCallback(callback, "test"); ASSERT_TRUE(LoadHtml( "<iframe srcdoc='" @@ -314,7 +312,6 @@ WaitForCondition(^{ return message_received; }); - web_state()->RemoveScriptCommandCallback("test"); EXPECT_FALSE(message_from_main_frame); EXPECT_TRUE(message_value.is_dict()); EXPECT_EQ(message_value.DictSize(), size_t(1));
diff --git a/ios/web/webui/BUILD.gn b/ios/web/webui/BUILD.gn index b86c57f9..3ae7ea0 100644 --- a/ios/web/webui/BUILD.gn +++ b/ios/web/webui/BUILD.gn
@@ -10,6 +10,7 @@ "//ios/web:resources", "//ios/web:resources_grit", "//ios/web/public", + "//ios/web/public/js_messaging", "//ios/web/public/webui", "//ios/web/web_state:web_state_impl_header", "//mojo/public/cpp/system",
diff --git a/ios/web/webui/web_ui_ios_impl.h b/ios/web/webui/web_ui_ios_impl.h index 73b79d6..96bc09b 100644 --- a/ios/web/webui/web_ui_ios_impl.h +++ b/ios/web/webui/web_ui_ios_impl.h
@@ -13,10 +13,10 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/values.h" +#import "ios/web/public/web_state/web_state.h" #include "ios/web/public/webui/web_ui_ios.h" namespace web { -class WebStateImpl; class WebFrame; } @@ -25,7 +25,7 @@ class WebUIIOSImpl : public web::WebUIIOS, public base::SupportsWeakPtr<WebUIIOSImpl> { public: - explicit WebUIIOSImpl(WebStateImpl* web_state); + explicit WebUIIOSImpl(WebState* web_state); ~WebUIIOSImpl() override; // WebUIIOS implementation: @@ -64,8 +64,11 @@ // The WebUIIOSMessageHandlers we own. std::vector<std::unique_ptr<WebUIIOSMessageHandler>> handlers_; - // Non-owning pointer to the WebStateImpl this WebUIIOS is associated with. - WebStateImpl* web_state_; + // Subscription for JS message. + std::unique_ptr<web::WebState::ScriptCommandSubscription> subscription_; + + // Non-owning pointer to the WebState this WebUIIOS is associated with. + WebState* web_state_; std::unique_ptr<WebUIIOSController> controller_;
diff --git a/ios/web/webui/web_ui_ios_impl.mm b/ios/web/webui/web_ui_ios_impl.mm index 4a36b64..a6001c8e 100644 --- a/ios/web/webui/web_ui_ios_impl.mm +++ b/ios/web/webui/web_ui_ios_impl.mm
@@ -10,11 +10,11 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "ios/web/public/js_messaging/web_frame.h" #import "ios/web/public/web_client.h" #include "ios/web/public/webui/web_ui_ios_controller.h" #include "ios/web/public/webui/web_ui_ios_controller_factory.h" #include "ios/web/public/webui/web_ui_ios_message_handler.h" -#import "ios/web/web_state/web_state_impl.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -45,15 +45,14 @@ base::char16(')') + base::char16(';'); } -WebUIIOSImpl::WebUIIOSImpl(WebStateImpl* web_state) : web_state_(web_state) { +WebUIIOSImpl::WebUIIOSImpl(WebState* web_state) : web_state_(web_state) { DCHECK(web_state); - web_state->AddScriptCommandCallback( + subscription_ = web_state->AddScriptCommandCallback( base::BindRepeating(&WebUIIOSImpl::OnJsMessage, base::Unretained(this)), kCommandPrefix); } WebUIIOSImpl::~WebUIIOSImpl() { - web_state_->RemoveScriptCommandCallback(kCommandPrefix); controller_.reset(); }
diff --git a/ios/web_view/BUILD.gn b/ios/web_view/BUILD.gn index 0a2e2bd..90b6505 100644 --- a/ios/web_view/BUILD.gn +++ b/ios/web_view/BUILD.gn
@@ -285,7 +285,6 @@ "//components/proxy_config", "//components/signin/core/browser", "//components/signin/public/webdata", - "//components/signin/internal/identity_manager", # TODO(crbug.com/974198): remove once closed "//components/signin/ios/browser", "//components/signin/ios/browser:active_state_manager", "//components/signin/public/identity_manager",
diff --git a/ios/web_view/internal/DEPS b/ios/web_view/internal/DEPS index 7403a39..13d3c10 100644 --- a/ios/web_view/internal/DEPS +++ b/ios/web_view/internal/DEPS
@@ -20,24 +20,7 @@ "+components/pref_registry", "+components/prefs", "+components/proxy_config", - "+components/signin/core", - # Use identity_manager.h instead of the below files; - # see https://groups.google.com/a/chromium.org/d/msg/chromium-dev/dgFLuxqZt1o/iEqkyoQQBwAJ for help and info. - "-components/signin/internal/identity_manager/account_fetcher_service.h", - "-components/signin/internal/identity_manager/account_info_fetcher.h", - "-components/signin/internal/identity_manager/account_tracker_service.h", - "-components/signin/internal/identity_manager/child_account_info_fetcher_android.h", - "-components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/gaia_cookie_manager_service.h", - "-components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_helper.h", - "-components/signin/internal/identity_manager/oauth2_multilogin_token_fetcher.h", - "-components/signin/internal/identity_manager/primary_account_manager.h", - "-components/signin/internal/identity_manager/primary_account_policy_manager.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service.h", - "-components/signin/internal/identity_manager/profile_oauth2_token_service_delegate_chromeos.h", - "-components/signin/internal/identity_manager/ubertoken_fetcher_impl.h", - + "+components/signin/core/browser", "+components/signin/ios", "+components/signin/public", "+components/ssl_errors",
diff --git a/ios/web_view/internal/app/application_context.mm b/ios/web_view/internal/app/application_context.mm index c4349553..15e85a01 100644 --- a/ios/web_view/internal/app/application_context.mm +++ b/ios/web_view/internal/app/application_context.mm
@@ -103,7 +103,7 @@ flags_ui::PrefServiceFlagsStorage::RegisterPrefs(pref_registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(pref_registry.get()); #if BUILDFLAG(IOS_WEB_VIEW_ENABLE_SYNC) - identity::IdentityManager::RegisterLocalStatePrefs(pref_registry.get()); + signin::IdentityManager::RegisterLocalStatePrefs(pref_registry.get()); #endif // BUILDFLAG(IOS_WEB_VIEW_ENABLE_SYNC) base::FilePath local_state_path;
diff --git a/ios/web_view/internal/autofill/cwv_autofill_controller.mm b/ios/web_view/internal/autofill/cwv_autofill_controller.mm index c886a6d..84c04d4 100644 --- a/ios/web_view/internal/autofill/cwv_autofill_controller.mm +++ b/ios/web_view/internal/autofill/cwv_autofill_controller.mm
@@ -340,8 +340,7 @@ - (void)findAllFormsWithCompletionHandler: (void (^)(NSArray<CWVAutofillForm*>*))completionHandler { - web::WebFramesManager* framesManager = - web::WebFramesManager::FromWebState(_webState); + web::WebFramesManager* framesManager = _webState->GetWebFramesManager(); DCHECK(framesManager); web::WebFrame* webFrame = framesManager->GetMainWebFrame(); if (!webFrame) { @@ -490,8 +489,7 @@ return; } - web::WebFramesManager* framesManager = - web::WebFramesManager::FromWebState(_webState); + web::WebFramesManager* framesManager = _webState->GetWebFramesManager(); DCHECK(framesManager); web::WebFrame* webFrame = framesManager->GetMainWebFrame(); if (!webFrame) {
diff --git a/ios/web_view/internal/autofill/cwv_autofill_controller_unittest.mm b/ios/web_view/internal/autofill/cwv_autofill_controller_unittest.mm index 3bef63d..ae5c8b06 100644 --- a/ios/web_view/internal/autofill/cwv_autofill_controller_unittest.mm +++ b/ios/web_view/internal/autofill/cwv_autofill_controller_unittest.mm
@@ -22,6 +22,7 @@ #import "ios/web/public/deprecated/crw_test_js_injection_receiver.h" #include "ios/web/public/js_messaging/web_frames_manager.h" #import "ios/web/public/test/fakes/fake_web_frame.h" +#import "ios/web/public/test/fakes/fake_web_frames_manager.h" #import "ios/web/public/test/fakes/test_web_state.h" #include "ios/web/public/test/test_web_thread_bundle.h" #include "ios/web/public/web_client.h" @@ -57,10 +58,10 @@ CWVAutofillControllerTest() : browser_state_(/*off_the_record=*/false) { web::SetWebClient(&web_client_); - web_state_.SetBrowserState(&browser_state_); + test_web_state_.SetBrowserState(&browser_state_); CRWTestJSInjectionReceiver* injectionReceiver = [[CRWTestJSInjectionReceiver alloc] init]; - web_state_.SetJSInjectionReceiver(injectionReceiver); + test_web_state_.SetJSInjectionReceiver(injectionReceiver); js_autofill_manager_ = [[FakeJSAutofillManager alloc] initWithReceiver:injectionReceiver]; @@ -68,22 +69,32 @@ autofill_agent_ = [[FakeAutofillAgent alloc] initWithPrefService:browser_state_.GetPrefs() - webState:&web_state_]; + webState:&test_web_state_]; - web_state_.CreateWebFramesManager(); + auto frames_manager = std::make_unique<web::FakeWebFramesManager>(); + fake_web_frames_manager_ = frames_manager.get(); + test_web_state_.SetWebFramesManager(std::move(frames_manager)); + autofill_controller_ = - [[CWVAutofillController alloc] initWithWebState:&web_state_ + [[CWVAutofillController alloc] initWithWebState:&test_web_state_ autofillAgent:autofill_agent_ JSAutofillManager:js_autofill_manager_ JSSuggestionManager:js_suggestion_manager_]; test_form_activity_tab_helper_ = - std::make_unique<autofill::TestFormActivityTabHelper>(&web_state_); + std::make_unique<autofill::TestFormActivityTabHelper>(&test_web_state_); + } + + void AddWebFrame(std::unique_ptr<web::WebFrame> frame) { + web::WebFrame* frame_ptr = frame.get(); + fake_web_frames_manager_->AddWebFrame(std::move(frame)); + test_web_state_.OnWebFrameDidBecomeAvailable(frame_ptr); } web::WebClient web_client_; web::TestWebThreadBundle web_thread_bundle_; ios_web_view::WebViewBrowserState browser_state_; - web::TestWebState web_state_; + web::TestWebState test_web_state_; + web::FakeWebFramesManager* fake_web_frames_manager_; CWVAutofillController* autofill_controller_; FakeAutofillAgent* autofill_agent_; FakeJSAutofillManager* js_autofill_manager_; @@ -158,7 +169,7 @@ TEST_F(CWVAutofillControllerTest, ClearForm) { auto frame = std::make_unique<web::FakeWebFrame>( base::SysNSStringToUTF8(kTestFrameId), true, GURL::EmptyGURL()); - web_state_.AddWebFrame(std::move(frame)); + AddWebFrame(std::move(frame)); __block BOOL clear_form_completion_was_called = NO; [autofill_controller_ clearFormWithName:kTestFormName fieldIdentifier:kTestFieldIdentifier
diff --git a/ios/web_view/internal/autofill/web_view_autofill_client_ios.h b/ios/web_view/internal/autofill/web_view_autofill_client_ios.h index f7cd61b..b4261dac 100644 --- a/ios/web_view/internal/autofill/web_view_autofill_client_ios.h +++ b/ios/web_view/internal/autofill/web_view_autofill_client_ios.h
@@ -33,7 +33,7 @@ AutocompleteHistoryManager* autocomplete_history_manager, web::WebState* web_state, id<CWVAutofillClientIOSBridge> bridge, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, StrikeDatabase* strike_database, scoped_refptr<AutofillWebDataService> autofill_web_data_service, syncer::SyncService* sync_service); @@ -44,7 +44,7 @@ AutocompleteHistoryManager* GetAutocompleteHistoryManager() override; PrefService* GetPrefs() override; syncer::SyncService* GetSyncService() override; - identity::IdentityManager* GetIdentityManager() override; + signin::IdentityManager* GetIdentityManager() override; FormDataImporter* GetFormDataImporter() override; payments::PaymentsClient* GetPaymentsClient() override; StrikeDatabase* GetStrikeDatabase() override; @@ -117,7 +117,7 @@ AutocompleteHistoryManager* autocomplete_history_manager_; web::WebState* web_state_; __weak id<CWVAutofillClientIOSBridge> bridge_; - identity::IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; std::unique_ptr<payments::PaymentsClient> payments_client_; std::unique_ptr<FormDataImporter> form_data_importer_; StrikeDatabase* strike_database_;
diff --git a/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm b/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm index d63134a2..748d47b 100644 --- a/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm +++ b/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm
@@ -30,7 +30,7 @@ AutocompleteHistoryManager* autocomplete_history_manager, web::WebState* web_state, id<CWVAutofillClientIOSBridge> bridge, - identity::IdentityManager* identity_manager, + signin::IdentityManager* identity_manager, StrikeDatabase* strike_database, scoped_refptr<AutofillWebDataService> autofill_web_data_service, syncer::SyncService* sync_service) @@ -77,7 +77,7 @@ return sync_service_; } -identity::IdentityManager* WebViewAutofillClientIOS::GetIdentityManager() { +signin::IdentityManager* WebViewAutofillClientIOS::GetIdentityManager() { return identity_manager_; }
diff --git a/ios/web_view/internal/cwv_web_view.mm b/ios/web_view/internal/cwv_web_view.mm index 55426b18..ddba312e0 100644 --- a/ios/web_view/internal/cwv_web_view.mm +++ b/ios/web_view/internal/cwv_web_view.mm
@@ -5,6 +5,7 @@ #import "ios/web_view/internal/cwv_web_view_internal.h" #include <memory> +#include <unordered_map> #include <utility> #include "base/bind.h" @@ -111,7 +112,11 @@ // Handles presentation of JavaScript dialogs. std::unique_ptr<ios_web_view::WebViewJavaScriptDialogPresenter> _javaScriptDialogPresenter; - std::map<std::string, web::WebState::ScriptCommandCallback> + // Stores the script command callbacks with subscriptions. + std::unordered_map< + std::string, + std::pair<web::WebState::ScriptCommandCallback, + std::unique_ptr<web::WebState::ScriptCommandSubscription>>> _scriptCommandCallbacks; CRWSessionStorage* _cachedSessionStorage; } @@ -298,10 +303,6 @@ - (void)webStateDestroyed:(web::WebState*)webState { webState->RemoveObserver(_webStateObserver.get()); _webStateObserver.reset(); - for (const auto& pair : _scriptCommandCallbacks) { - webState->RemoveScriptCommandCallback(pair.first); - } - _scriptCommandCallbacks.clear(); } - (void)webState:(web::WebState*)webState @@ -499,13 +500,14 @@ }); std::string stdCommandPrefix = base::SysNSStringToUTF8(commandPrefix); - _webState->AddScriptCommandCallback(callback, stdCommandPrefix); - _scriptCommandCallbacks[stdCommandPrefix] = callback; + auto subscription = + _webState->AddScriptCommandCallback(callback, stdCommandPrefix); + _scriptCommandCallbacks[stdCommandPrefix] = {callback, + std::move(subscription)}; } - (void)removeScriptCommandHandlerForCommandPrefix:(NSString*)commandPrefix { std::string stdCommandPrefix = base::SysNSStringToUTF8(commandPrefix); - _webState->RemoveScriptCommandCallback(stdCommandPrefix); _scriptCommandCallbacks.erase(stdCommandPrefix); } @@ -553,9 +555,7 @@ base::mac::ObjCCastStrict<JsSuggestionManager>( [_webState->GetJSInjectionReceiver() instanceOfClass:[JsSuggestionManager class]]); - web::WebFramesManager* framesManager = - web::WebFramesManager::FromWebState(_webState.get()); - [JSSuggestionManager setWebFramesManager:framesManager]; + [JSSuggestionManager setWebFramesManager:_webState->GetWebFramesManager()]; return [[CWVAutofillController alloc] initWithWebState:_webState.get() autofillAgent:autofillAgent JSAutofillManager:JSAutofillManager @@ -608,9 +608,6 @@ if (_webStateObserver) { _webState->RemoveObserver(_webStateObserver.get()); } - for (const auto& pair : _scriptCommandCallbacks) { - _webState->RemoveScriptCommandCallback(pair.first); - } WebViewHolder::RemoveFromWebState(_webState.get()); if (_webState->GetView().superview == self) { // The web view provided by the old |_webState| has been added as a @@ -653,8 +650,9 @@ std::make_unique<ios_web_view::WebViewJavaScriptDialogPresenter>(self, nullptr); - for (const auto& pair : _scriptCommandCallbacks) { - _webState->AddScriptCommandCallback(pair.second, pair.first); + for (auto& pair : _scriptCommandCallbacks) { + pair.second.second = + _webState->AddScriptCommandCallback(pair.second.first, pair.first); } _webState->GetWebViewProxy().allowsBackForwardNavigationGestures =
diff --git a/ios/web_view/internal/cwv_web_view_configuration.mm b/ios/web_view/internal/cwv_web_view_configuration.mm index 1154e1c..8c39426b 100644 --- a/ios/web_view/internal/cwv_web_view_configuration.mm +++ b/ios/web_view/internal/cwv_web_view_configuration.mm
@@ -149,7 +149,7 @@ syncer::SyncService* syncService = ios_web_view::WebViewProfileSyncServiceFactory::GetForBrowserState( self.browserState); - identity::IdentityManager* identityManager = + signin::IdentityManager* identityManager = ios_web_view::WebViewIdentityManagerFactory::GetForBrowserState( self.browserState); SigninErrorController* signinErrorController =
diff --git a/ios/web_view/internal/passwords/cwv_password_controller.mm b/ios/web_view/internal/passwords/cwv_password_controller.mm index 0bc6dd41..29e06e2 100644 --- a/ios/web_view/internal/passwords/cwv_password_controller.mm +++ b/ios/web_view/internal/passwords/cwv_password_controller.mm
@@ -17,7 +17,6 @@ #import "components/password_manager/ios/password_suggestion_helper.h" #import "ios/web/common/origin_util.h" #include "ios/web/public/js_messaging/web_frame.h" -#include "ios/web/public/js_messaging/web_frame_util.h" #include "ios/web/public/url_scheme_util.h" #import "ios/web/public/web_state/web_state_observer_bridge.h" #import "ios/web_view/internal/autofill/cwv_autofill_suggestion_internal.h"
diff --git a/ios/web_view/internal/signin/DEPS b/ios/web_view/internal/signin/DEPS deleted file mode 100644 index 8d75512..0000000 --- a/ios/web_view/internal/signin/DEPS +++ /dev/null
@@ -1,14 +0,0 @@ -specific_include_rules = { - # IdentityManagerFactory creates IdentityManager instances from internal - # dependencies. TODO(crbug.com/974198): Internalize this building and - # eliminate the need for these inclusions. - "web_view_identity_manager_factory.mm": [ - "+components/signin/internal/identity_manager/account_fetcher_service.h", - "+components/signin/internal/identity_manager/account_tracker_service.h", - "+components/signin/internal/identity_manager/gaia_cookie_manager_service.h", - "+components/signin/internal/identity_manager/primary_account_manager.h", - "+components/signin/internal/identity_manager/primary_account_policy_manager.h", - "+components/signin/internal/identity_manager/profile_oauth2_token_service.h", - "+components/signin/internal/identity_manager", # TODO(crbug.com/974198): remove once closed - ], -}
diff --git a/ios/web_view/internal/signin/web_view_identity_manager_factory.h b/ios/web_view/internal/signin/web_view_identity_manager_factory.h index b0f5121..23cf920 100644 --- a/ios/web_view/internal/signin/web_view_identity_manager_factory.h +++ b/ios/web_view/internal/signin/web_view_identity_manager_factory.h
@@ -9,7 +9,7 @@ #include "base/no_destructor.h" #include "components/keyed_service/ios/browser_state_keyed_service_factory.h" -namespace identity { +namespace signin { class IdentityManager; } @@ -21,7 +21,7 @@ // BrowserStates. class WebViewIdentityManagerFactory : public BrowserStateKeyedServiceFactory { public: - static identity::IdentityManager* GetForBrowserState( + static signin::IdentityManager* GetForBrowserState( WebViewBrowserState* browser_state); // Returns an instance of the WebViewIdentityManagerFactory singleton.
diff --git a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm index 8e62bc5..a7fd400 100644 --- a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm +++ b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm
@@ -30,7 +30,7 @@ void WebViewIdentityManagerFactory::RegisterBrowserStatePrefs( user_prefs::PrefRegistrySyncable* registry) { - identity::IdentityManager::RegisterProfilePrefs(registry); + signin::IdentityManager::RegisterProfilePrefs(registry); } WebViewIdentityManagerFactory::WebViewIdentityManagerFactory() @@ -43,9 +43,9 @@ WebViewIdentityManagerFactory::~WebViewIdentityManagerFactory() {} // static -identity::IdentityManager* WebViewIdentityManagerFactory::GetForBrowserState( +signin::IdentityManager* WebViewIdentityManagerFactory::GetForBrowserState( WebViewBrowserState* browser_state) { - return static_cast<identity::IdentityManager*>( + return static_cast<signin::IdentityManager*>( GetInstance()->GetServiceForBrowserState(browser_state, true)); } @@ -71,7 +71,7 @@ IOSWebViewSigninClient* client = WebViewSigninClientFactory::GetForBrowserState(browser_state); - identity::IdentityManagerBuildParams params; + signin::IdentityManagerBuildParams params; params.account_consistency = signin::AccountConsistencyMethod::kDisabled; params.device_accounts_provider = std::make_unique<WebViewDeviceAccountsProviderImpl>(client); @@ -81,7 +81,7 @@ params.profile_path = base::FilePath(); params.signin_client = client; - return identity::BuildIdentityManager(¶ms); + return signin::BuildIdentityManager(¶ms); } } // namespace ios_web_view
diff --git a/ios/web_view/internal/sync/cwv_sync_controller.mm b/ios/web_view/internal/sync/cwv_sync_controller.mm index f6db59c..f8f5462 100644 --- a/ios/web_view/internal/sync/cwv_sync_controller.mm +++ b/ios/web_view/internal/sync/cwv_sync_controller.mm
@@ -103,7 +103,7 @@ @implementation CWVSyncController { syncer::SyncService* _syncService; - identity::IdentityManager* _identityManager; + signin::IdentityManager* _identityManager; SigninErrorController* _signinErrorController; std::unique_ptr<ios_web_view::WebViewSyncControllerObserverBridge> _observer; @@ -115,7 +115,7 @@ @synthesize currentIdentity = _currentIdentity; - (instancetype)initWithSyncService:(syncer::SyncService*)syncService - identityManager:(identity::IdentityManager*)identityManager + identityManager:(signin::IdentityManager*)identityManager signinErrorController: (SigninErrorController*)signinErrorController { self = [super init]; @@ -177,7 +177,7 @@ - (void)stopSyncAndClearIdentity { auto* primaryAccountMutator = _identityManager->GetPrimaryAccountMutator(); primaryAccountMutator->ClearPrimaryAccount( - identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::ProfileSignout::USER_CLICKED_SIGNOUT_SETTINGS, signin_metrics::SignoutDelete::IGNORE_METRIC); _currentIdentity = nil;
diff --git a/ios/web_view/internal/sync/cwv_sync_controller_internal.h b/ios/web_view/internal/sync/cwv_sync_controller_internal.h index a93a54d..b9c08a44 100644 --- a/ios/web_view/internal/sync/cwv_sync_controller_internal.h +++ b/ios/web_view/internal/sync/cwv_sync_controller_internal.h
@@ -18,7 +18,7 @@ class SyncService; } // namespace syncer -namespace identity { +namespace signin { class IdentityManager; } @@ -28,7 +28,7 @@ // All dependencies must out live this class. - (instancetype)initWithSyncService:(syncer::SyncService*)syncService - identityManager:(identity::IdentityManager*)identityManager + identityManager:(signin::IdentityManager*)identityManager signinErrorController: (SigninErrorController*)SigninErrorController NS_DESIGNATED_INITIALIZER;
diff --git a/ios/web_view/internal/sync/cwv_sync_controller_unittest.mm b/ios/web_view/internal/sync/cwv_sync_controller_unittest.mm index 97be868..c5fadc74 100644 --- a/ios/web_view/internal/sync/cwv_sync_controller_unittest.mm +++ b/ios/web_view/internal/sync/cwv_sync_controller_unittest.mm
@@ -87,7 +87,7 @@ sync_service_observer_ = observer; } - identity::IdentityManager* identity_manager() { + signin::IdentityManager* identity_manager() { return WebViewIdentityManagerFactory::GetForBrowserState(&browser_state_); } @@ -163,7 +163,7 @@ // Create authentication error. GoogleServiceAuthError auth_error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( + signin::UpdatePersistentErrorOfRefreshTokenForAccount( identity_manager(), identity_manager()->GetPrimaryAccountId(), auth_error);
diff --git a/ios/web_view/internal/sync/web_view_profile_sync_service_factory.mm b/ios/web_view/internal/sync/web_view_profile_sync_service_factory.mm index c42f6eaa..ebee189 100644 --- a/ios/web_view/internal/sync/web_view_profile_sync_service_factory.mm +++ b/ios/web_view/internal/sync/web_view_profile_sync_service_factory.mm
@@ -80,7 +80,7 @@ WebViewBrowserState* browser_state = WebViewBrowserState::FromBrowserState(context); - identity::IdentityManager* identity_manager = + signin::IdentityManager* identity_manager = WebViewIdentityManagerFactory::GetForBrowserState(browser_state); WebViewGCMProfileServiceFactory::GetForBrowserState(browser_state);
diff --git a/mojo/public/cpp/bindings/lib/pending_remote_state.cc b/mojo/public/cpp/bindings/lib/pending_remote_state.cc index 6dcc618..cf99e42ec 100644 --- a/mojo/public/cpp/bindings/lib/pending_remote_state.cc +++ b/mojo/public/cpp/bindings/lib/pending_remote_state.cc
@@ -13,11 +13,12 @@ uint32_t version) : pipe(std::move(pipe)), version(version) {} -PendingRemoteState::PendingRemoteState(PendingRemoteState&&) = default; +PendingRemoteState::PendingRemoteState(PendingRemoteState&&) noexcept = default; PendingRemoteState::~PendingRemoteState() = default; -PendingRemoteState& PendingRemoteState::operator=(PendingRemoteState&& other) { +PendingRemoteState& PendingRemoteState::operator=( + PendingRemoteState&& other) noexcept { reset(); pipe = std::move(other.pipe); version = other.version;
diff --git a/mojo/public/cpp/bindings/lib/pending_remote_state.h b/mojo/public/cpp/bindings/lib/pending_remote_state.h index 12cd091b..ad22f22 100644 --- a/mojo/public/cpp/bindings/lib/pending_remote_state.h +++ b/mojo/public/cpp/bindings/lib/pending_remote_state.h
@@ -21,11 +21,11 @@ PendingRemoteState(); PendingRemoteState(ScopedMessagePipeHandle pipe, uint32_t version); PendingRemoteState(const PendingRemoteState&) = delete; - PendingRemoteState(PendingRemoteState&&); + PendingRemoteState(PendingRemoteState&&) noexcept; ~PendingRemoteState(); PendingRemoteState& operator=(const PendingRemoteState&) = delete; - PendingRemoteState& operator=(PendingRemoteState&&); + PendingRemoteState& operator=(PendingRemoteState&&) noexcept; void reset();
diff --git a/net/http/http_server_properties_manager.cc b/net/http/http_server_properties_manager.cc index 133c2276..8cb7cd9 100644 --- a/net/http/http_server_properties_manager.cc +++ b/net/http/http_server_properties_manager.cc
@@ -163,7 +163,7 @@ http_server_properties_impl_->SetSupportsSpdy(server, support_spdy); bool new_support_spdy = http_server_properties_impl_->GetSupportsSpdy(server); if (old_support_spdy != new_support_spdy) - ScheduleUpdatePrefs(SUPPORTS_SPDY); + ScheduleUpdatePrefs(); } bool HttpServerPropertiesManager::RequiresHTTP11(const HostPortPair& server) { @@ -176,7 +176,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); http_server_properties_impl_->SetHTTP11Required(server); - ScheduleUpdatePrefs(HTTP_11_REQUIRED); + ScheduleUpdatePrefs(); } void HttpServerPropertiesManager::MaybeForceHTTP11(const HostPortPair& server, @@ -200,7 +200,7 @@ const bool changed = http_server_properties_impl_->SetHttp2AlternativeService( origin, alternative_service, expiration); if (changed) { - ScheduleUpdatePrefs(SET_ALTERNATIVE_SERVICES); + ScheduleUpdatePrefs(); } return changed; } @@ -214,7 +214,7 @@ const bool changed = http_server_properties_impl_->SetQuicAlternativeService( origin, alternative_service, expiration, advertised_versions); if (changed) { - ScheduleUpdatePrefs(SET_ALTERNATIVE_SERVICES); + ScheduleUpdatePrefs(); } return changed; } @@ -226,7 +226,7 @@ const bool changed = http_server_properties_impl_->SetAlternativeServices( origin, alternative_service_info_vector); if (changed) { - ScheduleUpdatePrefs(SET_ALTERNATIVE_SERVICES); + ScheduleUpdatePrefs(); } return changed; } @@ -236,7 +236,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); http_server_properties_impl_->MarkAlternativeServiceBroken( alternative_service); - ScheduleUpdatePrefs(MARK_ALTERNATIVE_SERVICE_BROKEN); + ScheduleUpdatePrefs(); } void HttpServerPropertiesManager:: @@ -246,8 +246,7 @@ http_server_properties_impl_ ->MarkAlternativeServiceBrokenUntilDefaultNetworkChanges( alternative_service); - ScheduleUpdatePrefs( - MARK_ALTERNATIVE_SERVICE_BROKEN_UNTIL_DEFAULT_NETWORK_CHANGES); + ScheduleUpdatePrefs(); } void HttpServerPropertiesManager::MarkAlternativeServiceRecentlyBroken( @@ -255,7 +254,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); http_server_properties_impl_->MarkAlternativeServiceRecentlyBroken( alternative_service); - ScheduleUpdatePrefs(MARK_ALTERNATIVE_SERVICE_RECENTLY_BROKEN); + ScheduleUpdatePrefs(); } bool HttpServerPropertiesManager::IsAlternativeServiceBroken( @@ -283,14 +282,14 @@ // For persisting, we only care about the value returned by // IsAlternativeServiceBroken. If that value changes, then call persist. if (old_value != new_value) - ScheduleUpdatePrefs(CONFIRM_ALTERNATIVE_SERVICE); + ScheduleUpdatePrefs(); } bool HttpServerPropertiesManager::OnDefaultNetworkChanged() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool changed = http_server_properties_impl_->OnDefaultNetworkChanged(); if (changed) - ScheduleUpdatePrefs(ON_DEFAULT_NETWORK_CHANGED); + ScheduleUpdatePrefs(); return changed; } @@ -321,7 +320,7 @@ IPAddress new_last_quic_addr; http_server_properties_impl_->GetSupportsQuic(&new_last_quic_addr); if (old_last_quic_addr != new_last_quic_addr) - ScheduleUpdatePrefs(SET_SUPPORTS_QUIC); + ScheduleUpdatePrefs(); } void HttpServerPropertiesManager::SetServerNetworkStats( @@ -337,7 +336,7 @@ ServerNetworkStats new_stats = *(http_server_properties_impl_->GetServerNetworkStats(server)); if (old_stats != new_stats) - ScheduleUpdatePrefs(SET_SERVER_NETWORK_STATS); + ScheduleUpdatePrefs(); } void HttpServerPropertiesManager::ClearServerNetworkStats( @@ -347,7 +346,7 @@ http_server_properties_impl_->GetServerNetworkStats(server) != nullptr; http_server_properties_impl_->ClearServerNetworkStats(server); if (need_update) - ScheduleUpdatePrefs(CLEAR_SERVER_NETWORK_STATS); + ScheduleUpdatePrefs(); } const ServerNetworkStats* HttpServerPropertiesManager::GetServerNetworkStats( @@ -369,7 +368,7 @@ bool changed = http_server_properties_impl_->SetQuicServerInfo(server_id, server_info); if (changed) - ScheduleUpdatePrefs(SET_QUIC_SERVER_INFO); + ScheduleUpdatePrefs(); return changed; } @@ -588,7 +587,7 @@ // Update the prefs with what we have read (delete all corrupted prefs). if (detected_corrupted_prefs) - ScheduleUpdatePrefs(DETECTED_CORRUPTED_PREFS); + ScheduleUpdatePrefs(); } bool HttpServerPropertiesManager::AddToBrokenAlternativeServices( @@ -940,10 +939,7 @@ return !detected_corrupted_prefs; } -// -// Update Preferences with data from the cached data. -// -void HttpServerPropertiesManager::ScheduleUpdatePrefs(Location location) { +void HttpServerPropertiesManager::ScheduleUpdatePrefs() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Do not schedule a new update if there is already one scheduled. if (network_prefs_update_timer_.IsRunning()) @@ -953,10 +949,6 @@ FROM_HERE, kUpdatePrefsDelay, base::Bind(&HttpServerPropertiesManager::UpdatePrefsFromCache, base::Unretained(this), base::Passed(base::OnceClosure()))); - - // TODO(rtenneti): Delete the following histogram after collecting some data. - UMA_HISTOGRAM_ENUMERATION("Net.HttpServerProperties.UpdatePrefs", location, - HttpServerPropertiesManager::NUM_LOCATIONS); } void HttpServerPropertiesManager::UpdatePrefsFromCache(
diff --git a/net/http/http_server_properties_manager.h b/net/http/http_server_properties_manager.h index bd8da60..17d7d96 100644 --- a/net/http/http_server_properties_manager.h +++ b/net/http/http_server_properties_manager.h
@@ -146,33 +146,6 @@ void ScheduleUpdateCacheForTesting(); protected: - // The location where ScheduleUpdatePrefs was called. - // Must be kept up to date with HttpServerPropertiesUpdatePrefsLocation in - // histograms.xml. - enum Location { - SUPPORTS_SPDY = 0, - HTTP_11_REQUIRED = 1, - SET_ALTERNATIVE_SERVICES = 2, - MARK_ALTERNATIVE_SERVICE_BROKEN = 3, - MARK_ALTERNATIVE_SERVICE_RECENTLY_BROKEN = 4, - CONFIRM_ALTERNATIVE_SERVICE = 5, - CLEAR_ALTERNATIVE_SERVICE = 6, - // deprecated: SET_SPDY_SETTING = 7, - // deprecated: CLEAR_SPDY_SETTINGS = 8, - // deprecated: CLEAR_ALL_SPDY_SETTINGS = 9, - SET_SUPPORTS_QUIC = 10, - SET_SERVER_NETWORK_STATS = 11, - DETECTED_CORRUPTED_PREFS = 12, - SET_QUIC_SERVER_INFO = 13, - CLEAR_SERVER_NETWORK_STATS = 14, - MARK_ALTERNATIVE_SERVICE_BROKEN_UNTIL_DEFAULT_NETWORK_CHANGES = 15, - ON_DEFAULT_NETWORK_CHANGED = 16, - NUM_LOCATIONS = 17, - }; - - // -------------------- - // SPDY related methods - // These are used to delay updating of the cached data in // |http_server_properties_impl_| while the preferences are changing, and // execute only one update per simultaneous prefs changes. @@ -186,7 +159,7 @@ // |http_server_properties_impl_| is changing, and execute only one update per // simultaneous changes. // |location| specifies where this method is called from. - void ScheduleUpdatePrefs(Location location); + void ScheduleUpdatePrefs(); // Update prefs::kHttpServerProperties in preferences with the cached data // from |http_server_properties_impl_|. Invokes |callback| when changes have
diff --git a/services/identity/identity_accessor_impl.cc b/services/identity/identity_accessor_impl.cc index f1df1ba9..e7ca0d1 100644 --- a/services/identity/identity_accessor_impl.cc +++ b/services/identity/identity_accessor_impl.cc
@@ -18,7 +18,7 @@ scoped_refptr<base::RefCountedData<bool>> is_callback_done, GetAccessTokenCallback consumer_callback, GoogleServiceAuthError error, - AccessTokenInfo access_token_info) { + signin::AccessTokenInfo access_token_info) { if (error.state() == GoogleServiceAuthError::NONE) { std::move(consumer_callback) .Run(access_token_info.token, access_token_info.expiration_time, error); @@ -30,7 +30,8 @@ access_token_fetchers_.erase(callback_id); } -IdentityAccessorImpl::IdentityAccessorImpl(IdentityManager* identity_manager) +IdentityAccessorImpl::IdentityAccessorImpl( + signin::IdentityManager* identity_manager) : identity_manager_(identity_manager) { identity_manager_->AddObserver(this); } @@ -74,13 +75,13 @@ auto is_callback_done = base::MakeRefCounted<base::RefCountedData<bool>>(false); - std::unique_ptr<AccessTokenFetcher> fetcher = + std::unique_ptr<signin::AccessTokenFetcher> fetcher = identity_manager_->CreateAccessTokenFetcherForAccount( account_id, consumer_id, scopes, base::BindOnce(&IdentityAccessorImpl::OnTokenRequestCompleted, base::Unretained(this), callback_id, is_callback_done, std::move(callback)), - identity::AccessTokenFetcher::Mode::kImmediate); + signin::AccessTokenFetcher::Mode::kImmediate); // If our callback hasn't already been run, hold on to the AccessTokenFetcher // so it won't be cleaned up until the request is done.
diff --git a/services/identity/identity_accessor_impl.h b/services/identity/identity_accessor_impl.h index 2688555..da7b2e3 100644 --- a/services/identity/identity_accessor_impl.h +++ b/services/identity/identity_accessor_impl.h
@@ -16,19 +16,23 @@ #include "services/identity/public/cpp/scope_set.h" #include "services/identity/public/mojom/identity_accessor.mojom.h" -namespace identity { +namespace signin { struct AccessTokenInfo; +} + +namespace identity { class IdentityAccessorImpl : public mojom::IdentityAccessor, - public IdentityManager::Observer { + public signin::IdentityManager::Observer { public: - explicit IdentityAccessorImpl(IdentityManager* identity_manager); + explicit IdentityAccessorImpl(signin::IdentityManager* identity_manager); ~IdentityAccessorImpl() override; private: // Map of outstanding access token requests. using AccessTokenFetchers = - std::map<base::UnguessableToken, std::unique_ptr<AccessTokenFetcher>>; + std::map<base::UnguessableToken, + std::unique_ptr<signin::AccessTokenFetcher>>; // Invoked after access token request completes (successful or not). // Completes the pending access token request by calling back the consumer. @@ -37,7 +41,7 @@ scoped_refptr<base::RefCountedData<bool>> is_callback_done, GetAccessTokenCallback consumer_callback, GoogleServiceAuthError error, - AccessTokenInfo access_token_info); + signin::AccessTokenInfo access_token_info); // mojom::IdentityAccessor: void GetPrimaryAccountInfo(GetPrimaryAccountInfoCallback callback) override; @@ -48,7 +52,7 @@ const std::string& consumer_id, GetAccessTokenCallback callback) override; - // IdentityManager::Observer: + // signin::IdentityManager::Observer: void OnRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info) override; void OnPrimaryAccountSet(const CoreAccountInfo& account_info) override; @@ -60,7 +64,7 @@ // Gets the current state of the account represented by |account_info|. AccountState GetStateOfAccount(const CoreAccountInfo& account_info); - IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; // The set of pending requests for access tokens. AccessTokenFetchers access_token_fetchers_;
diff --git a/services/identity/identity_accessor_impl_unittest.cc b/services/identity/identity_accessor_impl_unittest.cc index 90488ae..1aa6967 100644 --- a/services/identity/identity_accessor_impl_unittest.cc +++ b/services/identity/identity_accessor_impl_unittest.cc
@@ -116,12 +116,12 @@ base::Optional<std::string> access_token_; GoogleServiceAuthError access_token_error_; - IdentityTestEnvironment* identity_test_environment() { + signin::IdentityTestEnvironment* identity_test_environment() { return &identity_test_environment_; } private: - identity::IdentityTestEnvironment identity_test_environment_; + signin::IdentityTestEnvironment identity_test_environment_; service_manager::TestConnectorFactory test_connector_factory_; IdentityService service_;
diff --git a/services/identity/identity_service.cc b/services/identity/identity_service.cc index 6eb1992d..57dc43d 100644 --- a/services/identity/identity_service.cc +++ b/services/identity/identity_service.cc
@@ -12,7 +12,7 @@ namespace identity { -IdentityService::IdentityService(IdentityManager* identity_manager, +IdentityService::IdentityService(signin::IdentityManager* identity_manager, service_manager::mojom::ServiceRequest request) : service_binding_(this, std::move(request)), identity_manager_(identity_manager) {
diff --git a/services/identity/identity_service.h b/services/identity/identity_service.h index bc35d4c..2fb7ebc 100644 --- a/services/identity/identity_service.h +++ b/services/identity/identity_service.h
@@ -21,7 +21,7 @@ class IdentityService : public service_manager::Service { public: - IdentityService(IdentityManager* identity_manager, + IdentityService(signin::IdentityManager* identity_manager, service_manager::mojom::ServiceRequest request); ~IdentityService() override; @@ -41,7 +41,7 @@ service_manager::ServiceBinding service_binding_; - IdentityManager* identity_manager_; + signin::IdentityManager* identity_manager_; mojo::StrongBindingSet<mojom::IdentityAccessor> identity_accessor_bindings_;
diff --git a/services/network/resource_scheduler/resource_scheduler_params_manager.cc b/services/network/resource_scheduler/resource_scheduler_params_manager.cc index f1a64570d..d44244f 100644 --- a/services/network/resource_scheduler/resource_scheduler_params_manager.cc +++ b/services/network/resource_scheduler/resource_scheduler_params_manager.cc
@@ -36,11 +36,27 @@ std::set<int32_t> GetThrottledHashes() { std::set<int32_t> throttled_hashes; - const std::string& throttled_traffic_annotation_tags = + if (!base::FeatureList::IsEnabled( + features::kPauseBrowserInitiatedHeavyTrafficForP2P)) { + return throttled_hashes; + } + + std::string throttled_traffic_annotation_tags = base::GetFieldTrialParamValueByFeature( features::kPauseBrowserInitiatedHeavyTrafficForP2P, "throttled_traffic_annotation_tags"); + // Use default values for blocked hashes if there is none specified using + // field trial: The list below includes annotation tags that generate a lot of + // either downlink or uplink traffic and are expected to cause traffic + // contention with the P2P traffic on slow connections. + if (throttled_traffic_annotation_tags.empty()) { + // 6019475: safe_browsing_module_loader + // 82509217: safe_browsing_v4_update + // 727528: metrics_report_uma + throttled_traffic_annotation_tags = "6019475,82509217,727528"; + } + const std::vector<std::string>& tokens = base::SplitString(throttled_traffic_annotation_tags, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
diff --git a/services/network/resource_scheduler/resource_scheduler_unittest.cc b/services/network/resource_scheduler/resource_scheduler_unittest.cc index 20c33bc4..cabb707 100644 --- a/services/network/resource_scheduler/resource_scheduler_unittest.cc +++ b/services/network/resource_scheduler/resource_scheduler_unittest.cc
@@ -811,12 +811,12 @@ true, }, { - "Field trial param not set", + "Field trial param not set, default params used", 1u, net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G, true, false, - true, + false, }, }; @@ -850,7 +850,8 @@ // (COMPUTE_NETWORK_TRAFFIC_ANNOTATION_ID_HASH("")); std::unique_ptr<TestRequest> lows = (NewBrowserRequestWithAnnotationTag( url.c_str(), net::LOWEST, tag)); //"metrics_report_uma")); - EXPECT_EQ(test.expected_browser_initiated_traffic_started, lows->started()); + EXPECT_EQ(test.expected_browser_initiated_traffic_started, lows->started()) + << " test_case=" << test.test_case; } }
diff --git a/services/network/restricted_cookie_manager.cc b/services/network/restricted_cookie_manager.cc index d7bdb85..1b6e4db 100644 --- a/services/network/restricted_cookie_manager.cc +++ b/services/network/restricted_cookie_manager.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/compiler_specific.h" // for FALLTHROUGH; +#include "base/debug/crash_logging.h" #include "base/memory/weak_ptr.h" #include "base/sequenced_task_runner.h" #include "base/strings/string_util.h" @@ -443,6 +444,20 @@ if (origin_.IsSameOriginWith(url::Origin::Create(url))) return true; + // TODO(https://crbug.com/983090): Remove the crash keys once fixed. + static base::debug::CrashKeyString* bound_origin = + base::debug::AllocateCrashKeyString( + "restricted_cookie_manager_bound_origin", + base::debug::CrashKeySize::Size256); + base::debug::SetCrashKeyString(bound_origin, origin_.GetDebugString()); + + static base::debug::CrashKeyString* url_origin = + base::debug::AllocateCrashKeyString( + "restricted_cookie_manager_url_origin", + base::debug::CrashKeySize::Size256); + base::debug::SetCrashKeyString(url_origin, + url::Origin::Create(url).GetDebugString()); + mojo::ReportBadMessage("Incorrect url origin"); return false; }
diff --git a/testing/buildbot/filters/navigation_loader_on_ui_browser_tests.filter b/testing/buildbot/filters/navigation_loader_on_ui_browser_tests.filter index 5d006fa..044935e 100644 --- a/testing/buildbot/filters/navigation_loader_on_ui_browser_tests.filter +++ b/testing/buildbot/filters/navigation_loader_on_ui_browser_tests.filter
@@ -1 +1,4 @@ # These tests currently fail when run with --enable-features=NavigationLoaderOnUI + +# https://crbug.com/978617 +-GcmApiTest.*
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 6b267bed..58071d43 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -330,7 +330,7 @@ "BlinkHeapConcurrentMarking", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables concurrently sweeping Blink's heap. const base::Feature kBlinkHeapConcurrentSweeping{ - "BlinkHeapConcurrentSweeping", base::FEATURE_DISABLED_BY_DEFAULT}; + "BlinkHeapConcurrentSweeping", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables incrementally marking Blink's heap. const base::Feature kBlinkHeapIncrementalMarking{ "BlinkHeapIncrementalMarking", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index cb721c1..05ee9b7 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -52,6 +52,7 @@ "frame/frame_host_test_interface.mojom", "frame/lifecycle.mojom", "frame/navigation_initiator.mojom", + "frame/surrounding_text.mojom", "geolocation/geolocation_service.mojom", "hid/hid.mojom", "hyphenation/hyphenation.mojom",
diff --git a/third_party/blink/public/mojom/frame/surrounding_text.mojom b/third_party/blink/public/mojom/frame/surrounding_text.mojom new file mode 100644 index 0000000..e8420f3 --- /dev/null +++ b/third_party/blink/public/mojom/frame/surrounding_text.mojom
@@ -0,0 +1,18 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module blink.mojom; + +import "mojo/public/mojom/base/string16.mojom"; + +// Implemented in Blink, this interface allows to retrieve the text surrounding +// the current text selection, along with its start & end offsets, for a given +// frame, from the browser process (accessed from content::RenderFrameHostImpl). +interface SurroundingText { + // Retrieves the text surrounding the current selection for the frame up to + // the length specified by |max_length|, along with its start and end offsets. + GetTextSurroundingSelection(uint32 max_length) + => (mojo_base.mojom.String16 content, uint32 start_offset, + uint32 end_offset); +};
diff --git a/third_party/blink/public/mojom/web_feature/web_feature.mojom b/third_party/blink/public/mojom/web_feature/web_feature.mojom index 1931f476..230e87a 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -2183,7 +2183,6 @@ kV8RemotePlayback_Prompt_Method = 2781, kLayoutShiftExplicitlyRequested = 2782, kMediaSessionSkipAd = 2783, - kAdFrameSizeIntervention = 2784, kV8UserActivation_HasBeenActive_AttributeGetter = 2785, kV8UserActivation_IsActive_AttributeGetter = 2786, kTextEncoderEncodeInto = 2787,
diff --git a/third_party/blink/public/platform/web_layer_tree_view.h b/third_party/blink/public/platform/web_layer_tree_view.h index cf57ffb..ad83def8 100644 --- a/third_party/blink/public/platform/web_layer_tree_view.h +++ b/third_party/blink/public/platform/web_layer_tree_view.h
@@ -67,14 +67,7 @@ float bottom_height, bool shrink_viewport) {} - // Flow control and scheduling --------------------------------------- - - // For when the embedder itself change scales on the page (e.g. devtools) - // and wants all of the content at the new scale to be crisp. - virtual void ForceRecalculateRasterScales() {} - // Input properties --------------------------------------------------- - virtual void UpdateEventRectsForSubframeIfNecessary() {} virtual void SetHaveScrollEventHandlers(bool) {} // Returns the FrameSinkId of the widget associated with this layer tree view.
diff --git a/third_party/blink/public/web/web_autofill_client.h b/third_party/blink/public/web/web_autofill_client.h index 9c932e1..62cfdfe 100644 --- a/third_party/blink/public/web/web_autofill_client.h +++ b/third_party/blink/public/web/web_autofill_client.h
@@ -65,9 +65,11 @@ virtual void DidCompleteFocusChangeInFrame() {} virtual void DidReceiveLeftMouseDownOrGestureTapInNode(const WebNode&) {} - // Queries the client whether filling data is available for a given control - // element. - virtual bool HasFillData(const WebFormControlElement&) const { return false; } + // Asks the client to show the touch to fill UI for the given control element. + // Returns whether the touch to fill UI was actually shown. + virtual bool TryToShowTouchToFill(const WebFormControlElement&) { + return false; + } protected: virtual ~WebAutofillClient() = default;
diff --git a/third_party/blink/public/web/web_local_frame.h b/third_party/blink/public/web/web_local_frame.h index c41afd0..c3c23c3 100644 --- a/third_party/blink/public/web/web_local_frame.h +++ b/third_party/blink/public/web/web_local_frame.h
@@ -724,9 +724,9 @@ // checkbox, radio etc.) virtual void AdvanceFocusInForm(WebFocusType) = 0; - // Returns whether the currently focused field could be autofilled by the - // active WebAutofillClient. - virtual bool CanFocusedFieldBeAutofilled() const = 0; + // Asks the active WebAutofillClient to show the touch to fill UI for the + // currently focused field. Returns whether this request succeeded. + virtual bool TryToShowTouchToFillForFocusedElement() = 0; // Performance --------------------------------------------------------
diff --git a/third_party/blink/public/web/web_widget_client.h b/third_party/blink/public/web/web_widget_client.h index 97f239bb..c8b46daa 100644 --- a/third_party/blink/public/web/web_widget_client.h +++ b/third_party/blink/public/web/web_widget_client.h
@@ -285,6 +285,10 @@ float new_page_scale, double duration_sec) {} + // For when the embedder itself change scales on the page (e.g. devtools) + // and wants all of the content at the new scale to be crisp. + virtual void ForceRecalculateRasterScales() {} + // Requests an image decode and will have the |callback| run asynchronously // when it completes. Forces a new main frame to occur that will trigger // pushing the decode through the compositor.
diff --git a/third_party/blink/renderer/bindings/BUILD.gn b/third_party/blink/renderer/bindings/BUILD.gn index f52d1e4..b77255a 100644 --- a/third_party/blink/renderer/bindings/BUILD.gn +++ b/third_party/blink/renderer/bindings/BUILD.gn
@@ -4,6 +4,7 @@ import("//third_party/blink/renderer/bindings/scripts/scripts.gni") import("//third_party/blink/renderer/build/scripts/scripts.gni") +import("//third_party/blink/renderer/core/core_idl_files.gni") import("//third_party/blink/renderer/modules/modules_idl_files.gni") action("interfaces_info") { @@ -46,31 +47,75 @@ ] } -blink_python_runner("web_idl_database") { - script = "$bindings_scripts_dir/build_web_idl_database.py" +template("collect_idl_files") { + action(target_name) { + script = "${bindings_scripts_dir}/collect_idl_files.py" + sources = invoker.sources + outputs = [ + invoker.output, + ] + deps = [ + "${bindings_scripts_dir}:web_idl_pylib", + ] + if (defined(invoker.deps)) { + deps += invoker.deps + } - inputs = - [ - "$bindings_core_output_dir/web_idl_collection_for_core.pickle", - "$bindings_modules_output_dir/web_idl_collection_for_modules.pickle", - ] + web_idl_scripts - outputs = [ - "$bindings_output_dir/web_idl_database.pickle", + # List input file names in a temporary file. + response_file_contents = rebase_path(sources, root_build_dir) + args = [ + "--idl-list-file", + "{{response_file_name}}", + "--component", + invoker.component, + "--output", + rebase_path(invoker.output, root_build_dir), + ] + } +} + +collect_idl_files("web_idl_in_core") { + # all IDL files in 'core' component + sources = core_static_interface_idl_files + + core_generated_interface_idl_files + core_all_dependency_idl_files + component = "core" + output = "${bindings_output_dir}/web_idl_in_core.pickle" + deps = [ + "core:core_global_constructors_idls", + "//third_party/blink/renderer/core:generated_testing_idls_internal_runtime_flags", + "//third_party/blink/renderer/core:generated_testing_idls_settings", ] +} - args = [ - "--output", - rebase_path("$bindings_output_dir/web_idl_database.pickle", root_build_dir), - "--", - rebase_path("$bindings_core_output_dir/web_idl_collection_for_core.pickle", - root_build_dir), - rebase_path( - "$bindings_modules_output_dir/web_idl_collection_for_modules.pickle", - root_build_dir), +collect_idl_files("web_idl_in_modules") { + # all IDL files in 'modules' component + sources = modules_definition_idl_files + modules_static_interface_idl_files + + modules_static_dependency_idl_files + component = "modules" + output = "${bindings_output_dir}/web_idl_in_modules.pickle" +} + +blink_python_runner("web_idl_database") { + script = "${bindings_scripts_dir}/build_web_idl_database.py" + + input_data_files = get_target_outputs(":web_idl_in_core") + + get_target_outputs(":web_idl_in_modules") + inputs = input_data_files + + output_data_file = "${bindings_output_dir}/web_idl_database.pickle" + outputs = [ + output_data_file, ] deps = [ - "//third_party/blink/renderer/bindings/core:core_web_idl_collection", - "//third_party/blink/renderer/bindings/modules:modules_web_idl_collection", + ":web_idl_in_core", + ":web_idl_in_modules", + "${bindings_scripts_dir}:web_idl_pylib", ] + + args = [ + "--output", + rebase_path(output_data_file, root_build_dir), + "--", + ] + rebase_path(input_data_files, root_build_dir) }
diff --git a/third_party/blink/renderer/bindings/core/BUILD.gn b/third_party/blink/renderer/bindings/core/BUILD.gn index 4aaf310..ba48ea2e 100644 --- a/third_party/blink/renderer/bindings/core/BUILD.gn +++ b/third_party/blink/renderer/bindings/core/BUILD.gn
@@ -38,17 +38,3 @@ ":core_global_objects", ] } - -generate_web_idl_collection("core_web_idl_collection") { - # |sources| contains all IDL files under core/. - sources = core_static_interface_idl_files + - core_generated_interface_idl_files + core_all_dependency_idl_files - output = "web_idl_collection_for_core.pickle" - component = "core" - output_dir = bindings_core_output_dir - deps = [ - ":core_global_constructors_idls", - "//third_party/blink/renderer/core:generated_testing_idls_internal_runtime_flags", - "//third_party/blink/renderer/core:generated_testing_idls_settings", - ] -}
diff --git a/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc b/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc index bb9e376..bfac971 100644 --- a/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc +++ b/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc
@@ -12,7 +12,7 @@ #include "third_party/blink/renderer/core/dom/events/event.h" #include "third_party/blink/renderer/core/dom/events/event_target.h" #include "third_party/blink/renderer/platform/bindings/v8_private_property.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" namespace blink {
diff --git a/third_party/blink/renderer/bindings/core/v8/script_promise.cc b/third_party/blink/renderer/bindings/core/v8/script_promise.cc index db9fa2d9..9a81d9d 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_promise.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_promise.cc
@@ -36,7 +36,7 @@ #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "v8/include/v8.h" namespace blink {
diff --git a/third_party/blink/renderer/bindings/modules/BUILD.gn b/third_party/blink/renderer/bindings/modules/BUILD.gn index 3084d87f..11fccb2 100644 --- a/third_party/blink/renderer/bindings/modules/BUILD.gn +++ b/third_party/blink/renderer/bindings/modules/BUILD.gn
@@ -38,6 +38,7 @@ "//third_party/blink/renderer/modules/mediastream/media_stream_event.idl", "//third_party/blink/renderer/modules/mediastream/media_stream_track_event.idl", "//third_party/blink/renderer/modules/nfc/nfc_error_event.idl", + "//third_party/blink/renderer/modules/nfc/nfc_reading_event.idl", "//third_party/blink/renderer/modules/notifications/notification_event.idl", "//third_party/blink/renderer/modules/payments/abort_payment_event.idl", "//third_party/blink/renderer/modules/payments/can_make_payment_event.idl", @@ -60,7 +61,7 @@ "//third_party/blink/renderer/modules/service_worker/extendable_message_event.idl", "//third_party/blink/renderer/modules/service_worker/fetch_event.idl", "//third_party/blink/renderer/modules/service_worker/install_event.idl", - "//third_party/blink/renderer/modules/speech/speech_recognition_error.idl", + "//third_party/blink/renderer/modules/speech/speech_recognition_error_event.idl", "//third_party/blink/renderer/modules/speech/speech_recognition_event.idl", "//third_party/blink/renderer/modules/speech/speech_synthesis_error_event.idl", "//third_party/blink/renderer/modules/speech/speech_synthesis_event.idl", @@ -169,12 +170,3 @@ "//v8", ] } - -generate_web_idl_collection("modules_web_idl_collection") { - # |sources| contains all IDL files under modules/. - sources = modules_definition_idl_files + modules_static_interface_idl_files + - modules_static_dependency_idl_files - output = "web_idl_collection_for_modules.pickle" - component = "modules" - output_dir = bindings_modules_output_dir -}
diff --git a/third_party/blink/renderer/bindings/modules/v8/generated.gni b/third_party/blink/renderer/bindings/modules/v8/generated.gni index 1622a8f..aa36ff5e 100644 --- a/third_party/blink/renderer/bindings/modules/v8/generated.gni +++ b/third_party/blink/renderer/bindings/modules/v8/generated.gni
@@ -76,8 +76,8 @@ "$bindings_modules_v8_output_dir/request_or_usv_string_or_request_or_usv_string_sequence.h", "$bindings_modules_v8_output_dir/rtc_ice_candidate_init_or_rtc_ice_candidate.cc", "$bindings_modules_v8_output_dir/rtc_ice_candidate_init_or_rtc_ice_candidate.h", - "$bindings_modules_v8_output_dir/string_or_array_buffer_or_ndef_message.cc", - "$bindings_modules_v8_output_dir/string_or_array_buffer_or_ndef_message.h", + "$bindings_modules_v8_output_dir/string_or_array_buffer_or_ndef_message_init.cc", + "$bindings_modules_v8_output_dir/string_or_array_buffer_or_ndef_message_init.h", "$bindings_modules_v8_output_dir/string_or_canvas_gradient_or_canvas_pattern.cc", "$bindings_modules_v8_output_dir/string_or_canvas_gradient_or_canvas_pattern.h", "$bindings_modules_v8_output_dir/string_or_string_sequence_or_constrain_dom_string_parameters.cc",
diff --git a/third_party/blink/renderer/bindings/scripts/BUILD.gn b/third_party/blink/renderer/bindings/scripts/BUILD.gn index 8868829..cf4b5c0 100644 --- a/third_party/blink/renderer/bindings/scripts/BUILD.gn +++ b/third_party/blink/renderer/bindings/scripts/BUILD.gn
@@ -46,3 +46,51 @@ rebase_path(stamp_file, root_build_dir), ] } + +# Python library that supports Web IDL compiler and database +group("web_idl_pylib") { + data = [ + "web_idl/argument.py", + "web_idl/ast_group.py", + "web_idl/attribute.py", + "web_idl/callback_function.py", + "web_idl/callback_interface.py", + "web_idl/common.py", + "web_idl/constant.py", + "web_idl/constructor.py", + "web_idl/database.py", + "web_idl/dictionary.py", + "web_idl/enumeration.py", + "web_idl/exposure.py", + "web_idl/extended_attribute.py", + "web_idl/identifier_ir_map.py", + "web_idl/idl_compiler.py", + "web_idl/idl_member.py", + "web_idl/idl_type.py", + "web_idl/includes.py", + "web_idl/interface.py", + "web_idl/ir_builder.py", + "web_idl/namespace.py", + "web_idl/operation.py", + "web_idl/reference.py", + "web_idl/typedef.py", + "web_idl/user_defined_type.py", + "web_idl/values.py", + ] + data += [ # dependencies to Python libraries + "//third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py", + + # PLY (Python Lex-Yacc) + "//third_party/ply/lex.py", + "//third_party/ply/yacc.py", + + # Web IDL lexer/parser (base parser) + "//tools/idl_parser/idl_lexer.py", + "//tools/idl_parser/idl_node.py", + "//tools/idl_parser/idl_parser.py", + + # Blink IDL lexer/parser/constructor + "blink_idl_lexer.py", + "blink_idl_parser.py", + ] +}
diff --git a/third_party/blink/renderer/bindings/scripts/build_web_idl_database.py b/third_party/blink/renderer/bindings/scripts/build_web_idl_database.py old mode 100755 new mode 100644 index 9344143..bac570c --- a/third_party/blink/renderer/bindings/scripts/build_web_idl_database.py +++ b/third_party/blink/renderer/bindings/scripts/build_web_idl_database.py
@@ -1,23 +1,18 @@ -#!/usr/bin/python -# # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -"""Generates a data collection of IDL information per component. -This scripts parses IDL files and stores the result ASTs in a pickle file. -The output file may contain information about component, too. +""" +Builds Web IDL database. + +Web IDL database is a Python object that supports a variety of accessors to +IDL definitions such as IDL interface and IDL attribute. """ import optparse import utilities - -from web_idl.identifier_ir_map import IdentifierIRMap -from web_idl.idl_compiler import IdlCompiler -from web_idl.idl_type import IdlTypeFactory -from web_idl.ir_builder import load_and_register_idl_definitions -from web_idl.reference import RefByIdFactory +import web_idl def parse_options(): @@ -34,19 +29,10 @@ def main(): options, filepaths = parse_options() - ir_map = IdentifierIRMap() - ref_to_idl_type_factory = RefByIdFactory() - ref_to_idl_def_factory = RefByIdFactory() - idl_type_factory = IdlTypeFactory() - load_and_register_idl_definitions( - filepaths, - ir_map.register, - ref_to_idl_type_factory.create, - ref_to_idl_def_factory.create, - idl_type_factory) - idl_compiler = IdlCompiler(ir_map) - idl_database = idl_compiler.build_database() - utilities.write_pickle_file(options.output, idl_database) + + database = web_idl.build_database(filepaths) + + utilities.write_pickle_file(options.output, database) if __name__ == '__main__':
diff --git a/third_party/blink/renderer/bindings/scripts/collect_idl_files.py b/third_party/blink/renderer/bindings/scripts/collect_idl_files.py new file mode 100644 index 0000000..1018baa9 --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/collect_idl_files.py
@@ -0,0 +1,57 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +Collects Web IDL definitions in IDL files into a Python object per Blink +component. + +Collected IDL definitions are parsed into ASTs and saved into a file with +a label of Blink component. +""" + +import optparse + +import blink_idl_parser +import utilities +import web_idl + + +_VALID_COMPONENTS = ("core", "modules") + + +def parse_options(): + parser = optparse.OptionParser() + parser.add_option('--idl-list-file', type='string', + help='a file path which lists IDL file paths to process') + parser.add_option('--component', type='choice', choices=_VALID_COMPONENTS, + help='specify a component name') + parser.add_option('--output', type='string', + help='the output file path') + options, args = parser.parse_args() + + if options.idl_list_file is None: + parser.error('Specify a file listing IDL files with --idl-list-file.') + if options.output is None: + parser.error('Specify the output file path with --output.') + if options.component is None: + parser.error('Specify a component with --component.') + + return options, args + + +def main(): + options, args = parse_options() + if args: + raise RuntimeError('unknown arguments {}'.format(args)) + + filepaths = utilities.read_idl_files_list_from_file(options.idl_list_file) + parser = blink_idl_parser.BlinkIDLParser() + ast_group = web_idl.AstGroup(options.component) + for filepath in filepaths: + ast_group.add_ast_node(blink_idl_parser.parse_file(parser, filepath)) + ast_group.write_to_file(options.output) + + +if __name__ == '__main__': + main()
diff --git a/third_party/blink/renderer/bindings/scripts/generate_web_idl_collection.py b/third_party/blink/renderer/bindings/scripts/generate_web_idl_collection.py deleted file mode 100644 index 4b31740..0000000 --- a/third_party/blink/renderer/bindings/scripts/generate_web_idl_collection.py +++ /dev/null
@@ -1,50 +0,0 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Generates a data collection of IDL information per component. -This scripts parses IDL files and stores the result ASTs in a pickle file. -The output file may contain information about component, too. -""" - -import blink_idl_parser -import optparse -import utilities -from web_idl.collector import Collector -from web_idl.collection import Collection - - -_VALID_COMPONENTS = ("core", "modules") - -def parse_options(): - parser = optparse.OptionParser() - parser.add_option('--idl-list-file', type='string', - help='a file path which lists IDL file paths to process') - parser.add_option('--component', type='choice', choices=_VALID_COMPONENTS, - help='specify a component name where IDLs belong') - parser.add_option('--output', type='string', - help='pickle file to write down') - options, args = parser.parse_args() - - if options.idl_list_file is None: - parser.error('Must specify a file listing IDL files using --idl-list-file.') - if options.output is None: - parser.error('Must specify a pickle file to output using --output.') - if options.component is None: - parser.error('Must specify a component using --component.') - - return options, args - - -def main(): - options, _ = parse_options() - idl_file_names = utilities.read_idl_files_list_from_file(options.idl_list_file) - - parser = blink_idl_parser.BlinkIDLParser() - collector = Collector(component=options.component, parser=parser) - collector.collect_from_idl_files(idl_file_names) - Collection.write_to_file(collector.get_collection(), options.output) - - -if __name__ == '__main__': - main()
diff --git a/third_party/blink/renderer/bindings/scripts/scripts.gni b/third_party/blink/renderer/bindings/scripts/scripts.gni index 20c7f72..00a0b2a5 100644 --- a/third_party/blink/renderer/bindings/scripts/scripts.gni +++ b/third_party/blink/renderer/bindings/scripts/scripts.gni
@@ -2,12 +2,12 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//third_party/blink/renderer/build/scripts/scripts.gni") import("//third_party/blink/renderer/core/core_idl_files.gni") import("//third_party/blink/renderer/modules/modules_idl_files.gni") bindings_scripts_dir = get_path_info(".", "abspath") -bindings_scripts_output_dir = - "$root_gen_dir/third_party/blink/renderer/bindings/scripts" +bindings_scripts_output_dir = get_path_info(".", "gen_dir") jinja_module_files = [ "//third_party/jinja2/__init__.py", @@ -57,37 +57,6 @@ ], "abspath") -web_idl_scripts = get_path_info([ - "web_idl/argument.py", - "web_idl/attribute.py", - "web_idl/callback_function.py", - "web_idl/callback_interface.py", - "web_idl/collection.py", - "web_idl/collector.py", - "web_idl/common.py", - "web_idl/constant.py", - "web_idl/constructor.py", - "web_idl/database.py", - "web_idl/dictionary.py", - "web_idl/enumeration.py", - "web_idl/exposure.py", - "web_idl/extended_attribute.py", - "web_idl/identifier_ir_map.py", - "web_idl/idl_compiler.py", - "web_idl/idl_member.py", - "web_idl/idl_type.py", - "web_idl/includes.py", - "web_idl/interface.py", - "web_idl/ir_builder.py", - "web_idl/namespace.py", - "web_idl/operation.py", - "web_idl/reference.py", - "web_idl/typedef.py", - "web_idl/user_defined_type.py", - "web_idl/values.py", - ], - "abspath") - # Calls the compute_interfaces_info_individual script. # # Parameters: @@ -505,34 +474,3 @@ invoker.deps } } - -template("generate_web_idl_collection") { - action(target_name) { - script = "${bindings_scripts_dir}/generate_web_idl_collection.py" - output_dir = invoker.output_dir - output_file_name = invoker.output - output_path = "${output_dir}/${output_file_name}" - inputs = [ - script, - "${bindings_scripts_dir}/web_idl/collection.py", - "${bindings_scripts_dir}/web_idl/collector.py", - ] + idl_lexer_parser_files + invoker.sources - outputs = [ - output_path, - ] - if (defined(invoker.deps)) { - deps = invoker.deps - } - - # List input file names in a temporary file. - response_file_contents = rebase_path(invoker.sources, root_build_dir) - args = [ - "--idl-list-file", - "{{response_file_name}}", - "--component", - invoker.component, - "--output", - rebase_path(output_path, root_build_dir), - ] - } -}
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/__init__.py b/third_party/blink/renderer/bindings/scripts/web_idl/__init__.py index a22a6ee..abe9202e 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/__init__.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/__init__.py
@@ -1,3 +1,13 @@ # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. + +from .ast_group import AstGroup +from .database import Database +from .database_builder import build_database + +__all__ = [ + "AstGroup", + "Database", + "build_database", +]
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/ast_group.py b/third_party/blink/renderer/bindings/scripts/web_idl/ast_group.py new file mode 100644 index 0000000..6f623b9 --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/ast_group.py
@@ -0,0 +1,40 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import pickle + +from .common import Component + + +class AstGroup(object): + """A set of Web IDL ASTs grouped by component.""" + + def __init__(self, component=None): + assert component is None or isinstance(component, Component) + self._nodes = [] + self._component = component + + def __iter__(self): + return self._nodes.__iter__() + + @staticmethod + def read_from_file(filepath): + with open(filepath, 'r') as pickle_file: + ast_group = pickle.load(pickle_file) + assert isinstance(ast_group, AstGroup) + return ast_group + + def write_to_file(self, filepath): + with open(filepath, 'w') as pickle_file: + pickle.dump(self, pickle_file) + + def add_ast_node(self, node): + assert node.GetClass() == 'File', ( + 'Root node of an AST must be a File node, but is %s.' % + node.GetClass()) + self._nodes.append(node) + + @property + def component(self): + return self._component
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/collection.py b/third_party/blink/renderer/bindings/scripts/web_idl/collection.py deleted file mode 100644 index 2fc705d..0000000 --- a/third_party/blink/renderer/bindings/scripts/web_idl/collection.py +++ /dev/null
@@ -1,46 +0,0 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import pickle -import idl_parser -from .common import Component - - -class Collection(object): - """ - Collection class stores ASTs of Web IDL files and meta information - like component. - """ - - def __init__(self, component=None): - assert component is None or isinstance(component, Component) - self._asts = [] - self._component = component - - def add_ast(self, ast): - assert isinstance(ast, idl_parser.idl_node.IDLNode) - assert ast.GetClass() == 'File', ( - 'Root node of an AST must be a File node., but is %s.' % ast.GetClass()) - self._asts.append(ast) - - @staticmethod - def load_from_file(filepath): - with open(filepath, 'r') as pickle_file: - collection = pickle.load(pickle_file) - assert isinstance(collection, Collection) - return collection - - @staticmethod - def write_to_file(collection, filepath): - assert isinstance(collection, Collection) - with open(filepath, 'w') as pickle_file: - pickle.dump(collection, pickle_file) - - @property - def asts(self): - return self._asts - - @property - def component(self): - return self._component
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/collector.py b/third_party/blink/renderer/bindings/scripts/web_idl/collector.py deleted file mode 100644 index 07c3134..0000000 --- a/third_party/blink/renderer/bindings/scripts/web_idl/collector.py +++ /dev/null
@@ -1,34 +0,0 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import blink_idl_parser -from .collection import Collection - - -class Collector(object): - - def __init__(self, component, parser=blink_idl_parser.BlinkIDLParser()): - self._component = component - self._collection = Collection(component) - self._parser = parser - - def collect_from_idl_files(self, filepaths): - if isinstance(filepaths, str): - filepaths = [filepaths] - for filepath in filepaths: - try: - ast = blink_idl_parser.parse_file(self._parser, filepath) - self.collect_from_ast(ast) - except ValueError as ve: - raise ValueError('%s\nin file %s' % (str(ve), filepath)) - - def collect_from_idl_text(self, text, filename='TEXT'): - ast = self._parser.ParseText(filename, text) # pylint: disable=no-member - self.collect_from_ast(ast) - - def collect_from_ast(self, node): - self._collection.add_ast(node) - - def get_collection(self): - return self._collection
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/common.py b/third_party/blink/renderer/bindings/scripts/web_idl/common.py index d17d109..0cb07cd 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/common.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/common.py
@@ -137,51 +137,51 @@ self._components.append(component) +class Location(object): + def __init__(self, filepath=None, line_number=None, column_number=None): + assert filepath is None or isinstance(filepath, str) + assert line_number is None or isinstance(line_number, int) + assert column_number is None or isinstance(column_number, int) + self._filepath = filepath + self._line_number = line_number + self._column_number = column_number + + def __str__(self): + text = '{}'.format(self._filepath or '<<unknown path>>') + if self._line_number: + text += ':{}'.format(self._line_number) + if self._column_number: + text += ':{}'.format(self._column_number) + return text + + def make_copy(self): + return Location( + filepath=self._filepath, + line_number=self._line_number, + column_number=self._column_number) + + @property + def filepath(self): + return self._filepath + + @property + def line_number(self): + return self._line_number + + @property + def column_number(self): + return self._column_number + + class DebugInfo(object): """Provides information useful for debugging.""" - class Location(object): - def __init__(self, filepath=None, line_number=None, - column_number=None): - assert filepath is None or isinstance(filepath, str) - assert line_number is None or isinstance(line_number, int) - assert column_number is None or isinstance(column_number, int) - self._filepath = filepath - self._line_number = line_number - self._column_number = column_number - - def __str__(self): - text = '{}'.format(self._filepath or '<<unknown path>>') - if self._line_number: - text += ':{}'.format(self._line_number) - if self._column_number: - text += ':{}'.format(self._column_number) - return text - - def make_copy(self): - return DebugInfo.Location( - filepath=self._filepath, - line_number=self._line_number, - column_number=self._column_number) - - @property - def filepath(self): - return self._filepath - - @property - def line_number(self): - return self._line_number - - @property - def column_number(self): - return self._column_number - def __init__(self, location=None, locations=None): - assert location is None or isinstance(location, DebugInfo.Location) - assert locations is None or (isinstance( - locations, (list, tuple)) and all( - isinstance(location, DebugInfo.Location) - for location in locations)) + assert location is None or isinstance(location, Location) + assert locations is None or (isinstance(locations, (list, tuple)) + and all( + isinstance(location, Location) + for location in locations)) assert not (location and locations) # The first entry is the primary location, e.g. location of non-partial # interface. The rest is secondary locations, e.g. location of partial @@ -189,17 +189,15 @@ if locations: self._locations = locations else: - self._locations = [location or DebugInfo.Location()] + self._locations = [location or Location()] def make_copy(self): - return DebugInfo( - locations=map(DebugInfo.Location.make_copy, self._locations)) + return DebugInfo(locations=map(Location.make_copy, self._locations)) @property def location(self): """ Returns the primary location, i.e. location of the main definition. - @return DebugInfo.Location """ return self._locations[0] @@ -208,13 +206,12 @@ """ Returns a list of locations of all related IDL definitions, including partial definitions and mixins. - @return tuple(DebugInfo.Location) """ return tuple(self._locations) def add_locations(self, locations): assert isinstance(locations, (list, tuple)) and all( - isinstance(location, DebugInfo.Location) for location in locations) + isinstance(location, Location) for location in locations) self._locations.extend(locations)
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/database.py b/third_party/blink/renderer/bindings/scripts/web_idl/database.py index adce30a..06f56cb 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/database.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/database.py
@@ -62,7 +62,7 @@ self._defs[kind][user_defined_type.identifier] = user_defined_type def find_by_identifier(self, identifier): - for defs_per_kind in self._defs: + for defs_per_kind in self._defs.itervalues(): if identifier in defs_per_kind: return defs_per_kind[identifier] raise KeyError(identifier)
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/database_builder.py b/third_party/blink/renderer/bindings/scripts/web_idl/database_builder.py new file mode 100644 index 0000000..8abc27d --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/database_builder.py
@@ -0,0 +1,24 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +from .identifier_ir_map import IdentifierIRMap +from .idl_compiler import IdlCompiler +from .idl_type import IdlTypeFactory +from .ir_builder import load_and_register_idl_definitions +from .reference import RefByIdFactory + + +def build_database(filepaths): + """Compiles IDL definitions in |filepaths| and builds a database.""" + + ir_map = IdentifierIRMap() + ref_to_idl_type_factory = RefByIdFactory() + ref_to_idl_def_factory = RefByIdFactory() + idl_type_factory = IdlTypeFactory() + load_and_register_idl_definitions( + filepaths, ir_map.register, ref_to_idl_type_factory.create, + ref_to_idl_def_factory.create, idl_type_factory) + compiler = IdlCompiler(ir_map, ref_to_idl_type_factory, + ref_to_idl_def_factory, idl_type_factory) + return compiler.build_database()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/idl_compiler.py b/third_party/blink/renderer/bindings/scripts/web_idl/idl_compiler.py index d7a5170..8ad9fcd 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/idl_compiler.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/idl_compiler.py
@@ -2,7 +2,12 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from .database import Database +from .database import DatabaseBody +from .dictionary import Dictionary from .identifier_ir_map import IdentifierIRMap +from .idl_type import IdlTypeFactory +from .reference import RefByIdFactory class IdlCompiler(object): @@ -26,29 +31,49 @@ the details. """ - def __init__(self, ir_map): + def __init__(self, ir_map, ref_to_idl_type_factory, ref_to_idl_def_factory, + idl_type_factory): + """ + Args: + ir_map: IdentifierIRMap filled with the initial IRs of IDL + definitions. + ref_to_idl_type_factory: RefByIdFactory that created all references + to IdlType. + ref_to_idl_def_factory: RefByIdFactory that created all references + to UserDefinedType. + idl_type_factory: IdlTypeFactory that created all instances of + IdlType. + """ + assert isinstance(ir_map, IdentifierIRMap) + assert isinstance(ref_to_idl_type_factory, RefByIdFactory) + assert isinstance(ref_to_idl_def_factory, RefByIdFactory) + assert isinstance(idl_type_factory, IdlTypeFactory) self._ir_map = ir_map + self._ref_to_idl_type_factory = ref_to_idl_type_factory + self._ref_to_idl_def_factory = ref_to_idl_def_factory + self._idl_type_factory = idl_type_factory + self._db = DatabaseBody() + self._did_run = False # Run only once. def build_database(self): - self._merge_partials() - self._merge_mixins() - self._resolve_inheritances() - self._resolve_exposures() - self._define_unions() - self._generate_database() + assert not self._did_run + self._did_run = True - def _generate_database(self): - """ - Returns an IDL database based on this compiler. - """ - pass - - def _merge_partials(self): - """ - Merges partial definitions with corresponding non-partial definitions. - """ + # Merge partial definitions. + self._merge_partial_interfaces() self._merge_partial_dictionaries() - # TODO(peria): Implement this. http:///crbug.com/839389 + + # Updates on IRs are finished. Create API objects. + self._create_public_objects() + + # Resolve references. + self._resolve_references_to_idl_type() + self._resolve_references_to_idl_def() + + return Database(self._db) + + def _merge_partial_interfaces(self): + pass def _merge_partial_dictionaries(self): old_dictionaries = self._ir_map.find_by_kind( @@ -71,31 +96,27 @@ ]) self._ir_map.add(new_dictionary) - def _merge_mixins(self): - """ - Merges mixins with interfaces that connected with includes statements. - """ - self._ir_map.move_to_new_phase() - # TODO(peria): Implement this. http:///crbug.com/839389 + def _create_public_objects(self): + """Creates public representations of compiled objects.""" + dictionary_irs = self._ir_map.find_by_kind( + IdentifierIRMap.IR.Kind.DICTIONARY) + for ir in dictionary_irs.itervalues(): + self._db.register(DatabaseBody.Kind.DICTIONARY, Dictionary(ir)) - def _resolve_inheritances(self): - """ - Resolves inheritances and [Unforgeable] - """ - self._ir_map.move_to_new_phase() - # TODO(peria): Implement this. http:///crbug.com/839389 + def _resolve_references_to_idl_type(self): + def resolve(ref): + # Resolve to stubs for the time being. + ref.set_target_object(False) - def _resolve_exposures(self): - """ - Links [Exposed] interfaces/namespaces with [Global] interfaces - """ - self._ir_map.move_to_new_phase() - # TODO(peria): Implement this. http:///crbug.com/839389 + self._ref_to_idl_type_factory.for_each(resolve) - def _define_unions(self): - """ - Create a definition of union, that is unique in union types that have - same flattened-like members. - """ - self._ir_map.move_to_new_phase() - # TODO(peria): Implement this. http:///crbug.com/839389 + def _resolve_references_to_idl_def(self): + def resolve(ref): + try: + ref.set_target_object( + self._db.find_by_identifier(ref.identifier)) + except KeyError: + # Resolve to stubs for the time being. + ref.set_target_object(False) + + self._ref_to_idl_def_factory.for_each(resolve)
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/ir_builder.py b/third_party/blink/renderer/bindings/scripts/web_idl/ir_builder.py index ef08aff5..b619dd32 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/ir_builder.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/ir_builder.py
@@ -3,11 +3,12 @@ # found in the LICENSE file. from .argument import Argument +from .ast_group import AstGroup from .attribute import Attribute from .callback_function import CallbackFunction from .callback_interface import CallbackInterface -from .collection import Collection from .common import DebugInfo +from .common import Location from .constant import Constant from .dictionary import Dictionary from .dictionary import DictionaryMember @@ -46,12 +47,12 @@ assert callable(register_ir) for filepath in filepaths: - asts_per_component = Collection.load_from_file(filepath) + asts_per_component = AstGroup.read_from_file(filepath) component = asts_per_component.component builder = _IRBuilder(component, create_ref_to_idl_type, create_ref_to_idl_def, idl_type_factory) - for file_node in asts_per_component.asts: + for file_node in asts_per_component: assert file_node.GetClass() == 'File' for top_level_node in file_node.GetChildren(): register_ir(builder.build_top_level_def(top_level_node)) @@ -317,7 +318,7 @@ def _build_debug_info(self, node): return DebugInfo( - location=DebugInfo.Location( + location=Location( filepath=node.GetProperty('FILENAME'), line_number=node.GetProperty('LINENO'), column_number=node.GetProperty('POSITION')))
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/reference.py b/third_party/blink/renderer/bindings/scripts/web_idl/reference.py index f1aa2ab..4f54e08e 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/reference.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/reference.py
@@ -17,14 +17,14 @@ """ Creates a new proxy to |target_object|. - Keyword arguments: - target_object -- The object to which attribute access is proxied. This - can be set later by set_target_object. - target_attrs -- None or list of attribute names to be proxied. If None, - all the attribute access is proxied. - target_attrs_with_priority -- None or list of attribute names to be - unconditionally proxied with priority over attributes defined on - |self|. If None, no attribute has priority over own attributes. + Args: + target_object: The object to which attribute access is proxied. + This can be set later by set_target_object. + target_attrs: None or list of attribute names to be proxied. If + None, all the attribute access is proxied. + target_attrs_with_priority: None or list of attribute names to be + unconditionally proxied with priority over attributes defined on + |self|. If None, no attribute has priority over own attributes. """ if target_attrs is not None: assert isinstance(target_attrs, (list, set, tuple)) @@ -36,7 +36,7 @@ def __getattr__(self, attribute): target_object = object.__getattribute__(self, '_target_object') target_attrs = object.__getattribute__(self, '_target_attrs') - assert target_object + assert target_object is not None if target_attrs is None or attribute in target_attrs: return getattr(target_object, attribute) raise AttributeError @@ -80,7 +80,7 @@ @property def target_object(self): - assert self._target_object + assert self._target_object is not None return self._target_object @@ -151,4 +151,4 @@ assert callable(callback) self._is_frozen = True for ref in self._references: - resolver(ref) + callback(ref)
diff --git a/third_party/blink/renderer/controller/blink_leak_detector.cc b/third_party/blink/renderer/controller/blink_leak_detector.cc index 96884ff..6a5b4fc 100644 --- a/third_party/blink/renderer/controller/blink_leak_detector.cc +++ b/third_party/blink/renderer/controller/blink_leak_detector.cc
@@ -19,7 +19,7 @@ #include "third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h" #include "third_party/blink/renderer/core/workers/worker_thread.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
diff --git a/third_party/blink/renderer/core/DEPS b/third_party/blink/renderer/core/DEPS index ad7fdaa6..07a2c16 100644 --- a/third_party/blink/renderer/core/DEPS +++ b/third_party/blink/renderer/core/DEPS
@@ -114,4 +114,9 @@ "find_task_controller.cc" : [ "+third_party/blink/renderer/core/frame/web_local_frame_impl.h", ], + # TODO(crbug.com/980151): Include this while WebSurroundingText is not + # removed from the public API and implemented in renderer/core. + "surrounding_text_impl.cc" : [ + "+third_party/blink/renderer/core/frame/web_local_frame_impl.h", + ], }
diff --git a/third_party/blink/renderer/core/animation/animation_test_helper.cc b/third_party/blink/renderer/core/animation/animation_test_helper.cc index 5e90ee4..dc54c2f 100644 --- a/third_party/blink/renderer/core/animation/animation_test_helper.cc +++ b/third_party/blink/renderer/core/animation/animation_test_helper.cc
@@ -8,6 +8,8 @@ #include "third_party/blink/renderer/core/animation/css_interpolation_environment.h" #include "third_party/blink/renderer/core/animation/css_interpolation_types_map.h" #include "third_party/blink/renderer/core/animation/invalidatable_interpolation.h" +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" +#include "third_party/blink/renderer/core/css/resolver/style_cascade.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/element.h" @@ -15,6 +17,39 @@ namespace blink { +namespace { + +class TestAnimator : public StyleCascade::Animator { + STACK_ALLOCATED(); + + public: + TestAnimator(StyleResolverState& state, + StyleCascade& cascade, + CSSInterpolationTypesMap& map, + const ActiveInterpolations& interpolations) + : state_(state), + cascade_(cascade), + map_(map), + interpolations_(interpolations) {} + + void Apply(const CSSProperty&, + const cssvalue::CSSPendingInterpolationValue& value, + StyleCascade::Resolver& resolver) override { + // Ignore CSSProperty here. We assume this function is only called once + // for each invocation of EnsureInterpolatedValueCached. + CSSInterpolationEnvironment environment(map_, state_, &cascade_, &resolver); + InvalidatableInterpolation::ApplyStack(interpolations_, environment); + } + + private: + StyleResolverState& state_; + StyleCascade& cascade_; + CSSInterpolationTypesMap& map_; + const ActiveInterpolations& interpolations_; +}; + +} // namespace + void SetV8ObjectPropertyAsString(v8::Isolate* isolate, v8::Local<v8::Object> object, const StringView& name, @@ -48,8 +83,21 @@ state.SetStyle(style); CSSInterpolationTypesMap map(state.GetDocument().GetPropertyRegistry(), state.GetDocument()); - CSSInterpolationEnvironment environment(map, state, nullptr); - InvalidatableInterpolation::ApplyStack(interpolations, environment); + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + // We must apply the animation effects via StyleCascade when the cascade + // is enabled. + StyleCascade cascade(state); + auto type = cssvalue::CSSPendingInterpolationValue::Type::kCSSProperty; + auto* pending = cssvalue::CSSPendingInterpolationValue::Create(type); + auto origin = StyleCascade::Origin::kAuthor; + cascade.Add(*CSSPropertyName::From("--unused"), pending, origin); + + TestAnimator animator(state, cascade, map, interpolations); + cascade.Apply(animator); + } else { + CSSInterpolationEnvironment environment(map, state, nullptr); + InvalidatableInterpolation::ApplyStack(interpolations, environment); + } } } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/css/css_animation_update.h b/third_party/blink/renderer/core/animation/css/css_animation_update.h index 315d0f9..bc051a4a 100644 --- a/third_party/blink/renderer/core/animation/css/css_animation_update.h +++ b/third_party/blink/renderer/core/animation/css/css_animation_update.h
@@ -97,7 +97,7 @@ // This class stores the CSS Animations/Transitions information we use during a // style recalc. This includes updates to animations/transitions as well as the // Interpolations to be applied. -class CSSAnimationUpdate final { +class CORE_EXPORT CSSAnimationUpdate final { DISALLOW_NEW(); public:
diff --git a/third_party/blink/renderer/core/animation/css/css_animations.h b/third_party/blink/renderer/core/animation/css/css_animations.h index 452c924..3d50f5b 100644 --- a/third_party/blink/renderer/core/animation/css/css_animations.h +++ b/third_party/blink/renderer/core/animation/css/css_animations.h
@@ -51,7 +51,7 @@ class StylePropertyShorthand; class StyleResolver; -class CSSAnimations final { +class CORE_EXPORT CSSAnimations final { DISALLOW_NEW(); public:
diff --git a/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc index 25eba0f..be7a9bad 100644 --- a/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc
@@ -20,17 +20,25 @@ InterpolationValue CSSDefaultInterpolationType::MaybeConvertSingle( const PropertySpecificKeyframe& keyframe, - const InterpolationEnvironment&, + const InterpolationEnvironment& environment, const InterpolationValue&, ConversionCheckers&) const { - if (!ToCSSPropertySpecificKeyframe(keyframe).Value()) { + const CSSValue* css_value = ToCSSPropertySpecificKeyframe(keyframe).Value(); + + if (!css_value) { DCHECK(keyframe.IsNeutral()); return nullptr; } - return InterpolationValue( - std::make_unique<InterpolableList>(0), - CSSDefaultNonInterpolableValue::Create( - ToCSSPropertySpecificKeyframe(keyframe).Value())); + + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + css_value = ToCSSInterpolationEnvironment(environment) + .Resolve(GetProperty(), css_value); + if (!css_value) + return nullptr; + } + + return InterpolationValue(std::make_unique<InterpolableList>(0), + CSSDefaultNonInterpolableValue::Create(css_value)); } void CSSDefaultInterpolationType::Apply(
diff --git a/third_party/blink/renderer/core/animation/css_interpolation_environment.h b/third_party/blink/renderer/core/animation/css_interpolation_environment.h index 03f270c..789ee655a 100644 --- a/third_party/blink/renderer/core/animation/css_interpolation_environment.h +++ b/third_party/blink/renderer/core/animation/css_interpolation_environment.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_INTERPOLATION_ENVIRONMENT_H_ #include "third_party/blink/renderer/core/animation/interpolation_environment.h" +#include "third_party/blink/renderer/core/css/resolver/style_cascade.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" namespace blink { @@ -24,6 +25,16 @@ variable_resolver_(variable_resolver) {} explicit CSSInterpolationEnvironment(const InterpolationTypesMap& map, + StyleResolverState& state, + StyleCascade* cascade, + StyleCascade::Resolver* cascade_resolver) + : InterpolationEnvironment(map), + state_(&state), + style_(state.Style()), + cascade_(cascade), + cascade_resolver_(cascade_resolver) {} + + explicit CSSInterpolationEnvironment(const InterpolationTypesMap& map, const ComputedStyle& style) : InterpolationEnvironment(map), style_(&style) {} @@ -43,17 +54,36 @@ return *style_; } - bool HasVariableResolver() const { return variable_resolver_; } + bool HasVariableResolver() const { + DCHECK(!RuntimeEnabledFeatures::CSSCascadeEnabled()); + return variable_resolver_; + } + // TODO(crbug.com/985023): This effective violates const. CSSVariableResolver& VariableResolver() const { + DCHECK(!RuntimeEnabledFeatures::CSSCascadeEnabled()); DCHECK(HasVariableResolver()); return *variable_resolver_; } + // TODO(crbug.com/985023): This effective violates const. + const CSSValue* Resolve(const PropertyHandle& property, + const CSSValue* value) const { + DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled()); + DCHECK(cascade_); + DCHECK(cascade_resolver_); + if (!value) + return value; + return cascade_->Resolve(property.GetCSSPropertyName(), *value, + *cascade_resolver_); + } + private: StyleResolverState* state_ = nullptr; const ComputedStyle* style_ = nullptr; CSSVariableResolver* variable_resolver_ = nullptr; + StyleCascade* cascade_ = nullptr; + StyleCascade::Resolver* cascade_resolver_ = nullptr; }; DEFINE_TYPE_CASTS(CSSInterpolationEnvironment,
diff --git a/third_party/blink/renderer/core/animation/css_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_interpolation_type.cc index 1643a75..a3dd876 100644 --- a/third_party/blink/renderer/core/animation/css_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_interpolation_type.cc
@@ -19,6 +19,7 @@ #include "third_party/blink/renderer/core/css/property_registration.h" #include "third_party/blink/renderer/core/css/resolver/css_variable_resolver.h" #include "third_party/blink/renderer/core/css/resolver/style_builder.h" +#include "third_party/blink/renderer/core/css/resolver/style_cascade.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/style/data_equivalency.h" @@ -26,8 +27,7 @@ namespace blink { -class ResolvedVariableChecker - : public CSSInterpolationType::CSSConversionChecker { +class ResolvedVariableChecker : public CSSInterpolationType::ConversionChecker { public: ResolvedVariableChecker(CSSPropertyID property, const CSSValue* variable_reference, @@ -37,14 +37,21 @@ resolved_value_(resolved_value) {} private: - bool IsValid(const StyleResolverState& state, - const InterpolationValue& underlying) const final { + bool IsValid(const InterpolationEnvironment& environment, + const InterpolationValue&) const final { + const auto& css_environment = ToCSSInterpolationEnvironment(environment); // TODO(alancutter): Just check the variables referenced instead of doing a // full CSSValue resolve. bool omit_animation_tainted = false; - const CSSValue* resolved_value = - CSSVariableResolver(state).ResolveVariableReferences( - property_, *variable_reference_, omit_animation_tainted); + const CSSValue* resolved_value = nullptr; + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + resolved_value = css_environment.Resolve( + PropertyHandle(CSSProperty::Get(property_)), variable_reference_); + } else { + const StyleResolverState& state = css_environment.GetState(); + resolved_value = CSSVariableResolver(state).ResolveVariableReferences( + property_, *variable_reference_, omit_animation_tainted); + } return DataEquivalent(resolved_value_.Get(), resolved_value); } @@ -94,14 +101,22 @@ private: bool IsValid(const InterpolationEnvironment& environment, const InterpolationValue&) const final { - DCHECK(ToCSSInterpolationEnvironment(environment).HasVariableResolver()); - bool cycle_detected = false; - scoped_refptr<CSSVariableData> resolved_tokens = - ToCSSInterpolationEnvironment(environment) - .VariableResolver() - .ResolveCustomPropertyAnimationKeyframe(*declaration_, - cycle_detected); - DCHECK(!cycle_detected); + const auto& css_environment = ToCSSInterpolationEnvironment(environment); + scoped_refptr<CSSVariableData> resolved_tokens = nullptr; + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + const CSSValue* resolved = css_environment.Resolve( + PropertyHandle(declaration_->GetName()), declaration_); + if (const auto* decl = DynamicTo<CSSCustomPropertyDeclaration>(resolved)) + resolved_tokens = decl->Value(); + } else { + DCHECK(css_environment.HasVariableResolver()); + bool cycle_detected = false; + resolved_tokens = ToCSSInterpolationEnvironment(environment) + .VariableResolver() + .ResolveCustomPropertyAnimationKeyframe( + *declaration_, cycle_detected); + DCHECK(!cycle_detected); + } return DataEquivalent(resolved_tokens, resolved_tokens_); } @@ -145,18 +160,23 @@ return MaybeConvertNeutral(underlying, conversion_checkers); if (GetProperty().IsCSSCustomProperty()) { - DCHECK(css_environment.HasVariableResolver()); return MaybeConvertCustomPropertyDeclaration( - To<CSSCustomPropertyDeclaration>(*value), state, - css_environment.VariableResolver(), conversion_checkers); + To<CSSCustomPropertyDeclaration>(*value), environment, + conversion_checkers); } if (value->IsVariableReferenceValue() || value->IsPendingSubstitutionValue()) { - bool omit_animation_tainted = false; - const CSSValue* resolved_value = - CSSVariableResolver(state).ResolveVariableReferences( - CssProperty().PropertyID(), *value, omit_animation_tainted); + const CSSValue* resolved_value = nullptr; + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + resolved_value = css_environment.Resolve(GetProperty(), value); + } else { + bool omit_animation_tainted = false; + resolved_value = CSSVariableResolver(state).ResolveVariableReferences( + CssProperty().PropertyID(), *value, omit_animation_tainted); + } + + DCHECK(resolved_value); conversion_checkers.push_back(std::make_unique<ResolvedVariableChecker>( CssProperty().PropertyID(), value, resolved_value)); value = resolved_value; @@ -176,9 +196,12 @@ InterpolationValue CSSInterpolationType::MaybeConvertCustomPropertyDeclaration( const CSSCustomPropertyDeclaration& declaration, - const StyleResolverState& state, - CSSVariableResolver& variable_resolver, + const InterpolationEnvironment& environment, ConversionCheckers& conversion_checkers) const { + const CSSInterpolationEnvironment& css_environment = + ToCSSInterpolationEnvironment(environment); + const StyleResolverState& state = css_environment.GetState(); + const AtomicString& name = declaration.GetName(); DCHECK_EQ(GetProperty().CustomPropertyName(), name); @@ -209,10 +232,20 @@ scoped_refptr<CSSVariableData> resolved_tokens; if (declaration.Value()->NeedsVariableResolution()) { - bool cycle_detected = false; - resolved_tokens = variable_resolver.ResolveCustomPropertyAnimationKeyframe( - declaration, cycle_detected); - DCHECK(!cycle_detected); + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + const CSSValue* resolved = + css_environment.Resolve(GetProperty(), &declaration); + if (const auto* decl = DynamicTo<CSSCustomPropertyDeclaration>(resolved)) + resolved_tokens = decl->Value(); + } else { + CSSVariableResolver& variable_resolver = + css_environment.VariableResolver(); + bool cycle_detected = false; + resolved_tokens = + variable_resolver.ResolveCustomPropertyAnimationKeyframe( + declaration, cycle_detected); + DCHECK(!cycle_detected); + } conversion_checkers.push_back( std::make_unique<ResolvedRegisteredCustomPropertyChecker>( declaration, resolved_tokens)); @@ -283,8 +316,23 @@ scoped_refptr<CSSVariableData> variable_data = CSSVariableData::Create( CSSParserTokenRange(tokens), is_animation_tainted, needs_variable_resolution, KURL(), WTF::TextEncoding()); - ComputedStyle& style = *state.Style(); const PropertyHandle property = GetProperty(); + + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + // When cascade is enabled, we need to go through the StyleBuilder, + // since the computed value is produced during ApplyProperty. (Without + // this, we'd end up with values like 10em on the computed style). + // + // TODO(andruud): Avoid making the CSSCustomPropertyDeclaration by allowing + // any CSSValue in CustomProperty::ApplyValue. + const CSSValue* value = MakeGarbageCollected<CSSCustomPropertyDeclaration>( + property.CustomPropertyName(), std::move(variable_data)); + StyleBuilder::ApplyProperty(GetProperty().GetCSSPropertyName(), state, + *value); + return; + } + + ComputedStyle& style = *state.Style(); const AtomicString& property_name = property.CustomPropertyName(); bool inherits = Registration().Inherits(); style.SetVariableData(property_name, std::move(variable_data), inherits);
diff --git a/third_party/blink/renderer/core/animation/css_interpolation_type.h b/third_party/blink/renderer/core/animation/css_interpolation_type.h index ae8df46e7..9d38ab8 100644 --- a/third_party/blink/renderer/core/animation/css_interpolation_type.h +++ b/third_party/blink/renderer/core/animation/css_interpolation_type.h
@@ -12,7 +12,6 @@ namespace blink { class CSSCustomPropertyDeclaration; -class CSSVariableResolver; class ComputedStyle; class PropertyRegistration; class StyleResolverState; @@ -87,8 +86,7 @@ InterpolationValue MaybeConvertCustomPropertyDeclaration( const CSSCustomPropertyDeclaration&, - const StyleResolverState&, - CSSVariableResolver&, + const InterpolationEnvironment&, ConversionCheckers&) const; const PropertyRegistration& Registration() const {
diff --git a/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc index 1173a1b..e596f35 100644 --- a/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc
@@ -14,6 +14,7 @@ #include "third_party/blink/renderer/core/css/property_registration.h" #include "third_party/blink/renderer/core/css/resolver/css_variable_resolver.h" #include "third_party/blink/renderer/core/css/resolver/style_builder.h" +#include "third_party/blink/renderer/core/css/resolver/style_cascade.h" #include "third_party/blink/renderer/core/style/computed_style.h" namespace blink { @@ -27,12 +28,15 @@ private: bool IsValid(const InterpolationEnvironment& environment, const InterpolationValue&) const final { - DCHECK(ToCSSInterpolationEnvironment(environment).HasVariableResolver()); - CSSVariableResolver& variable_resolver = - ToCSSInterpolationEnvironment(environment).VariableResolver(); + const auto& css_environment = ToCSSInterpolationEnvironment(environment); bool cycle_detected = false; - variable_resolver.ResolveCustomPropertyAnimationKeyframe(*declaration_, - cycle_detected); + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + cycle_detected = !css_environment.Resolve( + PropertyHandle(declaration_->GetName()), declaration_); + } else { + css_environment.VariableResolver().ResolveCustomPropertyAnimationKeyframe( + *declaration_, cycle_detected); + } return cycle_detected == cycle_detected_; } @@ -63,12 +67,16 @@ return nullptr; } - DCHECK(ToCSSInterpolationEnvironment(environment).HasVariableResolver()); - CSSVariableResolver& variable_resolver = - ToCSSInterpolationEnvironment(environment).VariableResolver(); + const auto& css_environment = ToCSSInterpolationEnvironment(environment); + bool cycle_detected = false; - variable_resolver.ResolveCustomPropertyAnimationKeyframe(declaration, - cycle_detected); + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + cycle_detected = !css_environment.Resolve(GetProperty(), &declaration); + } else { + css_environment.VariableResolver().ResolveCustomPropertyAnimationKeyframe( + declaration, cycle_detected); + } + conversion_checkers.push_back( std::make_unique<CycleChecker>(declaration, cycle_detected)); return cycle_detected ? CreateCycleDetectedValue() : nullptr;
diff --git a/third_party/blink/renderer/core/core_idl_files.gni b/third_party/blink/renderer/core/core_idl_files.gni index e93b9d0..3ddadb1 100644 --- a/third_party/blink/renderer/core/core_idl_files.gni +++ b/third_party/blink/renderer/core/core_idl_files.gni
@@ -325,16 +325,18 @@ "page/scrolling/scroll_state.idl", "resize_observer/resize_observer.idl", "resize_observer/resize_observer_entry.idl", + "streams/byte_length_queuing_strategy.idl", + "streams/count_queuing_strategy.idl", "streams/readable_stream.idl", "streams/readable_stream_default_controller.idl", "streams/readable_stream_default_reader.idl", "streams/transform_stream.idl", "streams/transform_stream_default_controller.idl", + "streams/underlying_sink_base.idl", + "streams/underlying_source_base.idl", "streams/writable_stream.idl", "streams/writable_stream_default_controller.idl", "streams/writable_stream_default_writer.idl", - "streams/underlying_source_base.idl", - "streams/underlying_sink_base.idl", "svg/svg_a_element.idl", "svg/svg_angle.idl", "svg/svg_animate_element.idl", @@ -693,6 +695,7 @@ "mojo/mojo_write_data_result.idl", "mojo/test/mojo_interface_request_event_init.idl", "page/scrolling/scroll_state_init.idl", + "streams/queuing_strategy_init.idl", "timing/performance_mark_options.idl", "timing/performance_measure_options.idl", "timing/performance_observer_init.idl",
diff --git a/third_party/blink/renderer/core/css/BUILD.gn b/third_party/blink/renderer/core/css/BUILD.gn index 09c9453..5181ee6 100644 --- a/third_party/blink/renderer/core/css/BUILD.gn +++ b/third_party/blink/renderer/core/css/BUILD.gn
@@ -129,6 +129,8 @@ "css_paint_value.h", "css_path_value.cc", "css_path_value.h", + "css_pending_interpolation_value.cc", + "css_pending_interpolation_value.h", "css_pending_substitution_value.cc", "css_pending_substitution_value.h", "css_primitive_value.cc", @@ -489,10 +491,14 @@ "resolver/selector_filter_parent_scope.h", "resolver/style_adjuster.cc", "resolver/style_adjuster.h", + "resolver/style_animator.cc", + "resolver/style_animator.h", "resolver/style_builder.cc", "resolver/style_builder.h", "resolver/style_builder_converter.cc", "resolver/style_builder_converter.h", + "resolver/style_cascade.cc", + "resolver/style_cascade.h", "resolver/style_resolver.cc", "resolver/style_resolver.h", "resolver/style_resolver_state.cc", @@ -583,6 +589,7 @@ "css_math_expression_node_test.cc", "css_page_rule_test.cc", "css_paint_value_test.cc", + "css_pending_interpolation_value_test.cc", "css_primitive_value_test.cc", "css_property_name_test.cc", "css_property_value_set_test.cc", @@ -634,6 +641,7 @@ "resolver/match_result_test.cc", "resolver/selector_filter_parent_scope_test.cc", "resolver/style_adjuster_test.cc", + "resolver/style_cascade_test.cc", "resolver/style_resolver_test.cc", "rule_feature_set_test.cc", "rule_set_test.cc",
diff --git a/third_party/blink/renderer/core/css/css_pending_interpolation_value.cc b/third_party/blink/renderer/core/css/css_pending_interpolation_value.cc new file mode 100644 index 0000000..d9756e10 --- /dev/null +++ b/third_party/blink/renderer/core/css/css_pending_interpolation_value.cc
@@ -0,0 +1,19 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" +#include "third_party/blink/renderer/core/css/css_value_pool.h" + +namespace blink { +namespace cssvalue { + +CSSPendingInterpolationValue* CSSPendingInterpolationValue::Create(Type type) { + return CssValuePool().PendingInterpolationValue(type); +} + +CSSPendingInterpolationValue::CSSPendingInterpolationValue(Type type) + : CSSValue(kPendingInterpolationClass), type_(type) {} + +} // namespace cssvalue +} // namespace blink
diff --git a/third_party/blink/renderer/core/css/css_pending_interpolation_value.h b/third_party/blink/renderer/core/css/css_pending_interpolation_value.h new file mode 100644 index 0000000..cc8ee83 --- /dev/null +++ b/third_party/blink/renderer/core/css/css_pending_interpolation_value.h
@@ -0,0 +1,61 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PENDING_INTERPOLATION_VALUE_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PENDING_INTERPOLATION_VALUE_H_ + +#include "third_party/blink/renderer/core/css/css_property_name.h" +#include "third_party/blink/renderer/core/css/css_value.h" +#include "third_party/blink/renderer/platform/wtf/casting.h" + +namespace blink { + +namespace cssvalue { + +// A CSSPendingInterpolationValue represents a value which we don't yet know +// what is, but we know that it's the result of an ongoing interpolation. +// It is a way for interpolations to participate in the cascade, without +// knowing the exact value cascade-time. +// +// See StyleCascade::Animator for more information. +class CORE_EXPORT CSSPendingInterpolationValue : public CSSValue { + public: + enum class Type { + kCSSProperty, + kPresentationAttribute, + }; + + static CSSPendingInterpolationValue* Create(Type); + CSSPendingInterpolationValue(Type); + + bool IsCSSProperty() const { return type_ == Type::kCSSProperty; } + bool IsPresentationAttribute() const { + return type_ == Type::kPresentationAttribute; + } + bool Equals(const CSSPendingInterpolationValue& v) const { + return type_ == v.type_; + } + + String CustomCSSText() const { return ""; } + + void TraceAfterDispatch(blink::Visitor* visitor) { + CSSValue::TraceAfterDispatch(visitor); + } + + private: + Type type_; +}; + +} // namespace cssvalue + +template <> +struct DowncastTraits<cssvalue::CSSPendingInterpolationValue> { + static bool AllowFrom(const CSSValue& value) { + return value.IsPendingInterpolationValue(); + } +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PENDING_INTERPOLATION_VALUE_H_
diff --git a/third_party/blink/renderer/core/css/css_pending_interpolation_value_test.cc b/third_party/blink/renderer/core/css/css_pending_interpolation_value_test.cc new file mode 100644 index 0000000..99ac8d49 --- /dev/null +++ b/third_party/blink/renderer/core/css/css_pending_interpolation_value_test.cc
@@ -0,0 +1,55 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/core/css/css_test_helpers.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { +namespace { + +using namespace cssvalue; +using Type = CSSPendingInterpolationValue::Type; + +CSSPendingInterpolationValue* Create(Type type) { + return CSSPendingInterpolationValue::Create(type); +} + +TEST(CSSPendingInterpolationValueTest, Create) { + EXPECT_TRUE(Create(Type::kCSSProperty)); + EXPECT_TRUE(Create(Type::kPresentationAttribute)); +} + +TEST(CSSPendingInterpolationValueTest, Pool) { + const auto* value1 = Create(Type::kCSSProperty); + const auto* value2 = Create(Type::kCSSProperty); + const auto* value3 = Create(Type::kPresentationAttribute); + const auto* value4 = Create(Type::kPresentationAttribute); + EXPECT_EQ(value1, value2); + EXPECT_EQ(value3, value4); + EXPECT_NE(value1, value4); +} + +TEST(CSSPendingInterpolationValueTest, Equals) { + const auto* value1 = Create(Type::kCSSProperty); + const auto* value2 = Create(Type::kCSSProperty); + const auto* value3 = Create(Type::kPresentationAttribute); + const auto* value4 = Create(Type::kPresentationAttribute); + EXPECT_TRUE(value1->Equals(*value2)); + EXPECT_TRUE(value2->Equals(*value1)); + EXPECT_TRUE(value3->Equals(*value4)); + EXPECT_TRUE(value4->Equals(*value3)); + EXPECT_FALSE(value1->Equals(*value4)); + EXPECT_FALSE(value4->Equals(*value1)); +} + +TEST(CSSPendingInterpolationValueTest, CustomCSSText) { + EXPECT_EQ("", Create(Type::kCSSProperty)->CustomCSSText()); + EXPECT_EQ("", Create(Type::kPresentationAttribute)->CustomCSSText()); +} + +} // namespace +} // namespace blink
diff --git a/third_party/blink/renderer/core/css/css_property_value.h b/third_party/blink/renderer/core/css/css_property_value.h index 2757d155..730ddf8e 100644 --- a/third_party/blink/renderer/core/css/css_property_value.h +++ b/third_party/blink/renderer/core/css/css_property_value.h
@@ -60,7 +60,7 @@ unsigned inherited_ : 1; }; -class CSSPropertyValue { +class CORE_EXPORT CSSPropertyValue { DISALLOW_NEW(); public:
diff --git a/third_party/blink/renderer/core/css/css_value.cc b/third_party/blink/renderer/core/css/css_value.cc index ef164597..1c0a54ad 100644 --- a/third_party/blink/renderer/core/css/css_value.cc +++ b/third_party/blink/renderer/core/css/css_value.cc
@@ -59,6 +59,7 @@ #include "third_party/blink/renderer/core/css/css_numeric_literal_value.h" #include "third_party/blink/renderer/core/css/css_paint_value.h" #include "third_party/blink/renderer/core/css/css_path_value.h" +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" #include "third_party/blink/renderer/core/css/css_pending_substitution_value.h" #include "third_party/blink/renderer/core/css/css_primitive_value.h" #include "third_party/blink/renderer/core/css/css_quad_value.h" @@ -252,6 +253,8 @@ return CompareCSSValues<CSSImageSetValue>(*this, other); case kCSSContentDistributionClass: return CompareCSSValues<CSSContentDistributionValue>(*this, other); + case kPendingInterpolationClass: + return CompareCSSValues<CSSPendingInterpolationValue>(*this, other); case kCustomPropertyDeclarationClass: return CompareCSSValues<CSSCustomPropertyDeclaration>(*this, other); case kVariableReferenceClass: @@ -365,6 +368,8 @@ return To<CSSImageSetValue>(this)->CustomCSSText(); case kCSSContentDistributionClass: return To<CSSContentDistributionValue>(this)->CustomCSSText(); + case kPendingInterpolationClass: + return To<CSSPendingInterpolationValue>(this)->CustomCSSText(); case kVariableReferenceClass: return To<CSSVariableReferenceValue>(this)->CustomCSSText(); case kCustomPropertyDeclarationClass: @@ -525,6 +530,9 @@ case kCSSContentDistributionClass: To<CSSContentDistributionValue>(this)->~CSSContentDistributionValue(); return; + case kPendingInterpolationClass: + To<CSSPendingInterpolationValue>(this)->~CSSPendingInterpolationValue(); + return; case kVariableReferenceClass: To<CSSVariableReferenceValue>(this)->~CSSVariableReferenceValue(); return; @@ -687,6 +695,9 @@ case kCSSContentDistributionClass: To<CSSContentDistributionValue>(this)->TraceAfterDispatch(visitor); return; + case kPendingInterpolationClass: + To<CSSPendingInterpolationValue>(this)->TraceAfterDispatch(visitor); + return; case kVariableReferenceClass: To<CSSVariableReferenceValue>(this)->TraceAfterDispatch(visitor); return;
diff --git a/third_party/blink/renderer/core/css/css_value.h b/third_party/blink/renderer/core/css/css_value.h index bf2e7133..447fc073 100644 --- a/third_party/blink/renderer/core/css/css_value.h +++ b/third_party/blink/renderer/core/css/css_value.h
@@ -142,6 +142,9 @@ bool IsContentDistributionValue() const { return class_type_ == kCSSContentDistributionClass; } + bool IsPendingInterpolationValue() const { + return class_type_ == kPendingInterpolationClass; + } bool IsUnicodeRangeValue() const { return class_type_ == kUnicodeRangeClass; } bool IsGridLineNamesValue() const { return class_type_ == kGridLineNamesClass; @@ -247,6 +250,7 @@ kCSSContentDistributionClass, + kPendingInterpolationClass, kKeyframeShorthandClass, // List class types must appear after ValueListClass.
diff --git a/third_party/blink/renderer/core/css/css_value_pool.cc b/third_party/blink/renderer/core/css/css_value_pool.cc index bbcab269..e6b18c2 100644 --- a/third_party/blink/renderer/core/css/css_value_pool.cc +++ b/third_party/blink/renderer/core/css/css_value_pool.cc
@@ -52,6 +52,19 @@ MakeGarbageCollected<CSSColorValue>(Color::kTransparent)), color_white_(MakeGarbageCollected<CSSColorValue>(Color::kWhite)), color_black_(MakeGarbageCollected<CSSColorValue>(Color::kBlack)) { + { + using Value = CSSPendingInterpolationValue; + using Type = CSSPendingInterpolationValue::Type; + pending_interpolation_values_[0] = + MakeGarbageCollected<Value>(Type::kCSSProperty); + pending_interpolation_values_[1] = + MakeGarbageCollected<Value>(Type::kPresentationAttribute); + static_assert(static_cast<size_t>(Type::kCSSProperty) == 0u, + "kCSSProperty must be 0"); + static_assert(static_cast<size_t>(Type::kPresentationAttribute) == 1u, + "kPresentationAttribute must be 1"); + } + identifier_value_cache_.resize(numCSSValueKeywords); pixel_value_cache_.resize(kMaximumCacheableIntegerValue + 1); percent_value_cache_.resize(kMaximumCacheableIntegerValue + 1); @@ -63,6 +76,8 @@ visitor->Trace(initial_value_); visitor->Trace(unset_value_); visitor->Trace(invalid_variable_value_); + visitor->Trace(pending_interpolation_values_[0]); + visitor->Trace(pending_interpolation_values_[1]); visitor->Trace(color_transparent_); visitor->Trace(color_white_); visitor->Trace(color_black_);
diff --git a/third_party/blink/renderer/core/css/css_value_pool.h b/third_party/blink/renderer/core/css/css_value_pool.h index 6e2af58b..7fe38566 100644 --- a/third_party/blink/renderer/core/css/css_value_pool.h +++ b/third_party/blink/renderer/core/css/css_value_pool.h
@@ -37,6 +37,7 @@ #include "third_party/blink/renderer/core/css/css_initial_value.h" #include "third_party/blink/renderer/core/css/css_invalid_variable_value.h" #include "third_party/blink/renderer/core/css/css_numeric_literal_value.h" +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" #include "third_party/blink/renderer/core/css/css_property_names.h" #include "third_party/blink/renderer/core/css/css_unset_value.h" #include "third_party/blink/renderer/core/css/css_value_list.h" @@ -54,6 +55,7 @@ static const int kMaximumCacheableIntegerValue = 255; using CSSColorValue = cssvalue::CSSColorValue; using CSSUnsetValue = cssvalue::CSSUnsetValue; + using CSSPendingInterpolationValue = cssvalue::CSSPendingInterpolationValue; using ColorValueCache = HeapHashMap<unsigned, Member<CSSColorValue>>; static const unsigned kMaximumColorCacheSize = 512; using FontFaceValueCache = @@ -73,6 +75,12 @@ CSSInvalidVariableValue* InvalidVariableValue() { return invalid_variable_value_; } + CSSPendingInterpolationValue* PendingInterpolationValue( + CSSPendingInterpolationValue::Type type) { + DCHECK_GE(static_cast<size_t>(type), 0u); + DCHECK_LE(static_cast<size_t>(type), 1u); + return pending_interpolation_values_[static_cast<size_t>(type)]; + } // Vector caches. CSSIdentifierValue* IdentifierCacheValue(CSSValueID ident) { @@ -134,6 +142,7 @@ Member<CSSInitialValue> initial_value_; Member<CSSUnsetValue> unset_value_; Member<CSSInvalidVariableValue> invalid_variable_value_; + Member<CSSPendingInterpolationValue> pending_interpolation_values_[2]; Member<CSSColorValue> color_transparent_; Member<CSSColorValue> color_white_; Member<CSSColorValue> color_black_;
diff --git a/third_party/blink/renderer/core/css/css_variable_reference_value.h b/third_party/blink/renderer/core/css/css_variable_reference_value.h index 70cabac..7ec8b2d 100644 --- a/third_party/blink/renderer/core/css/css_variable_reference_value.h +++ b/third_party/blink/renderer/core/css/css_variable_reference_value.h
@@ -28,7 +28,8 @@ CSSVariableData* VariableDataValue() const { return data_.get(); } const CSSParserContext* ParserContext() const { - DCHECK(parser_context_); + // TODO(crbug.com/985028): CSSVariableReferenceValue should always have + // a CSSParserContext. return parser_context_.Get(); }
diff --git a/third_party/blink/renderer/core/css/dom_window_css.cc b/third_party/blink/renderer/core/css/dom_window_css.cc index 593d399..e4959c2 100644 --- a/third_party/blink/renderer/core/css/dom_window_css.cc +++ b/third_party/blink/renderer/core/css/dom_window_css.cc
@@ -33,7 +33,6 @@ #include "third_party/blink/renderer/core/css/css_property_value_set.h" #include "third_party/blink/renderer/core/css/parser/css_parser.h" #include "third_party/blink/renderer/core/css/properties/css_property.h" -#include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" @@ -51,10 +50,8 @@ auto* dummy_style = MakeGarbageCollected<MutableCSSPropertyValueSet>(kHTMLStandardMode); bool is_animation_tainted = false; - const Document& document = To<Document>(*execution_context); - const PropertyRegistry* registry = document.GetPropertyRegistry(); return CSSParser::ParseValueForCustomProperty( - dummy_style, AtomicString(property), registry, value, false, + dummy_style, "--valid", nullptr, value, false, execution_context->GetSecureContextMode(), nullptr, is_animation_tainted) .did_parse;
diff --git a/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc b/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc index c24e5e8..fc49720 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc
@@ -9,7 +9,9 @@ #include "third_party/blink/renderer/core/css/parser/css_variable_parser.h" #include "third_party/blink/renderer/core/css/property_registration.h" #include "third_party/blink/renderer/core/css/property_registry.h" +#include "third_party/blink/renderer/core/css/resolver/style_builder_converter.h" #include "third_party/blink/renderer/core/style/computed_style.h" +#include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { @@ -65,6 +67,14 @@ void CustomProperty::ApplyValue(StyleResolverState& state, const CSSValue& value) const { + if (value.IsInvalidVariableValue()) { + DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled()); + state.Style()->SetVariableData(name_, nullptr, IsInherited()); + if (registration_) + state.Style()->SetVariableValue(name_, nullptr, IsInherited()); + return; + } + const auto& declaration = To<CSSCustomPropertyDeclaration>(value); bool is_inherited_property = IsInherited(); @@ -79,10 +89,45 @@ } else if (inherit) { ApplyInherit(state); } else { - state.Style()->SetVariableData(name_, declaration.Value(), - is_inherited_property); + if (!RuntimeEnabledFeatures::CSSCascadeEnabled()) { + state.Style()->SetVariableData(name_, declaration.Value(), + is_inherited_property); + if (registration_) + state.Style()->SetVariableValue(name_, nullptr, is_inherited_property); + return; + } + + scoped_refptr<CSSVariableData> data = declaration.Value(); + DCHECK(!data->NeedsVariableResolution()); + + state.Style()->SetVariableData(name_, data, is_inherited_property); + if (registration_) { - state.Style()->SetVariableValue(name_, nullptr, is_inherited_property); + // TODO(andruud): Store CSSParserContext on CSSCustomPropertyDeclaration + // and use that. + const CSSParserContext* context = + StrictCSSParserContext(state.GetDocument().GetSecureContextMode()); + auto mode = CSSParserLocalContext::VariableMode::kTyped; + auto local_context = CSSParserLocalContext().WithVariableMode(mode); + CSSParserTokenRange range = data->TokenRange(); + const CSSValue* registered_value = + ParseSingleValue(range, *context, local_context); + if (!registered_value) { + if (is_inherited_property) + ApplyInherit(state); + else + ApplyInitial(state); + return; + } + + registered_value = &StyleBuilderConverter::ConvertRegisteredPropertyValue( + state, *registered_value, data->BaseURL(), data->Charset()); + data = StyleBuilderConverter::ConvertRegisteredPropertyVariableData( + *registered_value, data->IsAnimationTainted()); + + state.Style()->SetVariableData(name_, data, is_inherited_property); + state.Style()->SetVariableValue(name_, registered_value, + is_inherited_property); } } }
diff --git a/third_party/blink/renderer/core/css/properties/longhands/custom_property.h b/third_party/blink/renderer/core/css/properties/longhands/custom_property.h index 30ab365..c7df30f61 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/custom_property.h +++ b/third_party/blink/renderer/core/css/properties/longhands/custom_property.h
@@ -48,6 +48,8 @@ Node* styled_node, bool allow_visited_style) const override; + bool IsRegistered() const { return registration_; } + void Trace(blink::Visitor* visitor) { visitor->Trace(registration_); } private: @@ -65,6 +67,14 @@ Member<const PropertyRegistration> registration_; }; +template <> +struct DowncastTraits<CustomProperty> { + static bool AllowFrom(const CSSProperty& property) { + DCHECK(!Variable::IsStaticInstance(property)); + return property.PropertyID() == CSSPropertyID::kVariable; + } +}; + } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_LONGHANDS_CUSTOM_PROPERTY_H_
diff --git a/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc b/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc index c7d3d620..a7d942a 100644 --- a/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc +++ b/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc
@@ -276,6 +276,11 @@ } TEST_F(CSSVariableResolverTest, NeedsResolutionClearedByResolver) { + // This test is not relevant when CSSCascade is enabled, as we won't store + // unresolved CSSVariableData on the ComputedStyle in that case. + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) + return; + const ComputedStyle* initial = &ComputedStyle::InitialStyle(); StyleResolverState state(GetDocument(), *GetDocument().documentElement(), nullptr /* pseudo_element */, initial, initial);
diff --git a/third_party/blink/renderer/core/css/resolver/match_result.cc b/third_party/blink/renderer/core/css/resolver/match_result.cc index b6265ac..4391044 100644 --- a/third_party/blink/renderer/core/css/resolver/match_result.cc +++ b/third_party/blink/renderer/core/css/resolver/match_result.cc
@@ -30,14 +30,18 @@ #include "third_party/blink/renderer/core/css/resolver/match_result.h" +#include <memory> #include <type_traits> #include "third_party/blink/renderer/core/css/css_property_value_set.h" #include "third_party/blink/renderer/core/css/style_rule.h" +#include "third_party/blink/renderer/platform/wtf/math_extras.h" namespace blink { -MatchedProperties::MatchedProperties() : possibly_padded_member(nullptr) {} +MatchedProperties::MatchedProperties() { + memset(&types_, 0, sizeof(types_)); +} MatchedProperties::~MatchedProperties() = default; @@ -56,6 +60,10 @@ new_properties.types_.valid_property_filter = static_cast<std::underlying_type_t<ValidPropertyFilter>>( valid_property_filter); + // TODO(andruud): MatchedProperties are stored here in reverse order. + // Reevaluate this when cascade has shipped. + new_properties.types_.tree_order = + std::numeric_limits<uint16_t>::max() - current_tree_order_; } void MatchResult::FinishAddingUARules() { @@ -71,6 +79,7 @@ user_range_ends_.back() == matched_properties_.size()) return; user_range_ends_.push_back(matched_properties_.size()); + current_tree_order_ = clampTo<uint16_t>(user_range_ends_.size()); } void MatchResult::FinishAddingAuthorRulesForTreeScope() { @@ -85,6 +94,7 @@ author_range_ends_.back() == matched_properties_.size()) return; author_range_ends_.push_back(matched_properties_.size()); + current_tree_order_ = clampTo<uint16_t>(author_range_ends_.size()); } } // namespace blink
diff --git a/third_party/blink/renderer/core/css/resolver/match_result.h b/third_party/blink/renderer/core/css/resolver/match_result.h index ac45f89..e555f79 100644 --- a/third_party/blink/renderer/core/css/resolver/match_result.h +++ b/third_party/blink/renderer/core/css/resolver/match_result.h
@@ -46,15 +46,22 @@ Member<CSSPropertyValueSet> properties; - union { - struct { - unsigned link_match_type : 2; - unsigned valid_property_filter : 2; - } types_; - // Used to make sure all memory is zero-initialized since we compute the - // hash over the bytes of this object. - void* possibly_padded_member; - }; + struct { + unsigned link_match_type : 2; + unsigned valid_property_filter : 2; + // This is approximately equivalent to the 'shadow-including tree order'. + // It can be used to evaluate the 'Shadow Tree' criteria. Note that the + // number stored here is 'local' to each origin (user, author), and is + // not used at all for the UA origin. Hence, it is not possible to compare + // tree_orders from two different origins. + // + // Note also that the tree_order will start at ~0u and then decrease. + // This is because we currently store the matched properties in reverse + // order. + // + // https://drafts.csswg.org/css-scoping/#shadow-cascading + uint16_t tree_order; + } types_; }; } // namespace blink @@ -149,6 +156,7 @@ Vector<unsigned, 16> author_range_ends_; unsigned ua_range_end_ = 0; bool is_cacheable_ = true; + uint16_t current_tree_order_ = 0; DISALLOW_COPY_AND_ASSIGN(MatchResult); };
diff --git a/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h b/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h index 143554a..deb17120 100644 --- a/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h +++ b/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h
@@ -47,9 +47,8 @@ // and provides methods to collect the rules that apply to a given element, // broken down by what kind of scope they apply to (e.g. shadow host, // tree-boundary-crossing, etc). -class ScopedStyleResolver final +class CORE_EXPORT ScopedStyleResolver final : public GarbageCollectedFinalized<ScopedStyleResolver> { - public: explicit ScopedStyleResolver(TreeScope& scope) : scope_(scope) {}
diff --git a/third_party/blink/renderer/core/css/resolver/style_animator.cc b/third_party/blink/renderer/core/css/resolver/style_animator.cc new file mode 100644 index 0000000..c9ebb4d --- /dev/null +++ b/third_party/blink/renderer/core/css/resolver/style_animator.cc
@@ -0,0 +1,78 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/css/resolver/style_animator.h" + +#include "third_party/blink/renderer/core/animation/css_interpolation_environment.h" +#include "third_party/blink/renderer/core/animation/css_interpolation_types_map.h" +#include "third_party/blink/renderer/core/animation/invalidatable_interpolation.h" +#include "third_party/blink/renderer/core/animation/transition_interpolation.h" +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" +#include "third_party/blink/renderer/core/css/properties/longhands/custom_property.h" + +namespace blink { + +namespace { + +PropertyHandle ToPropertyHandle( + const CSSProperty& property, + const cssvalue::CSSPendingInterpolationValue& value) { + if (IsA<CustomProperty>(property)) + return PropertyHandle(property.GetPropertyNameAtomicString()); + return PropertyHandle(property, value.IsPresentationAttribute()); +} + +const ActiveInterpolations& GetActiveInterpolations( + const ActiveInterpolationsMap& animations_map, + const ActiveInterpolationsMap& transitions_map, + const PropertyHandle& property) { + // Interpolations will never be found in both animations_map and + // transitions_map. This condition is ensured by + // CSSAnimations::CalculateTransitionUpdateForProperty(). + const auto& animation = animations_map.find(property); + if (animation != animations_map.end()) { + DCHECK_EQ(transitions_map.find(property), transitions_map.end()); + return animation->value; + } + const auto& transition = transitions_map.find(property); + DCHECK_NE(transition, transitions_map.end()); + return transition->value; +} + +const ActiveInterpolations& GetActiveInterpolations( + const CSSAnimationUpdate& update, + const PropertyHandle& property) { + if (property.IsCSSCustomProperty()) { + return GetActiveInterpolations( + update.ActiveInterpolationsForCustomAnimations(), + update.ActiveInterpolationsForCustomTransitions(), property); + } + return GetActiveInterpolations( + update.ActiveInterpolationsForStandardAnimations(), + update.ActiveInterpolationsForStandardTransitions(), property); +} + +} // namespace + +StyleAnimator::StyleAnimator(StyleResolverState& state, StyleCascade& cascade) + : state_(state), cascade_(cascade) {} + +void StyleAnimator::Apply(const CSSProperty& property, + const cssvalue::CSSPendingInterpolationValue& value, + StyleCascade::Resolver& resolver) { + PropertyHandle property_handle = ToPropertyHandle(property, value); + const ActiveInterpolations& interpolations = + GetActiveInterpolations(state_.AnimationUpdate(), property_handle); + const Interpolation& interpolation = *interpolations.front(); + if (interpolation.IsInvalidatableInterpolation()) { + CSSInterpolationTypesMap map(state_.GetDocument().GetPropertyRegistry(), + state_.GetDocument()); + CSSInterpolationEnvironment environment(map, state_, &cascade_, &resolver); + InvalidatableInterpolation::ApplyStack(interpolations, environment); + } else { + ToTransitionInterpolation(interpolation).Apply(state_); + } +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/css/resolver/style_animator.h b/third_party/blink/renderer/core/css/resolver/style_animator.h new file mode 100644 index 0000000..5bcbc7f2 --- /dev/null +++ b/third_party/blink/renderer/core/css/resolver/style_animator.h
@@ -0,0 +1,53 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_ANIMATOR_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_ANIMATOR_H_ + +#include "third_party/blink/renderer/core/animation/interpolation.h" +#include "third_party/blink/renderer/core/animation/property_handle.h" +#include "third_party/blink/renderer/core/css/resolver/style_cascade.h" + +namespace blink { + +class StyleResolverState; +class StyleCascade; + +namespace cssvalue { + +class CSSPendingInterpolationValue; + +} // namespace cssvalue + +// StyleAnimator is a class which knows how to apply active interpolations +// for given a CSSProperty. +// +// When the set of currently animating properties has been determined, +// a CSSPendingInterpolationValues is added to the cascade for each animating +// property (see StyleResolver::CascadeInterpolations). Later, when the +// cascade is applied, an Animator may be provided. That Animator is then +// responsible for applying the actual interpolated values represented by +// any CSSPendingInterpolationValues that may (or may not) remain in the +// cascade. See StyleCascade::Animator for more information. +// +// TODO(crbug.com/985051) Evaluate if there's a performance issue here, and +// if so possibly store active interpolations directly in the cascade. +class CORE_EXPORT StyleAnimator : public StyleCascade::Animator { + STACK_ALLOCATED(); + + public: + explicit StyleAnimator(StyleResolverState&, StyleCascade&); + + void Apply(const CSSProperty&, + const cssvalue::CSSPendingInterpolationValue&, + StyleCascade::Resolver&) override; + + private: + StyleResolverState& state_; + StyleCascade& cascade_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_ANIMATOR_H_
diff --git a/third_party/blink/renderer/core/css/resolver/style_builder.cc b/third_party/blink/renderer/core/css/resolver/style_builder.cc index 5ff5c45..744995d7 100644 --- a/third_party/blink/renderer/core/css/resolver/style_builder.cc +++ b/third_party/blink/renderer/core/css/resolver/style_builder.cc
@@ -109,11 +109,6 @@ is_initial = true; } - // CSSPropertyID::kVariable currently handles initial/inherit inside - // ApplyValue. - DCHECK(id != CSSPropertyID::kVariable || !is_initial); - DCHECK(id != CSSPropertyID::kVariable || !is_inherit); - if (is_initial) To<Longhand>(property).ApplyInitial(state); else if (is_inherit)
diff --git a/third_party/blink/renderer/core/css/resolver/style_cascade.cc b/third_party/blink/renderer/core/css/resolver/style_cascade.cc new file mode 100644 index 0000000..e3810cc --- /dev/null +++ b/third_party/blink/renderer/core/css/resolver/style_cascade.cc
@@ -0,0 +1,648 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/css/resolver/style_cascade.h" + +#include "third_party/blink/renderer/core/animation/css/css_animations.h" +#include "third_party/blink/renderer/core/animation/css_interpolation_environment.h" +#include "third_party/blink/renderer/core/animation/css_interpolation_types_map.h" +#include "third_party/blink/renderer/core/animation/invalidatable_interpolation.h" +#include "third_party/blink/renderer/core/animation/property_handle.h" +#include "third_party/blink/renderer/core/animation/transition_interpolation.h" +#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h" +#include "third_party/blink/renderer/core/css/css_font_selector.h" +#include "third_party/blink/renderer/core/css/css_invalid_variable_value.h" +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" +#include "third_party/blink/renderer/core/css/css_pending_substitution_value.h" +#include "third_party/blink/renderer/core/css/css_unset_value.h" +#include "third_party/blink/renderer/core/css/css_variable_data.h" +#include "third_party/blink/renderer/core/css/css_variable_reference_value.h" +#include "third_party/blink/renderer/core/css/document_style_environment_variables.h" +#include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h" +#include "third_party/blink/renderer/core/css/parser/css_property_parser.h" +#include "third_party/blink/renderer/core/css/properties/css_property.h" +#include "third_party/blink/renderer/core/css/properties/css_property_ref.h" +#include "third_party/blink/renderer/core/css/property_registry.h" +#include "third_party/blink/renderer/core/css/resolver/css_property_priority.h" +#include "third_party/blink/renderer/core/css/resolver/style_builder.h" +#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" +#include "third_party/blink/renderer/core/css/style_engine.h" +#include "third_party/blink/renderer/core/dom/shadow_root.h" +#include "third_party/blink/renderer/core/style/computed_style.h" + +namespace blink { + +using namespace cssvalue; + +namespace { + +class NullAnimator : public StyleCascade::Animator { + STACK_ALLOCATED(); + + public: + void Apply(const CSSProperty&, + const cssvalue::CSSPendingInterpolationValue&, + StyleCascade::Resolver&) override {} +}; + +AtomicString ConsumeVariableName(CSSParserTokenRange& range) { + range.ConsumeWhitespace(); + CSSParserToken ident_token = range.ConsumeIncludingWhitespace(); + DCHECK_EQ(ident_token.GetType(), kIdentToken); + return ident_token.Value().ToAtomicString(); +} + +bool ConsumeComma(CSSParserTokenRange& range) { + if (range.Peek().GetType() == kCommaToken) { + range.Consume(); + return true; + } + return false; +} + +const CSSValue* Parse(const CSSProperty& property, + CSSParserTokenRange range, + const CSSParserContext* context) { + return CSSPropertyParser::ParseSingleValue(property.PropertyID(), range, + context); +} + +constexpr bool IsImportant(StyleCascade::Origin origin) { + return static_cast<uint8_t>(origin) & StyleCascade::kImportantBit; +} + +static_assert(!IsImportant(StyleCascade::Origin::kNone), + "Origin::kNone is not important"); +static_assert(!IsImportant(StyleCascade::Origin::kUserAgent), + "Origin::kUserAgent is not important"); +static_assert(!IsImportant(StyleCascade::Origin::kUser), + "Origin::kUser is not important"); +static_assert(!IsImportant(StyleCascade::Origin::kAnimation), + "Origin::kAnimation is not important"); +static_assert(IsImportant(StyleCascade::Origin::kImportantAuthor), + "Origin::kImportantAuthor is important"); +static_assert(IsImportant(StyleCascade::Origin::kImportantUser), + "Origin::kImportantUser is important"); +static_assert(IsImportant(StyleCascade::Origin::kImportantUserAgent), + "Origin::kImportantUserAgent is important"); +static_assert(!IsImportant(StyleCascade::Origin::kTransition), + "Origin::kTransition is not important"); + +} // namespace + +StyleCascade::Priority::Priority(Origin origin, uint16_t tree_order) + : priority_((static_cast<uint64_t>(origin) << 32) | + (static_cast<uint64_t>(tree_order) << 16) | + StyleCascade::kMaxCascadeOrder) {} + +StyleCascade::Origin StyleCascade::Priority::GetOrigin() const { + return static_cast<StyleCascade::Origin>((priority_ >> 32) & 0xFF); +} + +bool StyleCascade::Priority::operator>=(const Priority& other) const { + uint64_t important_xor = IsImportant(GetOrigin()) ? 0 : (0xFF << 16); + return (priority_ ^ important_xor) >= (other.priority_ ^ important_xor); +} + +void StyleCascade::Add(const CSSPropertyName& name, + const CSSValue* value, + Priority priority) { + auto result = cascade_.insert(name, Value()); + if (priority >= result.stored_value->value.GetPriority()) { + result.stored_value->value = + Value(value, priority.WithCascadeOrder(++order_)); + } +} + +void StyleCascade::Apply() { + NullAnimator animator; + Apply(animator); +} + +void StyleCascade::Apply(Animator& animator) { + Resolver resolver(animator); + + // TODO(crbug.com/985031): Set bits ::Add-time to know if we need to do this. + ApplyHighPriority(resolver); + + // TODO(crbug.com/985010): Improve with non-destructive Apply. + while (!cascade_.IsEmpty()) { + auto iter = cascade_.begin(); + const CSSPropertyName& name = iter->key; + Apply(name, resolver); + } +} + +void StyleCascade::RemoveAnimationPriority() { + using AnimPrio = CSSPropertyPriorityData<kAnimationPropertyPriority>; + int first = static_cast<int>(AnimPrio::First()); + int last = static_cast<int>(AnimPrio::Last()); + for (int i = first; i <= last; ++i) { + CSSPropertyName name(convertToCSSPropertyID(i)); + cascade_.erase(name); + } +} + +const CSSValue* StyleCascade::Resolve(const CSSPropertyName& name, + const CSSValue& value, + Resolver& resolver) { + CSSPropertyRef ref(name, state_.GetDocument()); + + const CSSValue* resolved = Resolve(ref.GetProperty(), value, resolver); + + DCHECK(resolved); + + if (resolved->IsInvalidVariableValue()) + return nullptr; + + return resolved; +} + +void StyleCascade::ApplyHighPriority(Resolver& resolver) { + using HighPriority = CSSPropertyPriorityData<kHighPropertyPriority>; + int first = static_cast<int>(HighPriority::First()); + int last = static_cast<int>(HighPriority::Last()); + for (int i = first; i <= last; ++i) + Apply(CSSProperty::Get(convertToCSSPropertyID(i)), resolver); + + state_.GetFontBuilder().CreateFont( + state_.GetDocument().GetStyleEngine().GetFontSelector(), + state_.StyleRef()); + state_.SetConversionFontSizes(CSSToLengthConversionData::FontSizes( + state_.Style(), state_.RootElementStyle())); + state_.SetConversionZoom(state_.Style()->EffectiveZoom()); +} + +void StyleCascade::Apply(const CSSPropertyName& name) { + NullAnimator animator; + Resolver resolver(animator); + Apply(name, resolver); +} + +void StyleCascade::Apply(const CSSPropertyName& name, Resolver& resolver) { + CSSPropertyRef ref(name, state_.GetDocument()); + DCHECK(ref.IsValid()); + Apply(ref.GetProperty(), resolver); +} + +void StyleCascade::Apply(const CSSProperty& property, Resolver& resolver) { + CSSPropertyName name = property.GetCSSPropertyName(); + + DCHECK(!resolver.IsLocked(name)); + + Value cascaded = cascade_.Take(property.GetCSSPropertyName()); + if (cascaded.IsEmpty()) + return; + + const CSSValue* value = cascaded.GetValue(); + + if (const auto* v = DynamicTo<CSSPendingInterpolationValue>(value)) { + resolver.animator_.Apply(property, *v, resolver); + return; + } + + value = Resolve(property, *value, resolver); + + DCHECK(!value->IsVariableReferenceValue()); + DCHECK(!value->IsPendingSubstitutionValue()); + DCHECK(!value->IsPendingInterpolationValue()); + + if (!resolver.filter_.Add(property, cascaded)) + return; + + StyleBuilder::ApplyProperty(property, state_, *value); +} + +bool StyleCascade::HasValue(const CSSPropertyName& name, + const CSSValue* value) const { + auto iter = cascade_.find(name); + return (iter != cascade_.end()) && (iter->value.GetValue() == value); +} + +const CSSValue* StyleCascade::GetValue(const CSSPropertyName& name) const { + auto iter = cascade_.find(name); + return (iter != cascade_.end()) ? iter->value.GetValue() : nullptr; +} + +void StyleCascade::ReplaceValue(const CSSPropertyName& name, + const CSSValue* value) { + auto iter = cascade_.find(name); + if (iter != cascade_.end()) + iter->value = Value(value, iter->value.GetPriority()); +} + +bool StyleCascade::IsRootElement() const { + return &state_.GetElement() == state_.GetDocument().documentElement(); +} + +StyleCascade::TokenSequence::TokenSequence(const CSSVariableData* data) + : backing_strings_(data->BackingStrings()), + is_animation_tainted_(data->IsAnimationTainted()), + has_font_units_(data->HasFontUnits()), + has_root_font_units_(data->HasRootFontUnits()), + base_url_(data->BaseURL()), + charset_(data->Charset()) {} + +void StyleCascade::TokenSequence::Append(const TokenSequence& sequence) { + tokens_.AppendVector(sequence.tokens_); + backing_strings_.AppendVector(sequence.backing_strings_); + is_animation_tainted_ |= sequence.is_animation_tainted_; + has_font_units_ |= sequence.has_font_units_; + has_root_font_units_ |= sequence.has_root_font_units_; +} + +void StyleCascade::TokenSequence::Append(const CSSVariableData* data) { + tokens_.AppendVector(data->Tokens()); + backing_strings_.AppendVector(data->BackingStrings()); + is_animation_tainted_ |= data->IsAnimationTainted(); + has_font_units_ |= data->HasFontUnits(); + has_root_font_units_ |= data->HasRootFontUnits(); +} + +void StyleCascade::TokenSequence::Append(const CSSParserToken& token) { + tokens_.push_back(token); +} + +scoped_refptr<CSSVariableData> +StyleCascade::TokenSequence::BuildVariableData() { + // TODO(andruud): Why not also std::move tokens? + const bool absolutized = true; + return CSSVariableData::CreateResolved( + tokens_, std::move(backing_strings_), is_animation_tainted_, + has_font_units_, has_root_font_units_, absolutized, base_url_, charset_); +} + +const CSSValue* StyleCascade::Resolve(const CSSProperty& property, + const CSSValue& value, + Resolver& resolver) { + if (const auto* v = DynamicTo<CSSCustomPropertyDeclaration>(value)) + return ResolveCustomProperty(property, *v, resolver); + if (const auto* v = DynamicTo<CSSVariableReferenceValue>(value)) + return ResolveVariableReference(property, *v, resolver); + if (const auto* v = DynamicTo<CSSPendingSubstitutionValue>(value)) + return ResolvePendingSubstitution(property, *v, resolver); + return &value; +} + +const CSSValue* StyleCascade::ResolveCustomProperty( + const CSSProperty& property, + const CSSCustomPropertyDeclaration& decl, + Resolver& resolver) { + DCHECK(!resolver.IsLocked(property)); + AutoLock lock(property, resolver); + + // TODO(andruud): Don't transport css-wide keywords in this value. + if (!decl.Value()) + return &decl; + + scoped_refptr<CSSVariableData> data = decl.Value(); + + if (data->NeedsVariableResolution()) + data = ResolveVariableData(data.get(), resolver); + + if (HasFontSizeDependency(To<CustomProperty>(property), data.get())) + resolver.DetectCycle(GetCSSPropertyFontSize()); + + if (resolver.InCycle()) + return CSSInvalidVariableValue::Create(); + + if (!data) { + // TODO(crbug.com/980930): Treat custom properties as unset here, + // not invalid. This behavior is enforced by WPT, but violates the spec. + if (const auto* custom_property = DynamicTo<CustomProperty>(property)) { + if (!custom_property->IsRegistered()) + return CSSInvalidVariableValue::Create(); + } + return CSSUnsetValue::Create(); + } + + if (data == decl.Value()) + return &decl; + + return MakeGarbageCollected<CSSCustomPropertyDeclaration>(decl.GetName(), + data); +} + +const CSSValue* StyleCascade::ResolveVariableReference( + const CSSProperty& property, + const CSSVariableReferenceValue& value, + Resolver& resolver) { + DCHECK(!resolver.IsLocked(property)); + AutoLock lock(property, resolver); + + const CSSVariableData* data = value.VariableDataValue(); + const CSSParserContext* context = GetParserContext(value); + + DCHECK(data); + DCHECK(context); + + TokenSequence sequence; + + if (ResolveTokensInto(data->Tokens(), resolver, sequence)) { + if (const auto* parsed = Parse(property, sequence.TokenRange(), context)) + return parsed; + } + + return CSSUnsetValue::Create(); +} + +const CSSValue* StyleCascade::ResolvePendingSubstitution( + const CSSProperty& property, + const CSSPendingSubstitutionValue& value, + Resolver& resolver) { + DCHECK(!resolver.IsLocked(property)); + AutoLock lock(property, resolver); + + DCHECK_NE(property.PropertyID(), CSSPropertyID::kVariable); + + CSSVariableReferenceValue* shorthand_value = value.ShorthandValue(); + const auto* shorthand_data = shorthand_value->VariableDataValue(); + CSSPropertyID shorthand_property_id = value.ShorthandPropertyId(); + + TokenSequence sequence; + + if (!ResolveTokensInto(shorthand_data->Tokens(), resolver, sequence)) + return CSSUnsetValue::Create(); + + HeapVector<CSSPropertyValue, 256> parsed_properties; + const bool important = false; + + if (!CSSPropertyParser::ParseValue( + shorthand_property_id, important, sequence.TokenRange(), + shorthand_value->ParserContext(), parsed_properties, + StyleRule::RuleType::kStyle)) { + return CSSUnsetValue::Create(); + } + + // For -internal-visited-properties with CSSPendingSubstitutionValues, + // the inner 'shorthand_property_id' will expand to a set of longhands + // containing the unvisited equivalent. Hence, when parsing the + // CSSPendingSubstitutionValue, we look for the unvisited property in + // parsed_properties. + const CSSProperty* unvisited_property = + property.IsVisited() ? property.GetUnvisitedProperty() : &property; + + const CSSValue* result = nullptr; + + unsigned parsed_properties_count = parsed_properties.size(); + for (unsigned i = 0; i < parsed_properties_count; ++i) { + const CSSProperty& longhand = CSSProperty::Get(parsed_properties[i].Id()); + const CSSPropertyName& name = longhand.GetCSSPropertyName(); + const CSSValue* parsed = parsed_properties[i].Value(); + + if (unvisited_property == &longhand) + result = parsed; + else if (HasValue(name, &value)) + ReplaceValue(name, parsed); + } + + DCHECK(result); + return result; +} + +scoped_refptr<CSSVariableData> StyleCascade::ResolveVariableData( + CSSVariableData* data, + Resolver& resolver) { + DCHECK(data && data->NeedsVariableResolution()); + + TokenSequence sequence(data); + + if (!ResolveTokensInto(data->Tokens(), resolver, sequence)) + return nullptr; + + return sequence.BuildVariableData(); +} + +bool StyleCascade::ResolveTokensInto(CSSParserTokenRange range, + Resolver& resolver, + TokenSequence& out) { + bool success = true; + while (!range.AtEnd()) { + const CSSParserToken& token = range.Peek(); + if (token.FunctionId() == CSSValueID::kVar) + success &= ResolveVarInto(range.ConsumeBlock(), resolver, out); + else if (token.FunctionId() == CSSValueID::kEnv) + success &= ResolveEnvInto(range.ConsumeBlock(), resolver, out); + else + out.Append(range.Consume()); + } + return success; +} + +bool StyleCascade::ResolveVarInto(CSSParserTokenRange range, + Resolver& resolver, + TokenSequence& out) { + AtomicString variable_name = ConsumeVariableName(range); + DCHECK(range.AtEnd() || (range.Peek().GetType() == kCommaToken)); + + CustomProperty property(variable_name, state_.GetDocument()); + + // Any custom property referenced (by anything, even just once) in the + // document can currently not be animated on the compositor. Hence we mark + // properties that have been referenced. + MarkReferenced(property); + + if (!resolver.DetectCycle(property)) { + // We are about to substitute var(property). In order to do that, we must + // know the computed value of 'property', hence we Apply it. + // + // We can however not do this if we're in a cycle. If a cycle is detected + // here, it means we are already resolving 'property', and have discovered + // a reference to 'property' during that resolution. + Apply(property, resolver); + } + + // Note that even if we are in a cycle, we must proceed in order to discover + // secondary cycles via the var() fallback. + + scoped_refptr<CSSVariableData> data = GetVariableData(property); + + // If substitution is not allowed, treat the value as + // invalid-at-computed-value-time. + // + // https://drafts.csswg.org/css-variables/#animation-tainted + if (!resolver.AllowSubstitution(data.get())) + data = nullptr; + + // If we have a fallback, we must process it to look for cycles, + // even if we aren't going to use the fallback. + // + // https://drafts.csswg.org/css-variables/#cycles + if (ConsumeComma(range)) { + TokenSequence fallback; + bool success = ResolveTokensInto(range, resolver, fallback); + // The fallback must match the syntax of the referenced custom property. + // https://drafts.css-houdini.org/css-properties-values-api-1/#fallbacks-in-var-references + if (!ValidateFallback(property, fallback.TokenRange())) + return false; + if (!data && success) + data = fallback.BuildVariableData(); + } + + if (!data || resolver.InCycle()) + return false; + + // https://drafts.csswg.org/css-variables/#long-variables + if (data->Tokens().size() > kMaxSubstitutionTokens) + return false; + + out.Append(data.get()); + + return true; +} + +bool StyleCascade::ResolveEnvInto(CSSParserTokenRange range, + Resolver& resolver, + TokenSequence& out) { + AtomicString variable_name = ConsumeVariableName(range); + DCHECK(range.AtEnd() || (range.Peek().GetType() == kCommaToken)); + + CSSVariableData* data = GetEnvironmentVariable(variable_name); + + if (!data) { + if (ConsumeComma(range)) + return ResolveTokensInto(range, resolver, out); + return false; + } + + out.Append(data); + + return true; +} + +CSSVariableData* StyleCascade::GetVariableData( + const CustomProperty& property) const { + const AtomicString& name = property.GetPropertyNameAtomicString(); + const bool is_inherited = property.IsInherited(); + return state_.StyleRef().GetVariableData(name, is_inherited); +} + +CSSVariableData* StyleCascade::GetEnvironmentVariable( + const AtomicString& name) const { + // If we are in a User Agent Shadow DOM then we should not record metrics. + ContainerNode& scope_root = state_.GetTreeScope().RootNode(); + auto* shadow_root = DynamicTo<ShadowRoot>(&scope_root); + bool is_ua_scope = shadow_root && shadow_root->IsUserAgent(); + + return state_.GetDocument() + .GetStyleEngine() + .EnsureEnvironmentVariables() + .ResolveVariable(name, !is_ua_scope); +} + +const CSSParserContext* StyleCascade::GetParserContext( + const CSSVariableReferenceValue& value) { + // TODO(crbug.com/985028): CSSVariableReferenceValue should always have a + // CSSParserContext. (CSSUnparsedValue violates this). + if (value.ParserContext()) + return value.ParserContext(); + return StrictCSSParserContext(state_.GetDocument().GetSecureContextMode()); +} + +bool StyleCascade::HasFontSizeDependency(const CustomProperty& property, + CSSVariableData* data) const { + if (!property.IsRegistered() || !data) + return false; + if (data->HasFontUnits()) + return true; + if (data->HasRootFontUnits() && IsRootElement()) + return true; + return false; +} + +bool StyleCascade::ValidateFallback(const CustomProperty& property, + CSSParserTokenRange range) const { + if (!property.IsRegistered()) + return true; + auto context_mode = state_.GetDocument().GetSecureContextMode(); + auto var_mode = CSSParserLocalContext::VariableMode::kTyped; + auto* context = StrictCSSParserContext(context_mode); + auto local_context = CSSParserLocalContext().WithVariableMode(var_mode); + return property.ParseSingleValue(range, *context, local_context); +} + +void StyleCascade::MarkReferenced(const CustomProperty& property) { + if (!property.IsInherited()) + state_.Style()->SetHasVariableReferenceFromNonInheritedProperty(); + if (!property.IsRegistered()) + return; + const AtomicString& name = property.GetPropertyNameAtomicString(); + state_.GetDocument().GetPropertyRegistry()->MarkReferenced(name); +} + +bool StyleCascade::Filter::Add(const CSSProperty& property, + const Value& value) { + Priority& slot = GetSlot(property); + if (value.GetPriority() >= slot) { + slot = value.GetPriority(); + return true; + } + return false; +} + +StyleCascade::Priority& StyleCascade::Filter::GetSlot( + const CSSProperty& property) { + // TODO(crbug.com/985043): Ribbonize? + switch (property.PropertyID()) { + case CSSPropertyID::kWritingMode: + case CSSPropertyID::kWebkitWritingMode: + return writing_mode_; + case CSSPropertyID::kZoom: + case CSSPropertyID::kInternalEffectiveZoom: + return zoom_; + default: + none_ = Priority(); + return none_; + } +} + +bool StyleCascade::Resolver::IsLocked(const CSSProperty& property) const { + return IsLocked(property.GetCSSPropertyName()); +} + +bool StyleCascade::Resolver::IsLocked(const CSSPropertyName& name) const { + return stack_.Contains(name); +} + +bool StyleCascade::Resolver::AllowSubstitution(CSSVariableData* data) const { + if (data && data->IsAnimationTainted() && stack_.size()) { + const CSSPropertyName& name = stack_.back(); + if (name.IsCustomProperty()) + return true; + const CSSProperty& property = CSSProperty::Get(name.Id()); + return !CSSAnimations::IsAnimationAffectingProperty(property); + } + return true; +} + +bool StyleCascade::Resolver::DetectCycle(const CSSProperty& property) { + wtf_size_t index = stack_.Find(property.GetCSSPropertyName()); + if (index == kNotFound) + return false; + cycle_depth_ = std::min(cycle_depth_, index); + return true; +} + +bool StyleCascade::Resolver::InCycle() const { + return cycle_depth_ != kNotFound; +} + +StyleCascade::AutoLock::AutoLock(const CSSProperty& property, + Resolver& resolver) + : AutoLock(property.GetCSSPropertyName(), resolver) {} + +StyleCascade::AutoLock::AutoLock(const CSSPropertyName& name, + Resolver& resolver) + : resolver_(resolver) { + DCHECK(!resolver.IsLocked(name)); + resolver_.stack_.push_back(name); +} + +StyleCascade::AutoLock::~AutoLock() { + resolver_.stack_.pop_back(); + if (resolver_.stack_.size() <= resolver_.cycle_depth_) + resolver_.cycle_depth_ = kNotFound; +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/css/resolver/style_cascade.h b/third_party/blink/renderer/core/css/resolver/style_cascade.h new file mode 100644 index 0000000..d6cbce2 --- /dev/null +++ b/third_party/blink/renderer/core/css/resolver/style_cascade.h
@@ -0,0 +1,508 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_CASCADE_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_CASCADE_H_ + +#include "third_party/blink/renderer/core/css/css_property_name.h" +#include "third_party/blink/renderer/core/css/parser/css_parser_token.h" +#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h" +#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" + +namespace blink { + +class CSSCustomPropertyDeclaration; +class CSSParserContext; +class CSSProperty; +class CSSValue; +class CSSVariableData; +class CSSVariableReferenceValue; +class CustomProperty; +class StyleResolverState; + +namespace cssvalue { + +class CSSPendingSubstitutionValue; +class CSSPendingInterpolationValue; + +} // namespace cssvalue + +// The StyleCascade is responsible for managing cascaded values [1], resolving +// dependencies between them, and applying the values to the ComputedStyle. +// +// Its usage pattern is: +// +// const CSSPropertyName& name = ...; +// const CSSValue* value1 = ...; +// const CSSValue* value2 = ...; +// +// StyleCascade cascade(state); +// cascade.Add(name, value1, Priority(Origin::kAuthor)); +// cascade.Add(name, value2, Priority(Origin::kUA)); +// cascade.Apply(); // value1 is applied, value2 is ignored. +// +// [1] https://drafts.csswg.org/css-cascade/#cascade +class CORE_EXPORT StyleCascade { + STACK_ALLOCATED(); + + using CSSPendingSubstitutionValue = cssvalue::CSSPendingSubstitutionValue; + using CSSPendingInterpolationValue = cssvalue::CSSPendingInterpolationValue; + + public: + class Animator; + class Resolver; + class AutoLock; + + StyleCascade(StyleResolverState& state) : state_(state) {} + + static constexpr uint16_t kMaxCascadeOrder = ~static_cast<uint16_t>(0); + + // Represents the origin and importance criteria described by css-cascade [1]. + // + // Higher values are more significant than lower values. The values are + // chosen such that an important origin can be produced by inverting the bits + // of the corresponding non-important origin. + // + // [1] https://www.w3.org/TR/css-cascade-3/#cascade-origin + enum class Origin : uint8_t { + kNone = 0, + kUserAgent = 0b0001, + kUser = 0b0010, + kAuthor = 0b0011, + kAnimation = 0b0100, + kImportantAuthor = 0b1100, + kImportantUser = 0b1101, + kImportantUserAgent = 0b1110, + kTransition = 0b10000, + }; + + // All important Origins (and only those) must have this bit set. This + // provides a fast way to check if an Origin is important. + static constexpr uint8_t kImportantBit = 0b1000; + + // The Priority class encapsulates a subset of the cascading criteria + // described by css-cascade [1], and provides a way to compare priorities. + // + // It encompasses, from most significant to least significant: Origin (which + // includes importance); tree order, which is a number representing the + // shadow-including tree order [2]; and finally cascade order, which is + // a monotonically increasing number increased by one every time something + // is added to the cascade. + // + // The cascade order is initially kMaxCascadeOrder for an instance of + // Priority; an actual value will be assigned by StyleCascade::Add. + // + // [1] https://drafts.csswg.org/css-cascade/#cascading + // [2] https://drafts.csswg.org/css-scoping/#shadow-cascading + class CORE_EXPORT Priority { + DISALLOW_NEW(); + + public: + Priority() : Priority(Origin::kNone) {} + // Deliberately implicit. + Priority(Origin origin) : Priority(origin, 0) {} + // For an explanation of 'tree_order', see css-scoping [1]. + // [1] https://drafts.csswg.org/css-scoping/#shadow-cascading + Priority(Origin, uint16_t tree_order); + + Origin GetOrigin() const; + bool HasOrigin() const { return GetOrigin() != Origin::kNone; } + + // This function is used to determine if an incoming Value should win + // over the Value which already exists in the cascade. + bool operator>=(const Priority&) const; + + // Returns a copy of this Priority, except that the non-important origin + // has been converted to its important counterpart. + // + // Must be used with kUserAgent, kAuthor, and kAuthor only, as importance + // does not apply to the other origins. + // + // https://drafts.csswg.org/css-cascade/#important + inline Priority AddImportance() const { + DCHECK_GE(GetOrigin(), Origin::kUserAgent); + DCHECK_LE(GetOrigin(), Origin::kAuthor); + // Flip Origin bits, converting non-important to important. We only + // xor four bits here, because only those bits are in use by + // k[Important,][User,UserAgent,Author]. + return Priority(priority_ ^ (static_cast<uint64_t>(0b1111) << 32)); + } + + private: + friend class StyleCascade; + friend class StyleCascadeTest; + + Priority(uint64_t priority) : priority_(priority) {} + + // Returns a copy of this Priority, with the cascade order set to the + // specified value. + // + // For the purposes of StyleCascade::Add alone, we don't need to store the + // cascade order at all, since the cascade order is implicit in the order + // of the calls to ::Add. However, some properties unfortunately require + // that we store the cascade order and act upon it Apply-time. This is + // because we have multiple properties that mutate the same field on + // ComputedStyle, hence the relative ordering must be preserved between + // them to know which should be applied. (See class Filter). + inline Priority WithCascadeOrder(uint16_t cascade_order) const { + return Priority((priority_ & ~0xFFFF) | cascade_order); + } + + // To make Priority comparisons fast, the origin, tree_order and + // cascade_order are stored in a single uint64_t, as follows: + // + // Bit 0-15: cascade_order + // Bit 16-31: tree_order + // Bit 32-39: Origin + // + // This way, the numeric value of priority_ can be compared directly + // for all criteria simultaneously. + uint64_t priority_; + }; + + // The Value class simply represents the data we store for each property + // in the cascade. See StyleCascade::cascade_ field. + class CORE_EXPORT Value { + DISALLOW_NEW(); + + public: + // The empty Value is needed because we store it in a HashMap. + Value() = default; + Value(const CSSValue* value, Priority priority) + : value_(value), priority_(priority) {} + bool IsEmpty() const { return !priority_.HasOrigin(); } + const CSSValue* GetValue() const { return value_; } + const Priority& GetPriority() const { return priority_; } + void Trace(blink::Visitor* visitor) { visitor->Trace(value_); } + + private: + Member<const CSSValue> value_; + Priority priority_; + }; + + // Add a Value to the cascade. The Value will either become the cascaded + // value, or be discarded, depending on the Priority of the incoming value + // vs. the Priority of the existing value. + void Add(const CSSPropertyName&, const CSSValue*, Priority); + + // Applies all values currently in the cascade to the ComputedStyle. + // Any CSSPendingInterpolationValues present in the cascade will be ignored. + void Apply(); + // Applies all values currently in the cascade to the ComputedStyle, + // dispatching any CSSPendingInterpolationValues to the given Animator. + void Apply(Animator&); + + // Removes all kAnimationPropertyPriority properties from the cascade, + // without applying the properties. This is used when pre-emptively copying + // the cascade in case there are animations. + // + // TODO(crbug.com/985010): Improve with non-destructive Apply. + void RemoveAnimationPriority(); + + // The Filter class is responsible for resolving situations where + // we have multiple (non-alias) properties in the cascade that mutates the + // same fields on ComputedStyle. + // + // An example of this is writing-mode and -webkit-writing-mode, which + // both result in ComputedStyle::SetWritingMode calls. + // + // When applying the cascade (applying each property/value pair to the + // ComputedStyle), the order of the application is in the general case + // not defined. (It is determined by the iteration order of the HashMap). + // This means that if both writing-mode and -webkit-writing-mode exist in + // the cascade, we would get non-deterministic behavior: the application order + // would not be defined. To fix this, all Values pass through this Filter + // before being applied. + + // The Filter stores the Priority of the Value that was previously applied + // for a certain 'group' of properties (writing_mode_ is one such group). + // When we're about to apply a Value, we only actually do so if the call to + // Filter::Add succeeds. If the call to Filter::Add does not succeed, it means + // that we have previously added a Value with higher Priority, and that the + // current Value must be ignored. + + // A key difference between discarding Values in the Filter, vs. discarding + // them cascade-time (StyleCascade::Add), is that we are taking the cascade + // order into account. This means that, if everything else is equal (origin, + // tree order), the Value that entered the cascade last wins. This is crucial + // to resolve situations like writing-mode and -webkit-writing-mode. + + // The Filter is also expected to resolve similar difficulties with + // direction-aware properties in the future, although this is not yet + // implemented. + class CORE_EXPORT Filter { + STACK_ALLOCATED(); + + public: + // Attempts to add a given property/value to the Filter. If this returns + // true, the Value may be applied to the ComputedStyle. If not, it means + // that we have previously applied a Value with higher Priority, and the + // current Value must be discarded. + bool Add(const CSSProperty& property, const Value&); + + private: + Priority& GetSlot(const CSSProperty&); + + Priority none_; + Priority writing_mode_; + Priority zoom_; + }; + + // Resolver is an object passed on a stack during Apply. Its most important + // job is to detect cycles during Apply (in general, keep track of which + // properties we're currently applying). + class CORE_EXPORT Resolver { + STACK_ALLOCATED(); + + public: + // TODO(crbug.com/985047): Probably use a HashMap for this. + using NameStack = Vector<CSSPropertyName, 8>; + + // A 'locked' property is a property we are in the process of applying. + // In other words, once a property is locked, locking it again would form + // a cycle, and is therefore an error. + bool IsLocked(const CSSProperty&) const; + bool IsLocked(const CSSPropertyName&) const; + + // We do not allow substitution of animation-tainted values into + // an animation-affecting property. + // + // https://drafts.csswg.org/css-variables/#animation-tainted + bool AllowSubstitution(CSSVariableData*) const; + + private: + friend class AutoLock; + friend class StyleCascade; + friend class TestCascadeResolver; + + Resolver(Animator& animator) : animator_(animator) {} + // If the given property is already being applied, returns true. + // The return value is the same value you would get from InCycle(), and + // is just returned for convenience. + // + // When a cycle has been detected, the Resolver will *persist the cycle + // state* (i.e. InCycle() will continue to return true) until we reach + // the start of the cycle. + // + // The cycle state is cleared by ~AutoLock, once we have moved far enough + // up the stack. + bool DetectCycle(const CSSProperty&); + // Returns true whenever the Resolver is in a cycle state. + // This DOES NOT detect cycles; the caller must call DetectCycle first. + bool InCycle() const; + + NameStack stack_; + Animator& animator_; + wtf_size_t cycle_depth_ = kNotFound; + Filter filter_; + }; + + // Automatically locks and unlocks the given property. (See + // Resolver::IsLocked). + class CORE_EXPORT AutoLock { + STACK_ALLOCATED(); + + public: + AutoLock(const CSSProperty&, Resolver&); + AutoLock(const CSSPropertyName&, Resolver&); + ~AutoLock(); + + private: + Resolver& resolver_; + }; + + // Animator & CSSPendingInterpolationValue + // + // Blink's way of applying animations poses some difficulty for StyleCascade, + // as much of the code that applies the animation effects completely bypasses + // StyleBuilder; it sets the values on ComputedStyle directly. This prevents + // those values from participating properly in the cascade. + // + // At the same time, we don't want to actually create CSSValues for the + // animation effects, as this is (yet another?) unnecessary conversion, and + // it produces unwanted GC pressure. To solve this problem, the cascading + // and application aspects of interpolations are handled *separately*. + // + // CSSPendingInterpolationValue represents the cascading aspect of an + // interpolation: this means that, once we know that an interpolation is + // active for a given property, we add a CSSPendingInterpolationValue to the + // cascade (with the appropriate Priority). Apply-time, we then ask the + // Animator (see StyleAnimator) to actually apply the interpolated value + // using the interpolation infrastructure. + class CORE_EXPORT Animator { + public: + virtual void Apply(const CSSProperty&, + const CSSPendingInterpolationValue&, + Resolver&) = 0; + }; + + // Applying a CSSPendingInterpolationValue may involve resolving values, + // since we may be applying a keyframe from e.g. "color: var(--x)" to + // "color: var(--y)". Hence that code needs an entry point to the resolving + // process. + // + // TODO(crbug.com/985023): This function has an associated const + // violation, which isn't great. (This vilation was not introduced with + // StyleCascade, however). + // + // See documentation the other Resolve* functions for what resolve means. + const CSSValue* Resolve(const CSSPropertyName&, const CSSValue&, Resolver&); + + private: + friend class TestCascade; + + // The maximum number of tokens that may be produced by a var() + // reference. + // + // https://drafts.csswg.org/css-variables/#long-variables + static const size_t kMaxSubstitutionTokens = 16384; + + // Applies kHighPropertyPriority properties. + // + // In theory, it would be possible for each property/value that contains + // em/ch/etc to dynamically apply font-size (and related properties), but + // in practice, it is very inconvenient to detect these dependencies. Hence, + // we apply font-affecting properties (among others) before all the others. + void ApplyHighPriority(Resolver&); + + // Apply a single property (including any dependencies). + void Apply(const CSSPropertyName&); + void Apply(const CSSPropertyName&, Resolver&); + void Apply(const CSSProperty&, Resolver&); + + // True if the cascade currently holds the provided value for a given + // property. Note that the value is compared by address. + bool HasValue(const CSSPropertyName&, const CSSValue*) const; + + // Get current cascaded value for the specified property. + const CSSValue* GetValue(const CSSPropertyName&) const; + + // If there is a cascaded value for the specified property, replace it + // with the incoming value, maintaining the current cascade origin. + // Has no effect if there is no cascaded value for the property. + void ReplaceValue(const CSSPropertyName&, const CSSValue*); + + // Whether or not we are calculating the style for the root element. + // We need to know this to detect cycles with 'rem' units. + // https://drafts.css-houdini.org/css-properties-values-api-1/#dependency-cycles + bool IsRootElement() const; + + // The TokenSequence class acts as a builder for CSSVariableData. + // + // However, actually building a CSSVariableData is optional; you can also + // get a CSSParserTokenRange directly, which is useful when resolving a + // CSSVariableData which won't ultimately end up in a CSSVariableData + // (i.e. CSSVariableReferenceValue or CSSPendingSubstitutionValue). + class TokenSequence { + STACK_ALLOCATED(); + + public: + TokenSequence() = default; + // Initialize a TokenSequence from a CSSVariableData, preparing the + // TokenSequence for var() resolution. + // + // This copies everything except the tokens. + explicit TokenSequence(const CSSVariableData*); + + bool IsAnimationTainted() const { return is_animation_tainted_; } + CSSParserTokenRange TokenRange() const { return tokens_; } + + void Append(const TokenSequence&); + void Append(const CSSVariableData*); + void Append(const CSSParserToken&); + + scoped_refptr<CSSVariableData> BuildVariableData(); + + private: + Vector<CSSParserToken> tokens_; + Vector<String> backing_strings_; + // https://drafts.csswg.org/css-variables/#animation-tainted + bool is_animation_tainted_ = false; + // https://drafts.css-houdini.org/css-properties-values-api-1/#dependency-cycles + bool has_font_units_ = false; + bool has_root_font_units_ = false; + + // The base URL and charset are currently needed to calculate the computed + // value of <url>-registered custom properties correctly. + // + // TODO(crbug.com/985013): Store CSSParserContext on + // CSSCustomPropertyDeclaration and avoid this. + // + // https://drafts.css-houdini.org/css-properties-values-api-1/#relative-urls + String base_url_; + WTF::TextEncoding charset_; + }; + + // Resolving Values + // + // *Resolving* a value, means looking at the dependencies for a given + // CSSValue, and ensuring that these dependencies are satisfied. The result + // of a Resolve call is either the same CSSValue (e.g. if there were no + // dependencies), or a new CSSValue with the dependencies resolved. + // + // For example, consider the following properties: + // + // --x: 10px; + // --y: var(--x); + // width: var(--y); + // + // Here, to resolve 'width', the computed value of --y must be known. In + // other words, we must first Apply '--y'. Hence, resolving 'width' will + // Apply '--y' as a side-effect. (This process would then continue to '--x'). + + const CSSValue* Resolve(const CSSProperty&, const CSSValue&, Resolver&); + const CSSValue* ResolveCustomProperty(const CSSProperty&, + const CSSCustomPropertyDeclaration&, + Resolver&); + const CSSValue* ResolveVariableReference(const CSSProperty&, + const CSSVariableReferenceValue&, + Resolver&); + const CSSValue* ResolvePendingSubstitution(const CSSProperty&, + const CSSPendingSubstitutionValue&, + Resolver&); + + scoped_refptr<CSSVariableData> ResolveVariableData(CSSVariableData*, + Resolver&); + + // The Resolve*Into functions either resolve dependencies, append to the + // TokenSequence accordingly, and return true; or it returns false when + // the TokenSequence is "invalid at computed-value time" [1]. This happens + // when there was a reference to an invalid/missing custom property, or when a + // cycle was detected. + // + // [1] https://drafts.csswg.org/css-variables/#invalid-at-computed-value-time + + bool ResolveTokensInto(CSSParserTokenRange, Resolver&, TokenSequence&); + bool ResolveVarInto(CSSParserTokenRange, Resolver&, TokenSequence&); + bool ResolveEnvInto(CSSParserTokenRange, Resolver&, TokenSequence&); + + CSSVariableData* GetVariableData(const CustomProperty&) const; + CSSVariableData* GetEnvironmentVariable(const AtomicString&) const; + const CSSParserContext* GetParserContext(const CSSVariableReferenceValue&); + + // Detects if the given property/data depends on the font-size property + // of the Element we're calculating the style for. + // + // https://drafts.css-houdini.org/css-properties-values-api-1/#dependency-cycles + bool HasFontSizeDependency(const CustomProperty&, CSSVariableData*) const; + // The fallback must match the syntax of the custom property, otherwise the + // the declaration is "invalid at computed-value time".' + // + // https://drafts.css-houdini.org/css-properties-values-api-1/#fallbacks-in-var-references + bool ValidateFallback(const CustomProperty&, CSSParserTokenRange) const; + // Marks the CustomProperty as referenced by something. Needed to avoid + // animating these custom properties on the compositor, and to disable the + // matched properties cache in some cases. + void MarkReferenced(const CustomProperty&); + + StyleResolverState& state_; + HeapHashMap<CSSPropertyName, Value> cascade_; + uint16_t order_ = 0; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_CASCADE_H_
diff --git a/third_party/blink/renderer/core/css/resolver/style_cascade_test.cc b/third_party/blink/renderer/core/css/resolver/style_cascade_test.cc new file mode 100644 index 0000000..af7d9d24 --- /dev/null +++ b/third_party/blink/renderer/core/css/resolver/style_cascade_test.cc
@@ -0,0 +1,1976 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/css/resolver/style_cascade.h" + +#include <vector> + +#include "third_party/blink/renderer/core/animation/css/css_animations.h" +#include "third_party/blink/renderer/core/css/active_style_sheets.h" +#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h" +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" +#include "third_party/blink/renderer/core/css/css_pending_substitution_value.h" +#include "third_party/blink/renderer/core/css/css_primitive_value.h" +#include "third_party/blink/renderer/core/css/css_style_sheet_init.h" +#include "third_party/blink/renderer/core/css/css_test_helpers.h" +#include "third_party/blink/renderer/core/css/css_variable_reference_value.h" +#include "third_party/blink/renderer/core/css/document_style_environment_variables.h" +#include "third_party/blink/renderer/core/css/media_query_evaluator.h" +#include "third_party/blink/renderer/core/css/parser/css_parser_context.h" +#include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h" +#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h" +#include "third_party/blink/renderer/core/css/parser/css_property_parser.h" +#include "third_party/blink/renderer/core/css/parser/css_tokenizer.h" +#include "third_party/blink/renderer/core/css/parser/css_variable_parser.h" +#include "third_party/blink/renderer/core/css/properties/css_property_instances.h" +#include "third_party/blink/renderer/core/css/properties/css_property_ref.h" +#include "third_party/blink/renderer/core/css/properties/longhands/custom_property.h" +#include "third_party/blink/renderer/core/css/property_registry.h" +#include "third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h" +#include "third_party/blink/renderer/core/css/resolver/style_animator.h" +#include "third_party/blink/renderer/core/css/resolver/style_resolver.h" +#include "third_party/blink/renderer/core/css/style_engine.h" +#include "third_party/blink/renderer/core/css/style_sheet_contents.h" +#include "third_party/blink/renderer/core/html/html_element.h" +#include "third_party/blink/renderer/core/style/computed_style.h" +#include "third_party/blink/renderer/core/style_property_shorthand.h" +#include "third_party/blink/renderer/core/testing/page_test_base.h" +#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" + +namespace blink { + +using namespace css_test_helpers; +using namespace cssvalue; +using Origin = StyleCascade::Origin; +using Priority = StyleCascade::Priority; +using UnitType = CSSPrimitiveValue::UnitType; + +enum class AnimationTainted { kYes, kNo }; + +class TestCascade { + STACK_ALLOCATED(); + + public: + TestCascade(Document& document, Element* target = nullptr) + : state_(document, target ? *target : *document.body(), nullptr), + cascade_(InitState(state_)) {} + + scoped_refptr<ComputedStyle> TakeStyle() { return state_.TakeStyle(); } + + StyleResolverState& State() { return state_; } + StyleCascade& InnerCascade() { return cascade_; } + + void InheritFrom(scoped_refptr<ComputedStyle> parent) { + state_.SetParentStyle(parent); + state_.StyleRef().InheritFrom(*parent); + } + + void Add(String name, + String value, + Priority priority = Origin::kAuthor, + AnimationTainted animation_tainted = AnimationTainted::kNo) { + return Add(*CSSPropertyName::From(name), value, priority, + animation_tainted); + } + + void Add(const CSSPropertyName& name, + String value, + Priority priority = Origin::kAuthor, + AnimationTainted animation_tainted = AnimationTainted::kNo) { + HeapVector<CSSPropertyValue, 256> values = + ParseValues(name, value, animation_tainted); + + for (const CSSPropertyValue& v : values) + Add(v.Name(), v.Value(), priority); + } + + void Add(String name, + const CSSValue* value, + Priority priority = Origin::kAuthor) { + Add(*CSSPropertyName::From(name), value, priority); + } + + void Add(const CSSPropertyName& name, + const CSSValue* value, + Priority priority = Origin::kAuthor) { + DCHECK(CSSPropertyRef(name, GetDocument()).GetProperty().IsLonghand()); + cascade_.Add(name, value, priority); + } + + void Apply(const CSSPropertyName& name) { cascade_.Apply(name); } + void Apply(String name) { Apply(*CSSPropertyName::From(name)); } + void Apply() { cascade_.Apply(); } + void Apply(StyleCascade::Animator& animator) { cascade_.Apply(animator); } + + HeapVector<CSSPropertyValue, 256> ParseValues( + const CSSPropertyName& name, + String value, + AnimationTainted animation_tainted) { + CSSTokenizer tokenizer(value); + auto tokens = tokenizer.TokenizeToEOF(); + auto* context = MakeGarbageCollected<CSSParserContext>(GetDocument()); + context->SetMode(kUASheetMode); // Allows -internal variables. + + HeapVector<CSSPropertyValue, 256> parsed_properties; + + bool is_animation_tainted = animation_tainted == AnimationTainted::kYes; + if (name.Id() == CSSPropertyID::kVariable) { + // TODO(andruud): Make CSSPropertyParser::ParseValue handle custom props. + const CSSValue* decl = CSSVariableParser::ParseDeclarationValue( + name.ToAtomicString(), tokens, is_animation_tainted, *context); + DCHECK(decl); + parsed_properties.emplace_back(GetCSSPropertyVariable(), *decl); + return parsed_properties; + } + + const bool important = false; + + bool ok = CSSPropertyParser::ParseValue(name.Id(), important, tokens, + context, parsed_properties, + StyleRule::RuleType::kStyle); + DCHECK(ok); + + return parsed_properties; + } + + String ComputedValue(String name) const { + CSSPropertyRef ref(name, GetDocument()); + DCHECK(ref.IsValid()); + const LayoutObject* layout_object = nullptr; + bool allow_visited_style = false; + const CSSValue* value = ref.GetProperty().CSSValueFromComputedStyle( + *state_.Style(), layout_object, Body(), allow_visited_style); + return value ? value->CssText() : g_null_atom; + } + + bool HasValue(String name, const CSSValue* value) { + return cascade_.HasValue(*CSSPropertyName::From(name), value); + } + + const CSSValue* GetCSSValue(String name) { + return cascade_.GetValue(*CSSPropertyName::From(name)); + } + + const String GetValue(String name) { + const CSSValue* value = GetCSSValue(name); + // Per spec, CSSPendingSubstitutionValue serializes as an empty string, + // but for testing purposes it's nice to see the actual value. + if (const auto* v = DynamicTo<CSSPendingSubstitutionValue>(value)) + return v->ShorthandValue()->CssText(); + if (DynamicTo<CSSPendingInterpolationValue>(value)) + return "<interpolation>"; + return value ? value->CssText() : g_null_atom; + } + + CSSAnimationUpdate& CalculateTransitionUpdate() { + CSSAnimations::CalculateTransitionUpdate( + state_.AnimationUpdate(), CSSAnimations::PropertyPass::kCustom, + &state_.GetElement(), *state_.Style()); + CSSAnimations::CalculateTransitionUpdate( + state_.AnimationUpdate(), CSSAnimations::PropertyPass::kStandard, + &state_.GetElement(), *state_.Style()); + return state_.AnimationUpdate(); + } + + CSSAnimationUpdate& CalculateAnimationUpdate() { + CSSAnimations::CalculateAnimationUpdate( + state_.AnimationUpdate(), &state_.GetElement(), state_.GetElement(), + *state_.Style(), state_.ParentStyle(), + &GetDocument().EnsureStyleResolver()); + return state_.AnimationUpdate(); + } + + void AddAnimations() { + auto& update = CalculateAnimationUpdate(); + using Type = CSSPendingInterpolationValue::Type; + + for (const auto& entry : update.ActiveInterpolationsForCustomAnimations()) { + auto name = entry.key.GetCSSPropertyName(); + auto* v = CSSPendingInterpolationValue::Create(Type::kCSSProperty); + Add(name.ToAtomicString(), v); + } + for (const auto& entry : + update.ActiveInterpolationsForStandardAnimations()) { + auto name = entry.key.GetCSSPropertyName(); + auto* v = CSSPendingInterpolationValue::Create(Type::kCSSProperty); + Add(name.ToAtomicString(), v); + } + } + + void AddTransitions() { + auto& update = CalculateTransitionUpdate(); + using Type = CSSPendingInterpolationValue::Type; + + for (const auto& entry : + update.ActiveInterpolationsForCustomTransitions()) { + auto name = entry.key.GetCSSPropertyName(); + auto* v = CSSPendingInterpolationValue::Create(Type::kCSSProperty); + Add(name.ToAtomicString(), v); + } + for (const auto& entry : + update.ActiveInterpolationsForStandardTransitions()) { + auto name = entry.key.GetCSSPropertyName(); + auto* v = CSSPendingInterpolationValue::Create(Type::kCSSProperty); + Add(name.ToAtomicString(), v); + } + } + + private: + Document& GetDocument() const { return state_.GetDocument(); } + Element* Body() const { return GetDocument().body(); } + + static StyleResolverState& InitState(StyleResolverState& state) { + state.SetStyle(InitialStyle(state.GetDocument())); + state.SetParentStyle(InitialStyle(state.GetDocument())); + return state; + } + + static scoped_refptr<ComputedStyle> InitialStyle(Document& document) { + return StyleResolver::InitialStyleForElement(document); + } + + StyleResolverState state_; + StyleCascade cascade_; +}; + +class TestCascadeResolver { + STACK_ALLOCATED(); + + public: + TestCascadeResolver(Document& document, StyleAnimator& animator) + : document_(&document), resolver_(animator) {} + bool InCycle() const { return resolver_.InCycle(); } + bool DetectCycle(String name) { + CSSPropertyRef ref(name, *document_); + DCHECK(ref.IsValid()); + const CSSProperty& property = ref.GetProperty(); + return resolver_.DetectCycle(property); + } + wtf_size_t CycleDepth() const { return resolver_.cycle_depth_; } + + private: + friend class TestCascadeAutoLock; + + Member<Document> document_; + StyleCascade::Resolver resolver_; +}; + +class TestCascadeAutoLock { + STACK_ALLOCATED(); + + public: + TestCascadeAutoLock(const CSSPropertyName& name, + TestCascadeResolver& resolver) + : lock_(name, resolver.resolver_) {} + + private: + StyleCascade::AutoLock lock_; +}; + +class StyleCascadeTest : public PageTestBase { + public: + void SetUp() override { + RuntimeEnabledFeatures::SetCSSCascadeEnabled(true); + PageTestBase::SetUp(); + } + + void TearDown() override { + PageTestBase::TearDown(); + RuntimeEnabledFeatures::SetCSSCascadeEnabled(false); + } + + CSSStyleSheet* CreateSheet(const String& css_text) { + auto* init = MakeGarbageCollected<CSSStyleSheetInit>(); + DummyExceptionStateForTesting exception_state; + CSSStyleSheet* sheet = + CSSStyleSheet::Create(GetDocument(), init, exception_state); + sheet->replaceSync(css_text, exception_state); + sheet->Contents()->EnsureRuleSet(MediaQueryEvaluator(), + kRuleHasNoSpecialState); + return sheet; + } + + void AppendSheet(const String& css_text) { + CSSStyleSheet* sheet = CreateSheet(css_text); + ASSERT_TRUE(sheet); + + Element* body = GetDocument().body(); + ASSERT_TRUE(body->IsInTreeScope()); + TreeScope& tree_scope = body->GetTreeScope(); + ScopedStyleResolver& scoped_resolver = + tree_scope.EnsureScopedStyleResolver(); + ActiveStyleSheetVector active_sheets; + active_sheets.push_back( + std::make_pair(sheet, &sheet->Contents()->GetRuleSet())); + scoped_resolver.AppendActiveStyleSheets(0, active_sheets); + } + + Element* DocumentElement() const { return GetDocument().documentElement(); } + + void SetRootFont(String value) { + DocumentElement()->SetInlineStyleProperty(CSSPropertyID::kFontSize, value); + UpdateAllLifecyclePhasesForTest(); + } + + Priority AuthorPriority(uint16_t tree_order, uint16_t cascade_order) { + return Priority(Origin::kAuthor, tree_order) + .WithCascadeOrder(cascade_order); + } + + Priority ImportantAuthorPriority(uint16_t tree_order, + uint16_t cascade_order) { + return Priority(Origin::kImportantAuthor, tree_order) + .WithCascadeOrder(cascade_order); + } + + // Temporarily create a CSS Environment Variable. + // https://drafts.csswg.org/css-env-1/ + class AutoEnv { + STACK_ALLOCATED(); + + public: + AutoEnv(PageTestBase& test, AtomicString name, String value) + : document_(&test.GetDocument()), name_(name) { + EnsureEnvironmentVariables().SetVariable(name, value); + } + ~AutoEnv() { EnsureEnvironmentVariables().RemoveVariable(name_); } + + private: + DocumentStyleEnvironmentVariables& EnsureEnvironmentVariables() { + return document_->GetStyleEngine().EnsureEnvironmentVariables(); + } + + Member<Document> document_; + AtomicString name_; + }; +}; + +TEST_F(StyleCascadeTest, OriginImportance) { + EXPECT_EQ(Origin::kImportantUserAgent, + Priority(Origin::kUserAgent).AddImportance().GetOrigin()); + EXPECT_EQ(Origin::kImportantUser, + Priority(Origin::kUser).AddImportance().GetOrigin()); + EXPECT_EQ(Origin::kImportantAuthor, + Priority(Origin::kAuthor).AddImportance().GetOrigin()); +} + +TEST_F(StyleCascadeTest, PriorityOrigin) { + std::vector<Priority> priorities = { + Origin::kTransition, Origin::kImportantUserAgent, + Origin::kImportantUser, Origin::kImportantAuthor, + Origin::kAnimation, Origin::kAuthor, + Origin::kUser, Origin::kUserAgent, + Origin::kNone}; + + for (size_t i = 0; i < priorities.size(); ++i) { + for (size_t j = i; j < priorities.size(); ++j) + EXPECT_GE(priorities[i], priorities[j]); + } + + EXPECT_FALSE(Priority(Origin::kUser) >= Priority(Origin::kAuthor)); +} + +TEST_F(StyleCascadeTest, PriorityHasOrigin) { + EXPECT_TRUE(Priority(Origin::kTransition).HasOrigin()); + EXPECT_TRUE(Priority(Origin::kAuthor).HasOrigin()); + EXPECT_FALSE(Priority(Origin::kNone).HasOrigin()); +} + +TEST_F(StyleCascadeTest, PriorityTreeOrder) { + Origin origin = Origin::kAuthor; + EXPECT_GE(Priority(origin, 0), Priority(origin, 1)); + EXPECT_GE(Priority(origin, 6), Priority(origin, 7)); + EXPECT_GE(Priority(origin, 42), Priority(origin, 42)); + EXPECT_FALSE(Priority(origin, 8) >= Priority(origin, 1)); +} + +TEST_F(StyleCascadeTest, PriorityTreeOrderImportant) { + Origin origin = Origin::kImportantAuthor; + EXPECT_GE(Priority(origin, 1), Priority(origin, 0)); + EXPECT_GE(Priority(origin, 7), Priority(origin, 6)); + EXPECT_GE(Priority(origin, 42), Priority(origin, 42)); + EXPECT_FALSE(Priority(origin, 1) >= Priority(origin, 8)); +} + +TEST_F(StyleCascadeTest, PriorityTreeOrderDifferentOrigin) { + // Tree order does not matter if the origin is different. + Origin author = Origin::kAuthor; + Origin transition = Origin::kTransition; + EXPECT_GE(Priority(transition, 42), Priority(author, 1)); + EXPECT_GE(Priority(transition, 1), Priority(author, 1)); +} + +TEST_F(StyleCascadeTest, PriorityCascadeOrder) { + // AuthorPriority(tree_order, cascade_order) + EXPECT_GE(AuthorPriority(0, 0), AuthorPriority(0, 0)); + EXPECT_GE(AuthorPriority(0, 1), AuthorPriority(0, 1)); + EXPECT_GE(AuthorPriority(0, 1), AuthorPriority(0, 0)); + EXPECT_GE(AuthorPriority(0, 2), AuthorPriority(0, 1)); + EXPECT_GE(AuthorPriority(0, 0xFFFF), AuthorPriority(0, 0xFFFE)); + EXPECT_FALSE(AuthorPriority(0, 2) >= AuthorPriority(0, 3)); +} + +TEST_F(StyleCascadeTest, PriorityCascadeOrderAndTreeOrder) { + // AuthorPriority(tree_order, cascade_order) + EXPECT_GE(AuthorPriority(0, 0), AuthorPriority(1, 0)); + EXPECT_GE(AuthorPriority(0, 1), AuthorPriority(1, 1)); + EXPECT_GE(AuthorPriority(0, 1), AuthorPriority(1, 3)); + EXPECT_GE(AuthorPriority(0, 2), AuthorPriority(1, 0xFFFE)); +} + +TEST_F(StyleCascadeTest, PriorityCascadeOrderAndOrigin) { + // [Important]AuthorPriority(tree_order, cascade_order) + EXPECT_GE(ImportantAuthorPriority(0, 0), AuthorPriority(0, 0)); + EXPECT_GE(ImportantAuthorPriority(0, 1), AuthorPriority(0, 1)); + EXPECT_GE(ImportantAuthorPriority(0, 1), AuthorPriority(0, 3)); + EXPECT_GE(ImportantAuthorPriority(0, 2), AuthorPriority(0, 0xFFFE)); +} + +TEST_F(StyleCascadeTest, ApplySingle) { + TestCascade cascade(GetDocument()); + cascade.Add("width", "2px", Origin::kAuthor); + cascade.Add("width", "1px", Origin::kUser); + cascade.Apply("width"); + + EXPECT_EQ("2px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, ApplyCustomProperty) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", " 10px "); + cascade.Add("--y", "nope"); + cascade.Apply("--x"); + cascade.Apply("--y"); + + EXPECT_EQ(" 10px ", cascade.ComputedValue("--x")); + EXPECT_EQ("nope", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, Copy) { + StyleResolverState state(GetDocument(), *GetDocument().body(), nullptr); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "10px"); + cascade.Add("width", "20px"); + + // Take snapshot of the cascade, pointing to the same StyleResolverState. + StyleCascade snapshot(cascade.InnerCascade()); + + cascade.Add("--x", "0px"); + cascade.Add("width", "1px"); + cascade.Apply(); + + EXPECT_EQ("0px", cascade.ComputedValue("--x")); + EXPECT_EQ("1px", cascade.ComputedValue("width")); + + snapshot.Apply(); + EXPECT_EQ("10px", cascade.ComputedValue("--x")); + EXPECT_EQ("20px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, ApplyCustomPropertyVar) { + // Apply --x first. + { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "yes and var(--y)"); + cascade.Add("--y", "no"); + cascade.Apply("--x"); + cascade.Apply("--y"); + + EXPECT_EQ("yes and no", cascade.ComputedValue("--x")); + EXPECT_EQ("no", cascade.ComputedValue("--y")); + } + + // Apply --y first. + { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "yes and var(--y)"); + cascade.Add("--y", "no"); + cascade.Apply("--y"); + cascade.Apply("--x"); + + EXPECT_EQ("yes and no", cascade.ComputedValue("--x")); + EXPECT_EQ("no", cascade.ComputedValue("--y")); + } +} + +TEST_F(StyleCascadeTest, InvalidVarReferenceCauseInvalidVariable) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "nope var(--y)"); + cascade.Apply("--x"); + + EXPECT_EQ(g_null_atom, cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, ApplyCustomPropertyFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "yes and var(--y,no)"); + cascade.Apply("--x"); + + EXPECT_EQ("yes and no", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, RegisteredPropertyFallback) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "var(--y,10px)"); + cascade.Apply(); + + EXPECT_EQ("10px", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, RegisteredPropertyFallbackValidation) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "10px"); + cascade.Add("--y", "var(--x,red)"); // Fallback must be valid <length>. + cascade.Add("--z", "var(--y,pass)"); + cascade.Apply(); + + EXPECT_EQ("pass", cascade.ComputedValue("--z")); +} + +TEST_F(StyleCascadeTest, VarInFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "one var(--z,two var(--y))"); + cascade.Add("--y", "three"); + cascade.Apply("--x"); + + EXPECT_EQ("one two three", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, VarReferenceInNormalProperty) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "10px"); + cascade.Add("width", "var(--x)"); + cascade.Apply("width"); + + EXPECT_EQ("10px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, MultipleVarRefs) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "var(--y) bar var(--y)"); + cascade.Add("--y", "foo"); + cascade.Apply("--x"); + + EXPECT_EQ("foo bar foo", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, RegisteredPropertyComputedValue) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "1in"); + cascade.Apply("--x"); + + EXPECT_EQ("96px", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, RegisteredPropertySyntaxErrorCausesInitial) { + RegisterProperty(GetDocument(), "--x", "<length>", "10px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "#fefefe"); + cascade.Add("--y", "var(--x)"); + cascade.Apply("--x"); + cascade.Apply("--y"); + + EXPECT_EQ("10px", cascade.ComputedValue("--x")); + EXPECT_EQ("10px", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, RegisteredPropertySubstitution) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "1in"); + cascade.Add("--y", "var(--x)"); + cascade.Apply("--y"); + + EXPECT_EQ("96px", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, RegisteredPropertyChain) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + RegisterProperty(GetDocument(), "--z", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "1in"); + cascade.Add("--y", "var(--x)"); + cascade.Add("--z", "calc(var(--y) + 1in)"); + cascade.Apply(); + + EXPECT_EQ("96px", cascade.ComputedValue("--x")); + EXPECT_EQ("96px", cascade.ComputedValue("--y")); + EXPECT_EQ("192px", cascade.ComputedValue("--z")); +} + +TEST_F(StyleCascadeTest, BasicShorthand) { + TestCascade cascade(GetDocument()); + cascade.Add("margin", "1px 2px 3px 4px"); + cascade.Apply(); + + EXPECT_EQ("1px", cascade.ComputedValue("margin-top")); + EXPECT_EQ("2px", cascade.ComputedValue("margin-right")); + EXPECT_EQ("3px", cascade.ComputedValue("margin-bottom")); + EXPECT_EQ("4px", cascade.ComputedValue("margin-left")); +} + +TEST_F(StyleCascadeTest, BasicVarShorthand) { + TestCascade cascade(GetDocument()); + cascade.Add("margin", "1px var(--x) 3px 4px"); + cascade.Add("--x", "2px"); + cascade.Apply(); + + EXPECT_EQ("1px", cascade.ComputedValue("margin-top")); + EXPECT_EQ("2px", cascade.ComputedValue("margin-right")); + EXPECT_EQ("3px", cascade.ComputedValue("margin-bottom")); + EXPECT_EQ("4px", cascade.ComputedValue("margin-left")); +} + +TEST_F(StyleCascadeTest, ApplyingPendingSubstitutionFirst) { + TestCascade cascade(GetDocument()); + cascade.Add("margin", "1px var(--x) 3px 4px"); + cascade.Add("--x", "2px"); + cascade.Add("margin-right", "5px"); + + // Apply one of the pending substitution values first. This should not + // overwrite margin-right's 5px. + cascade.Apply("margin-left"); + cascade.Apply(); + + EXPECT_EQ("1px", cascade.ComputedValue("margin-top")); + EXPECT_EQ("5px", cascade.ComputedValue("margin-right")); + EXPECT_EQ("3px", cascade.ComputedValue("margin-bottom")); + EXPECT_EQ("4px", cascade.ComputedValue("margin-left")); +} + +TEST_F(StyleCascadeTest, ApplyingPendingSubstitutionLast) { + TestCascade cascade(GetDocument()); + cascade.Add("margin", "1px var(--x) 3px 4px"); + cascade.Add("--x", "2px"); + cascade.Add("margin-right", "5px"); + + // Apply margin-right before the others. Applying the pending substitution + // afterwards should not overwrite margin-right's 5px. + cascade.Apply("margin-right"); + cascade.Apply(); + + EXPECT_EQ("1px", cascade.ComputedValue("margin-top")); + EXPECT_EQ("5px", cascade.ComputedValue("margin-right")); + EXPECT_EQ("3px", cascade.ComputedValue("margin-bottom")); + EXPECT_EQ("4px", cascade.ComputedValue("margin-left")); +} + +TEST_F(StyleCascadeTest, ApplyingPendingSubstitutionModifiesCascade) { + TestCascade cascade(GetDocument()); + cascade.Add("margin", "1px var(--x) 3px 4px"); + cascade.Add("--x", "2px"); + cascade.Add("margin-right", "5px"); + + // We expect the pending substitution value for all the shorthands, + // except margin-right. + EXPECT_EQ("1px var(--x) 3px 4px", cascade.GetValue("margin-top")); + EXPECT_EQ("5px", cascade.GetValue("margin-right")); + EXPECT_EQ("1px var(--x) 3px 4px", cascade.GetValue("margin-bottom")); + EXPECT_EQ("1px var(--x) 3px 4px", cascade.GetValue("margin-left")); + + // Apply a pending substitution value should modify the cascade for other + // longhands with the same pending substitution value. + cascade.Apply("margin-left"); + + EXPECT_EQ("1px", cascade.GetValue("margin-top")); + EXPECT_EQ("5px", cascade.GetValue("margin-right")); + EXPECT_EQ("3px", cascade.GetValue("margin-bottom")); + EXPECT_FALSE(cascade.GetValue("margin-left")); +} + +TEST_F(StyleCascadeTest, ResolverDetectCycle) { + TestCascade cascade(GetDocument()); + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + TestCascadeResolver resolver(GetDocument(), animator); + + { + TestCascadeAutoLock lock(CSSPropertyName("--a"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + TestCascadeAutoLock lock(CSSPropertyName("--b"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + TestCascadeAutoLock lock(CSSPropertyName("--c"), resolver); + EXPECT_FALSE(resolver.InCycle()); + + EXPECT_TRUE(resolver.DetectCycle("--a")); + EXPECT_TRUE(resolver.InCycle()); + } + EXPECT_TRUE(resolver.InCycle()); + } + EXPECT_TRUE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); +} + +TEST_F(StyleCascadeTest, ResolverDetectNoCycle) { + TestCascade cascade(GetDocument()); + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + TestCascadeResolver resolver(GetDocument(), animator); + + { + TestCascadeAutoLock lock(CSSPropertyName("--a"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + TestCascadeAutoLock lock(CSSPropertyName("--b"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + TestCascadeAutoLock lock(CSSPropertyName("--c"), resolver); + EXPECT_FALSE(resolver.InCycle()); + + EXPECT_FALSE(resolver.DetectCycle("--x")); + EXPECT_FALSE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); +} + +TEST_F(StyleCascadeTest, ResolverDetectCycleSelf) { + TestCascade cascade(GetDocument()); + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + TestCascadeResolver resolver(GetDocument(), animator); + + { + TestCascadeAutoLock lock(CSSPropertyName("--a"), resolver); + EXPECT_FALSE(resolver.InCycle()); + + EXPECT_TRUE(resolver.DetectCycle("--a")); + EXPECT_TRUE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); +} + +TEST_F(StyleCascadeTest, ResolverDetectMultiCycle) { + using AutoLock = TestCascadeAutoLock; + + TestCascade cascade(GetDocument()); + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + TestCascadeResolver resolver(GetDocument(), animator); + + { + AutoLock lock(CSSPropertyName("--a"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + AutoLock lock(CSSPropertyName("--b"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + AutoLock lock(CSSPropertyName("--c"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + AutoLock lock(CSSPropertyName("--d"), resolver); + EXPECT_FALSE(resolver.InCycle()); + + // Cycle 1 (big cycle): + EXPECT_TRUE(resolver.DetectCycle("--b")); + EXPECT_TRUE(resolver.InCycle()); + EXPECT_EQ(1u, resolver.CycleDepth()); + + // Cycle 2 (small cycle): + EXPECT_TRUE(resolver.DetectCycle("--c")); + EXPECT_TRUE(resolver.InCycle()); + EXPECT_EQ(1u, resolver.CycleDepth()); + } + } + EXPECT_TRUE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); +} + +TEST_F(StyleCascadeTest, ResolverDetectMultiCycleReverse) { + using AutoLock = TestCascadeAutoLock; + + TestCascade cascade(GetDocument()); + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + TestCascadeResolver resolver(GetDocument(), animator); + + { + AutoLock lock(CSSPropertyName("--a"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + AutoLock lock(CSSPropertyName("--b"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + AutoLock lock(CSSPropertyName("--c"), resolver); + EXPECT_FALSE(resolver.InCycle()); + { + AutoLock lock(CSSPropertyName("--d"), resolver); + EXPECT_FALSE(resolver.InCycle()); + + // Cycle 1 (small cycle): + EXPECT_TRUE(resolver.DetectCycle("--c")); + EXPECT_TRUE(resolver.InCycle()); + EXPECT_EQ(2u, resolver.CycleDepth()); + + // Cycle 2 (big cycle): + EXPECT_TRUE(resolver.DetectCycle("--b")); + EXPECT_TRUE(resolver.InCycle()); + EXPECT_EQ(1u, resolver.CycleDepth()); + } + } + EXPECT_TRUE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); + } + EXPECT_FALSE(resolver.InCycle()); +} + +TEST_F(StyleCascadeTest, BasicCycle) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "foo"); + cascade.Add("--b", "bar"); + cascade.Apply(); + + EXPECT_EQ("foo", cascade.ComputedValue("--a")); + EXPECT_EQ("bar", cascade.ComputedValue("--b")); + + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--a)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); +} + +TEST_F(StyleCascadeTest, SelfCycle) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "foo"); + cascade.Apply(); + + EXPECT_EQ("foo", cascade.ComputedValue("--a")); + + cascade.Add("--a", "var(--a)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); +} + +TEST_F(StyleCascadeTest, SelfCycleInFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--x, var(--a))"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); +} + +TEST_F(StyleCascadeTest, SelfCycleInUnusedFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b, var(--a))"); + cascade.Add("--b", "10px"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_EQ("10px", cascade.ComputedValue("--b")); +} + +TEST_F(StyleCascadeTest, LongCycle) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--c)"); + cascade.Add("--c", "var(--d)"); + cascade.Add("--d", "var(--e)"); + cascade.Add("--e", "var(--a)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_FALSE(cascade.ComputedValue("--c")); + EXPECT_FALSE(cascade.ComputedValue("--d")); + EXPECT_FALSE(cascade.ComputedValue("--e")); +} + +TEST_F(StyleCascadeTest, PartialCycle) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--a)"); + cascade.Add("--c", "bar var(--d) var(--a)"); + cascade.Add("--d", "foo"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_FALSE(cascade.ComputedValue("--c")); + EXPECT_EQ("foo", cascade.ComputedValue("--d")); +} + +TEST_F(StyleCascadeTest, VarCycleViaFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--x, var(--a))"); + cascade.Add("--c", "var(--a)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_FALSE(cascade.ComputedValue("--c")); +} + +TEST_F(StyleCascadeTest, FallbackTriggeredByCycle) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--a)"); + cascade.Add("--c", "var(--a,foo)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_EQ("foo", cascade.ComputedValue("--c")); +} + +TEST_F(StyleCascadeTest, RegisteredCycle) { + RegisterProperty(GetDocument(), "--a", "<length>", "0px", false); + RegisterProperty(GetDocument(), "--b", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--a)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); +} + +TEST_F(StyleCascadeTest, PartiallyRegisteredCycle) { + RegisterProperty(GetDocument(), "--a", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--a)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); +} + +TEST_F(StyleCascadeTest, FallbackTriggeredByRegisteredCycle) { + RegisterProperty(GetDocument(), "--a", "<length>", "0px", false); + RegisterProperty(GetDocument(), "--b", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + // Cycle: + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--a)"); + // References to cycle: + cascade.Add("--c", "var(--a,1px)"); + cascade.Add("--d", "var(--b,2px)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_EQ("1px", cascade.ComputedValue("--c")); + EXPECT_EQ("2px", cascade.ComputedValue("--d")); +} + +TEST_F(StyleCascadeTest, CycleStillInvalidWithFallback) { + TestCascade cascade(GetDocument()); + // Cycle: + cascade.Add("--a", "var(--b,red)"); + cascade.Add("--b", "var(--a,red)"); + // References to cycle: + cascade.Add("--c", "var(--a,green)"); + cascade.Add("--d", "var(--b,green)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_EQ("green", cascade.ComputedValue("--c")); + EXPECT_EQ("green", cascade.ComputedValue("--d")); +} + +TEST_F(StyleCascadeTest, CycleInFallbackStillInvalid) { + TestCascade cascade(GetDocument()); + // Cycle: + cascade.Add("--a", "var(--b,red)"); + cascade.Add("--b", "var(--x,var(--a))"); + // References to cycle: + cascade.Add("--c", "var(--a,green)"); + cascade.Add("--d", "var(--b,green)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_EQ("green", cascade.ComputedValue("--c")); + EXPECT_EQ("green", cascade.ComputedValue("--d")); +} + +TEST_F(StyleCascadeTest, CycleMultiple) { + TestCascade cascade(GetDocument()); + // Cycle: + cascade.Add("--a", "var(--c, red)"); + cascade.Add("--b", "var(--c, red)"); + cascade.Add("--c", "var(--a, blue) var(--b, blue)"); + // References to cycle: + cascade.Add("--d", "var(--a,green)"); + cascade.Add("--e", "var(--b,green)"); + cascade.Add("--f", "var(--c,green)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_FALSE(cascade.ComputedValue("--c")); + EXPECT_EQ("green", cascade.ComputedValue("--d")); + EXPECT_EQ("green", cascade.ComputedValue("--e")); + EXPECT_EQ("green", cascade.ComputedValue("--f")); +} + +TEST_F(StyleCascadeTest, CycleMultipleFallback) { + TestCascade cascade(GetDocument()); + // Cycle: + cascade.Add("--a", "var(--b, red)"); + cascade.Add("--b", "var(--a, var(--c, red))"); + cascade.Add("--c", "var(--b, red)"); + // References to cycle: + cascade.Add("--d", "var(--a,green)"); + cascade.Add("--e", "var(--b,green)"); + cascade.Add("--f", "var(--c,green)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_FALSE(cascade.ComputedValue("--c")); + EXPECT_EQ("green", cascade.ComputedValue("--d")); + EXPECT_EQ("green", cascade.ComputedValue("--e")); + EXPECT_EQ("green", cascade.ComputedValue("--f")); +} + +TEST_F(StyleCascadeTest, CycleMultipleUnusedFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "red"); + // Cycle: + cascade.Add("--b", "var(--c, red)"); + cascade.Add("--c", "var(--a, var(--b, red) var(--d, red))"); + cascade.Add("--d", "var(--c, red)"); + // References to cycle: + cascade.Add("--e", "var(--b,green)"); + cascade.Add("--f", "var(--c,green)"); + cascade.Add("--g", "var(--d,green)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_FALSE(cascade.ComputedValue("--c")); + EXPECT_FALSE(cascade.ComputedValue("--d")); + EXPECT_EQ("green", cascade.ComputedValue("--e")); + EXPECT_EQ("green", cascade.ComputedValue("--f")); + EXPECT_EQ("green", cascade.ComputedValue("--g")); +} + +TEST_F(StyleCascadeTest, CycleReferencedFromStandardProperty) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--a)"); + cascade.Add("color", "var(--a,green)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_EQ("rgb(0, 128, 0)", cascade.ComputedValue("color")); +} + +TEST_F(StyleCascadeTest, CycleReferencedFromShorthand) { + TestCascade cascade(GetDocument()); + cascade.Add("--a", "var(--b)"); + cascade.Add("--b", "var(--a)"); + cascade.Add("background", "var(--a,green)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--a")); + EXPECT_FALSE(cascade.ComputedValue("--b")); + EXPECT_EQ("rgb(0, 128, 0)", cascade.ComputedValue("background-color")); +} + +TEST_F(StyleCascadeTest, EmUnit) { + TestCascade cascade(GetDocument()); + cascade.Add("font-size", "10px"); + cascade.Add("width", "10em"); + cascade.Apply(); + + EXPECT_EQ("100px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, EmUnitCustomProperty) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("font-size", "10px"); + cascade.Add("--x", "10em"); + cascade.Apply(); + + EXPECT_EQ("100px", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, EmUnitNonCycle) { + TestCascade parent(GetDocument()); + parent.Add("font-size", "10px"); + parent.Apply(); + + TestCascade cascade(GetDocument()); + cascade.InheritFrom(parent.TakeStyle()); + cascade.Add("font-size", "var(--x)"); + cascade.Add("--x", "10em"); + cascade.Apply(); + + // Note: Only registered properties can have cycles with font-size. + EXPECT_EQ("100px", cascade.ComputedValue("font-size")); +} + +TEST_F(StyleCascadeTest, EmUnitCycle) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("font-size", "var(--x)"); + cascade.Add("--x", "10em"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, SubstitutingEmCycles) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("font-size", "var(--x)"); + cascade.Add("--x", "10em"); + cascade.Add("--y", "var(--x)"); + cascade.Add("--z", "var(--x,1px)"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--y")); + EXPECT_EQ("1px", cascade.ComputedValue("--z")); +} + +TEST_F(StyleCascadeTest, RemUnit) { + SetRootFont("10px"); + UpdateAllLifecyclePhasesForTest(); + + TestCascade cascade(GetDocument()); + cascade.Add("width", "10rem"); + cascade.Apply(); + + EXPECT_EQ("100px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, RemUnitCustomProperty) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + SetRootFont("10px"); + UpdateAllLifecyclePhasesForTest(); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "10rem"); + cascade.Apply(); + + EXPECT_EQ("100px", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, RemUnitInFontSize) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + SetRootFont("10px"); + UpdateAllLifecyclePhasesForTest(); + + TestCascade cascade(GetDocument()); + cascade.Add("font-size", "1rem"); + cascade.Add("--x", "10rem"); + cascade.Apply(); + + EXPECT_EQ("100px", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, RemUnitInRootFontSizeCycle) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument(), DocumentElement()); + cascade.Add("font-size", "var(--x)"); + cascade.Add("--x", "1rem"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, RemUnitInRootFontSizeNonCycle) { + TestCascade cascade(GetDocument(), DocumentElement()); + cascade.Add("font-size", "initial"); + cascade.Apply(); + + String expected = cascade.ComputedValue("font-size"); + + cascade.Add("font-size", "var(--x)"); + cascade.Add("--x", "1rem"); + cascade.Apply(); + + // Note: Only registered properties can have cycles with font-size. + EXPECT_EQ("1rem", cascade.ComputedValue("--x")); + EXPECT_EQ(expected, cascade.ComputedValue("font-size")); +} + +TEST_F(StyleCascadeTest, Initial) { + TestCascade parent(GetDocument()); + parent.Add("--x", "foo"); + parent.Apply(); + + TestCascade cascade(GetDocument()); + cascade.InheritFrom(parent.TakeStyle()); + cascade.Add("--y", "foo"); + cascade.Apply(); + + EXPECT_EQ("foo", cascade.ComputedValue("--x")); + EXPECT_EQ("foo", cascade.ComputedValue("--y")); + + cascade.Add("--x", "initial"); + cascade.Add("--y", "initial"); + cascade.Apply(); + + EXPECT_FALSE(cascade.ComputedValue("--x")); + EXPECT_FALSE(cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, Inherit) { + TestCascade parent(GetDocument()); + parent.Add("--x", "foo"); + parent.Apply(); + + TestCascade cascade(GetDocument()); + cascade.InheritFrom(parent.TakeStyle()); + + EXPECT_EQ("foo", cascade.ComputedValue("--x")); + + cascade.Add("--x", "bar"); + cascade.Apply(); + EXPECT_EQ("bar", cascade.ComputedValue("--x")); + + cascade.Add("--x", "inherit"); + cascade.Apply(); + EXPECT_EQ("foo", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, Unset) { + TestCascade parent(GetDocument()); + parent.Add("--x", "foo"); + parent.Apply(); + + TestCascade cascade(GetDocument()); + cascade.InheritFrom(parent.TakeStyle()); + EXPECT_EQ("foo", cascade.ComputedValue("--x")); + + cascade.Add("--x", "bar"); + cascade.Apply(); + EXPECT_EQ("bar", cascade.ComputedValue("--x")); + + cascade.Add("--x", "unset"); + cascade.Apply(); + EXPECT_EQ("foo", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, RegisteredInitial) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Apply(); + EXPECT_EQ("0px", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, SubstituteRegisteredImplicitInitialValue) { + RegisterProperty(GetDocument(), "--x", "<length>", "13px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--y", " var(--x) "); + cascade.Apply(); + EXPECT_EQ("13px", cascade.ComputedValue("--x")); + EXPECT_EQ(" 13px ", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, SubstituteRegisteredUniversal) { + RegisterProperty(GetDocument(), "--x", "*", "foo", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "bar"); + cascade.Add("--y", "var(--x)"); + cascade.Apply(); + EXPECT_EQ("bar", cascade.ComputedValue("--x")); + EXPECT_EQ("bar", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, SubstituteRegisteredUniversalInvalid) { + RegisterProperty(GetDocument(), "--x", "*", g_null_atom, false); + + TestCascade cascade(GetDocument()); + cascade.Add("--y", " var(--x) "); + cascade.Apply(); + EXPECT_FALSE(cascade.ComputedValue("--x")); + EXPECT_FALSE(cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, SubstituteRegisteredUniversalInitial) { + RegisterProperty(GetDocument(), "--x", "*", "foo", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--y", " var(--x) "); + cascade.Apply(); + EXPECT_EQ("foo", cascade.ComputedValue("--x")); + EXPECT_EQ(" foo ", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, RegisteredExplicitInitial) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "10px"); + cascade.Apply(); + EXPECT_EQ("10px", cascade.ComputedValue("--x")); + + cascade.Add("--x", "initial"); + cascade.Add("--y", "var(--x)"); + cascade.Apply(); + EXPECT_EQ("0px", cascade.ComputedValue("--x")); + EXPECT_EQ("0px", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, RegisteredExplicitInherit) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade parent(GetDocument()); + parent.Add("--x", "15px"); + parent.Apply(); + EXPECT_EQ("15px", parent.ComputedValue("--x")); + + TestCascade cascade(GetDocument()); + cascade.InheritFrom(parent.TakeStyle()); + cascade.Apply(); + EXPECT_EQ("0px", cascade.ComputedValue("--x")); // Note: inherit==false + + cascade.Add("--x", "inherit"); + cascade.Add("--y", "var(--x)"); + cascade.Apply(); + EXPECT_EQ("15px", cascade.ComputedValue("--x")); + EXPECT_EQ("15px", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, RegisteredExplicitUnset) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + RegisterProperty(GetDocument(), "--y", "<length>", "0px", true); + + TestCascade parent(GetDocument()); + parent.Add("--x", "15px"); + parent.Add("--y", "15px"); + parent.Apply(); + EXPECT_EQ("15px", parent.ComputedValue("--x")); + EXPECT_EQ("15px", parent.ComputedValue("--y")); + + TestCascade cascade(GetDocument()); + cascade.InheritFrom(parent.TakeStyle()); + cascade.Add("--x", "2px"); + cascade.Add("--y", "2px"); + cascade.Apply(); + EXPECT_EQ("2px", cascade.ComputedValue("--x")); + EXPECT_EQ("2px", cascade.ComputedValue("--y")); + + cascade.Add("--x", "unset"); + cascade.Add("--y", "unset"); + cascade.Add("--z", "var(--x) var(--y)"); + cascade.Apply(); + EXPECT_EQ("0px", cascade.ComputedValue("--x")); + EXPECT_EQ("15px", cascade.ComputedValue("--y")); + EXPECT_EQ("0px 15px", cascade.ComputedValue("--z")); +} + +TEST_F(StyleCascadeTest, SubstituteAnimationTaintedInCustomProperty) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "15px", Origin::kAuthor, AnimationTainted::kYes); + cascade.Add("--y", "var(--x)"); + cascade.Apply(); + EXPECT_EQ("15px", cascade.ComputedValue("--x")); + EXPECT_EQ("15px", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, SubstituteAnimationTaintedInStandardProperty) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "15px", Origin::kAuthor, AnimationTainted::kYes); + cascade.Add("width", "var(--x)"); + cascade.Apply(); + EXPECT_EQ("15px", cascade.ComputedValue("--x")); + EXPECT_EQ("15px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, SubstituteAnimationTaintedInAnimationProperty) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "20s"); + cascade.Add("animation-duration", "var(--x)"); + cascade.Apply(); + + EXPECT_EQ("20s", cascade.ComputedValue("--x")); + EXPECT_EQ("20s", cascade.ComputedValue("animation-duration")); + + cascade.Add("--y", "20s", Origin::kAuthor, AnimationTainted::kYes); + cascade.Add("animation-duration", "var(--y)"); + cascade.Apply(); + + EXPECT_EQ("20s", cascade.ComputedValue("--y")); + EXPECT_EQ("0s", cascade.ComputedValue("animation-duration")); +} + +TEST_F(StyleCascadeTest, IndirectlyAnimationTainted) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "20s", Origin::kAuthor, AnimationTainted::kYes); + cascade.Add("--y", "var(--x)"); + cascade.Add("animation-duration", "var(--y)"); + cascade.Apply(); + + EXPECT_EQ("20s", cascade.ComputedValue("--x")); + EXPECT_EQ("20s", cascade.ComputedValue("--y")); + EXPECT_EQ("0s", cascade.ComputedValue("animation-duration")); +} + +TEST_F(StyleCascadeTest, AnimationTaintedFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "20s", Origin::kAuthor, AnimationTainted::kYes); + cascade.Add("animation-duration", "var(--x,1s)"); + cascade.Apply(); + + EXPECT_EQ("20s", cascade.ComputedValue("--x")); + EXPECT_EQ("1s", cascade.ComputedValue("animation-duration")); +} + +TEST_F(StyleCascadeTest, EnvMissingNestedVar) { + TestCascade cascade(GetDocument()); + cascade.Add("--x", "rgb(0, 0, 0)"); + cascade.Add("background-color", "env(missing, var(--x))"); + cascade.Apply(); + + EXPECT_EQ("rgb(0, 0, 0)", cascade.ComputedValue("--x")); + EXPECT_EQ("rgb(0, 0, 0)", cascade.ComputedValue("background-color")); +} + +TEST_F(StyleCascadeTest, EnvMissingNestedVarFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("background-color", "env(missing, var(--missing, blue))"); + cascade.Apply(); + + EXPECT_EQ("rgb(0, 0, 255)", cascade.ComputedValue("background-color")); +} + +TEST_F(StyleCascadeTest, EnvMissingFallback) { + TestCascade cascade(GetDocument()); + cascade.Add("background-color", "env(missing, blue)"); + cascade.Apply(); + + EXPECT_EQ("rgb(0, 0, 255)", cascade.ComputedValue("background-color")); +} + +TEST_F(StyleCascadeTest, ValidEnv) { + AutoEnv env(*this, "test", "red"); + + TestCascade cascade(GetDocument()); + cascade.Add("background-color", "env(test, blue)"); + cascade.Apply(); + + EXPECT_EQ("rgb(255, 0, 0)", cascade.ComputedValue("background-color")); +} + +TEST_F(StyleCascadeTest, ValidEnvFallback) { + AutoEnv env(*this, "test", "red"); + + TestCascade cascade(GetDocument()); + cascade.Add("background-color", "env(test, blue)"); + cascade.Apply(); + + EXPECT_EQ("rgb(255, 0, 0)", cascade.ComputedValue("background-color")); +} + +TEST_F(StyleCascadeTest, ValidEnvInUnusedFallback) { + AutoEnv env(*this, "test", "red"); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "rgb(0, 0, 0)"); + cascade.Add("background-color", "var(--x, env(test))"); + cascade.Apply(); + + EXPECT_EQ("rgb(0, 0, 0)", cascade.ComputedValue("--x")); + EXPECT_EQ("rgb(0, 0, 0)", cascade.ComputedValue("background-color")); +} + +TEST_F(StyleCascadeTest, ValidEnvInUsedFallback) { + AutoEnv env(*this, "test", "red"); + + TestCascade cascade(GetDocument()); + cascade.Add("background-color", "var(--missing, env(test))"); + cascade.Apply(); + + EXPECT_EQ("rgb(255, 0, 0)", cascade.ComputedValue("background-color")); +} + +// An Animator that just records the name of all the properties +// applied. +class RecordingAnimator : public StyleCascade::Animator { + public: + void Apply(const CSSProperty& property, + const cssvalue::CSSPendingInterpolationValue&, + StyleCascade::Resolver& resolver) override { + record.push_back(property.GetCSSPropertyName()); + } + + Vector<CSSPropertyName> record; +}; + +TEST_F(StyleCascadeTest, AnimatorCalledByPendingInterpolationValue) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + RecordingAnimator animator; + + using Type = CSSPendingInterpolationValue::Type; + TestCascade cascade(GetDocument()); + cascade.Add("--x", CSSPendingInterpolationValue::Create(Type::kCSSProperty)); + cascade.Add("--y", CSSPendingInterpolationValue::Create(Type::kCSSProperty)); + + cascade.Apply(animator); + + EXPECT_TRUE(animator.record.Contains(*CSSPropertyName::From("--x"))); + EXPECT_TRUE(animator.record.Contains(*CSSPropertyName::From("--y"))); +} + +TEST_F(StyleCascadeTest, PendingKeyframeAnimation) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + AppendSheet(R"HTML( + @keyframes test { + from { --x: 10px; } + to { --x: 20px; } + } + )HTML"); + + TestCascade cascade(GetDocument()); + + cascade.Add("animation-name", "test"); + cascade.Add("animation-duration", "1s"); + cascade.Apply(); + + cascade.AddAnimations(); + + EXPECT_EQ("<interpolation>", cascade.GetValue("--x")); +} + +TEST_F(StyleCascadeTest, PendingKeyframeAnimationApply) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + AppendSheet(R"HTML( + @keyframes test { + from { --x: 10px; } + to { --x: 20px; } + } + )HTML"); + + TestCascade cascade(GetDocument()); + + cascade.Add("animation-name", "test"); + cascade.Add("animation-duration", "10s"); + cascade.Add("animation-timing-function", "linear"); + cascade.Add("animation-delay", "-5s"); + cascade.Apply(); + + cascade.AddAnimations(); + + EXPECT_EQ("<interpolation>", cascade.GetValue("--x")); + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + cascade.Apply(animator); + EXPECT_EQ("15px", cascade.ComputedValue("--x")); +} + +TEST_F(StyleCascadeTest, TransitionCausesInterpolationValue) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + // First, simulate an "old style". + TestCascade cascade1(GetDocument()); + cascade1.Add("--x", "10px"); + cascade1.Add("transition", "--x 1s"); + cascade1.Apply(); + + // Set the old style on the element, so that the animation + // update detects it. + GetDocument().body()->SetComputedStyle(cascade1.TakeStyle()); + + // Now simulate a new style, with a new value for --x. + TestCascade cascade2(GetDocument()); + cascade2.Add("--x", "20px"); + cascade2.Add("transition", "--x 1s"); + cascade2.Apply(); + + // Detects transitions, and adds CSSPendingInterpolationValues + // to the cascade, as appropriate. + cascade2.AddTransitions(); + + EXPECT_EQ("<interpolation>", cascade2.GetValue("--x")); +} + +TEST_F(StyleCascadeTest, TransitionDetectedForChangedFontSize) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + TestCascade cascade1(GetDocument()); + cascade1.Add("font-size", "10px"); + cascade1.Add("--x", "10em"); + cascade1.Add("width", "10em"); + cascade1.Add("height", "10px"); + cascade1.Add("transition", "--x 1s, width 1s"); + cascade1.Apply(); + + GetDocument().body()->SetComputedStyle(cascade1.TakeStyle()); + + TestCascade cascade2(GetDocument()); + cascade2.Add("font-size", "20px"); + cascade2.Add("--x", "10em"); + cascade2.Add("width", "10em"); + cascade2.Add("height", "10px"); + cascade2.Add("transition", "--x 1s, width 1s"); + cascade2.Apply(); + + cascade2.AddTransitions(); + + EXPECT_EQ("<interpolation>", cascade2.GetValue("--x")); + EXPECT_EQ("<interpolation>", cascade2.GetValue("width")); + EXPECT_EQ("10px", cascade2.ComputedValue("height")); +} + +TEST_F(StyleCascadeTest, AnimatingVarReferences) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + AppendSheet(R"HTML( + @keyframes test { + from { --x: var(--from); } + to { --x: var(--to); } + } + )HTML"); + + TestCascade cascade(GetDocument()); + + cascade.Add("animation-name", "test"); + cascade.Add("animation-duration", "10s"); + cascade.Add("animation-timing-function", "linear"); + cascade.Add("animation-delay", "-5s"); + cascade.Apply(); + + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + + cascade.AddAnimations(); + cascade.Add("--from", "10px"); + cascade.Add("--to", "20px"); + cascade.Add("--y", "var(--x)"); + cascade.Apply(animator); + + EXPECT_EQ("15px", cascade.ComputedValue("--x")); + EXPECT_EQ("15px", cascade.ComputedValue("--y")); +} + +TEST_F(StyleCascadeTest, AnimateStandardProperty) { + AppendSheet(R"HTML( + @keyframes test { + from { width: 10px; } + to { width: 20px; } + } + )HTML"); + + TestCascade cascade(GetDocument()); + + cascade.Add("animation-name", "test"); + cascade.Add("animation-duration", "10s"); + cascade.Add("animation-timing-function", "linear"); + cascade.Add("animation-delay", "-5s"); + cascade.Apply(); + + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + + cascade.AddAnimations(); + EXPECT_EQ("<interpolation>", cascade.GetValue("width")); + + cascade.Apply(animator); + EXPECT_EQ("15px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, EmRespondsToAnimatedFontSize) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + AppendSheet(R"HTML( + @keyframes test { + from { font-size: 10px; } + to { font-size: 20px; } + } + )HTML"); + + TestCascade cascade(GetDocument()); + + cascade.Add("animation-name", "test"); + cascade.Add("animation-duration", "10s"); + cascade.Add("animation-timing-function", "linear"); + cascade.Add("animation-delay", "-5s"); + cascade.Apply(); + + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + + cascade.AddAnimations(); + cascade.Add("--x", "2em"); + cascade.Add("width", "10em"); + + cascade.Apply(animator); + EXPECT_EQ("30px", cascade.ComputedValue("--x")); + EXPECT_EQ("150px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, AnimateStandardPropertyWithVar) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + AppendSheet(R"HTML( + @keyframes test { + from { width: var(--from); } + to { width: var(--to); } + } + )HTML"); + + TestCascade cascade(GetDocument()); + + cascade.Add("animation-name", "test"); + cascade.Add("animation-duration", "10s"); + cascade.Add("animation-timing-function", "linear"); + cascade.Add("animation-delay", "-5s"); + cascade.Apply(); + + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + + cascade.AddAnimations(); + cascade.Add("--from", "10px"); + cascade.Add("--to", "20px"); + + cascade.Apply(animator); + EXPECT_EQ("15px", cascade.ComputedValue("width")); +} + +TEST_F(StyleCascadeTest, AnimateStandardShorthand) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + AppendSheet(R"HTML( + @keyframes test { + from { margin: 10px; } + to { margin: 20px; } + } + )HTML"); + + TestCascade cascade(GetDocument()); + + cascade.Add("animation-name", "test"); + cascade.Add("animation-duration", "10s"); + cascade.Add("animation-timing-function", "linear"); + cascade.Add("animation-delay", "-5s"); + cascade.Apply(); + + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + + cascade.AddAnimations(); + EXPECT_EQ("<interpolation>", cascade.GetValue("margin-top")); + EXPECT_EQ("<interpolation>", cascade.GetValue("margin-right")); + EXPECT_EQ("<interpolation>", cascade.GetValue("margin-bottom")); + EXPECT_EQ("<interpolation>", cascade.GetValue("margin-left")); + + cascade.Apply(animator); + EXPECT_EQ("15px", cascade.ComputedValue("margin-top")); + EXPECT_EQ("15px", cascade.ComputedValue("margin-right")); + EXPECT_EQ("15px", cascade.ComputedValue("margin-bottom")); + EXPECT_EQ("15px", cascade.ComputedValue("margin-left")); +} + +TEST_F(StyleCascadeTest, AnimatePendingSubstitutionValue) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + + AppendSheet(R"HTML( + @keyframes test { + from { margin: var(--from); } + to { margin: var(--to); } + } + )HTML"); + + TestCascade cascade(GetDocument()); + + cascade.Add("animation-name", "test"); + cascade.Add("animation-duration", "10s"); + cascade.Add("animation-timing-function", "linear"); + cascade.Add("animation-delay", "-5s"); + cascade.Apply(); + + StyleAnimator animator(cascade.State(), cascade.InnerCascade()); + + cascade.AddAnimations(); + cascade.Add("--from", "10px"); + cascade.Add("--to", "20px"); + EXPECT_EQ("<interpolation>", cascade.GetValue("margin-top")); + EXPECT_EQ("<interpolation>", cascade.GetValue("margin-right")); + EXPECT_EQ("<interpolation>", cascade.GetValue("margin-bottom")); + EXPECT_EQ("<interpolation>", cascade.GetValue("margin-left")); + + cascade.Apply(animator); + EXPECT_EQ("15px", cascade.ComputedValue("margin-top")); + EXPECT_EQ("15px", cascade.ComputedValue("margin-right")); + EXPECT_EQ("15px", cascade.ComputedValue("margin-bottom")); + EXPECT_EQ("15px", cascade.ComputedValue("margin-left")); +} + +TEST_F(StyleCascadeTest, ForeignObjectZoomVsEffectiveZoom) { + GetDocument().body()->SetInnerHTMLFromString(R"HTML( + <svg> + <foreignObject id='foreign'></foreignObject> + </svg> + )HTML"); + UpdateAllLifecyclePhasesForTest(); + + Element* foreign_object = GetDocument().getElementById("foreign"); + ASSERT_TRUE(foreign_object); + + TestCascade cascade(GetDocument(), foreign_object); + + cascade.Add("zoom", "200%"); + // TODO(andruud): Can't use CSSPropertyName to get -internal properties + // yet. + cascade.Add(CSSPropertyName(CSSPropertyID::kInternalEffectiveZoom), + "initial"); + cascade.Apply(); + + // If both zoom and -internal-zoom exists in the cascade, + // -internal-effective-zoom should win. + EXPECT_EQ(1.0f, cascade.TakeStyle()->EffectiveZoom()); +} + +TEST_F(StyleCascadeTest, ZoomCascadeOrder) { + CSSPropertyName effective_zoom(CSSPropertyID::kInternalEffectiveZoom); + TestCascade cascade(GetDocument()); + cascade.Add("zoom", "200%"); + cascade.Add(effective_zoom, "initial"); + cascade.Apply(); + + EXPECT_EQ(1.0f, cascade.TakeStyle()->EffectiveZoom()); +} + +TEST_F(StyleCascadeTest, ZoomReversedCascadeOrder) { + CSSPropertyName effective_zoom(CSSPropertyID::kInternalEffectiveZoom); + TestCascade cascade(GetDocument()); + cascade.Add(effective_zoom, "initial"); + cascade.Add("zoom", "200%"); + cascade.Apply(); + + EXPECT_EQ(2.0f, cascade.TakeStyle()->EffectiveZoom()); +} + +TEST_F(StyleCascadeTest, ZoomPriority) { + CSSPropertyName effective_zoom(CSSPropertyID::kInternalEffectiveZoom); + TestCascade cascade(GetDocument()); + cascade.Add("zoom", "200%", Origin::kImportantAuthor); + cascade.Add(effective_zoom, "initial"); + cascade.Apply(); + + EXPECT_EQ(2.0f, cascade.TakeStyle()->EffectiveZoom()); +} + +TEST_F(StyleCascadeTest, WritingModeCascadeOrder) { + TestCascade cascade(GetDocument()); + cascade.Add("writing-mode", "vertical-lr"); + cascade.Add("-webkit-writing-mode", "vertical-rl"); + cascade.Apply(); + + EXPECT_EQ("vertical-rl", cascade.ComputedValue("writing-mode")); + EXPECT_EQ("vertical-rl", cascade.ComputedValue("-webkit-writing-mode")); +} + +TEST_F(StyleCascadeTest, WritingModeReversedCascadeOrder) { + TestCascade cascade(GetDocument()); + cascade.Add("-webkit-writing-mode", "vertical-rl"); + cascade.Add("writing-mode", "vertical-lr"); + cascade.Apply(); + + EXPECT_EQ("vertical-lr", cascade.ComputedValue("writing-mode")); + EXPECT_EQ("vertical-lr", cascade.ComputedValue("-webkit-writing-mode")); +} + +TEST_F(StyleCascadeTest, WritingModePriority) { + TestCascade cascade(GetDocument()); + cascade.Add("writing-mode", "vertical-lr", Origin::kImportantAuthor); + cascade.Add("-webkit-writing-mode", "vertical-rl", Origin::kAuthor); + cascade.Apply(); + + EXPECT_EQ("vertical-lr", cascade.ComputedValue("writing-mode")); + EXPECT_EQ("vertical-lr", cascade.ComputedValue("-webkit-writing-mode")); +} + +TEST_F(StyleCascadeTest, MarkReferenced) { + RegisterProperty(GetDocument(), "--x", "<length>", "0px", false); + RegisterProperty(GetDocument(), "--y", "<length>", "0px", false); + + TestCascade cascade(GetDocument()); + cascade.Add("width", "var(--x)"); + cascade.Apply(); + + const auto* registry = GetDocument().GetPropertyRegistry(); + ASSERT_TRUE(registry); + + EXPECT_TRUE(registry->WasReferenced("--x")); + EXPECT_FALSE(registry->WasReferenced("--y")); +} + +TEST_F(StyleCascadeTest, InternalVisitedColorLonghand) { + CSSPropertyName visited_color(CSSPropertyID::kInternalVisitedColor); + + TestCascade cascade(GetDocument()); + cascade.Add(visited_color, "red"); + cascade.Add("color", "green"); + cascade.Apply(); + + cascade.State().Style()->SetInsideLink(EInsideLink::kInsideVisitedLink); + + EXPECT_EQ("rgb(0, 128, 0)", cascade.ComputedValue("color")); + + Color red(255, 0, 0); + const CSSProperty& color = GetCSSPropertyColor(); + EXPECT_EQ(red, cascade.TakeStyle()->VisitedDependentColor(color)); +} + +TEST_F(StyleCascadeTest, VarInInternalVisitedShorthand) { + CSSPropertyName visited_outline_color( + CSSPropertyID::kInternalVisitedOutlineColor); + + TestCascade cascade(GetDocument()); + cascade.Add("--x", "green"); + cascade.Add("outline", "medium solid var(--x)"); + + // Copy pending substitution value from outline-color to + // -internal-visited-outline-color, approximating StyleResolver's behavior + // for :visited declarations. + const CSSValue* pending_substitution = cascade.GetCSSValue("outline-color"); + ASSERT_TRUE(pending_substitution); + cascade.Add(visited_outline_color, pending_substitution); + cascade.Add("outline-color", "red"); + + // Apply "outline-color" manually first, to ensure that + // -internal-visited-outline-color is applied afterwards. + cascade.Apply("outline-color"); + + // When applying -internal-visited-outline-color, it should not modify + // outline-color. + cascade.Apply(); + + cascade.State().Style()->SetInsideLink(EInsideLink::kInsideVisitedLink); + + EXPECT_EQ("rgb(255, 0, 0)", cascade.ComputedValue("outline-color")); + + Color green(0, 128, 0); + const CSSProperty& outline_color = GetCSSPropertyOutlineColor(); + EXPECT_EQ(green, cascade.TakeStyle()->VisitedDependentColor(outline_color)); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/css/resolver/style_resolver.cc b/third_party/blink/renderer/core/css/resolver/style_resolver.cc index 9946056..6ec8f2f 100644 --- a/third_party/blink/renderer/core/css/resolver/style_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/style_resolver.cc
@@ -44,6 +44,7 @@ #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_keyframe_rule.h" #include "third_party/blink/renderer/core/css/css_keyframes_rule.h" +#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h" #include "third_party/blink/renderer/core/css/css_property_names.h" #include "third_party/blink/renderer/core/css/css_property_value_set.h" #include "third_party/blink/renderer/core/css/css_reflect_value.h" @@ -67,6 +68,7 @@ #include "third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h" #include "third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope.h" #include "third_party/blink/renderer/core/css/resolver/style_adjuster.h" +#include "third_party/blink/renderer/core/css/resolver/style_animator.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_stats.h" #include "third_party/blink/renderer/core/css/resolver/style_rule_usage_tracker.h" @@ -871,11 +873,18 @@ parent_style); state.SetStyle(ComputedStyle::Clone(base_style)); if (value) { - StyleBuilder::ApplyProperty(property.GetCSSPropertyName(), state, *value); - state.GetFontBuilder().CreateFont( - state.GetDocument().GetStyleEngine().GetFontSelector(), - state.StyleRef()); - CSSVariableResolver(state).ResolveVariableDefinitions(); + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + StyleCascade cascade(state); + auto name = property.GetCSSPropertyName(); + cascade.Add(name, value, StyleCascade::Origin::kAuthor); + cascade.Apply(); + } else { + StyleBuilder::ApplyProperty(property.GetCSSPropertyName(), state, *value); + state.GetFontBuilder().CreateFont( + state.GetDocument().GetStyleEngine().GetFontSelector(), + state.StyleRef()); + CSSVariableResolver(state).ResolveVariableDefinitions(); + } } return CompositorKeyframeValueFactory::Create(property, *state.Style()); } @@ -1182,14 +1191,33 @@ state.AnimationUpdate().ActiveInterpolationsForStandardAnimations(); const ActiveInterpolationsMap& transitions_map = state.AnimationUpdate().ActiveInterpolationsForStandardTransitions(); - ApplyAnimatedStandardProperties<kHighPropertyPriority>(state, animations_map); - ApplyAnimatedStandardProperties<kHighPropertyPriority>(state, - transitions_map); - UpdateFont(state); + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + // TODO(crbug.com/985049): Use main cascade. + // + // For now, we use a dedicated cascade for animation of standard properties. + // A StyleCascade is required, because otherwise we can't resolve any var() + // references that may appear in keyframes. Ultimately, we should use ONE + // cascade for everything, but this is not yet possible. + using Origin = StyleCascade::Origin; + StyleCascade cascade(state); + StyleAnimator animator(state, cascade); + CascadeInterpolations(cascade, animations_map, Origin::kAnimation); + CascadeInterpolations(cascade, transitions_map, Origin::kTransition); + cascade.Apply(animator); + } else { + ApplyAnimatedStandardProperties<kHighPropertyPriority>(state, + animations_map); + ApplyAnimatedStandardProperties<kHighPropertyPriority>(state, + transitions_map); - ApplyAnimatedStandardProperties<kLowPropertyPriority>(state, animations_map); - ApplyAnimatedStandardProperties<kLowPropertyPriority>(state, transitions_map); + UpdateFont(state); + + ApplyAnimatedStandardProperties<kLowPropertyPriority>(state, + animations_map); + ApplyAnimatedStandardProperties<kLowPropertyPriority>(state, + transitions_map); + } // Start loading resources used by animations. LoadPendingResources(state); @@ -1820,53 +1848,12 @@ apply_inherited_only = false; } -void StyleResolver::ApplyMatchedProperties(StyleResolverState& state, - const MatchResult& match_result, - const Element* animating_element) { - INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(), - matched_property_apply, 1); - - CacheSuccess cache_success = ApplyMatchedCache(state, match_result); - bool apply_inherited_only = cache_success.ShouldApplyInheritedOnly(); - NeedsApplyPass needs_apply_pass; - - if (!cache_success.IsFullCacheHit()) { - ApplyCustomProperties(state, match_result, cache_success, needs_apply_pass); - ApplyMatchedAnimationProperties(state, match_result, cache_success, - needs_apply_pass); - ApplyMatchedHighPriorityProperties(state, match_result, cache_success, - apply_inherited_only, needs_apply_pass); - } - - if (HasAnimationsOrTransitions(state, animating_element)) { - // Calculate pre-animated computed values for all registered properties. - // This is needed to calculate the animation update. - CSSVariableResolver(state).ComputeRegisteredVariables(); - - // Animation update calculation must happen after application of high - // priority properties, otherwise we can't resolve em' units, making it - // impossible to know if we should transition in some cases. - CalculateAnimationUpdate(state, animating_element); - - if (state.IsAnimatingCustomProperties()) { - cache_success.SetFailed(); - - CSSVariableAnimator(state).ApplyAll(); - - // Apply high priority properties again to re-resolve var() references - // to (now-)animated custom properties. - // TODO(andruud): Avoid this with https://crbug.com/947004 - ApplyMatchedHighPriorityProperties(state, match_result, cache_success, - apply_inherited_only, - needs_apply_pass); - } - } - - if (cache_success.IsFullCacheHit()) - return; - - CSSVariableResolver(state).ResolveVariableDefinitions(); - +void StyleResolver::ApplyMatchedLowPriorityProperties( + StyleResolverState& state, + const MatchResult& match_result, + const CacheSuccess& cache_success, + bool& apply_inherited_only, + NeedsApplyPass& needs_apply_pass) { // Now do the normal priority UA properties. ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>( state, match_result.UaRules(), false, apply_inherited_only, @@ -1921,6 +1908,243 @@ DCHECK(!state.GetFontBuilder().FontDirty()); } +void StyleResolver::ApplyMatchedProperties(StyleResolverState& state, + const MatchResult& match_result, + const Element* animating_element) { + INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(), + matched_property_apply, 1); + + if (RuntimeEnabledFeatures::CSSCascadeEnabled()) { + CascadeAndApplyMatchedProperties(state, match_result, animating_element); + return; + } + + CacheSuccess cache_success = ApplyMatchedCache(state, match_result); + bool apply_inherited_only = cache_success.ShouldApplyInheritedOnly(); + NeedsApplyPass needs_apply_pass; + + if (!cache_success.IsFullCacheHit()) { + ApplyCustomProperties(state, match_result, cache_success, needs_apply_pass); + ApplyMatchedAnimationProperties(state, match_result, cache_success, + needs_apply_pass); + ApplyMatchedHighPriorityProperties(state, match_result, cache_success, + apply_inherited_only, needs_apply_pass); + } + + if (HasAnimationsOrTransitions(state, animating_element)) { + // Calculate pre-animated computed values for all registered properties. + // This is needed to calculate the animation update. + CSSVariableResolver(state).ComputeRegisteredVariables(); + + // Animation update calculation must happen after application of high + // priority properties, otherwise we can't resolve em' units, making it + // impossible to know if we should transition in some cases. + CalculateAnimationUpdate(state, animating_element); + + if (state.IsAnimatingCustomProperties()) { + cache_success.SetFailed(); + + CSSVariableAnimator(state).ApplyAll(); + + // Apply high priority properties again to re-resolve var() references + // to (now-)animated custom properties. + // TODO(andruud): Avoid this with https://crbug.com/947004 + ApplyMatchedHighPriorityProperties(state, match_result, cache_success, + apply_inherited_only, + needs_apply_pass); + } + } + + if (cache_success.IsFullCacheHit()) + return; + + CSSVariableResolver(state).ResolveVariableDefinitions(); + + ApplyMatchedLowPriorityProperties(state, match_result, cache_success, + apply_inherited_only, needs_apply_pass); +} + +void StyleResolver::CascadeAndApplyMatchedProperties( + StyleResolverState& state, + const MatchResult& match_result, + const Element* animating_element) { + DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled()); + + CacheSuccess cache_success = ApplyMatchedCache(state, match_result); + + StyleCascade cascade(state); + CascadeMatchResult(state, cascade, match_result); + + // We need to copy the entire cascade before applying, in case there are + // animations. + // + // TODO(crbug.com/985010): Avoid this copy with non-destructive Apply. + StyleCascade cascade_copy(cascade); + cascade_copy.RemoveAnimationPriority(); + + if (!cache_success.IsFullCacheHit()) + cascade.Apply(); + + if (HasAnimationsOrTransitions(state, animating_element)) { + CalculateAnimationUpdate(state, animating_element); + + // Add animation effects for custom properties to the cascade. + if (state.IsAnimatingCustomProperties()) { + cache_success.SetFailed(); + CascadeAnimations(state, cascade_copy); + CascadeTransitions(state, cascade_copy); + StyleAnimator animator(state, cascade_copy); + cascade_copy.Apply(animator); + } + } + + if (cache_success.IsFullCacheHit()) + return; + + // TODO(crbug.com/985025): We only support full cache hits for now. + bool apply_inherited_only = false; + + // TODO(crbug.com/985027): Cascade kLowPropertyPriority. + // + // Ultimately NeedsApplyPass will be removed, so we don't bother fixing + // that for this codepath. For now, just always go through the low-priority + // properties. + const bool important = true; + NeedsApplyPass needs_apply_pass; + needs_apply_pass.Set(kLowPropertyPriority, important); + needs_apply_pass.Set(kLowPropertyPriority, !important); + ApplyMatchedLowPriorityProperties(state, match_result, cache_success, + apply_inherited_only, needs_apply_pass); +} + +static void CascadeDeclaration(StyleCascade& cascade, + const CSSPropertyName& name, + const CSSValue& value, + StyleCascade::Priority priority, + unsigned apply_mask) { + if (apply_mask & kApplyMaskRegular) + cascade.Add(name, &value, priority); + if (apply_mask & kApplyMaskVisited) { + const CSSProperty* visited = + CSSProperty::Get(name.Id()).GetVisitedProperty(); + if (visited) + cascade.Add(visited->GetCSSPropertyName(), &value, priority); + } +} + +// https://drafts.csswg.org/css-cascade/#all-shorthand +static void CascadeAll(StyleResolverState& state, + StyleCascade& cascade, + StyleCascade::Priority priority, + unsigned apply_mask, + ValidPropertyFilter filter, + const CSSValue& value) { + for (CSSPropertyID property_id : CSSPropertyIDList()) { + using LowPrioData = CSSPropertyPriorityData<kLowPropertyPriority>; + if (LowPrioData::PropertyHasPriority(property_id)) + continue; + + const CSSProperty& property = CSSProperty::Get(property_id); + + if (property.IsShorthand()) + continue; + if (!property.IsAffectedByAll()) + continue; + if (!PassesPropertyFilter(filter, property_id, state.GetDocument())) + continue; + + CascadeDeclaration(cascade, CSSPropertyName(property_id), value, priority, + apply_mask); + } +} + +void StyleResolver::CascadeMatchResult(StyleResolverState& state, + StyleCascade& cascade, + const MatchResult& result) { + DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled()); + + using Origin = StyleCascade::Origin; + CascadeRange(state, cascade, result.UaRules(), Origin::kUserAgent); + CascadeRange(state, cascade, result.AuthorRules(), Origin::kAuthor); + CascadeRange(state, cascade, result.UserRules(), Origin::kUser); +} + +void StyleResolver::CascadeRange(StyleResolverState& state, + StyleCascade& cascade, + const MatchedPropertiesRange& range, + StyleCascade::Origin origin) { + DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled()); + + if (range.IsEmpty()) + return; + + for (const auto& matched_properties : range) { + auto filter = static_cast<ValidPropertyFilter>( + matched_properties.types_.valid_property_filter); + uint16_t tree_order = matched_properties.types_.tree_order; + unsigned apply_mask = ComputeApplyMask(state, matched_properties); + const CSSPropertyValueSet* properties = matched_properties.properties.Get(); + unsigned property_count = properties->PropertyCount(); + + for (unsigned i = 0; i < property_count; ++i) { + CSSPropertyValueSet::PropertyReference current = + properties->PropertyAt(i); + CSSPropertyID property_id = current.Id(); + + StyleCascade::Priority priority(origin, tree_order); + + if (current.IsImportant()) + priority = priority.AddImportance(); + + if (property_id == CSSPropertyID::kAll) { + CascadeAll(state, cascade, priority, apply_mask, filter, + current.Value()); + continue; + } + + using LowPrioData = CSSPropertyPriorityData<kLowPropertyPriority>; + if (LowPrioData::PropertyHasPriority(property_id)) + continue; + + if (!PassesPropertyFilter(filter, property_id, state.GetDocument())) + continue; + + CascadeDeclaration(cascade, current.Name(), current.Value(), priority, + apply_mask); + } + } +} + +void StyleResolver::CascadeTransitions(StyleResolverState& state, + StyleCascade& cascade) { + const auto& update = state.AnimationUpdate(); + const auto& map = update.ActiveInterpolationsForCustomTransitions(); + const auto origin = StyleCascade::Origin::kTransition; + CascadeInterpolations(cascade, map, origin); +} + +void StyleResolver::CascadeAnimations(StyleResolverState& state, + StyleCascade& cascade) { + const auto& update = state.AnimationUpdate(); + const auto& map = update.ActiveInterpolationsForCustomAnimations(); + const auto origin = StyleCascade::Origin::kAnimation; + CascadeInterpolations(cascade, map, origin); +} + +void StyleResolver::CascadeInterpolations(StyleCascade& cascade, + const ActiveInterpolationsMap& map, + StyleCascade::Origin origin) { + using Type = cssvalue::CSSPendingInterpolationValue::Type; + for (const auto& entry : map) { + auto name = entry.key.GetCSSPropertyName(); + Type type = entry.key.IsPresentationAttribute() + ? Type::kPresentationAttribute + : Type::kCSSProperty; + auto* v = cssvalue::CSSPendingInterpolationValue::Create(type); + cascade.Add(name, v, origin); + } +} + bool StyleResolver::HasAuthorBackground(const StyleResolverState& state) { const CachedUAStyle* cached_ua_style = state.GetCachedUAStyle(); if (!cached_ua_style)
diff --git a/third_party/blink/renderer/core/css/resolver/style_resolver.h b/third_party/blink/renderer/core/css/resolver/style_resolver.h index f21181034..c136fb10 100644 --- a/third_party/blink/renderer/core/css/resolver/style_resolver.h +++ b/third_party/blink/renderer/core/css/resolver/style_resolver.h
@@ -33,6 +33,7 @@ #include "third_party/blink/renderer/core/css/resolver/css_property_priority.h" #include "third_party/blink/renderer/core/css/resolver/matched_properties_cache.h" #include "third_party/blink/renderer/core/css/resolver/style_builder.h" +#include "third_party/blink/renderer/core/css/resolver/style_cascade.h" #include "third_party/blink/renderer/core/css/selector_checker.h" #include "third_party/blink/renderer/core/css/selector_filter.h" #include "third_party/blink/renderer/platform/heap/handle.h" @@ -234,10 +235,31 @@ const CacheSuccess&, bool& apply_inherited_only, NeedsApplyPass&); + void ApplyMatchedLowPriorityProperties(StyleResolverState&, + const MatchResult&, + const CacheSuccess&, + bool& apply_inherited_only, + NeedsApplyPass&); void ApplyMatchedProperties(StyleResolverState&, const MatchResult&, const Element* animating_element); + void CascadeAndApplyMatchedProperties(StyleResolverState&, + const MatchResult&, + const Element* animating_element); + void CascadeMatchResult(StyleResolverState&, + StyleCascade&, + const MatchResult&); + void CascadeRange(StyleResolverState&, + StyleCascade&, + const MatchedPropertiesRange&, + StyleCascade::Origin); + void CascadeTransitions(StyleResolverState&, StyleCascade&); + void CascadeAnimations(StyleResolverState&, StyleCascade&); + void CascadeInterpolations(StyleCascade&, + const ActiveInterpolationsMap&, + StyleCascade::Origin); + void CalculateAnimationUpdate(StyleResolverState&, const Element* animating_element);
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index 9294b94..a1cecb00 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -283,7 +283,7 @@ #include "third_party/blink/renderer/platform/geometry/length_functions.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/histogram.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/document_resource_coordinator.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" @@ -323,10 +323,10 @@ using namespace html_names; -class DocumentOutliveTimeReporter : public HeapObserver { +class DocumentOutliveTimeReporter : public BlinkGCObserver { public: explicit DocumentOutliveTimeReporter(Document* document) - : HeapObserver(ThreadState::Current()), document_(document) {} + : BlinkGCObserver(ThreadState::Current()), document_(document) {} ~DocumentOutliveTimeReporter() override { // As not all documents are destroyed before the process dies, this might @@ -336,15 +336,13 @@ GetOutliveTimeCount() + 1, 101); } - void GCFinished(const ThreadHeapStatsCollector::Event& event) override { + void OnCompleteSweepDone() override { enum GCCount { kGCCount5, kGCCount10, kGCCountMax, }; - last_recorded_gc_age_ = event.gc_age; - // There are some cases that a document can live after shutting down because // the document can still be referenced (e.g. a document opened via // window.open can be referenced by the opener even after shutting down). To @@ -356,7 +354,7 @@ document_->domWindow())) { return; } - gc_age_when_document_detached_ = last_recorded_gc_age_; + gc_age_when_document_detached_ = ThreadState::Current()->GcAge(); } int outlive_time_count = GetOutliveTimeCount(); @@ -379,15 +377,13 @@ private: int GetOutliveTimeCount() const { - return gc_age_when_document_detached_ - ? static_cast<int>(last_recorded_gc_age_ - - gc_age_when_document_detached_) - : 0; + if (!gc_age_when_document_detached_) + return 0; + return ThreadState::Current()->GcAge() - gc_age_when_document_detached_; } WeakPersistent<Document> document_; - size_t last_recorded_gc_age_ = 0; - size_t gc_age_when_document_detached_ = 0; + int gc_age_when_document_detached_ = 0; }; static const unsigned kCMaxWriteRecursionDepth = 21;
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index c43e895..4a2d4ae1 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -4265,12 +4265,8 @@ if (PseudoElement* element = GetPseudoElement(pseudo_element_specifier)) return element->EnsureComputedStyle(); - if (!InActiveDocument()) { - // FIXME: Try to do better than this. Ensure that styleForElement() works - // for elements that are not in the document tree and figure out when to - // destroy the computed style for such elements. + if (!InActiveDocument()) return nullptr; - } // EnsureComputedStyle is expected to be called to forcibly compute style for // elements in display:none subtrees on otherwise style-clean documents. If @@ -4296,14 +4292,8 @@ const ComputedStyle* element_style = GetComputedStyle(); if (!element_style) { if (CanParticipateInFlatTree()) { - ContainerNode* parent = LayoutTreeBuilderTraversal::Parent(*this); - if (parent) + if (ContainerNode* parent = LayoutTreeBuilderTraversal::Parent(*this)) parent->EnsureComputedStyle(); - - ContainerNode* layout_parent = - parent ? LayoutTreeBuilderTraversal::LayoutParent(*this) : nullptr; - if (layout_parent) - layout_parent->EnsureComputedStyle(); } scoped_refptr<ComputedStyle> new_style = nullptr; // TODO(crbug.com/953707): Avoid setting inline style during
diff --git a/third_party/blink/renderer/core/dom/node.cc b/third_party/blink/renderer/core/dom/node.cc index f0485e5..6e90be8e 100644 --- a/third_party/blink/renderer/core/dom/node.cc +++ b/third_party/blink/renderer/core/dom/node.cc
@@ -114,7 +114,7 @@ #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/microtask.h" #include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
diff --git a/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc b/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc index 811db206..f0dcd0a 100644 --- a/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc +++ b/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc
@@ -27,7 +27,7 @@ #include "third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" namespace blink {
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 999984bc..b06dda59 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -2877,7 +2877,6 @@ if (transform == device_emulation_transform_) return; device_emulation_transform_ = transform; - GetPage()->GetVisualViewport().SetNeedsPaintPropertyUpdate(); UpdateDeviceEmulationTransform(); } @@ -2887,11 +2886,14 @@ void WebViewImpl::EnableDeviceEmulation( const WebDeviceEmulationParams& params) { - dev_tools_emulator_->EnableDeviceEmulation(params); + TransformationMatrix device_emulation_transform = + dev_tools_emulator_->EnableDeviceEmulation(params); + SetDeviceEmulationTransform(device_emulation_transform); } void WebViewImpl::DisableDeviceEmulation() { dev_tools_emulator_->DisableDeviceEmulation(); + SetDeviceEmulationTransform(TransformationMatrix()); } void WebViewImpl::PerformCustomContextMenuAction(unsigned action) { @@ -2997,7 +2999,6 @@ Color color = BaseBackgroundColor(); if (auto* local_frame = DynamicTo<LocalFrame>(AsView().page->MainFrame())) { LocalFrameView* view = local_frame->View(); - view->SetBaseBackgroundColor(color); view->UpdateBaseBackgroundColorRecursively(color); } } @@ -3114,11 +3115,21 @@ viewport.Scale(), viewport.IsPinchGestureActive(), MinimumPageScaleFactor(), MaximumPageScaleFactor()); AsView().client->PageScaleFactorChanged(viewport.Scale()); - dev_tools_emulator_->MainFrameScrollOrScaleChanged(); + + if (dev_tools_emulator_->HasViewportOverride()) { + TransformationMatrix device_emulation_transform = + dev_tools_emulator_->MainFrameScrollOrScaleChanged(); + SetDeviceEmulationTransform(device_emulation_transform); + } } void WebViewImpl::MainFrameScrollOffsetChanged() { - dev_tools_emulator_->MainFrameScrollOrScaleChanged(); + DCHECK(MainFrameImpl()); + if (dev_tools_emulator_->HasViewportOverride()) { + TransformationMatrix device_emulation_transform = + dev_tools_emulator_->MainFrameScrollOrScaleChanged(); + SetDeviceEmulationTransform(device_emulation_transform); + } } void WebViewImpl::SetBackgroundColorOverride(SkColor color) { @@ -3435,15 +3446,27 @@ } void WebViewImpl::UpdateDeviceEmulationTransform() { - if (!visual_viewport_container_layer_) - return; + if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) { + // This method may be called before a document lifecycle update runs, and + // attaches the |visual_viewport_container_layer_|. In that case, we will + // save the new transform and apply it when the container layer is attached. + // This is also null when CompositeAfterPaint is enabled. + if (visual_viewport_container_layer_) { + visual_viewport_container_layer_->SetTransform( + device_emulation_transform_); + } + } - // When the device emulation transform is updated, to avoid incorrect - // scales and fuzzy raster from the compositor, force all content to - // pick ideal raster scales. - visual_viewport_container_layer_->SetTransform(device_emulation_transform_); - if (layer_tree_view_) - layer_tree_view_->ForceRecalculateRasterScales(); + GetPage()->GetVisualViewport().SetNeedsPaintPropertyUpdate(); + + if (MainFrameImpl()) { + // When the device emulation transform is updated, to avoid incorrect + // scales and fuzzy raster from the compositor, force all content to + // pick ideal raster scales. + // TODO(wjmaclean): This is only done on the main frame's widget currently, + // it should update all local frames. + AsWidget().client->ForceRecalculateRasterScales(); + } } PageScheduler* WebViewImpl::Scheduler() const {
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.h b/third_party/blink/renderer/core/exported/web_view_impl.h index e31b1a5..720ea6fc 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.h +++ b/third_party/blink/renderer/core/exported/web_view_impl.h
@@ -216,7 +216,6 @@ void SetZoomFactorOverride(float); void SetCompositorDeviceScaleFactorOverride(float); - void SetDeviceEmulationTransform(const TransformationMatrix&); TransformationMatrix GetDeviceEmulationTransform() const; SkColor BackgroundColor() const; @@ -509,6 +508,8 @@ void SetIsAcceleratedCompositingActive(bool); void DoComposite(); void ReallocateRenderer(); + + void SetDeviceEmulationTransform(const TransformationMatrix&); void UpdateDeviceEmulationTransform(); // Helper function: Widens the width of |source| by the specified margins
diff --git a/third_party/blink/renderer/core/exported/web_view_test.cc b/third_party/blink/renderer/core/exported/web_view_test.cc index 3fd295d..28c2eaa6 100644 --- a/third_party/blink/renderer/core/exported/web_view_test.cc +++ b/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -3364,11 +3364,13 @@ } void UserGestureObserved() override { ++user_gesture_notifications_count_; } - bool HasFillData(const WebFormControlElement&) const override { - return has_fill_data_; + bool TryToShowTouchToFill(const WebFormControlElement&) override { + return can_show_touch_to_fill_; } - void SetFillData(bool has_fill_data) { has_fill_data_ = has_fill_data; } + void SetCanShowTouchToFill(bool can_show_touch_to_fill) { + can_show_touch_to_fill_ = can_show_touch_to_fill; + } void ClearChangeCounts() { text_changes_ = 0; } @@ -3382,7 +3384,7 @@ int text_changes_ = 0; int text_changes_from_user_gesture_ = 0; int user_gesture_notifications_count_ = 0; - bool has_fill_data_ = false; + bool can_show_touch_to_fill_ = false; }; TEST_F(WebViewTest, LosingFocusDoesNotTriggerAutofillTextChange) { @@ -4684,21 +4686,21 @@ RegisterMockedHttpURLLoad("input_field_password.html"); // Pretend client has fill data for all fields it's queried. MockAutofillClient client; - client.SetFillData(true); + client.SetCanShowTouchToFill(true); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_password.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetAutofillClient(&client); // No field is focused. - EXPECT_FALSE(frame->CanFocusedFieldBeAutofilled()); + EXPECT_FALSE(frame->TryToShowTouchToFillForFocusedElement()); // Focusing a field should result in treating it autofillable. web_view->SetInitialFocus(false); - EXPECT_TRUE(frame->CanFocusedFieldBeAutofilled()); + EXPECT_TRUE(frame->TryToShowTouchToFillForFocusedElement()); // Pretend that |client| no longer has autofill data available. - client.SetFillData(false); - EXPECT_FALSE(frame->CanFocusedFieldBeAutofilled()); + client.SetCanShowTouchToFill(false); + EXPECT_FALSE(frame->TryToShowTouchToFillForFocusedElement()); frame->SetAutofillClient(nullptr); } @@ -4852,9 +4854,10 @@ // Override applies transform, sets visible rect, and disables // visual viewport clipping. - dev_tools_emulator->ForceViewport(WebFloatPoint(50, 55), 2.f); + TransformationMatrix matrix = + dev_tools_emulator->ForceViewportForTesting(WebFloatPoint(50, 55), 2.f); expected_matrix.MakeIdentity().Scale(2.f).Translate(-50, -55); - EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform()); + EXPECT_EQ(expected_matrix, matrix); { IntRect visible_rect(1, 2, 3, 4); dev_tools_emulator->OverrideVisibleRect(IntSize(100, 150), &visible_rect); @@ -4863,9 +4866,10 @@ EXPECT_FALSE(visual_viewport->ContainerLayer()->MasksToBounds()); // Setting new override discards previous one. - dev_tools_emulator->ForceViewport(WebFloatPoint(5.4f, 10.5f), 1.5f); + matrix = dev_tools_emulator->ForceViewportForTesting( + WebFloatPoint(5.4f, 10.5f), 1.5f); expected_matrix.MakeIdentity().Scale(1.5f).Translate(-5.4f, -10.5f); - EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform()); + EXPECT_EQ(expected_matrix, matrix); { IntRect visible_rect(1, 2, 3, 4); dev_tools_emulator->OverrideVisibleRect(IntSize(100, 150), &visible_rect); @@ -4875,9 +4879,9 @@ // Clearing override restores original transform, visible rect and // visual viewport clipping. - dev_tools_emulator->ResetViewport(); + matrix = dev_tools_emulator->ResetViewportForTesting(); expected_matrix.MakeIdentity(); - EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform()); + EXPECT_EQ(expected_matrix, matrix); { IntRect visible_rect(1, 2, 3, 4); dev_tools_emulator->OverrideVisibleRect(IntSize(), &visible_rect); @@ -4903,8 +4907,9 @@ EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform()); // Device metrics offset and scale are applied before viewport override. - web_view_impl->GetDevToolsEmulator()->ForceViewport(WebFloatPoint(5, 10), - 1.5f); + emulation_params.viewport_offset = WebFloatPoint(5, 10); + emulation_params.viewport_scale = 1.5f; + web_view_impl->EnableDeviceEmulation(emulation_params); expected_matrix.MakeIdentity() .Scale(1.5f) .Translate(-5, -10) @@ -4931,7 +4936,11 @@ web_view_impl->SetPageScaleFactor(1.5f); frame_view->LayoutViewport()->SetScrollOffset( ScrollOffset(100, 150), kProgrammaticScroll, kScrollBehaviorInstant); - dev_tools_emulator->ForceViewport(WebFloatPoint(50, 55), 2.f); + + WebDeviceEmulationParams emulation_params; + emulation_params.viewport_offset = WebFloatPoint(50, 55); + emulation_params.viewport_scale = 2.f; + web_view_impl->EnableDeviceEmulation(emulation_params); expected_matrix.MakeIdentity() .Scale(2.f) .Translate(-50, -55)
diff --git a/third_party/blink/renderer/core/frame/BUILD.gn b/third_party/blink/renderer/core/frame/BUILD.gn index cd9e30c..4e7fc70 100644 --- a/third_party/blink/renderer/core/frame/BUILD.gn +++ b/third_party/blink/renderer/core/frame/BUILD.gn
@@ -170,6 +170,8 @@ "settings_delegate.h", "smart_clip.cc", "smart_clip.h", + "surrounding_text_impl.cc", + "surrounding_text_impl.h", "test_report_body.h", "use_counter_helper.cc", "use_counter_helper.h",
diff --git a/third_party/blink/renderer/core/frame/frame.cc b/third_party/blink/renderer/core/frame/frame.cc index 1e9b9e4..90948c5 100644 --- a/third_party/blink/renderer/core/frame/frame.cc +++ b/third_party/blink/renderer/core/frame/frame.cc
@@ -49,7 +49,7 @@ #include "third_party/blink/renderer/core/page/focus_controller.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/probe/core_probes.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_error.h" #include "third_party/blink/renderer/platform/wtf/assertions.h"
diff --git a/third_party/blink/renderer/core/frame/frame_overlay_test.cc b/third_party/blink/renderer/core/frame/frame_overlay_test.cc index a192fd3..180bfb9f 100644 --- a/third_party/blink/renderer/core/frame/frame_overlay_test.cc +++ b/third_party/blink/renderer/core/frame/frame_overlay_test.cc
@@ -8,6 +8,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/renderer/core/exported/web_view_impl.h" #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" @@ -113,7 +114,9 @@ } TEST_P(FrameOverlayTest, DeviceEmulationScale) { - GetWebView()->SetDeviceEmulationTransform(TransformationMatrix().Scale(1.5)); + WebDeviceEmulationParams params; + params.scale = 1.5; + GetWebView()->EnableDeviceEmulation(params); GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases( WebWidget::LifecycleUpdateReason::kTest);
diff --git a/third_party/blink/renderer/core/frame/local_frame.h b/third_party/blink/renderer/core/frame/local_frame.h index 7edd10d..46c9ab9 100644 --- a/third_party/blink/renderer/core/frame/local_frame.h +++ b/third_party/blink/renderer/core/frame/local_frame.h
@@ -52,7 +52,7 @@ #include "third_party/blink/renderer/core/loader/frame_loader.h" #include "third_party/blink/renderer/platform/graphics/touch_action.h" #include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h" #include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h" #include "third_party/blink/renderer/platform/supplementable.h"
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 8315f59..1985d03 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -3571,8 +3571,10 @@ void LocalFrameView::DidChangeScrollOffset() { GetFrame().Client()->DidChangeScrollOffset(); - if (GetFrame().IsMainFrame()) - GetFrame().GetPage()->GetChromeClient().MainFrameScrollOffsetChanged(); + if (GetFrame().IsMainFrame()) { + GetFrame().GetPage()->GetChromeClient().MainFrameScrollOffsetChanged( + GetFrame()); + } } ScrollableArea* LocalFrameView::ScrollableAreaWithElementId(
diff --git a/third_party/blink/renderer/core/frame/surrounding_text_impl.cc b/third_party/blink/renderer/core/frame/surrounding_text_impl.cc new file mode 100644 index 0000000..9817788 --- /dev/null +++ b/third_party/blink/renderer/core/frame/surrounding_text_impl.cc
@@ -0,0 +1,53 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/frame/surrounding_text_impl.h" + +#include <utility> + +#include "third_party/blink/public/platform/task_type.h" +#include "third_party/blink/public/web/web_surrounding_text.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" +#include "third_party/blink/renderer/platform/heap/persistent.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" + +namespace blink { + +SurroundingTextImpl::SurroundingTextImpl(WebLocalFrameImpl& frame, + InterfaceRegistry* interface_registry) + : frame_(&frame) { + if (!interface_registry) + return; + // TODO(crbug.com/800641): Use InterfaceValidator when it works for associated + // interfaces. + interface_registry->AddAssociatedInterface(WTF::BindRepeating( + &SurroundingTextImpl::BindToReceiver, WrapWeakPersistent(this))); +} + +void SurroundingTextImpl::BindToReceiver( + mojo::PendingAssociatedReceiver<mojom::blink::SurroundingText> receiver) { + receiver_.Bind(std::move(receiver), + frame_->GetTaskRunner(blink::TaskType::kInternalDefault)); +} + +void SurroundingTextImpl::GetTextSurroundingSelection( + uint32_t max_length, + GetTextSurroundingSelectionCallback callback) { + blink::WebSurroundingText surrounding_text(frame_, max_length); + + if (surrounding_text.IsEmpty()) { + // |surrounding_text| might not be correctly initialized, for example if + // |frame_->SelectionRange().IsNull()|, in other words, if there was no + // selection. + std::move(callback).Run(String(), 0, 0); + return; + } + + std::move(callback).Run(surrounding_text.TextContent(), + surrounding_text.StartOffsetInTextContent(), + surrounding_text.EndOffsetInTextContent()); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/frame/surrounding_text_impl.h b/third_party/blink/renderer/core/frame/surrounding_text_impl.h new file mode 100644 index 0000000..4ee5e0e --- /dev/null +++ b/third_party/blink/renderer/core/frame/surrounding_text_impl.h
@@ -0,0 +1,47 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_SURROUNDING_TEXT_IMPL_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_SURROUNDING_TEXT_IMPL_H_ + +#include "mojo/public/cpp/bindings/associated_receiver.h" +#include "mojo/public/cpp/bindings/pending_associated_receiver.h" +#include "third_party/blink/public/mojom/frame/surrounding_text.mojom-blink.h" +#include "third_party/blink/public/platform/interface_registry.h" +#include "third_party/blink/public/web/web_local_frame.h" +#include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" + +namespace blink { + +class WebLocalFrameImpl; + +// Implementation of mojom::blink::SurroundingText +class CORE_EXPORT SurroundingTextImpl final + : public GarbageCollectedFinalized<SurroundingTextImpl>, + public mojom::blink::SurroundingText { + public: + SurroundingTextImpl(WebLocalFrameImpl& frame, + InterfaceRegistry* interface_registry); + + void BindToReceiver( + mojo::PendingAssociatedReceiver<mojom::blink::SurroundingText> receiver); + + void GetTextSurroundingSelection( + uint32_t max_length, + GetTextSurroundingSelectionCallback callback) final; + + void Trace(blink::Visitor* visitor) { visitor->Trace(frame_); } + + private: + const Member<WebLocalFrameImpl> frame_; + + mojo::AssociatedReceiver<mojom::blink::SurroundingText> receiver_{this}; + + DISALLOW_COPY_AND_ASSIGN(SurroundingTextImpl); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_SURROUNDING_TEXT_IMPL_H_
diff --git a/third_party/blink/renderer/core/frame/visual_viewport_test.cc b/third_party/blink/renderer/core/frame/visual_viewport_test.cc index cb0714bf..ef25053 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport_test.cc +++ b/third_party/blink/renderer/core/frame/visual_viewport_test.cc
@@ -17,6 +17,7 @@ #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_ax_context.h" #include "third_party/blink/public/web/web_context_menu_data.h" +#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame_client.h" #include "third_party/blink/public/web/web_script_source.h" @@ -2564,21 +2565,26 @@ TEST_P(VisualViewportTest, DeviceEmulationTransformNode) { InitializeWithAndroidSettings(); - TransformationMatrix emulation_transform = TransformationMatrix(); - emulation_transform.Translate(314, 159); - WebView()->SetDeviceEmulationTransform(emulation_transform); + WebDeviceEmulationParams params; + params.viewport_offset = WebFloatPoint(314, 159); + params.viewport_scale = 1.f; + WebView()->EnableDeviceEmulation(params); WebView()->MainFrameWidget()->Resize(IntSize(400, 400)); NavigateTo("about:blank"); UpdateAllLifecyclePhases(); VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport(); - EXPECT_EQ(visual_viewport.GetDeviceEmulationTransformNode()->Translation2D(), - emulation_transform.To2DTranslation()); + + TransformationMatrix expected_transform = TransformationMatrix(); + expected_transform.Translate(-params.viewport_offset.x, + -params.viewport_offset.y); + EXPECT_EQ(expected_transform.To2DTranslation(), + visual_viewport.GetDeviceEmulationTransformNode()->Translation2D()); // Set an identity device emulation transform and ensure the transform // paint property node is cleared. - WebView()->SetDeviceEmulationTransform(TransformationMatrix()); + WebView()->EnableDeviceEmulation(WebDeviceEmulationParams()); UpdateAllLifecyclePhases(); EXPECT_EQ(visual_viewport.GetDeviceEmulationTransformNode(), nullptr); }
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index 21a0209..a0e9ad3 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -192,6 +192,7 @@ #include "third_party/blink/renderer/core/frame/screen_orientation_controller.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/frame/smart_clip.h" +#include "third_party/blink/renderer/core/frame/surrounding_text_impl.h" #include "third_party/blink/renderer/core/frame/visual_viewport.h" #include "third_party/blink/renderer/core/frame/web_frame_widget_base.h" #include "third_party/blink/renderer/core/html/forms/html_form_control_element.h" @@ -1714,6 +1715,8 @@ autofill_client_(nullptr), find_in_page_( MakeGarbageCollected<FindInPage>(*this, interface_registry)), + surrounding_text_impl_( + MakeGarbageCollected<SurroundingTextImpl>(*this, interface_registry)), interface_registry_(interface_registry), input_method_controller_(*this), spell_check_panel_host_client_(nullptr), @@ -1732,6 +1735,7 @@ void WebLocalFrameImpl::Trace(blink::Visitor* visitor) { visitor->Trace(local_frame_client_); visitor->Trace(find_in_page_); + visitor->Trace(surrounding_text_impl_); visitor->Trace(frame_); visitor->Trace(dev_tools_agent_); visitor->Trace(frame_widget_); @@ -2493,15 +2497,15 @@ next_element->focus(); } -bool WebLocalFrameImpl::CanFocusedFieldBeAutofilled() const { +bool WebLocalFrameImpl::TryToShowTouchToFillForFocusedElement() { + if (!autofill_client_) + return false; + DCHECK(GetFrame()->GetDocument()); auto* focused_form_control_element = ToHTMLFormControlElementOrNull( GetFrame()->GetDocument()->FocusedElement()); - - if (!focused_form_control_element) - return false; - - return autofill_client_->HasFillData(focused_form_control_element); + return focused_form_control_element && + autofill_client_->TryToShowTouchToFill(focused_form_control_element); } void WebLocalFrameImpl::PerformMediaPlayerAction(
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.h b/third_party/blink/renderer/core/frame/web_local_frame_impl.h index 043afe00..744a3f1 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.h +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.h
@@ -65,6 +65,7 @@ class LocalFrameClientImpl; class ResourceError; class ScrollableArea; +class SurroundingTextImpl; class TextFinder; class WebAssociatedURLLoader; struct WebAssociatedURLLoaderOptions; @@ -304,7 +305,7 @@ WebString& clip_html, WebRect& clip_rect) override; void AdvanceFocusInForm(WebFocusType) override; - bool CanFocusedFieldBeAutofilled() const override; + bool TryToShowTouchToFillForFocusedElement() override; void PerformMediaPlayerAction(const WebPoint&, const WebMediaPlayerAction&) override; void OnPortalActivated(const base::UnguessableToken& portal_token, @@ -505,6 +506,7 @@ WebContentSettingsClient* content_settings_client_ = nullptr; Member<FindInPage> find_in_page_; + Member<SurroundingTextImpl> surrounding_text_impl_; // Valid between calls to BeginPrint() and EndPrint(). Containts the print // information. Is used by PrintPage().
diff --git a/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc b/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc index 2eefbc9..9f97baf7 100644 --- a/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc +++ b/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc
@@ -219,7 +219,7 @@ web_view_->GetPage()->GetSettings().SetPrimaryHoverType(hover_type); } -void DevToolsEmulator::EnableDeviceEmulation( +TransformationMatrix DevToolsEmulator::EnableDeviceEmulation( const WebDeviceEmulationParams& params) { if (device_metrics_enabled_ && emulation_params_.view_size == params.view_size && @@ -228,7 +228,7 @@ emulation_params_.scale == params.scale && emulation_params_.viewport_offset == params.viewport_offset && emulation_params_.viewport_scale == params.viewport_scale) { - return; + return ComputeRootLayerTransform(); } if (emulation_params_.device_scale_factor != params.device_scale_factor || !device_metrics_enabled_) @@ -248,18 +248,19 @@ DisableMobileEmulation(); web_view_->SetCompositorDeviceScaleFactorOverride(params.device_scale_factor); - if (params.viewport_offset.x >= 0) - ForceViewport(params.viewport_offset, params.viewport_scale); - else - ResetViewport(); - // TODO(dgozman): MainFrameImpl() is null when it's remote. Figure out how - // we end up with enabling emulation in this case. + // TODO(wjmaclean): Tell all local frames in the WebView's frame tree, not + // just a local main frame. if (web_view_->MainFrameImpl()) { if (Document* document = web_view_->MainFrameImpl()->GetFrame()->GetDocument()) document->MediaQueryAffectingValueChanged(); } + + if (params.viewport_offset.x >= 0) + return ForceViewport(params.viewport_offset, params.viewport_scale); + else + return ResetViewport(); } void DevToolsEmulator::DisableDeviceEmulation() { @@ -273,13 +274,17 @@ DisableMobileEmulation(); web_view_->SetCompositorDeviceScaleFactorOverride(0.f); web_view_->SetPageScaleFactor(1.f); - ResetViewport(); - // mainFrameImpl() could be null during cleanup or remote <-> local swap. + + // TODO(wjmaclean): Tell all local frames in the WebView's frame tree, not + // just a local main frame. if (web_view_->MainFrameImpl()) { if (Document* document = web_view_->MainFrameImpl()->GetFrame()->GetDocument()) document->MediaQueryAffectingValueChanged(); } + + TransformationMatrix matrix = ResetViewport(); + DCHECK(matrix.IsIdentity()); } void DevToolsEmulator::EnableMobileEmulation() { @@ -319,8 +324,9 @@ original_default_maximum_page_scale_factor_ = web_view_->DefaultMaximumPageScaleFactor(); web_view_->SetDefaultPageScaleLimits(0.25f, 5); - // TODO(dgozman): MainFrameImpl() is null when it's remote. Figure out how - // we end up with enabling emulation in this case. + + // TODO(wjmaclean): Update all local frames in the WebView's frame tree, not + // just a local main frame. if (web_view_->MainFrameImpl()) web_view_->MainFrameImpl()->GetFrameView()->UpdateLayout(); } @@ -362,13 +368,14 @@ web_view_->MainFrameImpl()->GetFrameView()->UpdateLayout(); } -void DevToolsEmulator::ForceViewport(const WebFloatPoint& position, - float scale) { - GraphicsLayer* container_layer = - web_view_->GetPage()->GetVisualViewport().ContainerLayer(); +TransformationMatrix DevToolsEmulator::ForceViewport( + const WebFloatPoint& position, + float scale) { if (!viewport_override_) { viewport_override_ = ViewportOverride(); + GraphicsLayer* container_layer = + web_view_->GetPage()->GetVisualViewport().ContainerLayer(); // Disable clipping on the visual viewport layer, to ensure the whole area // is painted. if (container_layer) { @@ -383,31 +390,29 @@ // Move the correct (scaled) content area to show in the top left of the // CompositorFrame via the root transform. - UpdateRootLayerTransform(); + return ComputeRootLayerTransform(); } -void DevToolsEmulator::ResetViewport() { - if (!viewport_override_) { - UpdateRootLayerTransform(); - return; +TransformationMatrix DevToolsEmulator::ResetViewport() { + if (viewport_override_) { + GraphicsLayer* container_layer = + web_view_->GetPage()->GetVisualViewport().ContainerLayer(); + if (container_layer) { + container_layer->SetMasksToBounds( + viewport_override_->original_visual_viewport_masking); + } + + viewport_override_ = base::nullopt; } - bool original_masking = viewport_override_->original_visual_viewport_masking; - viewport_override_ = base::nullopt; - - GraphicsLayer* container_layer = - web_view_->GetPage()->GetVisualViewport().ContainerLayer(); - if (container_layer) - container_layer->SetMasksToBounds(original_masking); - - UpdateRootLayerTransform(); + return ComputeRootLayerTransform(); } -void DevToolsEmulator::MainFrameScrollOrScaleChanged() { +TransformationMatrix DevToolsEmulator::MainFrameScrollOrScaleChanged() { // Viewport override has to take current page scale and scroll offset into // account. Update the transform if override is active. - if (viewport_override_) - UpdateRootLayerTransform(); + DCHECK(viewport_override_); + return ComputeRootLayerTransform(); } void DevToolsEmulator::ApplyViewportOverride(TransformationMatrix* transform) { @@ -435,15 +440,14 @@ transform->Scale(1. / web_view_->PageScaleFactor()); } -void DevToolsEmulator::UpdateRootLayerTransform() { +TransformationMatrix DevToolsEmulator::ComputeRootLayerTransform() { TransformationMatrix transform; - // Apply device emulation transform first, so that it is affected by the // viewport override. ApplyViewportOverride(&transform); if (device_metrics_enabled_) transform.Scale(emulation_params_.scale); - web_view_->SetDeviceEmulationTransform(transform); + return transform; } void DevToolsEmulator::OverrideVisibleRect(const IntSize& viewport_size,
diff --git a/third_party/blink/renderer/core/inspector/dev_tools_emulator.h b/third_party/blink/renderer/core/inspector/dev_tools_emulator.h index 7ed7111..fc743bd 100644 --- a/third_party/blink/renderer/core/inspector/dev_tools_emulator.h +++ b/third_party/blink/renderer/core/inspector/dev_tools_emulator.h
@@ -13,12 +13,12 @@ #include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h" #include "third_party/blink/renderer/platform/wtf/forward.h" namespace blink { class IntRect; -class TransformationMatrix; class WebViewImpl; class CORE_EXPORT DevToolsEmulator final @@ -45,21 +45,24 @@ void SetPrimaryHoverType(HoverType); void SetMainFrameResizesAreOrientationChanges(bool); - // Emulation. - void EnableDeviceEmulation(const WebDeviceEmulationParams&); + // Enables and/or sets the parameters for emulation. Returns the emulation + // transform to be used as a result. + TransformationMatrix EnableDeviceEmulation(const WebDeviceEmulationParams&); + // Disables emulation. void DisableDeviceEmulation(); - // Position is given in CSS pixels, scale relative to a page scale of 1.0. - void ForceViewport(const WebFloatPoint& position, float scale); - void ResetViewport(); + bool ResizeIsDeviceSizeChange(); void SetTouchEventEmulationEnabled(bool, int max_touch_points); void SetScriptExecutionDisabled(bool); void SetScrollbarsHidden(bool); void SetDocumentCookieDisabled(bool); + bool HasViewportOverride() const { return !!viewport_override_; } + // Notify the DevToolsEmulator about a scroll or scale change of the main - // frame. Updates the transform for a viewport override. - void MainFrameScrollOrScaleChanged(); + // frame. Returns an updated emulation transform for a viewport override, and + // should only be called when HasViewportOverride() is true. + TransformationMatrix MainFrameScrollOrScaleChanged(); // Rewrites the |visible_rect| to the area of the devtools custom viewport if // it is enabled. Otherwise, leaves |visible_rect| unchanged. Takes as input @@ -73,16 +76,30 @@ // device metics. float InputEventsScaleForEmulation(); + TransformationMatrix ForceViewportForTesting(const WebFloatPoint& position, + float scale) { + return ForceViewport(position, scale); + } + TransformationMatrix ResetViewportForTesting() { return ResetViewport(); } + private: void EnableMobileEmulation(); void DisableMobileEmulation(); + // Enables viewport override and returns the emulation transform to be used. + // The |position| is in CSS pixels, and |scale| is relative to a page scale of + // 1.0. + TransformationMatrix ForceViewport(const WebFloatPoint& position, + float scale); + // Disables viewport override and returns the emulation transform to be used. + TransformationMatrix ResetViewport(); + // Returns the original device scale factor when overridden by DevTools, or // deviceScaleFactor() otherwise. float CompositorDeviceScaleFactor() const; void ApplyViewportOverride(TransformationMatrix*); - void UpdateRootLayerTransform(); + TransformationMatrix ComputeRootLayerTransform(); WebViewImpl* web_view_;
diff --git a/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc b/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc index 4b4d763..23adb49e 100644 --- a/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc
@@ -40,7 +40,7 @@ #include "third_party/blink/renderer/core/inspector/inspected_frames.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" namespace blink {
diff --git a/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc b/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc index e315558..ca49dbe 100644 --- a/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc
@@ -14,7 +14,7 @@ #include "third_party/blink/renderer/core/paint/paint_timing.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/wtf/dtoa/utils.h" namespace blink {
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc index c11673d..6d0f4cf7 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
@@ -35,7 +35,7 @@ #include "third_party/blink/renderer/core/workers/worker_thread.h" #include "third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h" #include "third_party/blink/renderer/platform/graphics/graphics_layer.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
diff --git a/third_party/blink/renderer/core/layout/layout_object.cc b/third_party/blink/renderer/core/layout/layout_object.cc index 4c1629d..9ddb242 100644 --- a/third_party/blink/renderer/core/layout/layout_object.cc +++ b/third_party/blink/renderer/core/layout/layout_object.cc
@@ -105,7 +105,7 @@ #include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h" #include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h" #include "third_party/blink/renderer/platform/graphics/touch_action.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h"
diff --git a/third_party/blink/renderer/core/layout/layout_object.h b/third_party/blink/renderer/core/layout/layout_object.h index 89c6b324..05ad47a2 100644 --- a/third_party/blink/renderer/core/layout/layout_object.h +++ b/third_party/blink/renderer/core/layout/layout_object.h
@@ -1270,9 +1270,9 @@ // It is also used for correctly sizing absolutely positioned elements // (point 3 above). LayoutObject* Container(AncestorSkipInfo* = nullptr) const; - // Finds the container as if this object is fixed-position. - LayoutObject* ContainerForAbsolutePosition(AncestorSkipInfo* = nullptr) const; // Finds the container as if this object is absolute-position. + LayoutObject* ContainerForAbsolutePosition(AncestorSkipInfo* = nullptr) const; + // Finds the container as if this object is fixed-position. LayoutObject* ContainerForFixedPosition(AncestorSkipInfo* = nullptr) const; bool CanContainOutOfFlowPositionedElement(EPosition position) const {
diff --git a/third_party/blink/renderer/core/layout/layout_text.cc b/third_party/blink/renderer/core/layout/layout_text.cc index 50adcc93..50b7c30 100644 --- a/third_party/blink/renderer/core/layout/layout_text.cc +++ b/third_party/blink/renderer/core/layout/layout_text.cc
@@ -293,9 +293,17 @@ Vector<TextBoxInfo> results; if (const NGOffsetMapping* mapping = GetNGOffsetMapping()) { auto fragments = NGPaintFragment::InlineFragmentsFor(this); + bool in_hidden_for_paint = false; for (const NGPaintFragment* fragment : fragments) { const auto& text_fragment = To<NGPhysicalTextFragment>(fragment->PhysicalFragment()); + if (text_fragment.IsHiddenForPaint()) { + in_hidden_for_paint = true; + } else if (in_hidden_for_paint) { + // Because of we finished original fragments (not painted), we should + // ignore truncated fragments (actually painted). + break; + } // When the corresponding DOM range contains collapsed whitespaces, NG // produces one fragment but legacy produces multiple text boxes broken at // collapsed whitespaces. We break the fragment at collapsed whitespaces
diff --git a/third_party/blink/renderer/core/layout/layout_text_test.cc b/third_party/blink/renderer/core/layout/layout_text_test.cc index 671bb18..14c8171 100644 --- a/third_party/blink/renderer/core/layout/layout_text_test.cc +++ b/third_party/blink/renderer/core/layout/layout_text_test.cc
@@ -431,6 +431,67 @@ EXPECT_EQ(LayoutRect(20, 0, 20, 10), boxes_remaining[1].local_rect); } +// For http://crbug.com/985488 +TEST_P(ParameterizedLayoutTextTest, GetTextBoxInfoWithHidden) { + LoadAhem(); + SetBodyInnerHTML(R"HTML( + <style> + #target { + font: 10px/1 Ahem; + overflow-x: hidden; + white-space: nowrap; + width: 9ch; + } + </style> + <div id="target"> abcde fghij </div> + )HTML"); + const Element& target = *GetElementById("target"); + const LayoutText& layout_text = + *To<Text>(target.firstChild())->GetLayoutObject(); + + auto boxes = layout_text.GetTextBoxInfo(); + EXPECT_EQ(2u, boxes.size()); + + EXPECT_EQ(2u, boxes[0].dom_start_offset); + EXPECT_EQ(6u, boxes[0].dom_length); + EXPECT_EQ(LayoutRect(0, 0, 60, 10), boxes[0].local_rect); + + EXPECT_EQ(9u, boxes[1].dom_start_offset); + EXPECT_EQ(5u, boxes[1].dom_length); + EXPECT_EQ(LayoutRect(60, 0, 50, 10), boxes[1].local_rect); +} + +// For http://crbug.com/985488 +TEST_P(ParameterizedLayoutTextTest, GetTextBoxInfoWithEllipsis) { + LoadAhem(); + SetBodyInnerHTML(R"HTML( + <style> + #target { + font: 10px/1 Ahem; + overflow-x: hidden; + text-overflow: ellipsis; + white-space: nowrap; + width: 9ch; + } + </style> + <div id="target"> abcde fghij </div> + )HTML"); + const Element& target = *GetElementById("target"); + const LayoutText& layout_text = + *To<Text>(target.firstChild())->GetLayoutObject(); + + auto boxes = layout_text.GetTextBoxInfo(); + EXPECT_EQ(2u, boxes.size()); + + EXPECT_EQ(2u, boxes[0].dom_start_offset); + EXPECT_EQ(6u, boxes[0].dom_length); + EXPECT_EQ(LayoutRect(0, 0, 60, 10), boxes[0].local_rect); + + EXPECT_EQ(9u, boxes[1].dom_start_offset); + EXPECT_EQ(5u, boxes[1].dom_length); + EXPECT_EQ(LayoutRect(60, 0, 50, 10), boxes[1].local_rect); +} + TEST_P(ParameterizedLayoutTextTest, IsBeforeAfterNonCollapsedCharacterNoLineWrap) { // Basic tests
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc index 96428ab..93a507f 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc
@@ -60,7 +60,7 @@ marker_positions_.clear(); if (!StyleRef().SvgStyle().HasMarkers() || - !SVGResources::SupportsMarkers(*ToSVGGraphicsElement(GetElement()))) + !SVGResources::SupportsMarkers(*To<SVGGraphicsElement>(GetElement()))) return; SVGResources* resources =
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc index fcbd0e1..0c23bf6 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc
@@ -84,9 +84,10 @@ return ModifyStrategyForClipPath(use_layout_object->StyleRef(), shape_strategy); } - if (!element.IsSVGGraphicsElement()) + auto* svg_graphics_element = DynamicTo<SVGGraphicsElement>(element); + if (!svg_graphics_element) return ClipStrategy::kNone; - return DetermineClipStrategy(ToSVGGraphicsElement(element)); + return DetermineClipStrategy(*svg_graphics_element); } bool ContributesToClip(const SVGElement& element) {
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc index a9e2489..4418ac8 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc
@@ -235,7 +235,7 @@ } bool LayoutSVGShape::UpdateLocalTransform() { - SVGGraphicsElement* graphics_element = ToSVGGraphicsElement(GetElement()); + auto* graphics_element = To<SVGGraphicsElement>(GetElement()); if (graphics_element->HasTransform(SVGElement::kIncludeMotionTransform)) { local_transform_.SetTransform(graphics_element->CalculateTransform( SVGElement::kIncludeMotionTransform));
diff --git a/third_party/blink/renderer/core/loader/empty_clients.h b/third_party/blink/renderer/core/loader/empty_clients.h index ed799ec..469d07148 100644 --- a/third_party/blink/renderer/core/loader/empty_clients.h +++ b/third_party/blink/renderer/core/loader/empty_clients.h
@@ -235,6 +235,8 @@ void SetCursorForPlugin(const WebCursorInfo&, LocalFrame*) override {} void InstallSupplements(LocalFrame&) override {} + + void MainFrameScrollOffsetChanged(LocalFrame& main_frame) const override {} }; class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
diff --git a/third_party/blink/renderer/core/loader/frame_loader.cc b/third_party/blink/renderer/core/loader/frame_loader.cc index 7775189..32125adc 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.cc +++ b/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -97,7 +97,7 @@ #include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h" #include "third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.h" #include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h"
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource.cc b/third_party/blink/renderer/core/loader/resource/image_resource.cc index 5674b55..343eba3 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource.cc
@@ -33,7 +33,7 @@ #include "third_party/blink/renderer/core/loader/resource/image_resource_content.h" #include "third_party/blink/renderer/core/loader/resource/image_resource_info.h" #include "third_party/blink/renderer/platform/histogram.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource_test.cc b/third_party/blink/renderer/core/loader/resource/image_resource_test.cc index 2c1d270..f3de598c 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource_test.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource_test.cc
@@ -45,7 +45,7 @@ #include "third_party/blink/renderer/platform/graphics/bitmap_image.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/heap/heap.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/loader/fetch/console_logger.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_info.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
diff --git a/third_party/blink/renderer/core/page/chrome_client.h b/third_party/blink/renderer/core/page/chrome_client.h index 0ddb011..f1a2e57 100644 --- a/third_party/blink/renderer/core/page/chrome_client.h +++ b/third_party/blink/renderer/core/page/chrome_client.h
@@ -294,7 +294,7 @@ virtual float ClampPageScaleFactorToLimits(float scale) const { return scale; } - virtual void MainFrameScrollOffsetChanged() const {} + virtual void MainFrameScrollOffsetChanged(LocalFrame& main_frame) const = 0; virtual void ResizeAfterLayout() const {} virtual void MainFrameLayoutUpdated() const {}
diff --git a/third_party/blink/renderer/core/page/chrome_client_impl.cc b/third_party/blink/renderer/core/page/chrome_client_impl.cc index 138801a..d4fc2b1 100644 --- a/third_party/blink/renderer/core/page/chrome_client_impl.cc +++ b/third_party/blink/renderer/core/page/chrome_client_impl.cc
@@ -508,7 +508,9 @@ web_view_->PageScaleFactorChanged(); } -void ChromeClientImpl::MainFrameScrollOffsetChanged() const { +void ChromeClientImpl::MainFrameScrollOffsetChanged( + LocalFrame& main_frame) const { + DCHECK(main_frame.IsMainFrame()); web_view_->MainFrameScrollOffsetChanged(); }
diff --git a/third_party/blink/renderer/core/page/chrome_client_impl.h b/third_party/blink/renderer/core/page/chrome_client_impl.h index 1b897c0..b90ab201 100644 --- a/third_party/blink/renderer/core/page/chrome_client_impl.h +++ b/third_party/blink/renderer/core/page/chrome_client_impl.h
@@ -132,7 +132,7 @@ bool DoubleTapToZoomEnabled() const override; void PageScaleFactorChanged() const override; float ClampPageScaleFactorToLimits(float scale) const override; - void MainFrameScrollOffsetChanged() const override; + void MainFrameScrollOffsetChanged(LocalFrame& main_frame) const override; void ResizeAfterLayout() const override; void MainFrameLayoutUpdated() const override; void ShowMouseOverURL(const HitTestResult&) override;
diff --git a/third_party/blink/renderer/core/paint/selection_painting_utils.cc b/third_party/blink/renderer/core/paint/selection_painting_utils.cc index 5426d6fb..8db7227 100644 --- a/third_party/blink/renderer/core/paint/selection_painting_utils.cc +++ b/third_party/blink/renderer/core/paint/selection_painting_utils.cc
@@ -9,6 +9,7 @@ #include "third_party/blink/renderer/core/dom/element_traversal.h" #include "third_party/blink/renderer/core/dom/node.h" #include "third_party/blink/renderer/core/dom/shadow_root.h" +#include "third_party/blink/renderer/core/dom/v0_insertion_point.h" #include "third_party/blink/renderer/core/editing/frame_selection.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/layout/layout_theme.h" @@ -46,10 +47,19 @@ // If we request ::selection style for LayoutText, query ::selection style on // the parent element instead, as that is the node for which ::selection - // matches. + // matches. This should must likely have used FlatTreeTraversal, but since we + // don't implement inheritance of ::selection styles, it would probably break + // cases where you style a shadow host with ::selection and expect light tree + // text children to be affected by that style. Element* element = Traversal<Element>::FirstAncestorOrSelf(*node); - if (!element || element->IsPseudoElement()) + + // <content> and <shadow> elements do not have ComputedStyle, hence they will + // return null for StyleForPseudoElement(). Return early to avoid DCHECK + // failure for GetComputedStyle() inside StyleForPseudoElement() below. + if (!element || element->IsPseudoElement() || + IsActiveV0InsertionPoint(*element)) { return nullptr; + } return element->StyleForPseudoElement(PseudoStyleRequest(kPseudoIdSelection)); }
diff --git a/third_party/blink/renderer/core/resize_observer/resize_observation.cc b/third_party/blink/renderer/core/resize_observer/resize_observation.cc index 8b1cb60..df02d02f 100644 --- a/third_party/blink/renderer/core/resize_observer/resize_observation.cc +++ b/third_party/blink/renderer/core/resize_observer/resize_observation.cc
@@ -39,10 +39,9 @@ LayoutSize ResizeObservation::ComputeTargetSize() const { if (target_) { if (LayoutObject* layout_object = target_->GetLayoutObject()) { - auto* svg_element = DynamicTo<SVGElement>(target_.Get()); - if (svg_element && svg_element->IsSVGGraphicsElement()) { - SVGGraphicsElement& svg = ToSVGGraphicsElement(*target_); - return LayoutSize(svg.GetBBox().Size()); + if (auto* svg_graphics_element = + DynamicTo<SVGGraphicsElement>(target_.Get())) { + return LayoutSize(svg_graphics_element->GetBBox().Size()); } if (layout_object->IsBox()) return ToLayoutBox(layout_object)->ContentSize();
diff --git a/third_party/blink/renderer/core/streams/BUILD.gn b/third_party/blink/renderer/core/streams/BUILD.gn index d8c60b6..e747d5e7 100644 --- a/third_party/blink/renderer/core/streams/BUILD.gn +++ b/third_party/blink/renderer/core/streams/BUILD.gn
@@ -6,12 +6,18 @@ blink_core_sources("streams") { sources = [ + "byte_length_queuing_strategy.cc", + "byte_length_queuing_strategy.h", + "count_queuing_strategy.cc", + "count_queuing_strategy.h", "miscellaneous_operations.cc", "miscellaneous_operations.h", "promise_handler.cc", "promise_handler.h", "queue_with_sizes.cc", "queue_with_sizes.h", + "queuing_strategy_common.cc", + "queuing_strategy_common.h", "readable_stream.cc", "readable_stream.h", "readable_stream_default_controller.cc",
diff --git a/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.cc b/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.cc new file mode 100644 index 0000000..aae8fb8 --- /dev/null +++ b/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.cc
@@ -0,0 +1,101 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h" + +#include "third_party/blink/renderer/bindings/core/v8/script_function.h" +#include "third_party/blink/renderer/bindings/core/v8/script_value.h" +#include "third_party/blink/renderer/core/streams/queuing_strategy_common.h" +#include "third_party/blink/renderer/core/streams/queuing_strategy_init.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/bindings/v8_binding.h" +#include "third_party/blink/renderer/platform/heap/visitor.h" + +namespace blink { + +namespace { + +class ByteLengthQueuingStrategySizeFunction final : public ScriptFunction { + public: + static v8::Local<v8::Function> CreateFunction(ScriptState* script_state) { + ByteLengthQueuingStrategySizeFunction* self = + MakeGarbageCollected<ByteLengthQueuingStrategySizeFunction>( + script_state); + return self->BindToV8Function(); + } + + explicit ByteLengthQueuingStrategySizeFunction(ScriptState* script_state) + : ScriptFunction(script_state) {} + + private: + void CallRaw(const v8::FunctionCallbackInfo<v8::Value>& args) override { + auto* isolate = args.GetIsolate(); + DCHECK_EQ(isolate, GetScriptState()->GetIsolate()); + auto context = GetScriptState()->GetContext(); + v8::Local<v8::Value> chunk; + if (args.Length() < 1) { + chunk = v8::Undefined(isolate); + } else { + chunk = args[0]; + } + + // https://streams.spec.whatwg.org/#blqs-size + // 1. Return ? GetV(chunk, "byteLength"). + + // https://tc39.es/ecma262/#sec-getv + // 1. Assert: IsPropertyKey(P) is true. + // 2. Let O be ? ToObject(V). + v8::Local<v8::Object> chunk_as_object; + if (!chunk->ToObject(context).ToLocal(&chunk_as_object)) { + // Should have thrown an exception, which will be caught further up the + // stack. + return; + } + // 3. Return ? O.[[Get]](P, V). + v8::Local<v8::Value> byte_length; + if (!chunk_as_object->Get(context, V8AtomicString(isolate, "byteLength")) + .ToLocal(&byte_length)) { + // Should have thrown an exception. + return; + } + args.GetReturnValue().Set(byte_length); + } +}; + +} // namespace + +ByteLengthQueuingStrategy* ByteLengthQueuingStrategy::Create( + ScriptState* script_state, + const QueuingStrategyInit* init) { + return MakeGarbageCollected<ByteLengthQueuingStrategy>(script_state, init); +} + +ByteLengthQueuingStrategy::ByteLengthQueuingStrategy( + ScriptState* script_state, + const QueuingStrategyInit* init) + : high_water_mark_(script_state->GetIsolate(), + HighWaterMarkOrUndefined(script_state, init)) {} + +ByteLengthQueuingStrategy::~ByteLengthQueuingStrategy() = default; + +ScriptValue ByteLengthQueuingStrategy::highWaterMark( + ScriptState* script_state) const { + return ScriptValue(script_state, + high_water_mark_.NewLocal(script_state->GetIsolate())); +} + +ScriptValue ByteLengthQueuingStrategy::size(ScriptState* script_state) const { + // We don't cache the result because normally this method will only be called + // once anyway. + return ScriptValue( + script_state, + ByteLengthQueuingStrategySizeFunction::CreateFunction(script_state)); +} + +void ByteLengthQueuingStrategy::Trace(Visitor* visitor) { + visitor->Trace(high_water_mark_); + ScriptWrappable::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h b/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h new file mode 100644 index 0000000..c154421 --- /dev/null +++ b/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h
@@ -0,0 +1,41 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_BYTE_LENGTH_QUEUING_STRATEGY_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_BYTE_LENGTH_QUEUING_STRATEGY_H_ + +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h" +#include "v8/include/v8.h" + +namespace blink { + +class QueuingStrategyInit; +class ScriptState; +class ScriptValue; +class Visitor; + +// https://streams.spec.whatwg.org/#blqs-class +class ByteLengthQueuingStrategy final : public ScriptWrappable { + DEFINE_WRAPPERTYPEINFO(); + + public: + static ByteLengthQueuingStrategy* Create(ScriptState*, + const QueuingStrategyInit*); + + ByteLengthQueuingStrategy(ScriptState*, const QueuingStrategyInit*); + ~ByteLengthQueuingStrategy() override; + + ScriptValue highWaterMark(ScriptState*) const; + ScriptValue size(ScriptState*) const; + + void Trace(Visitor*) override; + + private: + const TraceWrapperV8Reference<v8::Value> high_water_mark_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_BYTE_LENGTH_QUEUING_STRATEGY_H_
diff --git a/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.idl b/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.idl new file mode 100644 index 0000000..af68396e --- /dev/null +++ b/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.idl
@@ -0,0 +1,17 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://streams.spec.whatwg.org/#blqs-class + +[ + Exposed=(Window,Worker,Worklet), + RuntimeEnabled=StreamsNative, + ConstructorCallWith=ScriptState, + Constructor([PermissiveDictionaryConversion] QueuingStrategyInit init) +] interface ByteLengthQueuingStrategy { + [CallWith=ScriptState] readonly attribute any highWaterMark; + + // size is an accessor that returns a function. + [CallWith=ScriptState] readonly attribute any size; +};
diff --git a/third_party/blink/renderer/core/streams/count_queuing_strategy.cc b/third_party/blink/renderer/core/streams/count_queuing_strategy.cc new file mode 100644 index 0000000..2b1aa3b --- /dev/null +++ b/third_party/blink/renderer/core/streams/count_queuing_strategy.cc
@@ -0,0 +1,72 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/streams/count_queuing_strategy.h" + +#include "third_party/blink/renderer/bindings/core/v8/script_function.h" +#include "third_party/blink/renderer/bindings/core/v8/script_value.h" +#include "third_party/blink/renderer/core/streams/queuing_strategy_common.h" +#include "third_party/blink/renderer/core/streams/queuing_strategy_init.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/heap/visitor.h" + +namespace blink { + +namespace { + +class CountQueuingStrategySizeFunction final : public ScriptFunction { + public: + static v8::Local<v8::Function> CreateFunction(ScriptState* script_state) { + CountQueuingStrategySizeFunction* self = + MakeGarbageCollected<CountQueuingStrategySizeFunction>(script_state); + return self->BindToV8Function(); + } + + explicit CountQueuingStrategySizeFunction(ScriptState* script_state) + : ScriptFunction(script_state) {} + + private: + void CallRaw(const v8::FunctionCallbackInfo<v8::Value>& args) override { + // https://streams.spec.whatwg.org/#cqs-size + // 1. Return 1. + args.GetReturnValue().Set( + v8::Integer::New(GetScriptState()->GetIsolate(), 1)); + } +}; + +} // namespace + +CountQueuingStrategy* CountQueuingStrategy::Create( + ScriptState* script_state, + const QueuingStrategyInit* init) { + return MakeGarbageCollected<CountQueuingStrategy>(script_state, init); +} + +CountQueuingStrategy::CountQueuingStrategy(ScriptState* script_state, + const QueuingStrategyInit* init) + : high_water_mark_(script_state->GetIsolate(), + HighWaterMarkOrUndefined(script_state, init)) {} + +CountQueuingStrategy::~CountQueuingStrategy() = default; + +ScriptValue CountQueuingStrategy::highWaterMark( + ScriptState* script_state) const { + return ScriptValue(script_state, + high_water_mark_.NewLocal(script_state->GetIsolate())); +} + +ScriptValue CountQueuingStrategy::size(ScriptState* script_state) const { + // We don't cache the result because normally this method will only be called + // once anyway. + return ScriptValue( + script_state, + CountQueuingStrategySizeFunction::CreateFunction(script_state)); +} + +void CountQueuingStrategy::Trace(Visitor* visitor) { + visitor->Trace(high_water_mark_); + ScriptWrappable::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/streams/count_queuing_strategy.h b/third_party/blink/renderer/core/streams/count_queuing_strategy.h new file mode 100644 index 0000000..246c459 --- /dev/null +++ b/third_party/blink/renderer/core/streams/count_queuing_strategy.h
@@ -0,0 +1,40 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_COUNT_QUEUING_STRATEGY_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_COUNT_QUEUING_STRATEGY_H_ + +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h" +#include "v8/include/v8.h" + +namespace blink { + +class QueuingStrategyInit; +class ScriptState; +class ScriptValue; +class Visitor; + +// https://streams.spec.whatwg.org/#blqs-class +class CountQueuingStrategy final : public ScriptWrappable { + DEFINE_WRAPPERTYPEINFO(); + + public: + static CountQueuingStrategy* Create(ScriptState*, const QueuingStrategyInit*); + + CountQueuingStrategy(ScriptState*, const QueuingStrategyInit*); + ~CountQueuingStrategy() override; + + ScriptValue highWaterMark(ScriptState*) const; + ScriptValue size(ScriptState*) const; + + void Trace(Visitor*) override; + + private: + const TraceWrapperV8Reference<v8::Value> high_water_mark_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_COUNT_QUEUING_STRATEGY_H_
diff --git a/third_party/blink/renderer/core/streams/count_queuing_strategy.idl b/third_party/blink/renderer/core/streams/count_queuing_strategy.idl new file mode 100644 index 0000000..02cfe7a --- /dev/null +++ b/third_party/blink/renderer/core/streams/count_queuing_strategy.idl
@@ -0,0 +1,17 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://streams.spec.whatwg.org/#cqs-class + +[ + Exposed=(Window,Worker,Worklet), + RuntimeEnabled=StreamsNative, + ConstructorCallWith=ScriptState, + Constructor([PermissiveDictionaryConversion] QueuingStrategyInit init) +] interface CountQueuingStrategy { + [CallWith=ScriptState] readonly attribute any highWaterMark; + + // size is an accessor that returns a function. + [CallWith=ScriptState] readonly attribute any size; +};
diff --git a/third_party/blink/renderer/core/streams/queuing_strategy_common.cc b/third_party/blink/renderer/core/streams/queuing_strategy_common.cc new file mode 100644 index 0000000..4441a89 --- /dev/null +++ b/third_party/blink/renderer/core/streams/queuing_strategy_common.cc
@@ -0,0 +1,23 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/streams/queuing_strategy_common.h" + +#include "third_party/blink/renderer/core/streams/queuing_strategy_init.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" + +namespace blink { + +v8::Local<v8::Value> HighWaterMarkOrUndefined(ScriptState* script_state, + const QueuingStrategyInit* init) { + v8::Local<v8::Value> high_water_mark; + if (init->hasHighWaterMark()) { + high_water_mark = init->highWaterMark().V8Value(); + } else { + high_water_mark = v8::Undefined(script_state->GetIsolate()); + } + return high_water_mark; +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/streams/queuing_strategy_common.h b/third_party/blink/renderer/core/streams/queuing_strategy_common.h new file mode 100644 index 0000000..d62e6a8 --- /dev/null +++ b/third_party/blink/renderer/core/streams/queuing_strategy_common.h
@@ -0,0 +1,20 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_QUEUING_STRATEGY_COMMON_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_QUEUING_STRATEGY_COMMON_H_ + +#include "v8/include/v8.h" + +namespace blink { + +class ScriptState; +class QueuingStrategyInit; + +v8::Local<v8::Value> HighWaterMarkOrUndefined(ScriptState* script_state, + const QueuingStrategyInit* init); + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_QUEUING_STRATEGY_COMMON_H_
diff --git a/third_party/blink/renderer/core/streams/queuing_strategy_init.idl b/third_party/blink/renderer/core/streams/queuing_strategy_init.idl new file mode 100644 index 0000000..7d5bd0c --- /dev/null +++ b/third_party/blink/renderer/core/streams/queuing_strategy_init.idl
@@ -0,0 +1,10 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://streams.spec.whatwg.org/#cqs-class + +[PermissiveDictionaryConversion] +dictionary QueuingStrategyInit { + any highWaterMark; +};
diff --git a/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.cc b/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.cc index bff583e1..503581cf8 100644 --- a/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.cc +++ b/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.cc
@@ -31,8 +31,7 @@ namespace blink { -SMILAnimationSandwich::SMILAnimationSandwich() - : earliest_fire_time_(SMILTime::Unresolved()) {} +SMILAnimationSandwich::SMILAnimationSandwich() {} void SMILAnimationSandwich::Schedule(SVGSMILElement* animation) { DCHECK(!sandwich_.Contains(animation)); @@ -70,15 +69,19 @@ } else { animation->ClearAnimatedType(); } - - SMILTime next_fire_time = animation->NextProgressTime(); - if (next_fire_time.IsFinite()) - earliest_fire_time_ = std::min(next_fire_time, earliest_fire_time_); } } SMILTime SMILAnimationSandwich::GetNextFireTime() { - return earliest_fire_time_; + SMILTime earliest_fire_time = SMILTime::Unresolved(); + for (const auto& it_animation : sandwich_) { + SVGSMILElement* animation = it_animation.Get(); + + SMILTime next_fire_time = animation->NextProgressTime(); + if (next_fire_time.IsFinite()) + earliest_fire_time = std::min(next_fire_time, earliest_fire_time); + } + return earliest_fire_time; } void SMILAnimationSandwich::SendEvents(double elapsed, bool seek_to_time) { @@ -106,12 +109,6 @@ scheduled->ClearAnimatedType(); it = active_.erase(it); } - - for (auto& animation : active_) { - SMILTime next_fire_time = animation->NextProgressTime(); - if (next_fire_time.IsFinite()) - earliest_fire_time_ = std::min(next_fire_time, earliest_fire_time_); - } } SVGSMILElement* SMILAnimationSandwich::ApplyAnimationValues() {
diff --git a/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h b/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h index 1511fe9..f783f3d 100644 --- a/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h +++ b/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h
@@ -76,7 +76,6 @@ // The list stored here is always sorted. ScheduledVector sandwich_; ScheduledVector active_; - SMILTime earliest_fire_time_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/svg/svg_graphics_element.h b/third_party/blink/renderer/core/svg/svg_graphics_element.h index fd03167..2b60208 100644 --- a/third_party/blink/renderer/core/svg/svg_graphics_element.h +++ b/third_party/blink/renderer/core/svg/svg_graphics_element.h
@@ -91,6 +91,14 @@ return element.IsSVGGraphicsElement(); } +template <> +struct DowncastTraits<SVGGraphicsElement> { + static bool AllowFrom(const Node& node) { + auto* svg_element = DynamicTo<SVGElement>(node); + return svg_element && IsSVGGraphicsElement(*svg_element); + } +}; + DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGGraphicsElement); } // namespace blink
diff --git a/third_party/blink/renderer/core/svg/svg_svg_element.cc b/third_party/blink/renderer/core/svg/svg_svg_element.cc index d078db9..fa5d203 100644 --- a/third_party/blink/renderer/core/svg/svg_svg_element.cc +++ b/third_party/blink/renderer/core/svg/svg_svg_element.cc
@@ -323,7 +323,7 @@ return false; AffineTransform ctm = - ToSVGGraphicsElement(element).ComputeCTM(kAncestorScope, this); + To<SVGGraphicsElement>(element).ComputeCTM(kAncestorScope, this); FloatRect mapped_repaint_rect = ctm.MapRect(layout_object->VisualRectInLocalSVGCoordinates());
diff --git a/third_party/blink/renderer/core/svg/svg_use_element.cc b/third_party/blink/renderer/core/svg/svg_use_element.cc index 86b6df14..2d5a2b3 100644 --- a/third_party/blink/renderer/core/svg/svg_use_element.cc +++ b/third_party/blink/renderer/core/svg/svg_use_element.cc
@@ -499,23 +499,21 @@ SVGGraphicsElement* SVGUseElement::VisibleTargetGraphicsElementForClipping() const { - auto* element = DynamicTo<SVGElement>(UseShadowRoot().firstChild()); - if (!element) - return nullptr; - - if (!element->IsSVGGraphicsElement()) + auto* svg_graphics_element = + DynamicTo<SVGGraphicsElement>(UseShadowRoot().firstChild()); + if (!svg_graphics_element) return nullptr; // Spec: "If a <use> element is a child of a clipPath element, it must // directly reference <path>, <text> or basic shapes elements. Indirect // references are an error and the clipPath element must be ignored." // https://drafts.fxtf.org/css-masking/#the-clip-path - if (!IsDirectReference(*element)) { + if (!IsDirectReference(*svg_graphics_element)) { // Spec: Indirect references are an error (14.3.5) return nullptr; } - return &ToSVGGraphicsElement(*element); + return svg_graphics_element; } void SVGUseElement::AddReferencesToFirstDegreeNestedUseElements(
diff --git a/third_party/blink/renderer/core/testing/internals.cc b/third_party/blink/renderer/core/testing/internals.cc index b093fa8..ad853e1b 100644 --- a/third_party/blink/renderer/core/testing/internals.cc +++ b/third_party/blink/renderer/core/testing/internals.cc
@@ -34,6 +34,7 @@ #include "gpu/command_buffer/client/gles2_interface.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_graphics_context_3d_provider.h" +#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/renderer/bindings/core/v8/script_function.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" @@ -164,7 +165,7 @@ #include "third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/heap/heap.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/language.h" #include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h" @@ -272,8 +273,7 @@ // call. page->SetDefaultPageScaleLimits(1, 4); page->SetPageScaleFactor(1); - page->GetChromeClient().GetWebView()->SetDeviceEmulationTransform( - TransformationMatrix()); + page->GetChromeClient().GetWebView()->DisableDeviceEmulation(); // Ensure timers are reset so timers such as EventHandler's |hover_timer_| do // not cause additional lifecycle updates. @@ -3461,8 +3461,9 @@ "The document's page cannot be retrieved."); return; } - page->GetChromeClient().GetWebView()->SetDeviceEmulationTransform( - TransformationMatrix().Scale(scale)); + WebDeviceEmulationParams params; + params.scale = scale; + page->GetChromeClient().GetWebView()->EnableDeviceEmulation(params); } void Internals::ResolveResourcePriority(ScriptPromiseResolver* resolver,
diff --git a/third_party/blink/renderer/core/workers/worker_global_scope.cc b/third_party/blink/renderer/core/workers/worker_global_scope.cc index 86d6f330..a50179a 100644 --- a/third_party/blink/renderer/core/workers/worker_global_scope.cc +++ b/third_party/blink/renderer/core/workers/worker_global_scope.cc
@@ -63,7 +63,7 @@ #include "third_party/blink/renderer/core/workers/worker_thread.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/microtask.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h" #include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
diff --git a/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc b/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc index feedc00..664e74c5 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc +++ b/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc
@@ -52,7 +52,7 @@ #include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h" #include "third_party/blink/renderer/platform/content_decryption_module_result.h" #include "third_party/blink/renderer/platform/heap/heap.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/network/mime/content_type.h" #include "third_party/blink/renderer/platform/timer.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
diff --git a/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc b/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc index 9b64c93..6fdacf0 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc +++ b/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc
@@ -42,7 +42,7 @@ #include "third_party/blink/renderer/modules/encryptedmedia/media_keys_policy.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/timer.h"
diff --git a/third_party/blink/renderer/modules/modules_idl_files.gni b/third_party/blink/renderer/modules/modules_idl_files.gni index 6c90bfb..f270ac9 100644 --- a/third_party/blink/renderer/modules/modules_idl_files.gni +++ b/third_party/blink/renderer/modules/modules_idl_files.gni
@@ -225,8 +225,11 @@ "native_file_system/file_system_handle.idl", "native_file_system/file_system_writer.idl", "netinfo/network_information.idl", - "nfc/nfc.idl", + "nfc/ndef_message.idl", + "nfc/ndef_record.idl", "nfc/nfc_error_event.idl", + "nfc/nfc.idl", + "nfc/nfc_reading_event.idl", "nfc/nfc_writer.idl", "notifications/notification.idl", "notifications/notification_event.idl", @@ -327,7 +330,7 @@ "speech/speech_grammar_list.idl", "speech/speech_recognition.idl", "speech/speech_recognition_alternative.idl", - "speech/speech_recognition_error.idl", + "speech/speech_recognition_error_event.idl", "speech/speech_recognition_event.idl", "speech/speech_recognition_result.idl", "speech/speech_recognition_result_list.idl", @@ -672,11 +675,12 @@ "native_file_system/file_system_remove_options.idl", "native_file_system/get_system_directory_options.idl", "native_file_system/native_file_system_directory_iterator_entry.idl", - "nfc/ndef_message.idl", + "nfc/ndef_message_init.idl", "nfc/nfc_push_options.idl", - "nfc/ndef_record.idl", + "nfc/ndef_record_init.idl", "nfc/nfc_reader_options.idl", "nfc/nfc_error_event_init.idl", + "nfc/nfc_reading_event_init.idl", "notifications/get_notification_options.idl", "notifications/notification_action.idl", "notifications/notification_event_init.idl", @@ -771,7 +775,7 @@ "shapedetection/face_detector_options.idl", "shapedetection/landmark.idl", "sms/sms_receiver_options.idl", - "speech/speech_recognition_error_init.idl", + "speech/speech_recognition_error_event_init.idl", "speech/speech_recognition_event_init.idl", "speech/speech_synthesis_error_event_init.idl", "speech/speech_synthesis_event_init.idl",
diff --git a/third_party/blink/renderer/modules/nfc/BUILD.gn b/third_party/blink/renderer/modules/nfc/BUILD.gn index 6e256b1..9b4f4715 100644 --- a/third_party/blink/renderer/modules/nfc/BUILD.gn +++ b/third_party/blink/renderer/modules/nfc/BUILD.gn
@@ -8,6 +8,10 @@ sources = [ "navigator_nfc.cc", "navigator_nfc.h", + "ndef_message.cc", + "ndef_message.h", + "ndef_record.cc", + "ndef_record.h", "nfc.cc", "nfc.h", "nfc_constants.cc", @@ -20,6 +24,8 @@ "nfc_proxy.h", "nfc_reader.cc", "nfc_reader.h", + "nfc_reading_event.cc", + "nfc_reading_event.h", "nfc_type_converters.cc", "nfc_type_converters.h", "nfc_utils.cc",
diff --git a/third_party/blink/renderer/modules/nfc/ndef_message.cc b/third_party/blink/renderer/modules/nfc/ndef_message.cc new file mode 100644 index 0000000..914adad --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/ndef_message.cc
@@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/nfc/ndef_message.h" + +#include "services/device/public/mojom/nfc.mojom-blink.h" +#include "third_party/blink/renderer/modules/nfc/ndef_message_init.h" +#include "third_party/blink/renderer/modules/nfc/ndef_record.h" + +namespace blink { + +// static +NDEFMessage* NDEFMessage::Create(const NDEFMessageInit* init) { + return MakeGarbageCollected<NDEFMessage>(init); +} + +NDEFMessage::NDEFMessage(const NDEFMessageInit* init) : url_(init->url()) { + if (init->hasRecords()) { + for (const NDEFRecordInit* record_init : init->records()) + records_.push_back(NDEFRecord::Create(record_init)); + } +} + +NDEFMessage::NDEFMessage(const device::mojom::blink::NDEFMessagePtr& message) + : url_(message->url) { + for (wtf_size_t i = 0; i < message->data.size(); ++i) { + records_.push_back(MakeGarbageCollected<NDEFRecord>(message->data[i])); + } +} + +const String& NDEFMessage::url() const { + return url_; +} + +const HeapVector<Member<NDEFRecord>>& NDEFMessage::records() const { + return records_; +} + +void NDEFMessage::Trace(blink::Visitor* visitor) { + visitor->Trace(records_); + ScriptWrappable::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/nfc/ndef_message.h b/third_party/blink/renderer/modules/nfc/ndef_message.h new file mode 100644 index 0000000..0b74cca --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/ndef_message.h
@@ -0,0 +1,40 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_MESSAGE_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_MESSAGE_H_ + +#include "services/device/public/mojom/nfc.mojom-blink-forward.h" +#include "third_party/blink/renderer/modules/modules_export.h" +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { + +class NDEFMessageInit; +class NDEFRecord; + +class MODULES_EXPORT NDEFMessage final : public ScriptWrappable { + DEFINE_WRAPPERTYPEINFO(); + + public: + static NDEFMessage* Create(const NDEFMessageInit*); + + NDEFMessage(const NDEFMessageInit*); + NDEFMessage(const device::mojom::blink::NDEFMessagePtr&); + + const String& url() const; + const HeapVector<Member<NDEFRecord>>& records() const; + + void Trace(blink::Visitor*) override; + + private: + String url_; + HeapVector<Member<NDEFRecord>> records_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_MESSAGE_H_
diff --git a/third_party/blink/renderer/modules/nfc/ndef_message.idl b/third_party/blink/renderer/modules/nfc/ndef_message.idl index a5e816e..d3c808b0 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_message.idl +++ b/third_party/blink/renderer/modules/nfc/ndef_message.idl
@@ -4,7 +4,12 @@ // https://w3c.github.io/web-nfc/#dom-ndefmessage -dictionary NDEFMessage { - sequence<NDEFRecord> records; - USVString url; +[ + RuntimeEnabled=WebNFC, + SecureContext, + Constructor(NDEFMessageInit messageInit), + Exposed=Window +] interface NDEFMessage { + readonly attribute USVString url; + readonly attribute FrozenArray<NDEFRecord> records; };
diff --git a/third_party/blink/renderer/modules/nfc/ndef_message_init.idl b/third_party/blink/renderer/modules/nfc/ndef_message_init.idl new file mode 100644 index 0000000..d6b68ae --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/ndef_message_init.idl
@@ -0,0 +1,10 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://w3c.github.io/web-nfc/#dom-ndefmessageinit + +dictionary NDEFMessageInit { + USVString url; + sequence<NDEFRecordInit> records; +};
diff --git a/third_party/blink/renderer/modules/nfc/ndef_record.cc b/third_party/blink/renderer/modules/nfc/ndef_record.cc new file mode 100644 index 0000000..69d9246 --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/ndef_record.cc
@@ -0,0 +1,157 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/nfc/ndef_record.h" + +#include "services/device/public/mojom/nfc.mojom-blink.h" +#include "third_party/blink/renderer/bindings/modules/v8/string_or_unrestricted_double_or_array_buffer_or_dictionary.h" +#include "third_party/blink/renderer/modules/nfc/ndef_record_init.h" +#include "third_party/blink/renderer/modules/nfc/nfc_utils.h" + +namespace blink { + +// static +NDEFRecord* NDEFRecord::Create(const NDEFRecordInit* init) { + return MakeGarbageCollected<NDEFRecord>(init); +} + +NDEFRecord::NDEFRecord(const NDEFRecordInit* init) + : record_type_(init->recordType()), media_type_(init->mediaType()) { + if (init->data().IsArrayBuffer()) { + data_type_ = DataType::kArrayBuffer; + // Keep our own copy of data so that modifications of the original + // ArrayBuffer |init->data()| in JS world do not affect us. + DOMArrayBuffer* original = init->data().GetAsArrayBuffer(); + array_buffer_ = + WTF::ArrayBuffer::Create(original->Data(), original->ByteLength()); + } else if (init->data().IsDictionary()) { + data_type_ = DataType::kDictionary; + // |dictionary| holds a V8 value of a JS Dictionary object, because WebIDL + // spec (https://heycam.github.io/webidl/#idl-dictionaries) says that + // dictionaries are always passed by value, rather than holding a reference + // to it, here we stringify and save the dictionary data as |string_|, from + // which we can build new Dictionary objects later when necessary. + Dictionary dictionary = init->data().GetAsDictionary(); + v8::Local<v8::String> jsonString; + v8::Isolate* isolate = dictionary.GetIsolate(); + v8::TryCatch try_catch(isolate); + if (v8::JSON::Stringify(dictionary.V8Context(), dictionary.V8Value()) + .ToLocal(&jsonString) && + !try_catch.HasCaught()) { + string_ = ToBlinkString<String>(jsonString, kDoNotExternalize); + } + } else if (init->data().IsString()) { + data_type_ = DataType::kString; + string_ = init->data().GetAsString(); + } else if (init->data().IsUnrestrictedDouble()) { + data_type_ = DataType::kUnrestrictedDouble; + unrestricted_double_ = init->data().GetAsUnrestrictedDouble(); + } +} + +NDEFRecord::NDEFRecord(const device::mojom::blink::NDEFRecordPtr& record) + : record_type_(NDEFRecordTypeToString(record->record_type)), + media_type_(record->media_type) { + switch (record->record_type) { + case device::mojom::blink::NDEFRecordType::TEXT: + case device::mojom::blink::NDEFRecordType::URL: + case device::mojom::blink::NDEFRecordType::JSON: { + String string_data; + if (!record->data.IsEmpty()) { + string_data = String::FromUTF8WithLatin1Fallback( + static_cast<unsigned char*>(&record->data.front()), + record->data.size()); + } + + // Convert back the stringified double. + if (record->record_type == device::mojom::blink::NDEFRecordType::TEXT) { + bool can_convert = false; + double number = string_data.ToDouble(&can_convert); + if (can_convert) { + data_type_ = DataType::kUnrestrictedDouble; + unrestricted_double_ = number; + return; + } + } + + // Save the stringified JSON. + if (record->record_type == device::mojom::blink::NDEFRecordType::JSON) { + data_type_ = DataType::kDictionary; + string_ = string_data; + return; + } + + data_type_ = DataType::kString; + string_ = string_data; + return; + } + + case device::mojom::blink::NDEFRecordType::OPAQUE_RECORD: { + if (!record->data.IsEmpty()) { + data_type_ = DataType::kArrayBuffer; + array_buffer_ = WTF::ArrayBuffer::Create( + static_cast<void*>(&record->data.front()), record->data.size()); + } + return; + } + + case device::mojom::blink::NDEFRecordType::EMPTY: + return; + } + NOTREACHED(); + return; +} + +const String& NDEFRecord::recordType() const { + return record_type_; +} + +const String& NDEFRecord::mediaType() const { + return media_type_; +} + +void NDEFRecord::data( + ScriptState* script_state, + StringOrUnrestrictedDoubleOrArrayBufferOrDictionary& out) const { + switch (data_type_) { + case DataType::kNone: + return; + case DataType::kArrayBuffer: + // We want NDEFRecord.data() to return a new ArrayBuffer object in JS + // world each time. + out.SetArrayBuffer(DOMArrayBuffer::Create(array_buffer_->Data(), + array_buffer_->ByteLength())); + return; + case DataType::kDictionary: { + // We want NDEFRecord.data() to return a new Dictionary object in JS world + // each time. + v8::Isolate* isolate = script_state->GetIsolate(); + v8::Local<v8::String> string = V8String(isolate, string_); + v8::Local<v8::Value> json_object; + v8::TryCatch try_catch(isolate); + NonThrowableExceptionState exception_state; + if (v8::JSON::Parse(script_state->GetContext(), string) + .ToLocal(&json_object)) { + out.SetDictionary(Dictionary(isolate, json_object, exception_state)); + } else { + out.SetDictionary(Dictionary()); + } + return; + } + case DataType::kString: + out.SetString(string_); + return; + case DataType::kUnrestrictedDouble: + out.SetUnrestrictedDouble(unrestricted_double_); + return; + } + NOTREACHED(); + return; +} + +void NDEFRecord::Trace(blink::Visitor* visitor) { + ScriptWrappable::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/nfc/ndef_record.h b/third_party/blink/renderer/modules/nfc/ndef_record.h new file mode 100644 index 0000000..cd1d561b --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/ndef_record.h
@@ -0,0 +1,58 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_RECORD_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_RECORD_H_ + +#include "services/device/public/mojom/nfc.mojom-blink-forward.h" +#include "third_party/blink/renderer/modules/modules_export.h" +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { + +class NDEFRecordInit; +class ScriptState; +class StringOrUnrestrictedDoubleOrArrayBufferOrDictionary; + +class MODULES_EXPORT NDEFRecord final : public ScriptWrappable { + DEFINE_WRAPPERTYPEINFO(); + + public: + static NDEFRecord* Create(const NDEFRecordInit*); + + NDEFRecord(const NDEFRecordInit*); + NDEFRecord(const device::mojom::blink::NDEFRecordPtr&); + + const String& recordType() const; + const String& mediaType() const; + void data(ScriptState*, + StringOrUnrestrictedDoubleOrArrayBufferOrDictionary&) const; + + void Trace(blink::Visitor*) override; + + private: + String record_type_; + String media_type_; + + enum class DataType { + kNone, + kArrayBuffer, + kDictionary, + kString, + kUnrestrictedDouble, + }; + DataType data_type_ = DataType::kNone; + // For array buffer data type. + scoped_refptr<WTF::ArrayBuffer> array_buffer_; + // For dictionary or string data type. + String string_; + // For double data type. + double unrestricted_double_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_RECORD_H_
diff --git a/third_party/blink/renderer/modules/nfc/ndef_record.idl b/third_party/blink/renderer/modules/nfc/ndef_record.idl index a335b3f..46a5063 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_record.idl +++ b/third_party/blink/renderer/modules/nfc/ndef_record.idl
@@ -2,14 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://w3c.github.io/web-nfc/#the-nfcrecord-dictionary +// https://w3c.github.io/web-nfc/#dom-ndefrecord -enum NDEFRecordType { "empty", "text", "url", "json", "opaque" }; - -typedef (DOMString or unrestricted double or ArrayBuffer or Dictionary) NDEFRecordData; - -dictionary NDEFRecord { - NDEFRecordType recordType; - USVString mediaType; - NDEFRecordData data; +[ + RuntimeEnabled=WebNFC, + SecureContext, + Constructor(NDEFRecordInit recordInit), + Exposed=Window +] interface NDEFRecord { + readonly attribute NDEFRecordType recordType; + readonly attribute USVString mediaType; + [CallWith=ScriptState] NDEFRecordData data(); };
diff --git a/third_party/blink/renderer/modules/nfc/ndef_record_init.idl b/third_party/blink/renderer/modules/nfc/ndef_record_init.idl new file mode 100644 index 0000000..8affcfb06 --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/ndef_record_init.idl
@@ -0,0 +1,15 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://w3c.github.io/web-nfc/#dom-ndefrecordinit + +enum NDEFRecordType { "empty", "text", "url", "json", "opaque" }; + +typedef (DOMString or unrestricted double or ArrayBuffer or Dictionary) NDEFRecordData; + +dictionary NDEFRecordInit { + NDEFRecordType recordType; + USVString mediaType; + NDEFRecordData data; +};
diff --git a/third_party/blink/renderer/modules/nfc/nfc.cc b/third_party/blink/renderer/modules/nfc/nfc.cc index ae491f3..826f3b4 100644 --- a/third_party/blink/renderer/modules/nfc/nfc.cc +++ b/third_party/blink/renderer/modules/nfc/nfc.cc
@@ -265,10 +265,8 @@ callback->CallbackRelevantScriptStateOrReportError("NFC", "watch"); if (!script_state) continue; - ScriptState::Scope scope(script_state); - const NDEFMessage* ndef_message = - MojoToBlinkNDEFMessage(script_state, message); - callback->InvokeAndReportException(nullptr, ndef_message); + callback->InvokeAndReportException( + nullptr, MakeGarbageCollected<NDEFMessage>(message)); } } }
diff --git a/third_party/blink/renderer/modules/nfc/nfc.idl b/third_party/blink/renderer/modules/nfc/nfc.idl index 9876547d..b610a71 100644 --- a/third_party/blink/renderer/modules/nfc/nfc.idl +++ b/third_party/blink/renderer/modules/nfc/nfc.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/web-nfc/#dom-ndefmessagesource -typedef (DOMString or ArrayBuffer or NDEFMessage) NDEFMessageSource; +typedef (DOMString or ArrayBuffer or NDEFMessageInit) NDEFMessageSource; // https://w3c.github.io/web-nfc/#the-nfc-interface
diff --git a/third_party/blink/renderer/modules/nfc/nfc_constants.h b/third_party/blink/renderer/modules/nfc/nfc_constants.h index 4fef80ef..3a25c9dc 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_constants.h +++ b/third_party/blink/renderer/modules/nfc/nfc_constants.h
@@ -5,12 +5,12 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NFC_CONSTANTS_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NFC_CONSTANTS_H_ -#include "third_party/blink/renderer/bindings/modules/v8/string_or_array_buffer_or_ndef_message.h" +#include "third_party/blink/renderer/bindings/modules/v8/string_or_array_buffer_or_ndef_message_init.h" #include "third_party/blink/renderer/bindings/modules/v8/string_or_unrestricted_double_or_array_buffer_or_dictionary.h" namespace blink { -using NDEFMessageSource = blink::StringOrArrayBufferOrNDEFMessage; +using NDEFMessageSource = blink::StringOrArrayBufferOrNDEFMessageInit; using NDEFRecordData = blink::StringOrUnrestrictedDoubleOrArrayBufferOrDictionary;
diff --git a/third_party/blink/renderer/modules/nfc/nfc_reading_event.cc b/third_party/blink/renderer/modules/nfc/nfc_reading_event.cc new file mode 100644 index 0000000..6d244fb --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/nfc_reading_event.cc
@@ -0,0 +1,39 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/nfc/nfc_reading_event.h" + +#include "third_party/blink/renderer/modules/nfc/ndef_message.h" +#include "third_party/blink/renderer/modules/nfc/nfc_reading_event_init.h" + +namespace blink { + +NFCReadingEvent::NFCReadingEvent(const AtomicString& event_type, + const NFCReadingEventInit* initializer) + : Event(event_type, initializer), + serial_number_(initializer->serialNumber()), + message_(NDEFMessage::Create(initializer->message())) {} + +NFCReadingEvent::~NFCReadingEvent() = default; + +const AtomicString& NFCReadingEvent::InterfaceName() const { + return event_interface_names::kNFCReadingEvent; +} + +void NFCReadingEvent::Trace(blink::Visitor* visitor) { + visitor->Trace(message_); + Event::Trace(visitor); +} + +const String& NFCReadingEvent::serialNumber() const { + if (serial_number_.IsNull()) + return g_empty_string; + return serial_number_; +} + +NDEFMessage* NFCReadingEvent::message() const { + return message_; +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/nfc/nfc_reading_event.h b/third_party/blink/renderer/modules/nfc/nfc_reading_event.h new file mode 100644 index 0000000..7ade2c02 --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/nfc_reading_event.h
@@ -0,0 +1,51 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NFC_READING_EVENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NFC_READING_EVENT_H_ + +#include "third_party/blink/renderer/modules/event_modules.h" +#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { + +class NDEFMessage; +class NFCReadingEventInit; + +class NFCReadingEvent final : public Event { + DEFINE_WRAPPERTYPEINFO(); + + public: + static NFCReadingEvent* Create(const AtomicString& event_type, + const NFCReadingEventInit* initializer) { + return MakeGarbageCollected<NFCReadingEvent>(event_type, initializer); + } + + NFCReadingEvent(const AtomicString&, const NFCReadingEventInit*); + ~NFCReadingEvent() override; + + const AtomicString& InterfaceName() const override; + + void Trace(blink::Visitor*) override; + + const String& serialNumber() const; + NDEFMessage* message() const; + + private: + String serial_number_; + Member<NDEFMessage> message_; +}; + +DEFINE_TYPE_CASTS(NFCReadingEvent, + Event, + event, + event->InterfaceName() == + event_interface_names::kNFCReadingEvent, + event.InterfaceName() == + event_interface_names::kNFCReadingEvent); + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NFC_READING_EVENT_H_
diff --git a/third_party/blink/renderer/modules/nfc/nfc_reading_event.idl b/third_party/blink/renderer/modules/nfc/nfc_reading_event.idl new file mode 100644 index 0000000..e5ad46c37 --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/nfc_reading_event.idl
@@ -0,0 +1,16 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Specification at: +// http://w3c.github.io/web-nfc/#dom-nfcreadingevent + +[ + RuntimeEnabled=WebNFC, + SecureContext, + Constructor(DOMString type, NFCReadingEventInit eventInitDict), + Exposed=Window +] interface NFCReadingEvent : Event { + readonly attribute DOMString serialNumber; + [SameObject] readonly attribute NDEFMessage message; +};
diff --git a/third_party/blink/renderer/modules/nfc/nfc_reading_event_init.idl b/third_party/blink/renderer/modules/nfc/nfc_reading_event_init.idl new file mode 100644 index 0000000..69641859 --- /dev/null +++ b/third_party/blink/renderer/modules/nfc/nfc_reading_event_init.idl
@@ -0,0 +1,11 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Specification at: +// http://w3c.github.io/web-nfc/#dom-nfcreadingeventinit + +dictionary NFCReadingEventInit : EventInit { + DOMString? serialNumber = ""; + required NDEFMessageInit message; +};
diff --git a/third_party/blink/renderer/modules/nfc/nfc_type_converters.cc b/third_party/blink/renderer/modules/nfc/nfc_type_converters.cc index 25c3a40..972ff8f 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_type_converters.cc +++ b/third_party/blink/renderer/modules/nfc/nfc_type_converters.cc
@@ -100,6 +100,13 @@ return mojo::ConvertTo<Vector<uint8_t>>(value.GetAsString()); } + // TODO(https://crbug.com/520391): Remove this duplicate code for stringifying + // json, by reusing the same code in NDEFRecord ctor. i.e. Make users of this + // type converter: + // 1. first construct a NDEFRecord from the given NDEFRecordInit, the + // NDEFRecord ctor would stringify json. + // 2. then convert the NDEFRecord into an mojom::NDEFRecordPtr, which should + // be just simple. if (value.IsDictionary()) { v8::Local<v8::String> jsonString; blink::Dictionary dictionary = value.GetAsDictionary(); @@ -126,8 +133,8 @@ return base::nullopt; } -NDEFRecordPtr TypeConverter<NDEFRecordPtr, blink::NDEFRecord*>::Convert( - const blink::NDEFRecord* record) { +NDEFRecordPtr TypeConverter<NDEFRecordPtr, blink::NDEFRecordInit*>::Convert( + const blink::NDEFRecordInit* record) { NDEFRecordPtr recordPtr = NDEFRecord::New(); if (record->hasRecordType()) { @@ -172,8 +179,8 @@ return recordPtr; } -NDEFMessagePtr TypeConverter<NDEFMessagePtr, blink::NDEFMessage*>::Convert( - const blink::NDEFMessage* message) { +NDEFMessagePtr TypeConverter<NDEFMessagePtr, blink::NDEFMessageInit*>::Convert( + const blink::NDEFMessageInit* message) { NDEFMessagePtr messagePtr = NDEFMessage::New(); messagePtr->url = message->url(); messagePtr->data.resize(message->records().size()); @@ -199,8 +206,8 @@ if (message.IsString()) return NDEFMessage::From(message.GetAsString()); - if (message.IsNDEFMessage()) - return NDEFMessage::From(message.GetAsNDEFMessage()); + if (message.IsNDEFMessageInit()) + return NDEFMessage::From(message.GetAsNDEFMessageInit()); if (message.IsArrayBuffer()) return NDEFMessage::From(message.GetAsArrayBuffer());
diff --git a/third_party/blink/renderer/modules/nfc/nfc_type_converters.h b/third_party/blink/renderer/modules/nfc/nfc_type_converters.h index 73f3693..998b3a8 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_type_converters.h +++ b/third_party/blink/renderer/modules/nfc/nfc_type_converters.h
@@ -11,8 +11,8 @@ namespace blink { class DOMArrayBuffer; -class NDEFRecord; -class NDEFMessage; +class NDEFRecordInit; +class NDEFMessageInit; class NFCReaderOptions; class NFCPushOptions; } // namespace blink @@ -55,16 +55,17 @@ }; template <> -struct TypeConverter<device::mojom::blink::NDEFRecordPtr, blink::NDEFRecord*> { +struct TypeConverter<device::mojom::blink::NDEFRecordPtr, + blink::NDEFRecordInit*> { static device::mojom::blink::NDEFRecordPtr Convert( - const blink::NDEFRecord* record); + const blink::NDEFRecordInit* record); }; template <> struct TypeConverter<device::mojom::blink::NDEFMessagePtr, - blink::NDEFMessage*> { + blink::NDEFMessageInit*> { static device::mojom::blink::NDEFMessagePtr Convert( - const blink::NDEFMessage* message); + const blink::NDEFMessageInit* message); }; template <>
diff --git a/third_party/blink/renderer/modules/nfc/nfc_utils.cc b/third_party/blink/renderer/modules/nfc/nfc_utils.cc index eefa920..1d2c3574 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_utils.cc +++ b/third_party/blink/renderer/modules/nfc/nfc_utils.cc
@@ -19,7 +19,7 @@ namespace blink { ScriptPromise RejectIfInvalidTextRecord(ScriptState* script_state, - const NDEFRecord* record) { + const NDEFRecordInit* record) { const NDEFRecordData& value = record->data(); if (!value.IsString() && !(value.IsUnrestrictedDouble() && @@ -42,7 +42,7 @@ } ScriptPromise RejectIfInvalidURLRecord(ScriptState* script_state, - const NDEFRecord* record) { + const NDEFRecordInit* record) { if (!record->data().IsString()) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( @@ -60,7 +60,7 @@ } ScriptPromise RejectIfInvalidJSONRecord(ScriptState* script_state, - const NDEFRecord* record) { + const NDEFRecordInit* record) { if (!record->data().IsDictionary()) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( @@ -83,7 +83,7 @@ } ScriptPromise RejectIfInvalidOpaqueRecord(ScriptState* script_state, - const NDEFRecord* record) { + const NDEFRecordInit* record) { if (!record->data().IsArrayBuffer()) { return ScriptPromise::Reject( script_state, @@ -95,7 +95,7 @@ } ScriptPromise RejectIfInvalidNDEFRecord(ScriptState* script_state, - const NDEFRecord* record) { + const NDEFRecordInit* record) { NDEFRecordType type; if (record->hasRecordType()) { type = StringToNDEFRecordType(record->recordType()); @@ -140,7 +140,7 @@ ScriptPromise RejectIfInvalidNDEFRecordArray( ScriptState* script_state, - const HeapVector<Member<NDEFRecord>>& records) { + const HeapVector<Member<NDEFRecordInit>>& records) { for (const auto& record : records) { ScriptPromise isValidRecord = RejectIfInvalidNDEFRecord(script_state, record); @@ -155,17 +155,17 @@ ScriptState* script_state, const NDEFMessageSource& push_message) { // If NDEFMessageSource of invalid type, reject promise with TypeError - if (!push_message.IsNDEFMessage() && !push_message.IsString() && + if (!push_message.IsNDEFMessageInit() && !push_message.IsString() && !push_message.IsArrayBuffer()) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), kNfcMsgTypeError)); } - if (push_message.IsNDEFMessage()) { + if (push_message.IsNDEFMessageInit()) { // https://w3c.github.io/web-nfc/#the-push-method // If NDEFMessage.records is empty, reject promise with TypeError - const NDEFMessage* message = push_message.GetAsNDEFMessage(); + const NDEFMessageInit* message = push_message.GetAsNDEFMessageInit(); if (!message->hasRecords() || message->records().IsEmpty()) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( @@ -178,74 +178,13 @@ return ScriptPromise(); } -NDEFRecordData BuildRecordData( - ScriptState* script_state, - const device::mojom::blink::NDEFRecordPtr& record) { - NDEFRecordData result = NDEFRecordData(); - switch (record->record_type) { - case NDEFRecordType::TEXT: - case NDEFRecordType::URL: - case NDEFRecordType::JSON: { - String string_data; - if (!record->data.IsEmpty()) { - string_data = String::FromUTF8WithLatin1Fallback( - static_cast<unsigned char*>(&record->data.front()), - record->data.size()); - } - - // Convert back the stringified double. - if (record->record_type == NDEFRecordType::TEXT) { - bool can_convert = false; - double number = string_data.ToDouble(&can_convert); - if (can_convert) { - result.SetUnrestrictedDouble(number); - return result; - } - } - - // Stringified JSON must be converted back to an Object. - if (record->record_type == NDEFRecordType::JSON) { - v8::Isolate* isolate = script_state->GetIsolate(); - v8::Local<v8::String> string = V8String(isolate, string_data); - v8::Local<v8::Value> json_object; - v8::TryCatch try_catch(isolate); - NonThrowableExceptionState exception_state; - - if (v8::JSON::Parse(script_state->GetContext(), string) - .ToLocal(&json_object)) { - result.SetDictionary( - Dictionary(isolate, json_object, exception_state)); - return result; - } - } - - result.SetString(string_data); - return result; - } - - case NDEFRecordType::OPAQUE_RECORD: { - if (!record->data.IsEmpty()) { - result.SetArrayBuffer(DOMArrayBuffer::Create( - static_cast<void*>(&record->data.front()), record->data.size())); - } - - return result; - } - - case NDEFRecordType::EMPTY: - return result; - } - - NOTREACHED(); - return result; -} - // https://w3c.github.io/web-nfc/#creating-web-nfc-message Step 2.1 // If NDEFRecord type is not provided, deduce NDEFRecord type from JS data type: // String or Number => 'text' record // ArrayBuffer => 'opaque' record // Dictionary, JSON serializable Object => 'json' record -NDEFRecordType DeduceRecordTypeFromDataType(const blink::NDEFRecord* record) { +NDEFRecordType DeduceRecordTypeFromDataType( + const blink::NDEFRecordInit* record) { if (record->hasData()) { const blink::NDEFRecordData& value = record->data(); @@ -349,26 +288,4 @@ return NFCPushTarget::ANY; } -NDEFRecord* MojoToBlinkNDEFRecord( - ScriptState* script_state, - const device::mojom::blink::NDEFRecordPtr& record) { - NDEFRecord* nfc_record = NDEFRecord::Create(); - nfc_record->setMediaType(record->media_type); - nfc_record->setRecordType(NDEFRecordTypeToString(record->record_type)); - nfc_record->setData(BuildRecordData(script_state, record)); - return nfc_record; -} - -NDEFMessage* MojoToBlinkNDEFMessage( - ScriptState* script_state, - const device::mojom::blink::NDEFMessagePtr& message) { - NDEFMessage* ndef_message = NDEFMessage::Create(); - ndef_message->setURL(message->url); - blink::HeapVector<Member<NDEFRecord>> records; - for (wtf_size_t i = 0; i < message->data.size(); ++i) - records.push_back(MojoToBlinkNDEFRecord(script_state, message->data[i])); - ndef_message->setRecords(records); - return ndef_message; -} - } // namespace blink
diff --git a/third_party/blink/renderer/modules/nfc/nfc_utils.h b/third_party/blink/renderer/modules/nfc/nfc_utils.h index 142c196..338241e 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_utils.h +++ b/third_party/blink/renderer/modules/nfc/nfc_utils.h
@@ -7,40 +7,38 @@ #include "services/device/public/mojom/nfc.mojom-blink-forward.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/modules/nfc/ndef_message.h" +#include "third_party/blink/renderer/modules/nfc/ndef_record.h" #include "third_party/blink/renderer/modules/nfc/nfc_constants.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { ScriptPromise RejectIfInvalidTextRecord(ScriptState* script_state, - const NDEFRecord* record); + const NDEFRecordInit* record); ScriptPromise RejectIfInvalidURLRecord(ScriptState* script_state, - const NDEFRecord* record); + const NDEFRecordInit* record); ScriptPromise RejectIfInvalidJSONRecord(ScriptState* script_state, - const NDEFRecord* record); + const NDEFRecordInit* record); ScriptPromise RejectIfInvalidOpaqueRecord(ScriptState* script_state, - const NDEFRecord* record); + const NDEFRecordInit* record); ScriptPromise RejectIfInvalidNDEFRecord(ScriptState* script_state, - const NDEFRecord* record); + const NDEFRecordInit* record); ScriptPromise RejectIfInvalidNDEFRecordArray( ScriptState* script_state, - const HeapVector<Member<NDEFRecord>>& records); + const HeapVector<Member<NDEFRecordInit>>& records); ScriptPromise RejectIfInvalidNDEFMessageSource( ScriptState* script_state, const NDEFMessageSource& push_message); -NDEFRecordData BuildRecordData( - ScriptState* script_state, - const device::mojom::blink::NDEFRecordPtr& record); - device::mojom::blink::NDEFRecordType DeduceRecordTypeFromDataType( - const blink::NDEFRecord* record); + const blink::NDEFRecordInit* record); size_t GetNDEFMessageSize(const device::mojom::blink::NDEFMessagePtr& message); @@ -59,14 +57,6 @@ device::mojom::blink::NFCPushTarget StringToNFCPushTarget( const WTF::String& target); -NDEFRecord* MojoToBlinkNDEFRecord( - ScriptState* script_state, - const device::mojom::blink::NDEFRecordPtr& record); - -NDEFMessage* MojoToBlinkNDEFMessage( - ScriptState* script_state, - const device::mojom::blink::NDEFMessagePtr& message); - } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NFC_UTILS_H_
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc index c6c98b20..4bbd200 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc
@@ -71,12 +71,17 @@ if (channel.negotiated()) IncrementCounter(DataChannelCounters::kNegotiated); - UMA_HISTOGRAM_CUSTOM_COUNTS("WebRTC.DataChannelMaxRetransmits", - channel.maxRetransmits(), 1, - std::numeric_limits<uint16_t>::max(), 50); - UMA_HISTOGRAM_CUSTOM_COUNTS("WebRTC.DataChannelMaxRetransmitTime", - channel.maxRetransmitTime(), 1, - std::numeric_limits<uint16_t>::max(), 50); + // Only record max retransmits and max packet life time if set. + if (channel.maxRetransmitsOpt()) { + UMA_HISTOGRAM_CUSTOM_COUNTS("WebRTC.DataChannelMaxRetransmits", + *(channel.maxRetransmitsOpt()), 1, + std::numeric_limits<uint16_t>::max(), 50); + } + if (channel.maxPacketLifeTime()) { + UMA_HISTOGRAM_CUSTOM_COUNTS("WebRTC.DataChannelMaxPacketLifeTime", + *channel.maxPacketLifeTime(), 1, + std::numeric_limits<uint16_t>::max(), 50); + } } void RecordMessageSent(const webrtc::DataChannelInterface& channel, @@ -257,14 +262,24 @@ return channel()->ordered(); } -uint16_t RTCDataChannel::maxRetransmitTime() const { +uint16_t RTCDataChannel::maxPacketLifeTime(bool& is_null) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return channel()->maxRetransmitTime(); + if (channel()->maxPacketLifeTime()) { + is_null = false; + return *(channel()->maxPacketLifeTime()); + } + is_null = true; + return -1; } -uint16_t RTCDataChannel::maxRetransmits() const { +uint16_t RTCDataChannel::maxRetransmits(bool& is_null) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return channel()->maxRetransmits(); + if (channel()->maxRetransmitsOpt()) { + is_null = false; + return *(channel()->maxRetransmitsOpt()); + } + is_null = true; + return -1; } String RTCDataChannel::protocol() const {
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h index fee0a31..dd39e9c 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h
@@ -66,8 +66,8 @@ bool reliable() const; bool ordered() const; - uint16_t maxRetransmitTime() const; - uint16_t maxRetransmits() const; + uint16_t maxPacketLifeTime(bool&) const; + uint16_t maxRetransmits(bool&) const; String protocol() const; bool negotiated() const; uint16_t id(bool& is_null) const;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.idl b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.idl index 92e630b..85f38c6 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.idl
@@ -40,10 +40,8 @@ ] interface RTCDataChannel : EventTarget { readonly attribute USVString label; readonly attribute boolean ordered; - // TODO(foolip): |maxRetransmitTime| is called |maxPacketLifeTime| in the - // spec and both it and |maxRetransmits| are nullable. - [Measure] readonly attribute unsigned short maxRetransmitTime; - [Measure] readonly attribute unsigned short maxRetransmits; + readonly attribute unsigned short? maxPacketLifeTime; + readonly attribute unsigned short? maxRetransmits; readonly attribute USVString protocol; readonly attribute boolean negotiated; readonly attribute unsigned short? id;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc index 3eea9f50..b0c1661 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc
@@ -84,8 +84,12 @@ std::string label() const override { return std::string(); } bool reliable() const override { return false; } bool ordered() const override { return false; } - uint16_t maxRetransmitTime() const override { return 0; } - uint16_t maxRetransmits() const override { return 0; } + absl::optional<int> maxPacketLifeTime() const override { + return absl::nullopt; + } + absl::optional<int> maxRetransmitsOpt() const override { + return absl::nullopt; + } std::string protocol() const override { return std::string(); } bool negotiated() const override { return false; } int id() const override { return 0; }
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc index a9193de..b75a74049 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -113,7 +113,7 @@ #include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/heap/persistent.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_answer_options_platform.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_offer_options_platform.h"
diff --git a/third_party/blink/renderer/modules/permissions/permissions.cc b/third_party/blink/renderer/modules/permissions/permissions.cc index ef94bd7..383fdcc 100644 --- a/third_party/blink/renderer/modules/permissions/permissions.cc +++ b/third_party/blink/renderer/modules/permissions/permissions.cc
@@ -145,7 +145,8 @@ if (name == "idle-detection") return CreatePermissionDescriptor(PermissionName::IDLE_DETECTION); if (name == "periodic-background-sync") { - if (!RuntimeEnabledFeatures::PeriodicBackgroundSyncEnabled()) { + if (!RuntimeEnabledFeatures::PeriodicBackgroundSyncEnabled( + ExecutionContext::From(script_state))) { exception_state.ThrowTypeError( "Periodic Background Sync is not enabled."); return nullptr;
diff --git a/third_party/blink/renderer/modules/speech/BUILD.gn b/third_party/blink/renderer/modules/speech/BUILD.gn index 7a45f96..6b664e1 100644 --- a/third_party/blink/renderer/modules/speech/BUILD.gn +++ b/third_party/blink/renderer/modules/speech/BUILD.gn
@@ -19,8 +19,8 @@ "speech_recognition_alternative.h", "speech_recognition_controller.cc", "speech_recognition_controller.h", - "speech_recognition_error.cc", - "speech_recognition_error.h", + "speech_recognition_error_event.cc", + "speech_recognition_error_event.h", "speech_recognition_event.cc", "speech_recognition_event.h", "speech_recognition_result.cc",
diff --git a/third_party/blink/renderer/modules/speech/speech_recognition.cc b/third_party/blink/renderer/modules/speech/speech_recognition.cc index a8180d7..9b6db1d 100644 --- a/third_party/blink/renderer/modules/speech/speech_recognition.cc +++ b/third_party/blink/renderer/modules/speech/speech_recognition.cc
@@ -30,7 +30,7 @@ #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/modules/speech/speech_recognition_controller.h" -#include "third_party/blink/renderer/modules/speech/speech_recognition_error.h" +#include "third_party/blink/renderer/modules/speech/speech_recognition_error_event.h" #include "third_party/blink/renderer/modules/speech/speech_recognition_event.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" @@ -141,7 +141,7 @@ DispatchEvent(*SpeechRecognitionEvent::CreateNoMatch(nullptr)); } else { // TODO(primiano): message? - DispatchEvent(*SpeechRecognitionError::Create(error->code, String())); + DispatchEvent(*SpeechRecognitionErrorEvent::Create(error->code, String())); } }
diff --git a/third_party/blink/renderer/modules/speech/speech_recognition_error.cc b/third_party/blink/renderer/modules/speech/speech_recognition_error_event.cc similarity index 78% rename from third_party/blink/renderer/modules/speech/speech_recognition_error.cc rename to third_party/blink/renderer/modules/speech/speech_recognition_error_event.cc index 19f2123..b6af5b3 100644 --- a/third_party/blink/renderer/modules/speech/speech_recognition_error.cc +++ b/third_party/blink/renderer/modules/speech/speech_recognition_error_event.cc
@@ -23,7 +23,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "third_party/blink/renderer/modules/speech/speech_recognition_error.h" +#include "third_party/blink/renderer/modules/speech/speech_recognition_error_event.h" #include "third_party/blink/renderer/core/event_type_names.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" @@ -59,28 +59,29 @@ return String(); } -SpeechRecognitionError* SpeechRecognitionError::Create( +SpeechRecognitionErrorEvent* SpeechRecognitionErrorEvent::Create( mojom::blink::SpeechRecognitionErrorCode code, const String& message) { - return MakeGarbageCollected<SpeechRecognitionError>(ErrorCodeToString(code), - message); + return MakeGarbageCollected<SpeechRecognitionErrorEvent>( + ErrorCodeToString(code), message); } -SpeechRecognitionError* SpeechRecognitionError::Create( +SpeechRecognitionErrorEvent* SpeechRecognitionErrorEvent::Create( const AtomicString& event_name, - const SpeechRecognitionErrorInit* initializer) { - return MakeGarbageCollected<SpeechRecognitionError>(event_name, initializer); + const SpeechRecognitionErrorEventInit* initializer) { + return MakeGarbageCollected<SpeechRecognitionErrorEvent>(event_name, + initializer); } -SpeechRecognitionError::SpeechRecognitionError(const String& error, - const String& message) +SpeechRecognitionErrorEvent::SpeechRecognitionErrorEvent(const String& error, + const String& message) : Event(event_type_names::kError, Bubbles::kNo, Cancelable::kNo), error_(error), message_(message) {} -SpeechRecognitionError::SpeechRecognitionError( +SpeechRecognitionErrorEvent::SpeechRecognitionErrorEvent( const AtomicString& event_name, - const SpeechRecognitionErrorInit* initializer) + const SpeechRecognitionErrorEventInit* initializer) : Event(event_name, initializer) { if (initializer->hasError()) error_ = initializer->error(); @@ -88,8 +89,8 @@ message_ = initializer->message(); } -const AtomicString& SpeechRecognitionError::InterfaceName() const { - return event_interface_names::kSpeechRecognitionError; +const AtomicString& SpeechRecognitionErrorEvent::InterfaceName() const { + return event_interface_names::kSpeechRecognitionErrorEvent; } } // namespace blink
diff --git a/third_party/blink/renderer/modules/speech/speech_recognition_error.h b/third_party/blink/renderer/modules/speech/speech_recognition_error_event.h similarity index 81% rename from third_party/blink/renderer/modules/speech/speech_recognition_error.h rename to third_party/blink/renderer/modules/speech/speech_recognition_error_event.h index 2d09edd..b2a4bfc 100644 --- a/third_party/blink/renderer/modules/speech/speech_recognition_error.h +++ b/third_party/blink/renderer/modules/speech/speech_recognition_error_event.h
@@ -23,30 +23,31 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_ERROR_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_ERROR_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_ERROR_EVENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_ERROR_EVENT_H_ #include "third_party/blink/public/mojom/speech/speech_recognition_error_code.mojom-blink.h" #include "third_party/blink/renderer/modules/event_modules.h" #include "third_party/blink/renderer/modules/modules_export.h" -#include "third_party/blink/renderer/modules/speech/speech_recognition_error_init.h" +#include "third_party/blink/renderer/modules/speech/speech_recognition_error_event_init.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { -class MODULES_EXPORT SpeechRecognitionError final : public Event { +class MODULES_EXPORT SpeechRecognitionErrorEvent final : public Event { DEFINE_WRAPPERTYPEINFO(); public: - static SpeechRecognitionError* Create( + static SpeechRecognitionErrorEvent* Create( mojom::blink::SpeechRecognitionErrorCode, const String&); - static SpeechRecognitionError* Create(const AtomicString&, - const SpeechRecognitionErrorInit*); + static SpeechRecognitionErrorEvent* Create( + const AtomicString&, + const SpeechRecognitionErrorEventInit*); - SpeechRecognitionError(const String&, const String&); - SpeechRecognitionError(const AtomicString&, - const SpeechRecognitionErrorInit*); + SpeechRecognitionErrorEvent(const String&, const String&); + SpeechRecognitionErrorEvent(const AtomicString&, + const SpeechRecognitionErrorEventInit*); const String& error() { return error_; } const String& message() { return message_; } @@ -62,4 +63,4 @@ } // namespace blink -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_ERROR_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_ERROR_EVENT_H_
diff --git a/third_party/blink/renderer/modules/speech/speech_recognition_error.idl b/third_party/blink/renderer/modules/speech/speech_recognition_error_event.idl similarity index 91% rename from third_party/blink/renderer/modules/speech/speech_recognition_error.idl rename to third_party/blink/renderer/modules/speech/speech_recognition_error_event.idl index 8d75ad25..837251cb 100644 --- a/third_party/blink/renderer/modules/speech/speech_recognition_error.idl +++ b/third_party/blink/renderer/modules/speech/speech_recognition_error_event.idl
@@ -27,8 +27,8 @@ [ NoInterfaceObject, - Constructor(DOMString type, optional SpeechRecognitionErrorInit initDict) -] interface SpeechRecognitionError : Event { + Constructor(DOMString type, optional SpeechRecognitionErrorEventInit eventInitDict) +] interface SpeechRecognitionErrorEvent : Event { readonly attribute DOMString error; readonly attribute DOMString message; };
diff --git a/third_party/blink/renderer/modules/speech/speech_recognition_error_init.idl b/third_party/blink/renderer/modules/speech/speech_recognition_error_event_init.idl similarity index 83% rename from third_party/blink/renderer/modules/speech/speech_recognition_error_init.idl rename to third_party/blink/renderer/modules/speech/speech_recognition_error_event_init.idl index 5e47501..997973f 100644 --- a/third_party/blink/renderer/modules/speech/speech_recognition_error_init.idl +++ b/third_party/blink/renderer/modules/speech/speech_recognition_error_event_init.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/speech-api/#dictdef-speechrecognitionerroreventinit -dictionary SpeechRecognitionErrorInit : EventInit { +dictionary SpeechRecognitionErrorEventInit : EventInit { DOMString error; DOMString message; };
diff --git a/third_party/blink/renderer/modules/speech/window_speech.idl b/third_party/blink/renderer/modules/speech/window_speech.idl index 4aa18e25..9f30b4fd 100644 --- a/third_party/blink/renderer/modules/speech/window_speech.idl +++ b/third_party/blink/renderer/modules/speech/window_speech.idl
@@ -9,6 +9,7 @@ [Measure] attribute SpeechGrammarConstructor webkitSpeechGrammar; [Measure] attribute SpeechGrammarListConstructor webkitSpeechGrammarList; [Measure] attribute SpeechRecognitionConstructor webkitSpeechRecognition; - [Measure] attribute SpeechRecognitionErrorConstructor webkitSpeechRecognitionError; + // Note that the prefixed variant does not end with "Event". + [Measure] attribute SpeechRecognitionErrorEventConstructor webkitSpeechRecognitionError; [Measure] attribute SpeechRecognitionEventConstructor webkitSpeechRecognitionEvent; };
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node.cc b/third_party/blink/renderer/modules/webaudio/audio_node.cc index c559fdb..9106a384 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_node.cc
@@ -32,7 +32,7 @@ #include "third_party/blink/renderer/modules/webaudio/base_audio_context.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #if DEBUG_AUDIONODE_REFERENCES #include <stdio.h>
diff --git a/third_party/blink/renderer/modules/webaudio/testing/internals_web_audio.cc b/third_party/blink/renderer/modules/webaudio/testing/internals_web_audio.cc index f45f5db..cca65bc8 100644 --- a/third_party/blink/renderer/modules/webaudio/testing/internals_web_audio.cc +++ b/third_party/blink/renderer/modules/webaudio/testing/internals_web_audio.cc
@@ -5,7 +5,7 @@ #include "third_party/blink/renderer/modules/webaudio/testing/internals_web_audio.h" #include "third_party/blink/renderer/modules/webaudio/audio_node.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" namespace blink {
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_queue.idl b/third_party/blink/renderer/modules/webgpu/gpu_queue.idl index d047a2b..85ad859 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_queue.idl +++ b/third_party/blink/renderer/modules/webgpu/gpu_queue.idl
@@ -8,6 +8,7 @@ RuntimeEnabled=WebGPU ] interface GPUQueue { void submit(sequence<GPUCommandBuffer> buffers); + + GPUFence createFence(optional GPUFenceDescriptor descriptor); void signal(GPUFence fence, unsigned long long signalValue); - GPUFence createFence(GPUFenceDescriptor descriptor); };
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 7c61d0e..1fe682f9 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -1150,10 +1150,6 @@ "image-encoders/image_encoder.h", "image-encoders/image_encoder_utils.cc", "image-encoders/image_encoder_utils.h", - "instance_counters.cc", - "instance_counters.h", - "instance_counters_memory_dump_provider.cc", - "instance_counters_memory_dump_provider.h", "json/json_parser.cc", "json/json_parser.h", "json/json_values.cc",
diff --git a/third_party/blink/renderer/platform/bindings/DEPS b/third_party/blink/renderer/platform/bindings/DEPS index 07d4036..8ccefe1 100644 --- a/third_party/blink/renderer/platform/bindings/DEPS +++ b/third_party/blink/renderer/platform/bindings/DEPS
@@ -9,7 +9,7 @@ "+gin/public", "+third_party/blink/renderer/platform/wtf/cross_thread_functional.h", "+third_party/blink/renderer/platform/heap", - "+third_party/blink/renderer/platform/instance_counters.h", + "+third_party/blink/renderer/platform/instrumentation/instance_counters.h", "+third_party/blink/renderer/platform/instrumentation", "+third_party/blink/renderer/platform/instrumentation/memory_pressure_listener.h", "+third_party/blink/renderer/platform/platform_export.h",
diff --git a/third_party/blink/renderer/platform/bindings/script_state.cc b/third_party/blink/renderer/platform/bindings/script_state.cc index 8475e28..e6428e1 100644 --- a/third_party/blink/renderer/platform/bindings/script_state.cc +++ b/third_party/blink/renderer/platform/bindings/script_state.cc
@@ -6,7 +6,7 @@ #include "third_party/blink/renderer/platform/bindings/v8_binding.h" #include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" namespace blink {
diff --git a/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc b/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc index 386783f..c1aa7f71 100644 --- a/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc +++ b/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc
@@ -41,7 +41,7 @@ #include "third_party/blink/renderer/platform/bindings/v8_binding.h" #include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h" #include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" namespace blink {
diff --git a/third_party/blink/renderer/platform/exported/platform.cc b/third_party/blink/renderer/platform/exported/platform.cc index 55b90ec..fa5319ac 100644 --- a/third_party/blink/renderer/platform/exported/platform.cc +++ b/third_party/blink/renderer/platform/exported/platform.cc
@@ -54,7 +54,7 @@ #include "third_party/blink/renderer/platform/heap/blink_gc_memory_dump_provider.h" #include "third_party/blink/renderer/platform/heap/gc_task_runner.h" #include "third_party/blink/renderer/platform/histogram.h" -#include "third_party/blink/renderer/platform/instance_counters_memory_dump_provider.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters_memory_dump_provider.h" #include "third_party/blink/renderer/platform/instrumentation/memory_pressure_listener.h" #include "third_party/blink/renderer/platform/instrumentation/partition_alloc_memory_dump_provider.h" #include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/renderer_resource_coordinator.h"
diff --git a/third_party/blink/renderer/platform/heap/heap_stats_collector.cc b/third_party/blink/renderer/platform/heap/heap_stats_collector.cc index dc454f7..0dd41b7c 100644 --- a/third_party/blink/renderer/platform/heap/heap_stats_collector.cc +++ b/third_party/blink/renderer/platform/heap/heap_stats_collector.cc
@@ -100,13 +100,11 @@ collected_wrapper_count_ += count; } -void ThreadHeapStatsCollector::NotifyMarkingStarted(BlinkGC::GCReason reason, - size_t gc_age) { +void ThreadHeapStatsCollector::NotifyMarkingStarted(BlinkGC::GCReason reason) { DCHECK(!is_started_); DCHECK(current_.marking_time().is_zero()); is_started_ = true; current_.reason = reason; - current_.gc_age = gc_age; } void ThreadHeapStatsCollector::NotifyMarkingCompleted(size_t marked_bytes) { @@ -130,24 +128,19 @@ } void ThreadHeapStatsCollector::NotifySweepingCompleted() { - DCHECK(is_started()); is_started_ = false; current_.live_object_rate = current_.object_size_in_bytes_before_sweeping ? static_cast<double>(current().marked_bytes) / current_.object_size_in_bytes_before_sweeping : 0.0; - current_.gc_nested_in_v8 = gc_nested_in_v8_; + current_.gc_nested_in_v8_ = gc_nested_in_v8_; gc_nested_in_v8_ = base::TimeDelta(); // Reset the current state. static_assert(std::is_trivially_copyable<Event>::value, "Event should be trivially copyable"); previous_ = std::move(current_); current_ = Event(); - - ForAllObservers([this](ThreadHeapStatsObserver* observer) { - observer->GCFinished(previous_); - }); } void ThreadHeapStatsCollector::UpdateReason(BlinkGC::GCReason reason) {
diff --git a/third_party/blink/renderer/platform/heap/heap_stats_collector.h b/third_party/blink/renderer/platform/heap/heap_stats_collector.h index bff2b9f..3a127c7 100644 --- a/third_party/blink/renderer/platform/heap/heap_stats_collector.h +++ b/third_party/blink/renderer/platform/heap/heap_stats_collector.h
@@ -16,7 +16,30 @@ namespace blink { -class ThreadHeapStatsObserver; +// Interface for observing changes to heap sizing. +class PLATFORM_EXPORT ThreadHeapStatsObserver { + public: + // Called upon allocating/releasing chunks of memory that contain objects. + // + // Must not trigger GC or allocate. + virtual void IncreaseAllocatedSpace(size_t) = 0; + virtual void DecreaseAllocatedSpace(size_t) = 0; + + // Called once per GC cycle with the accurate number of live |bytes|. + // + // Must not trigger GC or allocate. + virtual void ResetAllocatedObjectSize(size_t bytes) = 0; + + // Called after observing at least + // |ThreadHeapStatsCollector::kUpdateThreshold| changed bytes through + // allocation or explicit free. Reports both, negative and positive + // increments, to allow observer to decide whether absolute values or only the + // deltas is interesting. + // + // May trigger GC but most not allocate. + virtual void IncreaseAllocatedObjectSize(size_t) = 0; + virtual void DecreaseAllocatedObjectSize(size_t) = 0; +}; #define FOR_ALL_SCOPES(V) \ V(AtomicPauseCompaction) \ @@ -256,12 +279,11 @@ size_t partition_alloc_bytes_before_sweeping = 0; double live_object_rate = 0; size_t wrapper_count_before_sweeping = 0; - base::TimeDelta gc_nested_in_v8; - size_t gc_age = 0; + base::TimeDelta gc_nested_in_v8_; }; // Indicates a new garbage collection cycle. - void NotifyMarkingStarted(BlinkGC::GCReason, size_t); + void NotifyMarkingStarted(BlinkGC::GCReason); // Indicates that marking of the current garbage collection cycle is // completed. @@ -327,6 +349,7 @@ // Statistics for the previously running garbage collection. const Event& previous() const { return previous_; } + void RegisterObserver(ThreadHeapStatsObserver* observer); void UnregisterObserver(ThreadHeapStatsObserver* observer); @@ -379,34 +402,6 @@ #undef FOR_ALL_SCOPES #undef FOR_ALL_CONCURRENT_SCOPES -// Interface for observing garbage collections and heap sizing. -class PLATFORM_EXPORT ThreadHeapStatsObserver { - public: - // Called upon allocating/releasing chunks of memory that contain objects. - // - // Must not trigger GC or allocate. - virtual void IncreaseAllocatedSpace(size_t) {} - virtual void DecreaseAllocatedSpace(size_t) {} - - // Called once per GC cycle with the accurate number of live |bytes|. - // - // Must not trigger GC or allocate. - virtual void ResetAllocatedObjectSize(size_t bytes) {} - - // Called after observing at least - // |ThreadHeapStatsCollector::kUpdateThreshold| changed bytes through - // allocation or explicit free. Reports both, negative and positive - // increments, to allow observer to decide whether absolute values or only the - // deltas is interesting. - // - // May trigger GC but most not allocate. - virtual void IncreaseAllocatedObjectSize(size_t) {} - virtual void DecreaseAllocatedObjectSize(size_t) {} - - // Called at the end of a GC cycle. - virtual void GCFinished(const ThreadHeapStatsCollector::Event& stats) {} -}; - } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_STATS_COLLECTOR_H_
diff --git a/third_party/blink/renderer/platform/heap/heap_stats_collector_test.cc b/third_party/blink/renderer/platform/heap/heap_stats_collector_test.cc index 009c938..314f68f9 100644 --- a/third_party/blink/renderer/platform/heap/heap_stats_collector_test.cc +++ b/third_party/blink/renderer/platform/heap/heap_stats_collector_test.cc
@@ -12,7 +12,6 @@ namespace { constexpr size_t kNoMarkedBytes = 0; -constexpr size_t kDefaultGCAge = 0; } // namespace @@ -22,8 +21,7 @@ TEST(ThreadHeapStatsCollectorTest, InitialEmpty) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); for (int i = 0; i < ThreadHeapStatsCollector::kNumScopeIds; i++) { EXPECT_EQ(base::TimeDelta(), stats_collector.current().scope_data[i]); } @@ -33,8 +31,7 @@ TEST(ThreadHeapStatsCollectorTest, IncreaseScopeTime) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kIncrementalMarkingStep, base::TimeDelta::FromMilliseconds(1)); @@ -47,8 +44,7 @@ TEST(ThreadHeapStatsCollectorTest, StopMovesCurrentToPrevious) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kIncrementalMarkingStep, base::TimeDelta::FromMilliseconds(1)); @@ -61,8 +57,7 @@ TEST(ThreadHeapStatsCollectorTest, StopResetsCurrent) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kIncrementalMarkingStep, base::TimeDelta::FromMilliseconds(1)); @@ -76,8 +71,7 @@ TEST(ThreadHeapStatsCollectorTest, StartStop) { ThreadHeapStatsCollector stats_collector; EXPECT_FALSE(stats_collector.is_started()); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); EXPECT_TRUE(stats_collector.is_started()); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.NotifySweepingCompleted(); @@ -92,8 +86,7 @@ TEST(ThreadHeapStatsCollectorTest, UpdateReason) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.UpdateReason(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifySweepingCompleted(); @@ -103,8 +96,7 @@ TEST(ThreadHeapStatsCollectorTest, InitialEstimatedObjectSize) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); EXPECT_EQ(0u, stats_collector.object_size_in_bytes()); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.NotifySweepingCompleted(); @@ -112,8 +104,7 @@ TEST(ThreadHeapStatsCollectorTest, EstimatedObjectSizeNoMarkedBytes) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseAllocatedObjectSizeForTesting(512); EXPECT_EQ(512u, stats_collector.object_size_in_bytes()); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); @@ -122,12 +113,10 @@ TEST(ThreadHeapStatsCollectorTest, EstimatedObjectSizeWithMarkedBytes) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.IncreaseAllocatedObjectSizeForTesting(512); EXPECT_EQ(640u, stats_collector.object_size_in_bytes()); @@ -137,12 +126,10 @@ TEST(ThreadHeapStatsCollectorTest, EstimatedObjectSizeDoNotCountCurrentlyMarkedBytes) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); // Currently marked bytes should not account to the estimated object size. stats_collector.IncreaseAllocatedObjectSizeForTesting(512); @@ -154,8 +141,7 @@ // Checks that a marking time estimate can be retrieved before the first // garbage collection triggers. ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); EXPECT_LT(0u, stats_collector.estimated_marking_time_in_seconds()); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.NotifySweepingCompleted(); @@ -163,15 +149,13 @@ TEST(ThreadHeapStatsCollectorTest, EstimatedMarkingTime1) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kAtomicPauseMarkTransitiveClosure, base::TimeDelta::FromSeconds(1)); stats_collector.NotifyMarkingCompleted(1024); stats_collector.NotifySweepingCompleted(); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); EXPECT_DOUBLE_EQ(1.0, stats_collector.estimated_marking_time_in_seconds()); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.NotifySweepingCompleted(); @@ -179,15 +163,13 @@ TEST(ThreadHeapStatsCollectorTest, EstimatedMarkingTime2) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kAtomicPauseMarkTransitiveClosure, base::TimeDelta::FromSeconds(1)); stats_collector.NotifyMarkingCompleted(1024); stats_collector.NotifySweepingCompleted(); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseAllocatedObjectSizeForTesting(512); EXPECT_DOUBLE_EQ(1.5, stats_collector.estimated_marking_time_in_seconds()); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); @@ -196,8 +178,7 @@ TEST(ThreadHeapStatsCollectorTest, SubMilliSecondMarkingTime) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kIncrementalMarkingStartMarking, base::TimeDelta::FromMillisecondsD(.5)); @@ -210,8 +191,7 @@ TEST(ThreadHeapStatsCollectorTest, AllocatedSpaceInBytesInitialZero) { ThreadHeapStatsCollector stats_collector; EXPECT_EQ(0u, stats_collector.allocated_space_bytes()); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); EXPECT_EQ(0u, stats_collector.allocated_space_bytes()); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); EXPECT_EQ(0u, stats_collector.allocated_space_bytes()); @@ -238,8 +218,7 @@ TEST(ThreadHeapStatsCollectorTest, EventPrevGCMarkedObjectSize) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(1024); stats_collector.NotifySweepingCompleted(); EXPECT_EQ(1024u, stats_collector.previous().marked_bytes); @@ -248,8 +227,7 @@ TEST(ThreadHeapStatsCollectorTest, EventMarkingTimeFromIncrementalStandAloneGC) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kIncrementalMarkingStartMarking, base::TimeDelta::FromMilliseconds(7)); @@ -267,8 +245,7 @@ TEST(ThreadHeapStatsCollectorTest, EventMarkingTimeFromIncrementalUnifiedGC) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kIncrementalMarkingStartMarking, base::TimeDelta::FromMilliseconds(7)); @@ -295,8 +272,7 @@ TEST(ThreadHeapStatsCollectorTest, EventMarkingTime) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kIncrementalMarkingStep, base::TimeDelta::FromMilliseconds(2)); @@ -311,8 +287,7 @@ TEST(ThreadHeapStatsCollectorTest, EventAtomicMarkingTime) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kAtomicPauseMarkPrologue, base::TimeDelta::FromMilliseconds(5)); @@ -330,8 +305,7 @@ TEST(ThreadHeapStatsCollectorTest, EventAtomicPause) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kAtomicPauseMarkTransitiveClosure, base::TimeDelta::FromMilliseconds(17)); @@ -346,8 +320,7 @@ TEST(ThreadHeapStatsCollectorTest, EventMarkingTimePerByteInS) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseScopeTime( ThreadHeapStatsCollector::kAtomicPauseMarkTransitiveClosure, base::TimeDelta::FromSeconds(1)); @@ -359,8 +332,7 @@ TEST(ThreadHeapStatsCollectorTest, EventSweepingTime) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.IncreaseScopeTime(ThreadHeapStatsCollector::kLazySweepInIdle, base::TimeDelta::FromMilliseconds(1)); @@ -380,8 +352,7 @@ TEST(ThreadHeapStatsCollectorTest, EventCompactionFreedBytes) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.IncreaseCompactionFreedSize(512); stats_collector.NotifySweepingCompleted(); @@ -390,8 +361,7 @@ TEST(ThreadHeapStatsCollectorTest, EventCompactionFreedPages) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.IncreaseCompactionFreedPages(3); stats_collector.NotifySweepingCompleted(); @@ -400,8 +370,7 @@ TEST(ThreadHeapStatsCollectorTest, EventInitialEstimatedLiveObjectRate) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); EXPECT_DOUBLE_EQ(0.0, stats_collector.previous().live_object_rate); @@ -410,12 +379,10 @@ TEST(ThreadHeapStatsCollectorTest, EventEstimatedLiveObjectRateSameMarkedBytes) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); EXPECT_DOUBLE_EQ(1.0, stats_collector.previous().live_object_rate); @@ -424,12 +391,10 @@ TEST(ThreadHeapStatsCollectorTest, EventEstimatedLiveObjectRateHalfMarkedBytes) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(256); stats_collector.NotifySweepingCompleted(); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); EXPECT_DOUBLE_EQ(0.5, stats_collector.previous().live_object_rate); @@ -437,12 +402,10 @@ TEST(ThreadHeapStatsCollectorTest, EventEstimatedLiveObjectRateNoMarkedBytes) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(256); stats_collector.NotifySweepingCompleted(); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifySweepingCompleted(); EXPECT_DOUBLE_EQ(0.0, stats_collector.previous().live_object_rate); } @@ -450,13 +413,11 @@ TEST(ThreadHeapStatsCollectorTest, EventEstimatedLiveObjectRateWithAllocatedBytes1) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); stats_collector.IncreaseAllocatedObjectSize(128); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); EXPECT_DOUBLE_EQ(.5, stats_collector.previous().live_object_rate); @@ -465,13 +426,11 @@ TEST(ThreadHeapStatsCollectorTest, EventEstimatedLiveObjectRateWithAllocatedBytes2) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.NotifySweepingCompleted(); stats_collector.IncreaseAllocatedObjectSize(128); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); EXPECT_DOUBLE_EQ(1.0, stats_collector.previous().live_object_rate); @@ -480,8 +439,7 @@ TEST(ThreadHeapStatsCollectorTest, EventEstimatedLiveObjectRateWithAllocatedBytes3) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.NotifySweepingCompleted(); EXPECT_DOUBLE_EQ(0, stats_collector.previous().live_object_rate); @@ -490,12 +448,10 @@ TEST(ThreadHeapStatsCollectorTest, EventEstimatedLiveObjectRateWithAllocatedBytes4) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(128); stats_collector.NotifySweepingCompleted(); - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.NotifySweepingCompleted(); EXPECT_DOUBLE_EQ(0, stats_collector.previous().live_object_rate); @@ -503,8 +459,7 @@ TEST(ThreadHeapStatsCollectorTest, EventAllocatedSpaceBeforeSweeping1) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseAllocatedSpace(1024); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.IncreaseAllocatedSpace(2048); @@ -516,8 +471,7 @@ TEST(ThreadHeapStatsCollectorTest, EventAllocatedSpaceBeforeSweeping2) { ThreadHeapStatsCollector stats_collector; - stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector.NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector.IncreaseAllocatedSpace(1024); stats_collector.NotifyMarkingCompleted(kNoMarkedBytes); stats_collector.DecreaseAllocatedSpace(1024); @@ -543,8 +497,7 @@ }; void FakeGC(ThreadHeapStatsCollector* stats_collector, size_t marked_bytes) { - stats_collector->NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting, - kDefaultGCAge); + stats_collector->NotifyMarkingStarted(BlinkGC::GCReason::kForcedGCForTesting); stats_collector->NotifyMarkingCompleted(marked_bytes); stats_collector->NotifySweepingCompleted(); }
diff --git a/third_party/blink/renderer/platform/heap/heap_test.cc b/third_party/blink/renderer/platform/heap/heap_test.cc index 534efc4e..3e8fcfe 100644 --- a/third_party/blink/renderer/platform/heap/heap_test.cc +++ b/third_party/blink/renderer/platform/heap/heap_test.cc
@@ -385,7 +385,7 @@ explicit TestGCScope(BlinkGC::StackState state) : TestGCCollectGarbageScope(state) { ThreadState::Current()->Heap().stats_collector()->NotifyMarkingStarted( - BlinkGC::GCReason::kForcedGCForTesting, 0); + BlinkGC::GCReason::kForcedGCForTesting); ThreadState::Current()->AtomicPauseMarkPrologue( state, BlinkGC::kAtomicMarking, BlinkGC::GCReason::kPreciseGC); }
diff --git a/third_party/blink/renderer/platform/heap/thread_state.cc b/third_party/blink/renderer/platform/heap/thread_state.cc index 995e1ccc..156b5f1 100644 --- a/third_party/blink/renderer/platform/heap/thread_state.cc +++ b/third_party/blink/renderer/platform/heap/thread_state.cc
@@ -645,7 +645,7 @@ } if (sweep_completed) { - NotifySweepDone(); + PostSweep(); } } @@ -892,7 +892,7 @@ if (!IsSweepingInProgress()) { // Sweeping was finished during the atomic pause. Update statistics needs to // run outside of the top-most stats scope. - PostSweep(); + UpdateStatisticsAfterSweeping(); } } @@ -927,7 +927,7 @@ if (!was_in_atomic_pause) LeaveAtomicPause(); } - NotifySweepDone(); + PostSweep(); } void ThreadState::SynchronizeAndFinishConcurrentSweeping() { @@ -943,6 +943,15 @@ Heap().InvokeFinalizersOnSweptPages(); } +BlinkGCObserver::BlinkGCObserver(ThreadState* thread_state) + : thread_state_(thread_state) { + thread_state_->AddObserver(this); +} + +BlinkGCObserver::~BlinkGCObserver() { + thread_state_->RemoveObserver(this); +} + namespace { // Update trace counters with statistics from the current and previous garbage @@ -1011,7 +1020,7 @@ UMA_HISTOGRAM_TIMES("BlinkGC.TimeForIncrementalMarking", event.incremental_marking_time()); UMA_HISTOGRAM_TIMES("BlinkGC.TimeForMarking", event.marking_time()); - UMA_HISTOGRAM_TIMES("BlinkGC.TimeForNestedInV8", event.gc_nested_in_v8); + UMA_HISTOGRAM_TIMES("BlinkGC.TimeForNestedInV8", event.gc_nested_in_v8_); UMA_HISTOGRAM_TIMES("BlinkGC.TimeForSweepingForeground", event.foreground_sweeping_time()); UMA_HISTOGRAM_TIMES("BlinkGC.TimeForSweepingBackground", @@ -1110,28 +1119,32 @@ } // namespace -void ThreadState::NotifySweepDone() { - DCHECK(CheckThread()); - SetGCPhase(GCPhase::kNone); - if (!in_atomic_pause()) { - PostSweep(); - } -} - -void ThreadState::PostSweep() { - DCHECK(!in_atomic_pause()); +void ThreadState::UpdateStatisticsAfterSweeping() { DCHECK(!IsSweepingInProgress()); - - gc_age_++; - + DCHECK(Heap().stats_collector()->is_started()); Heap().stats_collector()->NotifySweepingCompleted(); - if (IsMainThread()) UpdateHistograms(Heap().stats_collector()->previous()); // Emit trace counters for all threads. UpdateTraceCounters(*Heap().stats_collector()); } +void ThreadState::PostSweep() { + DCHECK(CheckThread()); + + SetGCPhase(GCPhase::kNone); + + gc_age_++; + + for (auto* const observer : observers_) + observer->OnCompleteSweepDone(); + + if (!in_atomic_pause()) { + // Immediately update the statistics if running outside of the atomic pause. + UpdateStatisticsAfterSweeping(); + } +} + void ThreadState::SafePoint(BlinkGC::StackState stack_state) { DCHECK(CheckThread()); @@ -1153,6 +1166,18 @@ VisitStack(static_cast<MarkingVisitor*>(CurrentVisitor())); } +void ThreadState::AddObserver(BlinkGCObserver* observer) { + DCHECK(observer); + DCHECK(!observers_.Contains(observer)); + observers_.insert(observer); +} + +void ThreadState::RemoveObserver(BlinkGCObserver* observer) { + DCHECK(observer); + DCHECK(observers_.Contains(observer)); + observers_.erase(observer); +} + void ThreadState::ReportMemoryToV8() { if (!isolate_ || base::FeatureList::IsEnabled( blink::features::kBlinkHeapUnifiedGCScheduling)) @@ -1262,7 +1287,7 @@ DCHECK(!IsMarkingInProgress()); CompleteSweep(); DCHECK(!IsSweepingInProgress()); - Heap().stats_collector()->NotifyMarkingStarted(reason, gc_age_); + Heap().stats_collector()->NotifyMarkingStarted(reason); { ThreadHeapStatsCollector::EnabledScope stats_scope( Heap().stats_collector(), @@ -1377,7 +1402,7 @@ if (should_do_full_gc) { CompleteSweep(); SetGCState(kNoGCScheduled); - Heap().stats_collector()->NotifyMarkingStarted(reason, gc_age_); + Heap().stats_collector()->NotifyMarkingStarted(reason); RunAtomicPause(stack_state, marking_type, sweeping_type, reason); } @@ -1700,13 +1725,4 @@ previous_incremental_marking_time_left_ = time_left; } -HeapObserver::HeapObserver(ThreadState* thread_state) - : thread_state_(thread_state) { - thread_state_->Heap().stats_collector()->RegisterObserver(this); -} - -HeapObserver::~HeapObserver() { - thread_state_->Heap().stats_collector()->UnregisterObserver(this); -} - } // namespace blink
diff --git a/third_party/blink/renderer/platform/heap/thread_state.h b/third_party/blink/renderer/platform/heap/thread_state.h index befb5140..63d384f 100644 --- a/third_party/blink/renderer/platform/heap/thread_state.h +++ b/third_party/blink/renderer/platform/heap/thread_state.h
@@ -38,7 +38,6 @@ #include "third_party/blink/renderer/platform/heap/atomic_entry_flag.h" #include "third_party/blink/renderer/platform/heap/blink_gc.h" #include "third_party/blink/renderer/platform/heap/cancelable_task_scheduler.h" -#include "third_party/blink/renderer/platform/heap/heap_stats_collector.h" #include "third_party/blink/renderer/platform/heap/threading_traits.h" #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/scheduler/public/rail_mode_observer.h" @@ -123,15 +122,24 @@ ThreadState::PrefinalizerRegistration<Class> prefinalizer_dummy_ = this; \ using UsingPreFinalizerMacroNeedsTrailingSemiColon = char -// Automically registers as observer for heap and garabge collection changes. -// For individual overrides see documentation of |ThreadHeapStatsObserver|. -class PLATFORM_EXPORT HeapObserver : public ThreadHeapStatsObserver { +class PLATFORM_EXPORT BlinkGCObserver { + USING_FAST_MALLOC(BlinkGCObserver); + public: - HeapObserver(ThreadState*); - virtual ~HeapObserver(); + // The constructor automatically register this object to ThreadState's + // observer lists. The argument must not be null. + explicit BlinkGCObserver(ThreadState*); + + // The destructor automatically unregister this object from ThreadState's + // observer lists. + virtual ~BlinkGCObserver(); + + virtual void OnCompleteSweepDone() = 0; private: - ThreadState* const thread_state_; + // As a ThreadState must live when a BlinkGCObserver lives, holding a raw + // pointer is safe. + ThreadState* thread_state_; }; class PLATFORM_EXPORT ThreadState final : private RAILModeObserver { @@ -276,7 +284,6 @@ void CompleteSweep(); void FinishSnapshot(); - void NotifySweepDone(); void PostSweep(); // Returns whether it is currently allowed to allocate an object. Mainly used @@ -416,7 +423,7 @@ return &FromObject(object)->Heap() == &Heap(); } - size_t GcAge() const { return gc_age_; } + int GcAge() const { return gc_age_; } MarkingVisitor* CurrentVisitor() { return current_gc_data_.visitor.get(); } @@ -492,6 +499,8 @@ BlinkGC::SweepingType, BlinkGC::GCReason); + void UpdateStatisticsAfterSweeping(); + // The version is needed to be able to start incremental marking. void MarkPhasePrologue(BlinkGC::StackState, BlinkGC::MarkingType, @@ -544,6 +553,16 @@ void ReportMemoryToV8(); + // Adds the given observer to the ThreadState's observer list. This doesn't + // take ownership of the argument. The argument must not be null. The argument + // must not be registered before calling this. + void AddObserver(BlinkGCObserver*); + + // Removes the given observer from the ThreadState's observer list. This + // doesn't take ownership of the argument. The argument must not be null. + // The argument must be registered before calling this. + void RemoveObserver(BlinkGCObserver*); + std::unique_ptr<ThreadHeap> heap_; base::PlatformThreadId thread_; std::unique_ptr<PersistentRegion> persistent_region_; @@ -583,6 +602,8 @@ void* asan_fake_stack_; #endif + HashSet<BlinkGCObserver*> observers_; + // PersistentNodes that are stored in static references; // references that either have to be cleared upon the thread // detaching from Oilpan and shutting down or references we @@ -596,7 +617,7 @@ size_t reported_memory_to_v8_; - size_t gc_age_ = 0; + int gc_age_ = 0; struct GCData { BlinkGC::StackState stack_state; @@ -608,6 +629,7 @@ CancelableTaskScheduler sweeper_scheduler_; + friend class BlinkGCObserver; friend class incremental_marking_test::IncrementalMarkingScope; friend class incremental_marking_test::IncrementalMarkingTestDriver; friend class HeapAllocator;
diff --git a/third_party/blink/renderer/platform/instance_counters.cc b/third_party/blink/renderer/platform/instance_counters.cc deleted file mode 100644 index 36251b56..0000000 --- a/third_party/blink/renderer/platform/instance_counters.cc +++ /dev/null
@@ -1,45 +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: -* -* * 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. -*/ - -#include "third_party/blink/renderer/platform/instance_counters.h" - -namespace blink { - -// static -std::atomic_int InstanceCounters::counters_[kCounterTypeLength]; - -// static -int InstanceCounters::node_counter_ = 0; - -int InstanceCounters::CounterValue(CounterType type) { - return counters_[type].load(std::memory_order_relaxed); -} - -} // namespace blink
diff --git a/third_party/blink/renderer/platform/instance_counters.h b/third_party/blink/renderer/platform/instance_counters.h deleted file mode 100644 index 8225d40..0000000 --- a/third_party/blink/renderer/platform/instance_counters.h +++ /dev/null
@@ -1,108 +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: -* -* * 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 THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTANCE_COUNTERS_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTANCE_COUNTERS_H_ - -#include <atomic> -#include "third_party/blink/renderer/platform/platform_export.h" -#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" -#include "third_party/blink/renderer/platform/wtf/wtf.h" - -namespace blink { - -#define INSTANCE_COUNTERS_LIST(V) \ - V(AudioHandler) \ - V(Document) \ - V(Frame) \ - V(JSEventListener) \ - V(LayoutObject) \ - V(MediaKeySession) \ - V(MediaKeys) \ - V(Node) \ - V(Resource) \ - V(ScriptPromise) \ - V(ContextLifecycleStateObserver) \ - V(V8PerContextData) \ - V(WorkerGlobalScope) \ - V(UACSSResource) \ - V(RTCPeerConnection) \ - V(ResourceFetcher) \ - V(AdSubframe) \ - V(DetachedScriptState) - -// Atomic counters of the number of instances of objects that exist. -// -// Note that while these operations are atomic, they do not imply that other -// changes to memory are visible to the accessing thread. As a result, this -// is primarily useful where either other synchronization exists (e.g. the -// objects are only used on one thread), or an inconsistent answer is -// acceptable. -class InstanceCounters { - STATIC_ONLY(InstanceCounters); - - public: - enum CounterType { -#define DECLARE_INSTANCE_COUNTER(name) k##name##Counter, - INSTANCE_COUNTERS_LIST(DECLARE_INSTANCE_COUNTER) -#undef DECLARE_INSTANCE_COUNTER - kCounterTypeLength - }; - - static inline void IncrementCounter(CounterType type) { - // There are lots of nodes created. Atomic barriers or locks - // should be avoided for the sake of performance. See crbug.com/641019 - if (type == kNodeCounter) { - DCHECK(IsMainThread()); - ++counters_[kNodeCounter]; - } else { - counters_[type].fetch_add(1, std::memory_order_relaxed); - } - } - - static inline void DecrementCounter(CounterType type) { - if (type == kNodeCounter) { - DCHECK(IsMainThread()); - --counters_[kNodeCounter]; - } else { - counters_[type].fetch_sub(1, std::memory_order_relaxed); - } - } - - PLATFORM_EXPORT static int CounterValue(CounterType); - - private: - PLATFORM_EXPORT static std::atomic_int counters_[]; - PLATFORM_EXPORT static int node_counter_; -}; - -} // namespace blink - -#endif // !defined(InstanceCounters_h)
diff --git a/third_party/blink/renderer/platform/instrumentation/BUILD.gn b/third_party/blink/renderer/platform/instrumentation/BUILD.gn index 032f2806..43453323 100644 --- a/third_party/blink/renderer/platform/instrumentation/BUILD.gn +++ b/third_party/blink/renderer/platform/instrumentation/BUILD.gn
@@ -7,6 +7,10 @@ blink_platform_sources("instrumentation") { sources = [ + "instance_counters.cc", + "instance_counters.h", + "instance_counters_memory_dump_provider.cc", + "instance_counters_memory_dump_provider.h", "memory_pressure_listener.cc", "memory_pressure_listener.h", "partition_alloc_memory_dump_provider.cc",
diff --git a/third_party/blink/renderer/platform/instrumentation/instance_counters.cc b/third_party/blink/renderer/platform/instrumentation/instance_counters.cc new file mode 100644 index 0000000..14d27b1 --- /dev/null +++ b/third_party/blink/renderer/platform/instrumentation/instance_counters.cc
@@ -0,0 +1,45 @@ +/* + * 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: + * + * * 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. + */ + +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" + +namespace blink { + +// static +std::atomic_int InstanceCounters::counters_[kCounterTypeLength]; + +// static +int InstanceCounters::node_counter_ = 0; + +int InstanceCounters::CounterValue(CounterType type) { + return counters_[type].load(std::memory_order_relaxed); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/platform/instrumentation/instance_counters.h b/third_party/blink/renderer/platform/instrumentation/instance_counters.h new file mode 100644 index 0000000..ccb12f2 --- /dev/null +++ b/third_party/blink/renderer/platform/instrumentation/instance_counters.h
@@ -0,0 +1,108 @@ +/* + * 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: + * + * * 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 THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_INSTANCE_COUNTERS_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_INSTANCE_COUNTERS_H_ + +#include <atomic> +#include "third_party/blink/renderer/platform/platform_export.h" +#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" +#include "third_party/blink/renderer/platform/wtf/wtf.h" + +namespace blink { + +#define INSTANCE_COUNTERS_LIST(V) \ + V(AudioHandler) \ + V(Document) \ + V(Frame) \ + V(JSEventListener) \ + V(LayoutObject) \ + V(MediaKeySession) \ + V(MediaKeys) \ + V(Node) \ + V(Resource) \ + V(ScriptPromise) \ + V(ContextLifecycleStateObserver) \ + V(V8PerContextData) \ + V(WorkerGlobalScope) \ + V(UACSSResource) \ + V(RTCPeerConnection) \ + V(ResourceFetcher) \ + V(AdSubframe) \ + V(DetachedScriptState) + +// Atomic counters of the number of instances of objects that exist. +// +// Note that while these operations are atomic, they do not imply that other +// changes to memory are visible to the accessing thread. As a result, this +// is primarily useful where either other synchronization exists (e.g. the +// objects are only used on one thread), or an inconsistent answer is +// acceptable. +class InstanceCounters { + STATIC_ONLY(InstanceCounters); + + public: + enum CounterType { +#define DECLARE_INSTANCE_COUNTER(name) k##name##Counter, + INSTANCE_COUNTERS_LIST(DECLARE_INSTANCE_COUNTER) +#undef DECLARE_INSTANCE_COUNTER + kCounterTypeLength + }; + + static inline void IncrementCounter(CounterType type) { + // There are lots of nodes created. Atomic barriers or locks + // should be avoided for the sake of performance. See crbug.com/641019 + if (type == kNodeCounter) { + DCHECK(IsMainThread()); + ++counters_[kNodeCounter]; + } else { + counters_[type].fetch_add(1, std::memory_order_relaxed); + } + } + + static inline void DecrementCounter(CounterType type) { + if (type == kNodeCounter) { + DCHECK(IsMainThread()); + --counters_[kNodeCounter]; + } else { + counters_[type].fetch_sub(1, std::memory_order_relaxed); + } + } + + PLATFORM_EXPORT static int CounterValue(CounterType); + + private: + PLATFORM_EXPORT static std::atomic_int counters_[]; + PLATFORM_EXPORT static int node_counter_; +}; + +} // namespace blink + +#endif // !defined(InstanceCounters_h)
diff --git a/third_party/blink/renderer/platform/instance_counters_memory_dump_provider.cc b/third_party/blink/renderer/platform/instrumentation/instance_counters_memory_dump_provider.cc similarity index 85% rename from third_party/blink/renderer/platform/instance_counters_memory_dump_provider.cc rename to third_party/blink/renderer/platform/instrumentation/instance_counters_memory_dump_provider.cc index 8f93777a..83411aa 100644 --- a/third_party/blink/renderer/platform/instance_counters_memory_dump_provider.cc +++ b/third_party/blink/renderer/platform/instrumentation/instance_counters_memory_dump_provider.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 "third_party/blink/renderer/platform/instance_counters_memory_dump_provider.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters_memory_dump_provider.h" #include "base/trace_event/process_memory_dump.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" namespace blink {
diff --git a/third_party/blink/renderer/platform/instance_counters_memory_dump_provider.h b/third_party/blink/renderer/platform/instrumentation/instance_counters_memory_dump_provider.h similarity index 76% rename from third_party/blink/renderer/platform/instance_counters_memory_dump_provider.h rename to third_party/blink/renderer/platform/instrumentation/instance_counters_memory_dump_provider.h index f135f48a..76f1d638 100644 --- a/third_party/blink/renderer/platform/instance_counters_memory_dump_provider.h +++ b/third_party/blink/renderer/platform/instrumentation/instance_counters_memory_dump_provider.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTANCE_COUNTERS_MEMORY_DUMP_PROVIDER_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTANCE_COUNTERS_MEMORY_DUMP_PROVIDER_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_INSTANCE_COUNTERS_MEMORY_DUMP_PROVIDER_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_INSTANCE_COUNTERS_MEMORY_DUMP_PROVIDER_H_ #include "base/macros.h" #include "base/trace_event/memory_dump_provider.h" @@ -32,4 +32,4 @@ } // namespace blink -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTANCE_COUNTERS_MEMORY_DUMP_PROVIDER_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_INSTANCE_COUNTERS_MEMORY_DUMP_PROVIDER_H_
diff --git a/third_party/blink/renderer/platform/loader/DEPS b/third_party/blink/renderer/platform/loader/DEPS index f316a1d..337c3cf 100644 --- a/third_party/blink/renderer/platform/loader/DEPS +++ b/third_party/blink/renderer/platform/loader/DEPS
@@ -21,7 +21,7 @@ "+third_party/blink/renderer/platform/exported", "+third_party/blink/renderer/platform/heap", "+third_party/blink/renderer/platform/histogram.h", - "+third_party/blink/renderer/platform/instance_counters.h", + "+third_party/blink/renderer/platform/instrumentation/instance_counters.h", "+third_party/blink/renderer/platform/instrumentation", "+third_party/blink/renderer/platform/language.h", "+third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h",
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource.cc b/third_party/blink/renderer/platform/loader/fetch/resource.cc index fcebfd4..7a9a0ad1 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource.cc
@@ -38,7 +38,7 @@ #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_security_origin.h" #include "third_party/blink/renderer/platform/histogram.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/loader/cors/cors.h" #include "third_party/blink/renderer/platform/loader/fetch/cached_metadata.h"
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc index 74896e601..ea9274b 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
@@ -45,7 +45,7 @@ #include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/histogram.h" -#include "third_party/blink/renderer/platform/instance_counters.h" +#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h" #include "third_party/blink/renderer/platform/loader/cors/cors.h"
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index cb70c28..c0ef014 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -330,6 +330,9 @@ name: "CSSCalcAsInt", status: "test", }, + { + name: "CSSCascade", + }, // Support for the CSS color-scheme property from the css-color-adjust spec. // https://drafts.csswg.org/css-color-adjust/#color-scheme-prop { @@ -1184,6 +1187,7 @@ }, { name: "PeriodicBackgroundSync", + origin_trial_feature_name: "PeriodicBackgroundSync", settable_from_internals: true, status: "test", },
diff --git a/third_party/blink/tools/blinkpy/web_tests/controllers/test_result_writer.py b/third_party/blink/tools/blinkpy/web_tests/controllers/test_result_writer.py index 16116d4b..308162a 100644 --- a/third_party/blink/tools/blinkpy/web_tests/controllers/test_result_writer.py +++ b/third_party/blink/tools/blinkpy/web_tests/controllers/test_result_writer.py
@@ -119,16 +119,11 @@ self._root_output_dir = root_output_dir self._test_name = test_name - def _make_output_directory(self): - """Creates the output directory (if needed) for a given test filename.""" - fs = self._filesystem - output_filename = fs.join(self._root_output_dir, self._test_name) - fs.maybe_make_directory(fs.dirname(output_filename)) - def _write_file(self, path, contents): if contents is not None: - self._make_output_directory() - self._filesystem.write_binary_file(path, contents) + fs = self._filesystem + fs.maybe_make_directory(fs.dirname(path)) + fs.write_binary_file(path, contents) def _output_filename(self, suffix, extension): """Returns a filename based on the given suffix and extension.
diff --git a/third_party/blink/tools/blinkpy/web_tests/controllers/test_result_writer_unittest.py b/third_party/blink/tools/blinkpy/web_tests/controllers/test_result_writer_unittest.py index e58463f2..ac75cf9 100644 --- a/third_party/blink/tools/blinkpy/web_tests/controllers/test_result_writer_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/controllers/test_result_writer_unittest.py
@@ -39,54 +39,67 @@ class TestResultWriterTests(unittest.TestCase): - def run_test(self, failures=None, files=None): + def run_test(self, failures=None, files=None, filename='foo.html'): failures = failures or [] host = MockSystemHost() host.filesystem.files = files or {} port = TestPort(host=host, port_name='test-mac-mac10.11', options=optparse.Values()) actual_output = DriverOutput(text='', image=None, image_hash=None, audio=None) expected_output = DriverOutput(text='', image=None, image_hash=None, audio=None) - write_test_result(host.filesystem, port, '/tmp', 'foo.html', actual_output, expected_output, failures) - return host.filesystem.written_files + write_test_result(host.filesystem, port, '/tmp', filename, actual_output, expected_output, failures) + return host.filesystem def test_success(self): # Nothing is written when the test passes. - written_files = self.run_test(failures=[]) - self.assertEqual(written_files, {}) + fs = self.run_test(failures=[]) + self.assertEqual(fs.written_files, {}) def test_reference_exists(self): failure = test_failures.FailureReftestMismatch() failure.reference_filename = '/src/exists-expected.html' files = {'/src/exists-expected.html': 'yup'} - written_files = self.run_test(failures=[failure], files=files) - self.assertEqual(written_files, {'/tmp/exists-expected.html': 'yup'}) + fs = self.run_test(failures=[failure], files=files) + self.assertEqual(fs.written_files, {'/tmp/exists-expected.html': 'yup'}) failure = test_failures.FailureReftestMismatchDidNotOccur() failure.reference_filename = '/src/exists-expected-mismatch.html' files = {'/src/exists-expected-mismatch.html': 'yup'} - written_files = self.run_test(failures=[failure], files=files) - self.assertEqual(written_files, {'/tmp/exists-expected-mismatch.html': 'yup'}) + fs = self.run_test(failures=[failure], files=files) + self.assertEqual(fs.written_files, {'/tmp/exists-expected-mismatch.html': 'yup'}) def test_reference_is_missing(self): failure = test_failures.FailureReftestMismatch() failure.reference_filename = 'notfound.html' - written_files = self.run_test(failures=[failure], files={}) - self.assertEqual(written_files, {}) + fs = self.run_test(failures=[failure], files={}) + self.assertEqual(fs.written_files, {}) failure = test_failures.FailureReftestMismatchDidNotOccur() failure.reference_filename = 'notfound.html' - written_files = self.run_test(failures=[failure], files={}) - self.assertEqual(written_files, {}) + fs = self.run_test(failures=[failure], files={}) + self.assertEqual(fs.written_files, {}) def test_reftest_image_missing(self): failure = test_failures.FailureReftestNoImageGenerated() failure.reference_filename = '/src/exists-expected.html' files = {'/src/exists-expected.html': 'yup'} - written_files = self.run_test(failures=[failure], files=files) - self.assertEqual(written_files, {'/tmp/exists-expected.html': 'yup'}) + fs = self.run_test(failures=[failure], files=files) + self.assertEqual(fs.written_files, {'/tmp/exists-expected.html': 'yup'}) failure = test_failures.FailureReftestNoReferenceImageGenerated() failure.reference_filename = '/src/exists-expected.html' files = {'/src/exists-expected.html': 'yup'} - written_files = self.run_test(failures=[failure], files=files) - self.assertEqual(written_files, {'/tmp/exists-expected.html': 'yup'}) + fs = self.run_test(failures=[failure], files=files) + self.assertEqual(fs.written_files, {'/tmp/exists-expected.html': 'yup'}) + + def test_slash_in_test_name(self): + failure = test_failures.FailureTestHarnessAssertion() + fs = self.run_test(failures=[failure], filename='foo.html?a/b') + self.assertTrue('/tmp/foo_a_b-actual.txt' in fs.written_files) + self.assertEqual(set(fs.written_files.keys()), { + '/tmp/foo_a_b-actual.txt', + '/tmp/foo_a_b-diff.txt', + '/tmp/foo_a_b-expected.txt', + '/tmp/foo_a_b-pretty-diff.html', + }) + # Should not mkdir '/tmp/foo.html?a' + self.assertEqual(fs.dirs, {'/', '/tmp'})
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 8553810b..ad644e4 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -2194,6 +2194,23 @@ # ====== OOPIF-mode failures until here ====== +# ====== Cascade failures from here ====== + +# These expectations are copied from the main expectations; they also fail +# without the CSSCascade feature enabled. +crbug.com/626703 virtual/cascade/external/wpt/css/css-scoping/shadow-directionality-001.tentative.html [ Failure ] +crbug.com/626703 virtual/cascade/external/wpt/css/css-scoping/shadow-directionality-002.tentative.html [ Failure ] +crbug.com/791529 virtual/cascade/external/wpt/css/css-variables/variable-transitions-from-no-value.html [ Skip ] +crbug.com/791529 virtual/cascade/external/wpt/css/css-variables/variable-transitions-to-no-value.html [ Skip ] +crbug.com/791529 virtual/cascade/external/wpt/css/css-variables/variable-transitions-transition-property-variable-before-value.html [ Skip ] +crbug.com/791529 virtual/cascade/external/wpt/css/css-variables/variable-transitions-value-before-transition-property-variable.html [ Skip ] +crbug.com/552085 virtual/cascade/external/wpt/css/css-cascade/important-prop.html [ Failure ] + +# This is for some reason WontFix'd in the main expectations (see NeverFixTests). +# That seems wrong, as we should support 'revert' eventually. +crbug.com/579788 virtual/cascade/external/wpt/css/css-cascade/revert-val-001.html [ Skip ] + +# ====== Cascade failures until here ====== ### sheriff 2019-07-16 crbug.com/983799 [ Win ] http/tests/navigation/redirect-on-back-updates-history-item.html [ Timeout Pass ] @@ -2378,6 +2395,13 @@ crbug.com/686118 http/tests/security/setDomainRelaxationForbiddenForURLScheme.html [ Crash Pass ] +# Service worker updates need to succeed when the script shrinks. +crbug.com/986688 external/wpt/service-workers/service-worker/update.https.html [ Skip ] +crbug.com/986688 virtual/blink-cors/external/wpt/service-workers/service-worker/update.https.html [ Skip ] +crbug.com/986688 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/update.https.html [ Skip ] +crbug.com/986688 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/update.https.html [ Skip ] +crbug.com/986688 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/update.https.html [ Skip ] + # In external/wpt/html/, we prefer checking in failure # expectation files. The following tests with [ Failure ] don't have failure # expectation files because they contain local path names. @@ -6317,10 +6341,6 @@ crbug.com/986019 [ Linux ] virtual/disable-blink-gen-property-trees/animations/play-state.html [ Pass Timeout ] # ecosystem-infra sheriff 2019-07-22 -crbug.com/986286 external/wpt/fetch/api/response/response-consume-empty.html [ Pass Failure ] -crbug.com/986286 virtual/blink-cors/external/wpt/fetch/api/response/response-consume-empty.html [ Pass Failure ] -crbug.com/986286 virtual/not-omt-sw-fetch/external/wpt/fetch/api/response/response-consume-empty.html [ Pass Failure ] -crbug.com/986286 virtual/omt-worker-fetch/external/wpt/fetch/api/response/response-consume-empty.html [ Pass Failure ] crbug.com/986457 [ Linux ] http/tests/misc/object-image-error-with-onload.html [ Pass Failure ] crbug.com/986477 [ Win ] external/wpt/cookies/path/match.html [ Pass Timeout ] crbug.com/986477 [ Win ] virtual/samesite-by-default-cookies/external/wpt/cookies/path/match.html [ Pass Timeout ] @@ -6332,4 +6352,3 @@ crbug.com/986666 animations/web-animations/animation-state-changes-negative-playback-rate.html [ Pass Failure ] crbug.com/986666 virtual/threaded/animations/web-animations/animation-state-changes-negative-playback-rate.html [ Pass Failure ] crbug.com/986666 virtual/disable-blink-gen-property-trees/animations/web-animations/animation-state-changes-negative-playback-rate.html [ Pass Failure ] -
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index 1c19790..dd618504 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -1128,6 +1128,56 @@ "args": ["--enable-blink-features=ForceDeferScriptIntervention"] }, { + "prefix": "cascade", + "base": "animations/custom-properties", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "animations/interpolation", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "external/wpt/css/css-cascade", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "external/wpt/css/css-paint-api", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "external/wpt/css/css-properties-values-api", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "external/wpt/css/css-scoping", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "external/wpt/css/css-typed-om", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "external/wpt/css/css-variables", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "external/wpt/css/css-forced-colors-adjust", + "args": ["--enable-blink-features=CSSCascade"] + }, + { + "prefix": "cascade", + "base": "fast/css/variables", + "args": ["--enable-blink-features=CSSCascade"] + }, + { "prefix": "at-property", "base": "fast/css/css-properties-values-api", "args": ["--enable-blink-features=CSSVariables2AtProperty"]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json index e9ae4a0a..64c1ecc4 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
@@ -147042,6 +147042,9 @@ "css/cssom-view/scrollIntoView-vertical-lr-writing-mode-and-rtl-direction-expected.txt": [ [] ], + "css/cssom-view/scrollLeftTop-expected.txt": [ + [] + ], "css/cssom-view/scrollTop-display-change-ref.html": [ [] ], @@ -167577,6 +167580,15 @@ "service-workers/service-worker/resources/update-registration-with-type.py": [ [] ], + "service-workers/service-worker/resources/update-smaller-body-after-update-worker.js": [ + [] + ], + "service-workers/service-worker/resources/update-smaller-body-before-update-worker.js": [ + [] + ], + "service-workers/service-worker/resources/update-worker-from-file.py": [ + [] + ], "service-workers/service-worker/resources/update-worker.py": [ [] ], @@ -168033,6 +168045,12 @@ "streams/README.md": [ [] ], + "streams/byte-length-queuing-strategy.any-expected.txt": [ + [] + ], + "streams/count-queuing-strategy.any-expected.txt": [ + [] + ], "streams/piping/abort.any-expected.txt": [ [] ], @@ -173403,9 +173421,6 @@ "web-nfc/NFCReader_options_url-manual.https-expected.txt": [ [] ], - "web-nfc/NFCReadingEvent_constructor.https-expected.txt": [ - [] - ], "web-nfc/NFCWriter_push.https-expected.txt": [ [] ], @@ -199532,6 +199547,12 @@ {} ] ], + "css/css-box/parsing/margin-computed.html": [ + [ + "css/css-box/parsing/margin-computed.html", + {} + ] + ], "css/css-box/parsing/margin-invalid.html": [ [ "css/css-box/parsing/margin-invalid.html", @@ -203714,6 +203735,12 @@ {} ] ], + "css/css-logical/parsing/block-size-computed.html": [ + [ + "css/css-logical/parsing/block-size-computed.html", + {} + ] + ], "css/css-logical/parsing/block-size-invalid.html": [ [ "css/css-logical/parsing/block-size-invalid.html", @@ -203846,6 +203873,12 @@ {} ] ], + "css/css-logical/parsing/inline-size-computed.html": [ + [ + "css/css-logical/parsing/inline-size-computed.html", + {} + ] + ], "css/css-logical/parsing/inline-size-invalid.html": [ [ "css/css-logical/parsing/inline-size-invalid.html", @@ -209000,15 +209033,21 @@ {} ] ], - "css/css-transforms/parsing/perspective-origin-parsing-invalid.html": [ + "css/css-transforms/parsing/perspective-origin-computed.html": [ [ - "css/css-transforms/parsing/perspective-origin-parsing-invalid.html", + "css/css-transforms/parsing/perspective-origin-computed.html", {} ] ], - "css/css-transforms/parsing/perspective-origin-parsing-valid.html": [ + "css/css-transforms/parsing/perspective-origin-invalid.html": [ [ - "css/css-transforms/parsing/perspective-origin-parsing-valid.html", + "css/css-transforms/parsing/perspective-origin-invalid.html", + {} + ] + ], + "css/css-transforms/parsing/perspective-origin-valid.html": [ + [ + "css/css-transforms/parsing/perspective-origin-valid.html", {} ] ], @@ -209060,6 +209099,12 @@ {} ] ], + "css/css-transforms/parsing/transform-origin-computed.html": [ + [ + "css/css-transforms/parsing/transform-origin-computed.html", + {} + ] + ], "css/css-transforms/parsing/transform-origin-invalid.html": [ [ "css/css-transforms/parsing/transform-origin-invalid.html", @@ -213354,6 +213399,12 @@ {} ] ], + "css/cssom-view/scrollLeftTop.html": [ + [ + "css/cssom-view/scrollLeftTop.html", + {} + ] + ], "css/cssom-view/scrollWidthHeight.xht": [ [ "css/cssom-view/scrollWidthHeight.xht", @@ -238004,6 +238055,12 @@ {} ] ], + "html/semantics/embedded-content/media-elements/media_fragment_seek.html": [ + [ + "html/semantics/embedded-content/media-elements/media_fragment_seek.html", + {} + ] + ], "html/semantics/embedded-content/media-elements/mime-types/canPlayType.html": [ [ "html/semantics/embedded-content/media-elements/mime-types/canPlayType.html", @@ -291272,6 +291329,18 @@ {} ] ], + "web-nfc/NDEFMessage_constructor.https.html": [ + [ + "web-nfc/NDEFMessage_constructor.https.html", + {} + ] + ], + "web-nfc/NDEFRecord_constructor.https.html": [ + [ + "web-nfc/NDEFRecord_constructor.https.html", + {} + ] + ], "web-nfc/NFCErrorEvent_constructor.https.html": [ [ "web-nfc/NFCErrorEvent_constructor.https.html", @@ -345165,6 +345234,10 @@ "7cc09a594ed17648ec29b9bdc2615fa6dbcbd3a7", "testharness" ], + "css/css-box/parsing/margin-computed.html": [ + "f22f6cdc0f503488418b7741f12ec5554f213477", + "testharness" + ], "css/css-box/parsing/margin-invalid.html": [ "77009170938d9634497f73bc21501ced502c7008", "testharness" @@ -364109,6 +364182,10 @@ "3e133db880cd32d963d701bb184d28faae959aa5", "testharness" ], + "css/css-logical/parsing/block-size-computed.html": [ + "de3a3c2a0c5c80b5f0f4225a5904b81797afb34e", + "testharness" + ], "css/css-logical/parsing/block-size-invalid.html": [ "37d88907735ff58ab4bebb9073f626e14d864955", "testharness" @@ -364213,6 +364290,10 @@ "81c7049c5e94c891b72f953356fadac0aeb3ae5c", "testharness" ], + "css/css-logical/parsing/inline-size-computed.html": [ + "0f60165a347e1ad8e67715d03d1b46c9a27b146c", + "testharness" + ], "css/css-logical/parsing/inline-size-invalid.html": [ "d3d5d3f84d9d01392533e787b9e6755d592ec96e", "testharness" @@ -379698,19 +379779,19 @@ "reftest" ], "css/css-text/white-space/pre-wrap-leading-spaces-006.html": [ - "cff928c2fd537b4f2db6ed282882c9a14f795452", + "de1c0de11c67871c5ce8df1dd7e1ee268182c8c6", "reftest" ], "css/css-text/white-space/pre-wrap-leading-spaces-007.html": [ - "ca27b98c2f68940287fc61d4f24709af196ced10", + "9089466338f9dba6c60b8e786ff905d4856488fc", "reftest" ], "css/css-text/white-space/pre-wrap-leading-spaces-008.html": [ - "7331142c2ea0cf56441bd98504610b6ae3150f79", + "f112a0c20b9586f365345227e926ac03cc2edf8a", "reftest" ], "css/css-text/white-space/pre-wrap-leading-spaces-009.html": [ - "e2786419c1a56466fc3850fd371bdac45203fdf3", + "2fe58aa5ceb5abc19d00db01d01452c7cf3ec1d5", "reftest" ], "css/css-text/white-space/pre-wrap-leading-spaces-010.html": [ @@ -381781,11 +381862,15 @@ "eb7431078c42e08dbfe07e6de2e154ba9ecb2297", "testharness" ], - "css/css-transforms/parsing/perspective-origin-parsing-invalid.html": [ + "css/css-transforms/parsing/perspective-origin-computed.html": [ + "effeb2974e136831a646318e7fabf30cf27183a6", + "testharness" + ], + "css/css-transforms/parsing/perspective-origin-invalid.html": [ "2ed6721e091702a436217086eebd81172f359339", "testharness" ], - "css/css-transforms/parsing/perspective-origin-parsing-valid.html": [ + "css/css-transforms/parsing/perspective-origin-valid.html": [ "79f4e0df12e84e880e8c501856a977e1a2c468b8", "testharness" ], @@ -381829,8 +381914,12 @@ "7fb8367ecb2f6e2f151a1ee6afaab9896f07f8c8", "testharness" ], + "css/css-transforms/parsing/transform-origin-computed.html": [ + "696d89db67fc9dd611fa0c09fccbe0408134e744", + "testharness" + ], "css/css-transforms/parsing/transform-origin-invalid.html": [ - "19a7c963a708912d347a4c708dc848a7e580966b", + "0dd1eeaf592b94fe65d0ccfb731c826b5dfcb3dc", "testharness" ], "css/css-transforms/parsing/transform-origin-valid.html": [ @@ -399209,6 +399298,14 @@ "cec27f412c926ab087f2cd736e4c6a7d4efb4c99", "testharness" ], + "css/cssom-view/scrollLeftTop-expected.txt": [ + "a0ecd95107eab1d8a403a948f58213a84a0214da", + "support" + ], + "css/cssom-view/scrollLeftTop.html": [ + "55b4013600727a3dcae0ab2c286a38801cdd8426", + "testharness" + ], "css/cssom-view/scrollTop-display-change-ref.html": [ "9f1259787bbb33e8f8be6d8fc415738bffee6590", "support" @@ -429401,6 +429498,10 @@ "cd1ebb9e492673feb095a227e7ca04ceae7643b9", "testharness" ], + "html/semantics/embedded-content/media-elements/media_fragment_seek.html": [ + "d6f6e6c30bf89cbb87c7fbab1529973aa69b03f6", + "testharness" + ], "html/semantics/embedded-content/media-elements/mime-types/canPlayType-expected.txt": [ "90116f2a0790416fa5edd8e83ec1dee119054d92", "support" @@ -440766,7 +440867,7 @@ "testharness" ], "lint.whitelist": [ - "02b1bb0c78f9765257a35aed076701e2f0aa757e", + "c344c3a834444db4be24db1d0132c85a4b14395c", "support" ], "loading/lazyload/common.js": [ @@ -468457,6 +468558,18 @@ "4f6d5ae28200e09cba0e25c2769168bc1622a360", "support" ], + "service-workers/service-worker/resources/update-smaller-body-after-update-worker.js": [ + "d43f6b2f5c3d64156ae68970eab3a65511c5c960", + "support" + ], + "service-workers/service-worker/resources/update-smaller-body-before-update-worker.js": [ + "30c8783a70255012e5763403d15467d148b249b0", + "support" + ], + "service-workers/service-worker/resources/update-worker-from-file.py": [ + "7604719c8e0c5dacd216bf96921d825dd0211aea", + "support" + ], "service-workers/service-worker/resources/update-worker.py": [ "446d547ca78277c69795233f0d7c0f64125059d8", "support" @@ -468694,11 +468807,11 @@ "testharness" ], "service-workers/service-worker/update.https-expected.txt": [ - "2a9900e26cc6d994e15d14bfca9139313acb16a8", + "8f751d0283340a9f8184dbf9a52de2b3bc085da9", "support" ], "service-workers/service-worker/update.https.html": [ - "7232419cd0acc33515113363540b332e397025d7", + "f7fae35ed28d7c82c261752c22cd091e473801b0", "testharness" ], "service-workers/service-worker/waiting.https.html": [ @@ -470337,12 +470450,20 @@ "fd964cf7e5b75db408e0b5813cb94172186f5c26", "support" ], + "streams/byte-length-queuing-strategy.any-expected.txt": [ + "e319f57bdc42ff6a688144807c643713d24ce4ae", + "support" + ], "streams/byte-length-queuing-strategy.any.js": [ - "d47e7cd4faa787933920c48d99a75eea98eaefe7", + "6a61adcdc96cf1f002e70642a87e8e1218e52c06", "testharness" ], + "streams/count-queuing-strategy.any-expected.txt": [ + "48bb81fca5cd7b7fb689c0ce7ed22e9894461e63", + "support" + ], "streams/count-queuing-strategy.any.js": [ - "20bb4c1842d258f2de7ff3261c4a93c9d427707e", + "5aae61eda3394e3017d51d241159112f5ef9883f", "testharness" ], "streams/piping/abort.any-expected.txt": [ @@ -480553,6 +480674,14 @@ "32c24570db165422a60a18b767c828dab10c5b9c", "support" ], + "web-nfc/NDEFMessage_constructor.https.html": [ + "73bbb4f8ab5182995fd66459148e3399be1361a4", + "testharness" + ], + "web-nfc/NDEFRecord_constructor.https.html": [ + "81148856473c4823422f59511a5e9de8bbfc4771", + "testharness" + ], "web-nfc/NFCErrorEvent_constructor.https.html": [ "1cc9ce160be46955a9b15485ee4c040605722961", "testharness" @@ -480629,12 +480758,8 @@ "aa0e72b089a1b1c445eb8b7ba8c478158d47173f", "manual" ], - "web-nfc/NFCReadingEvent_constructor.https-expected.txt": [ - "b660be28769db33c24fe0ac17f57057928a76a4b", - "support" - ], "web-nfc/NFCReadingEvent_constructor.https.html": [ - "3c4242943d6c44540676c6e12acb83a51e2d11f0", + "172b0a619c2b27b9c8d0f04101094f7969aa11e9", "testharness" ], "web-nfc/NFCWriter_push.https-expected.txt": [ @@ -480658,7 +480783,7 @@ "support" ], "web-nfc/idlharness.https.window-expected.txt": [ - "975bd5e1d9d8a8207be992fc646ea1938ce8b8b7", + "5e3a1003a9a46e8b9df411a370cda6985f7ed558", "support" ], "web-nfc/idlharness.https.window.js": [ @@ -480694,7 +480819,7 @@ "manual" ], "web-nfc/resources/nfc_help.js": [ - "812d0f071183f53cef973c58fdbbc260e3154296", + "67fd5af381c9fa96c921b9fd6a2d6559562f4066", "support" ], "web-share/META.yml": [ @@ -484038,7 +484163,7 @@ "testharness" ], "webrtc/idlharness.https.window-expected.txt": [ - "a9a7a013d79367dcd7b5809d31066f2792341c7f", + "1f26f0d506c51105c2e769caa4270ebc6d3e472a", "support" ], "webrtc/idlharness.https.window.js": [ @@ -488802,7 +488927,7 @@ "support" ], "webxr/resources/webxr_util.js": [ - "baf1d66b00daa98c07b9bfc91436018d12eef097", + "d75e5c7bd2e26cf79794a01b8bed637c165926e6", "support" ], "webxr/webGLCanvasContext_create_xrcompatible.https.html": [
diff --git a/third_party/blink/web_tests/external/wpt/css/css-properties-values-api/conditional-rules.html b/third_party/blink/web_tests/external/wpt/css/css-properties-values-api/conditional-rules.html index b4de630..0bff8798 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-properties-values-api/conditional-rules.html +++ b/third_party/blink/web_tests/external/wpt/css/css-properties-values-api/conditional-rules.html
@@ -1,5 +1,5 @@ <!DOCTYPE html> -<link rel="help" href="https://drafts.css-houdini.org/css-properties-values-api-1/#conditional-rules" /> +<link rel="help" href="https://drafts.css-houdini.org/css-properties-values-api-1/#conditional-rules"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -35,8 +35,9 @@ }, 'CSS.supports(conditionText) should ignore registered syntax'); test(function() { - assert_false(CSS.supports('--length', 'red')); + assert_true(CSS.supports('--length', 'red')); assert_true(CSS.supports('--length', '10px')); -}, 'CSS.supports(property, value) should parse against registered syntax'); + assert_true(CSS.supports('--length', ' anything, really')); +}, 'CSS.supports(property, value) should ignore registered syntax'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-006.html b/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-006.html index cff928c..de1c0de 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-006.html +++ b/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-006.html
@@ -28,5 +28,5 @@ <p>Test passes if there is a <strong>filled green square</strong> and <strong>no red</strong>.</p> <div class="ref">XXX<span>XX<br>XXX</span>XX<br><span>XXXXX<br>XXXXX<br>XXXXX</span></div> -<div class="test">XXX +<div class="test">XXX <!--end of line space intentional--> XX</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-007.html b/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-007.html index ca27b98..9089466 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-007.html +++ b/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-007.html
@@ -28,5 +28,5 @@ <p>Test passes if there is a <strong>filled green square</strong> and <strong>no red</strong>.</p> <div class="ref">XXX<span>XX<br>XXX</span>XX<br><span>XXXXX<br>XXXXX<br>XXXXX</span></div> -<div class="test">XXX +<div class="test">XXX <!--end of line spaces intentional--> XX</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-008.html b/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-008.html index 7331142..f112a0c 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-008.html +++ b/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-008.html
@@ -28,5 +28,5 @@ <p>Test passes if there is a <strong>filled green square</strong> and <strong>no red</strong>.</p> <div class="ref">XX<span>XXX<br>XXX</span>XX<br><span>XXXXX<br>XXXXX<br>XXXXX</span></div> -<div class="test">XX +<div class="test">XX <!--end of line spaces intentional--> XX</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-009.html b/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-009.html index e278641..2fe58aa 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-009.html +++ b/third_party/blink/web_tests/external/wpt/css/css-text/white-space/pre-wrap-leading-spaces-009.html
@@ -28,5 +28,5 @@ <p>Test passes if there is a <strong>filled green square</strong> and <strong>no red</strong>.</p> <div class="ref">X<span>XXXX<br>XXX</span>XX<br><span>XXXXX<br>XXXXX<br>XXXXX</span></div> -<div class="test">X +<div class="test">X <!--end of line spaces intentional--> XX</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom-view/scrollLeftTop-expected.txt b/third_party/blink/web_tests/external/wpt/css/cssom-view/scrollLeftTop-expected.txt new file mode 100644 index 0000000..a0ecd95 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/cssom-view/scrollLeftTop-expected.txt
@@ -0,0 +1,9 @@ +This is a testharness.js-based test. +PASS writing-mode:horizontal-tb; direction:ltr +FAIL writing-mode:horizontal-tb; direction:rtl assert_approx_equals: initial scrollLeft expected 0 +/- 0.5 but got 165 +PASS writing-mode:vertical-lr; direction:ltr +FAIL writing-mode:vertical-lr; direction:rtl assert_approx_equals: initial scrollTop expected 0 +/- 0.5 but got 315 +FAIL writing-mode:vertical-rl; direction:ltr assert_approx_equals: initial scrollLeft expected 0 +/- 0.5 but got 165 +FAIL writing-mode:vertical-rl; direction:rtl assert_approx_equals: initial scrollLeft expected 0 +/- 0.5 but got 165 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom-view/scrollLeftTop.html b/third_party/blink/web_tests/external/wpt/css/cssom-view/scrollLeftTop.html new file mode 100644 index 0000000..55b4013 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/cssom-view/scrollLeftTop.html
@@ -0,0 +1,136 @@ +<!DOCTYPE html> +<title>CSSOM View - scrollLeft/scrollTop considers writing-mode and css direction</title> +<meta charset="utf-8"> +<link rel="author" title="Cathie Chen" href="mailto:cathiechen@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/cssom-view/#scrolling-area-origin"> +<link rel="help" href="https://drafts.csswg.org/cssom-view/#scroll-an-element"> +<meta name="assert" content="This test verifies the assigned and extreme values of the scroll positions of an element."> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<head> + <style> + .scroller { + overflow: scroll; + width: 150px; + height: 100px; + } + .content { + width: 300px; + height: 400px; + } + .horizontal-tb { + writing-mode: horizontal-tb; + } + .vertical-lr { + writing-mode: vertical-lr; + } + .vertical-rl { + writing-mode: vertical-rl; + } + .rtl { + direction: rtl; + } + </style> +</head> + +<body> + <h1>scrollLeft/scrollTop</h1> + <h2>writing-mode: horizontal-tb;</h2> + <div id="target_scroller" class="scroller horizontal-tb ltr"> + <div id="target_content" class="content"></div> + </div> + <div class="scroller horizontal-tb rtl"> + <div class="content"></div> + </div> + <h2>writing-mode: vertical-lr;</h2> + <div class="scroller vertical-lr ltr"> + <div class="content"></div> + </div> + <div class="scroller vertical-lr rtl"> + <div class="content"></div> + </div> + <h2>writing-mode: vertical-rl;</h2> + <div class="scroller vertical-rl ltr"> + <div class="content"></div> + </div> + <div class="scroller vertical-rl rtl"> + <div class="content"></div> + </div> + + <script> + var scroller = document.querySelector("#target_scroller"); + var content = document.querySelector("#target_content"); + var scrollbar_width = scroller.offsetWidth - scroller.clientWidth; + var scroller_width = scroller.offsetWidth; + var scroller_height = scroller.offsetHeight; + var content_width = content.offsetWidth; + var content_height = content.offsetHeight; + + expectedScrollTop = content_height - scroller_height + scrollbar_width; + expectedScrollLeft = content_width - scroller_width + scrollbar_width; + + const epsilon = 0.5; + test(() => { + var scroller = document.querySelector(".horizontal-tb.ltr"); + assert_approx_equals(scroller.scrollLeft, 0, epsilon, "initial scrollLeft"); + assert_approx_equals(scroller.scrollTop, 0, epsilon, "initial scrollTop"); + scroller.scrollLeft = 2*content_width; + scroller.scrollTop = 2*content_height; + assert_approx_equals(scroller.scrollLeft, expectedScrollLeft, epsilon, "ending scrollLeft"); + assert_approx_equals(scroller.scrollTop, expectedScrollTop, epsilon, "ending scrollTop"); + }, `writing-mode:horizontal-tb; direction:ltr`); + + test(() => { + var scroller = document.querySelector(".horizontal-tb.rtl"); + assert_approx_equals(scroller.scrollLeft, 0, epsilon, "initial scrollLeft"); + assert_approx_equals(scroller.scrollTop, 0, epsilon, "initial scrollTop"); + scroller.scrollLeft = -2*content_width; + scroller.scrollTop = 2*content_height; + assert_approx_equals(scroller.scrollLeft, -expectedScrollLeft, epsilon, "ending scrollLeft"); + assert_approx_equals(scroller.scrollTop, expectedScrollTop, epsilon, "ending scrollTop"); + }, `writing-mode:horizontal-tb; direction:rtl`); + + test(() => { + var scroller = document.querySelector(".vertical-lr.ltr"); + assert_approx_equals(scroller.scrollLeft, 0, epsilon, "initial scrollLeft"); + assert_approx_equals(scroller.scrollTop, 0, epsilon, "initial scrollTop"); + scroller.scrollLeft = 2*content_width; + scroller.scrollTop = 2*content_height; + assert_approx_equals(scroller.scrollLeft, expectedScrollLeft, epsilon, "ending scrollLeft"); + assert_approx_equals(scroller.scrollTop, expectedScrollTop, epsilon, "ending scrollTop"); + }, `writing-mode:vertical-lr; direction:ltr`); + + test(() => { + var scroller = document.querySelector(".vertical-lr.rtl"); + assert_approx_equals(scroller.scrollLeft, 0, epsilon, "initial scrollLeft"); + assert_approx_equals(scroller.scrollTop, 0, epsilon, "initial scrollTop"); + scroller.scrollLeft = 2*content_width; + scroller.scrollTop = -2*content_height; + assert_approx_equals(scroller.scrollLeft, expectedScrollLeft, epsilon, "ending scrollLeft"); + assert_approx_equals(scroller.scrollTop, -expectedScrollTop, epsilon, "ending scrollTop"); + }, `writing-mode:vertical-lr; direction:rtl`); + + test(() => { + var scroller = document.querySelector(".vertical-rl.ltr"); + assert_approx_equals(scroller.scrollLeft, 0, epsilon, "initial scrollLeft"); + assert_approx_equals(scroller.scrollTop, 0, epsilon, "initial scrollTop"); + scroller.scrollLeft = -2*content_width; + scroller.scrollTop = 2*content_height; + assert_approx_equals(scroller.scrollLeft, -expectedScrollLeft, epsilon, "ending scrollLeft"); + assert_approx_equals(scroller.scrollTop, expectedScrollTop, epsilon, "ending scrollTop"); + }, `writing-mode:vertical-rl; direction:ltr`); + + test(() => { + var scroller = document.querySelector(".vertical-rl.rtl"); + assert_approx_equals(scroller.scrollLeft, 0, epsilon, "initial scrollLeft"); + assert_approx_equals(scroller.scrollTop, 0, epsilon, "initial scrollTop"); + scroller.scrollLeft = -2*content_width; + scroller.scrollTop = -2*content_height; + assert_approx_equals(scroller.scrollLeft, -expectedScrollLeft, epsilon, "ending scrollLeft"); + assert_approx_equals(scroller.scrollTop, -expectedScrollTop, epsilon, "ending scrollTop"); + }, `writing-mode:vertical-rl; direction:rtl`); + </script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/media-elements/media_fragment_seek.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/media-elements/media_fragment_seek.html new file mode 100644 index 0000000..d6f6e6c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/media-elements/media_fragment_seek.html
@@ -0,0 +1,48 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Video should seek to time specified in media fragment syntax</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/media.js"></script> +<div id="log"></div> +<video id="video"></video> +<script> +async_test(function () { + let video = document.getElementById("video"); + video.src = getVideoURI('/media/movie_5') + "#t=4,7"; + video.load(); + this.step_timeout(function () { + assert_equals(video.currentTime, 4.0); + + video.src = getVideoURI('/media/movie_5') + "#t=%6Ept:3"; + video.load(); + this.step_timeout(function () { + assert_true(video.src.endsWith("t=%6Ept:3")); + assert_equals(video.currentTime, 3.0); + + video.src = getVideoURI('/media/movie_5') + "#t=00:00:01.00"; + video.load(); + this.step_timeout(function () { + assert_true(video.src.endsWith("t=00:00:01.00")); + assert_equals(video.currentTime, 1.0); + + video.src = getVideoURI('/media/movie_5') + "#u=12&t=3"; + video.load(); + this.step_timeout(function () { + assert_true(video.src.endsWith("#u=12&t=3")); + assert_equals(video.currentTime, 3.0); + + video.src = getVideoURI('/media/movie_5') + "#t=npt%3A3"; + video.load(); + this.step_timeout(function () { + assert_true(video.src.endsWith("t=npt%3A3")); + assert_equals(video.currentTime, 3.0); + this.done(); + }, 1000); + }, 1000); + }, 1000); + }, 1000); + }, 1000); +}); +</script> +
diff --git a/third_party/blink/web_tests/external/wpt/lint.whitelist b/third_party/blink/web_tests/external/wpt/lint.whitelist index 02b1bb0c..c344c3a 100644 --- a/third_party/blink/web_tests/external/wpt/lint.whitelist +++ b/third_party/blink/web_tests/external/wpt/lint.whitelist
@@ -28,10 +28,6 @@ TRAILING WHITESPACE: WebIDL/* TRAILING WHITESPACE: webvtt/* TRAILING WHITESPACE: server-timing/resources/parsing/*.sub.headers -TRAILING WHITESPACE: css/css-text/white-space/pre-wrap-leading-spaces-006.html -TRAILING WHITESPACE: css/css-text/white-space/pre-wrap-leading-spaces-007.html -TRAILING WHITESPACE: css/css-text/white-space/pre-wrap-leading-spaces-008.html -TRAILING WHITESPACE: css/css-text/white-space/pre-wrap-leading-spaces-009.html ## File types that should never be checked ##
diff --git a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-smaller-body-after-update-worker.js b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-smaller-body-after-update-worker.js new file mode 100644 index 0000000..d43f6b2f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-smaller-body-after-update-worker.js
@@ -0,0 +1 @@ +// Hello world!
diff --git a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-smaller-body-before-update-worker.js b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-smaller-body-before-update-worker.js new file mode 100644 index 0000000..30c8783a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-smaller-body-before-update-worker.js
@@ -0,0 +1,2 @@ +// Hello world! +// **with extra body**
diff --git a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-worker-from-file.py b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-worker-from-file.py new file mode 100644 index 0000000..7604719 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-worker-from-file.py
@@ -0,0 +1,31 @@ +import os + +def serve_js_from_file(request, response, filename): + body = '' + path = os.path.join(os.path.dirname(__file__), filename) + with open(path, 'rb') as f: + body = f.read() + return ( + [ + ('Cache-Control', 'no-cache, must-revalidate'), + ('Pragma', 'no-cache'), + ('Content-Type', 'application/javascript') + ], body) + +def main(request, response): + key = request.GET["Key"] + + visited_count = request.server.stash.take(key) + if visited_count is None: + visited_count = 0 + + # Keep how many times the test requested this resource. + visited_count += 1 + request.server.stash.put(key, visited_count) + + # Serve a file based on how many times it's requested. + if visited_count == 1: + return serve_js_from_file(request, response, request.GET["First"]) + if visited_count == 2: + return serve_js_from_file(request, response, request.GET["Second"]) + raise "Unknown state"
diff --git a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/update.https.html b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/update.https.html index 7f5ec4a..f7fae35e 100644 --- a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/update.https.html +++ b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/update.https.html
@@ -10,11 +10,12 @@ 'use strict'; const SCOPE = 'resources/simple.txt'; -const WORKER_URL_BASE = 'resources/update-worker.py'; -async function prepare_ready_registration(t, mode) { +// Create a service worker (update-worker.py). The response to update() will be +// different based on the mode. +async function prepare_ready_registration_with_mode(t, mode) { const key = token(); - const worker_url = `${WORKER_URL_BASE}?Key=${key}&Mode=${mode}`; + const worker_url = `resources/update-worker.py?Key=${key}&Mode=${mode}`; const expected_url = normalizeURL(worker_url); const registration = await service_worker_unregister_and_register( t, worker_url, SCOPE); @@ -28,6 +29,27 @@ return [registration, expected_url]; } +// Create a service worker (update-worker-from-file.py), which is initially +// |initial_worker| and |updated_worker| later. +async function prepare_ready_registration_with_file( + t, initial_worker, updated_worker) { + const key = token(); + const worker_url = `resources/update-worker-from-file.py?` + + `First=${initial_worker}&Second=${updated_worker}&Key=${key}`; + const expected_url = normalizeURL(worker_url); + + const registration = await service_worker_unregister_and_register( + t, worker_url, SCOPE); + await wait_for_state(t, registration.installing, 'activated'); + assert_equals(registration.installing, null, + 'prepare_ready: installing'); + assert_equals(registration.waiting, null, + 'prepare_ready: waiting'); + assert_equals(registration.active.scriptURL, expected_url, + 'prepare_ready: active'); + return [registration, expected_url]; +} + function assert_installing_and_active(registration, expected_url) { assert_equals(registration.installing.scriptURL, expected_url, 'assert_installing_and_active: installing'); @@ -57,7 +79,7 @@ promise_test(async t => { const [registration, expected_url] = - await prepare_ready_registration(t, 'normal'); + await prepare_ready_registration_with_mode(t, 'normal'); t.add_cleanup(() => registration.unregister()); await Promise.all([registration.update(), wait_for_update(t, registration)]); @@ -72,7 +94,7 @@ promise_test(async t => { const [registration, expected_url] = - await prepare_ready_registration(t, 'bad_mime_type'); + await prepare_ready_registration_with_mode(t, 'bad_mime_type'); t.add_cleanup(() => registration.unregister()); await promise_rejects(t, 'SecurityError', registration.update()); @@ -81,7 +103,7 @@ promise_test(async t => { const [registration, expected_url] = - await prepare_ready_registration(t, 'redirect'); + await prepare_ready_registration_with_mode(t, 'redirect'); t.add_cleanup(() => registration.unregister()); await promise_rejects(t, new TypeError(), registration.update()); @@ -90,7 +112,7 @@ promise_test(async t => { const [registration, expected_url] = - await prepare_ready_registration(t, 'syntax_error'); + await prepare_ready_registration_with_mode(t, 'syntax_error'); t.add_cleanup(() => registration.unregister()); await promise_rejects(t, new TypeError(), registration.update()); @@ -99,7 +121,7 @@ promise_test(async t => { const [registration, expected_url] = - await prepare_ready_registration(t, 'throw_install'); + await prepare_ready_registration_with_mode(t, 'throw_install'); t.add_cleanup(() => registration.unregister()); await Promise.all([registration.update(), wait_for_update(t, registration)]); @@ -108,7 +130,7 @@ promise_test(async t => { const [registration, expected_url] = - await prepare_ready_registration(t, 'normal'); + await prepare_ready_registration_with_mode(t, 'normal'); t.add_cleanup(() => registration.unregister()); // We need to hold a client alive so that unregister() below doesn't remove @@ -120,5 +142,23 @@ await promise_rejects( t, new TypeError(), Promise.all([registration.unregister(), registration.update()])); -}, 'update() should fail when the pending uninstall flag is set.') +}, 'update() should fail when the pending uninstall flag is set.'); + +promise_test(async t => { + const [registration, expected_url] = + await prepare_ready_registration_with_file( + t, + 'update-smaller-body-before-update-worker.js', + 'update-smaller-body-after-update-worker.js'); + t.add_cleanup(() => registration.unregister()); + + await Promise.all([registration.update(), wait_for_update(t, registration)]); + assert_installing_and_active(registration, expected_url); + + await wait_for_state(t, registration.installing, 'installed'); + assert_waiting_and_active(registration, expected_url); + + await wait_for_state(t, registration.waiting, 'activated'); + assert_active_only(registration, expected_url); +}, 'update() should succeed when the script shrinks.'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/streams/byte-length-queuing-strategy.any-expected.txt b/third_party/blink/web_tests/external/wpt/streams/byte-length-queuing-strategy.any-expected.txt new file mode 100644 index 0000000..e319f57b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/byte-length-queuing-strategy.any-expected.txt
@@ -0,0 +1,12 @@ +This is a testharness.js-based test. +PASS Can construct a ByteLengthQueuingStrategy with a valid high water mark +PASS Can construct a ByteLengthQueuingStrategy with any value as its high water mark +FAIL ByteLengthQueuingStrategy constructor behaves as expected with strange arguments assert_throws: construction fails with null function "() => new ByteLengthQueuingStrategy(null)" did not throw +FAIL ByteLengthQueuingStrategy size behaves as expected with strange arguments Illegal invocation +FAIL ByteLengthQueuingStrategy.prototype.size should work generically on its this and its arguments Illegal invocation +FAIL ByteLengthQueuingStrategy instances have the correct properties assert_object_equals: highWaterMark property should be a data property with the value passed the constructor value is undefined, expected object +FAIL ByteLengthQueuingStrategy's highWaterMark property can be set to anything Cannot assign to read only property 'highWaterMark' of object '#<ByteLengthQueuingStrategy>' +PASS ByteLengthQueuingStrategy.name is correct +PASS subclassing ByteLengthQueuingStrategy should work correctly +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/byte-length-queuing-strategy.any.js b/third_party/blink/web_tests/external/wpt/streams/byte-length-queuing-strategy.any.js index d47e7cd..6a61adc 100644 --- a/third_party/blink/web_tests/external/wpt/streams/byte-length-queuing-strategy.any.js +++ b/third_party/blink/web_tests/external/wpt/streams/byte-length-queuing-strategy.any.js
@@ -107,3 +107,26 @@ 'ByteLengthQueuingStrategy.name must be "ByteLengthQueuingStrategy"'); }, 'ByteLengthQueuingStrategy.name is correct'); + +class SubClass extends ByteLengthQueuingStrategy { + size() { + return 2; + } + + subClassMethod() { + return true; + } +} + +test(() => { + + const sc = new SubClass({highWaterMark: 77}); + assert_equals(sc.constructor.name, 'SubClass', + 'constructor.name should be correct'); + assert_equals(sc.highWaterMark, 77, + 'highWaterMark should come from the parent class'); + assert_equals(sc.size(), 2, + 'size() on the subclass should override the parent'); + assert_true(sc.subClassMethod(), 'subClassMethod() should work'); + +}, 'subclassing ByteLengthQueuingStrategy should work correctly');
diff --git a/third_party/blink/web_tests/external/wpt/streams/count-queuing-strategy.any-expected.txt b/third_party/blink/web_tests/external/wpt/streams/count-queuing-strategy.any-expected.txt new file mode 100644 index 0000000..48bb81fc --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/streams/count-queuing-strategy.any-expected.txt
@@ -0,0 +1,12 @@ +This is a testharness.js-based test. +PASS Can construct a CountQueuingStrategy with a valid high water mark +PASS Can construct a CountQueuingStrategy with any value as its high water mark +FAIL CountQueuingStrategy constructor behaves as expected with strange arguments assert_throws: construction fails with null function "() => new CountQueuingStrategy(null)" did not throw +FAIL CountQueuingStrategy.prototype.size should work generically on its this and its arguments Illegal invocation +FAIL CountQueuingStrategy size behaves as expected with strange arguments Illegal invocation +FAIL CountQueuingStrategy instances have the correct properties assert_object_equals: highWaterMark property should be a data property with the value passed the constructor value is undefined, expected object +FAIL CountQueuingStrategy's highWaterMark property can be set to anything Cannot assign to read only property 'highWaterMark' of object '#<CountQueuingStrategy>' +PASS CountQueuingStrategy.name is correct +PASS subclassing CountQueuingStrategy should work correctly +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/streams/count-queuing-strategy.any.js b/third_party/blink/web_tests/external/wpt/streams/count-queuing-strategy.any.js index 20bb4c1..5aae61e 100644 --- a/third_party/blink/web_tests/external/wpt/streams/count-queuing-strategy.any.js +++ b/third_party/blink/web_tests/external/wpt/streams/count-queuing-strategy.any.js
@@ -106,3 +106,26 @@ 'CountQueuingStrategy.name must be "CountQueuingStrategy"'); }, 'CountQueuingStrategy.name is correct'); + +class SubClass extends CountQueuingStrategy { + size() { + return 2; + } + + subClassMethod() { + return true; + } +} + +test(() => { + + const sc = new SubClass({highWaterMark: 77}); + assert_equals(sc.constructor.name, 'SubClass', + 'constructor.name should be correct'); + assert_equals(sc.highWaterMark, 77, + 'highWaterMark should come from the parent class'); + assert_equals(sc.size(), 2, + 'size() on the subclass should override the parent'); + assert_true(sc.subClassMethod(), 'subClassMethod() should work'); + +}, 'subclassing CountQueuingStrategy should work correctly');
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFMessage_constructor.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFMessage_constructor.https.html new file mode 100644 index 0000000..73bbb4f8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFMessage_constructor.https.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<title>NDEFMessage constructor</title> +<link rel="help" href="https://w3c.github.io/web-nfc/#dom-ndefmessage"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/nfc_help.js"></script> +<script> + + test(() => { + assert_equals(NDEFMessage.length, 1); + assert_throws(new TypeError, () => new NDEFMessage()); + }, 'NDEFMessage constructor without init dict'); + + test(() => { + const message = new NDEFMessage(null); + assert_equals(message.url.length, 0, 'empty url'); + assert_equals(message.records.length, 0, 'empty records'); + }, 'NDEFMessage constructor with null init dict'); + + test(() => { + const message = new NDEFMessage( + createMessage([createTextRecord(test_text_data)])); + assert_equals(message.records.length, 1, 'one text record'); + assert_equals(message.records[0].recordType, 'text', 'messageType'); + assert_equals(message.records[0].mediaType, 'text/plain', 'mediaType'); + assert_true(typeof message.records[0].data() === 'string'); + assert_equals(message.records[0].data(), test_text_data, + 'data() contains the same text content'); + }, 'NDEFMessage constructor with a text record'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFRecord_constructor.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFRecord_constructor.https.html new file mode 100644 index 0000000..81148856 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFRecord_constructor.https.html
@@ -0,0 +1,71 @@ +<!DOCTYPE html> +<title>NDEFRecord constructor</title> +<link rel="help" href="https://w3c.github.io/web-nfc/#dom-ndefrecord"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/nfc_help.js"></script> +<script> + + test(() => { + assert_equals(NDEFRecord.length, 1); + assert_throws(new TypeError, () => new NDEFRecord()); + }, 'NDEFRecord constructor without init dict'); + + test(() => { + const record = new NDEFRecord(null); + assert_equals(record.recordType.length, 0, 'empty recordType'); + assert_equals(record.mediaType.length, 0, 'empty mediaType'); + assert_equals(record.data(), null, 'null data'); + }, 'NDEFRecord constructor with null init dict'); + + test(() => { + let buffer = new ArrayBuffer(4); + let buffer_view = new Uint8Array(buffer); + let original_data = new Uint8Array([1, 2, 3, 4]); + buffer_view.set(original_data); + const record = new NDEFRecord(createOpaqueRecord(buffer)); + assert_equals(record.recordType, 'opaque', 'recordType'); + assert_equals(record.mediaType, 'application/octet-stream', 'mediaType'); + + const data_1 = record.data(); + assert_true(data_1 instanceof ArrayBuffer); + assert_not_equals(data_1, buffer, 'data() returns a new object'); + assert_array_equals(new Uint8Array(data_1), original_data, + 'data() has the same content with the original buffer'); + + const data_2 = record.data(); + assert_true(data_2 instanceof ArrayBuffer); + assert_not_equals(data_2, data_1, 'data() again returns another new object'); + assert_array_equals(new Uint8Array(data_2), original_data, + 'data() has the same content with the original buffer'); + + buffer_view.set([4, 3, 2, 1]); + const data_3 = record.data(); + assert_true(data_3 instanceof ArrayBuffer); + assert_array_equals(new Uint8Array(data_1), original_data, + 'Modifying the original buffer does not affect data() content'); + assert_array_equals(new Uint8Array(data_2), original_data, + 'Modifying the original buffer does not affect data() content'); + assert_array_equals(new Uint8Array(data_3), original_data, + 'Modifying the original buffer does not affect data() content'); + }, 'NDEFRecord constructor with opaque data'); + + test(() => { + const record = new NDEFRecord(createJsonRecord(test_json_data)); + assert_equals(record.recordType, 'json', 'recordType'); + assert_equals(record.mediaType, 'application/json', 'mediaType'); + + const data_1 = record.data(); + assert_true(typeof data_1 === 'object'); + assert_not_equals(data_1, test_json_data, 'data() returns a new object'); + assert_object_equals(data_1, test_json_data, + 'data() has the same content with the original dictionary'); + + const data_2 = record.data(); + assert_true(typeof data_2 === 'object'); + assert_not_equals(data_2, data_1, 'data() again returns another new object'); + assert_object_equals(data_2, test_json_data, + 'data() has the same content with the original dictionary'); + }, 'NDEFRecord constructor with json data'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index b660be2..0000000 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,6 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with invalid serialNumber NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NFCReadingEvent_constructor.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NFCReadingEvent_constructor.https.html index 3c424294..172b0a6 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NFCReadingEvent_constructor.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NFCReadingEvent_constructor.https.html
@@ -13,10 +13,28 @@ test(() => { const message = createMessage([createJsonRecord(test_json_data)]); + const event = new NFCReadingEvent('type', {serialNumber: null, message: message}); + assert_equals(event.serialNumber, '', 'serialNumber'); + }, 'NFCReadingEvent constructor with null serialNumber'); + + test(() => { + const message = createMessage([createJsonRecord(test_json_data)]); + const event = new NFCReadingEvent('type', {message: message}); + assert_equals(event.serialNumber, '', 'serialNumber'); + }, 'NFCReadingEvent constructor with serialNumber not present'); + + test(() => { + const event = new NFCReadingEvent('type', {serialNumber: '', message: null}); + assert_equals(0, event.message.records.length, 'no records'); + assert_equals(0, event.message.url.length, 'empty url'); + }, 'NFCReadingEvent constructor with null message'); + + test(() => { + const message = createMessage([createJsonRecord(test_json_data)]); const event = new NFCReadingEvent('type', {serialNumber: '', message: message}); assert_equals(event.type, 'type', 'type'); assert_equals(event.serialNumber, '', 'serialNumber'); - assertWebNDEFMessagesEqual(event.message, message, 'message'); + assertWebNDEFMessagesEqual(event.message, new NDEFMessage(message), 'message'); }, 'NFCReadingEvent constructor with valid parameters'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt index 975bd5e..5e3a100 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 50 tests; 22 PASS, 28 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 50 tests; 34 PASS, 16 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS NFCWriter interface: existence and properties of interface object PASS NFCWriter interface object length @@ -28,18 +28,18 @@ FAIL NFCReader interface: new NFCReader(); must inherit property "onerror" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: NFCReader is not defined" FAIL NFCReader interface: new NFCReader(); must inherit property "start()" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: NFCReader is not defined" FAIL NFCReader interface: new NFCReader(); must inherit property "stop()" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: NFCReader is not defined" -FAIL NFCReadingEvent interface: existence and properties of interface object assert_own_property: self does not have own property "NFCReadingEvent" expected property "NFCReadingEvent" missing -FAIL NFCReadingEvent interface object length assert_own_property: self does not have own property "NFCReadingEvent" expected property "NFCReadingEvent" missing -FAIL NFCReadingEvent interface object name assert_own_property: self does not have own property "NFCReadingEvent" expected property "NFCReadingEvent" missing -FAIL NFCReadingEvent interface: existence and properties of interface prototype object assert_own_property: self does not have own property "NFCReadingEvent" expected property "NFCReadingEvent" missing -FAIL NFCReadingEvent interface: existence and properties of interface prototype object's "constructor" property assert_own_property: self does not have own property "NFCReadingEvent" expected property "NFCReadingEvent" missing -FAIL NFCReadingEvent interface: existence and properties of interface prototype object's @@unscopables property assert_own_property: self does not have own property "NFCReadingEvent" expected property "NFCReadingEvent" missing -FAIL NFCReadingEvent interface: attribute serialNumber assert_own_property: self does not have own property "NFCReadingEvent" expected property "NFCReadingEvent" missing -FAIL NFCReadingEvent interface: attribute message assert_own_property: self does not have own property "NFCReadingEvent" expected property "NFCReadingEvent" missing -FAIL NFCReadingEvent must be primary interface of new NFCReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World"}]} }) assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: NFCReadingEvent is not defined" -FAIL Stringification of new NFCReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World"}]} }) assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: NFCReadingEvent is not defined" -FAIL NFCReadingEvent interface: new NFCReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World"}]} }) must inherit property "serialNumber" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: NFCReadingEvent is not defined" -FAIL NFCReadingEvent interface: new NFCReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World"}]} }) must inherit property "message" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: NFCReadingEvent is not defined" +PASS NFCReadingEvent interface: existence and properties of interface object +PASS NFCReadingEvent interface object length +PASS NFCReadingEvent interface object name +PASS NFCReadingEvent interface: existence and properties of interface prototype object +PASS NFCReadingEvent interface: existence and properties of interface prototype object's "constructor" property +PASS NFCReadingEvent interface: existence and properties of interface prototype object's @@unscopables property +PASS NFCReadingEvent interface: attribute serialNumber +PASS NFCReadingEvent interface: attribute message +PASS NFCReadingEvent must be primary interface of new NFCReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World"}]} }) +PASS Stringification of new NFCReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World"}]} }) +PASS NFCReadingEvent interface: new NFCReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World"}]} }) must inherit property "serialNumber" with the proper type +PASS NFCReadingEvent interface: new NFCReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World"}]} }) must inherit property "message" with the proper type PASS NFCErrorEvent interface: existence and properties of interface object PASS NFCErrorEvent interface object length PASS NFCErrorEvent interface object name
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/resources/nfc_help.js b/third_party/blink/web_tests/external/wpt/web-nfc/resources/nfc_help.js index 812d0f0..67fd5af3 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/resources/nfc_help.js +++ b/third_party/blink/web_tests/external/wpt/web-nfc/resources/nfc_help.js
@@ -6,6 +6,7 @@ const test_json_data = {level: 1, score: 100, label: 'Game'}; const test_url_data = "https://w3c.github.io/web-nfc"; const test_buffer_data = new ArrayBuffer(test_text_byte_array.length); +const test_buffer_view = new Uint8Array(test_buffer_data).set(test_text_byte_array); function noop() {}; @@ -55,14 +56,14 @@ let recordB = b.records[i]; assert_equals(recordA.recordType, recordB.recordType); assert_equals(recordA.mediaType, recordB.mediaType); - if (recordA.data instanceof ArrayBuffer) { - assert_array_equals(new Uint8Array(recordA.data), - new Uint8Array(recordB.data)); - } else if (typeof recordA.data === 'object') { - assert_object_equals(recordA.data, recordB.data); - } else if (typeof recordA.data === 'number' - || typeof recordA.data === 'string') { - assert_true(recordA.data == recordB.data); + if (recordA.data() instanceof ArrayBuffer) { + assert_array_equals(new Uint8Array(recordA.data()), + new Uint8Array(recordB.data())); + } else if (typeof recordA.data() === 'object') { + assert_object_equals(recordA.data(), recordB.data()); + } else if (typeof recordA.data() === 'number' + || typeof recordA.data() === 'string') { + assert_true(recordA.data() == recordB.data()); } } }
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-createDataChannel-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-createDataChannel-expected.txt index 8d92a63..74dac5e 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-createDataChannel-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-createDataChannel-expected.txt
@@ -1,15 +1,15 @@ This is a testharness.js-based test. PASS createDataChannel with no argument should throw TypeError PASS createDataChannel with closed connection should throw InvalidStateError -FAIL createDataChannel attribute default values assert_equals: expected (object) null but got (undefined) undefined -FAIL createDataChannel with provided parameters should initialize attributes to provided values assert_equals: expected (object) null but got (undefined) undefined +FAIL createDataChannel attribute default values assert_equals: expected (string) "low" but got (undefined) undefined +FAIL createDataChannel with provided parameters should initialize attributes to provided values assert_equals: expected (string) "high" but got (undefined) undefined PASS createDataChannel with label "foo" should succeed PASS createDataChannel with label null should succeed PASS createDataChannel with label undefined should succeed PASS createDataChannel with label lone surrogate should succeed PASS createDataChannel with ordered false should succeed PASS createDataChannel with ordered null/undefined should succeed -FAIL createDataChannel with maxPacketLifeTime 0 should succeed assert_equals: expected (number) 0 but got (undefined) undefined +PASS createDataChannel with maxPacketLifeTime 0 should succeed PASS createDataChannel with maxRetransmits 0 should succeed PASS createDataChannel with both maxPacketLifeTime and maxRetransmits undefined should succeed PASS createDataChannel with both maxPacketLifeTime and maxRetransmits should throw TypeError
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-ondatachannel-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-ondatachannel-expected.txt index d04de3ba..1e0c99b8 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-ondatachannel-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-ondatachannel-expected.txt
@@ -4,8 +4,8 @@ FAIL Open event should not be raised when closing the channel in the datachannel event assert_unreached: Open event should not fire Reached unreachable code PASS Open event should be raised when closing the channel in the datachannel event after enqueuing a task FAIL Open event should not be raised when sending and immediately closing the channel in the datachannel event assert_unreached: Open event should not fire Reached unreachable code -FAIL In-band negotiated channel created on remote peer should match the same configuration as local peer assert_equals: expected (object) null but got (undefined) undefined -FAIL In-band negotiated channel created on remote peer should match the same (default) configuration as local peer assert_equals: expected (object) null but got (undefined) undefined +FAIL In-band negotiated channel created on remote peer should match the same configuration as local peer assert_equals: expected (string) "high" but got (undefined) undefined +FAIL In-band negotiated channel created on remote peer should match the same (default) configuration as local peer assert_equals: expected (string) "low" but got (undefined) undefined PASS Negotiated channel should not fire datachannel event on remote peer Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/historical-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/historical-expected.txt index 4353e86..68050e46 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/historical-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/historical-expected.txt
@@ -1,6 +1,6 @@ This is a testharness.js-based test. FAIL RTCDataChannel member reliable should not exist assert_false: expected false got true -FAIL RTCDataChannel member maxRetransmitTime should not exist assert_false: expected false got true +PASS RTCDataChannel member maxRetransmitTime should not exist FAIL RTCPeerConnection member addStream should not exist assert_false: expected false got true FAIL RTCPeerConnection member createDTMFSender should not exist assert_false: expected false got true FAIL RTCPeerConnection member getLocalStreams should not exist assert_false: expected false got true
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt index 1f26f0d..2dd1e4d 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 508 tests; 468 PASS, 40 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 508 tests; 470 PASS, 38 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Test driver for asyncInitCertificate PASS Test driver for asyncInitTransports @@ -398,7 +398,7 @@ PASS RTCDataChannel interface: existence and properties of interface prototype object's @@unscopables property PASS RTCDataChannel interface: attribute label PASS RTCDataChannel interface: attribute ordered -FAIL RTCDataChannel interface: attribute maxPacketLifeTime assert_true: The prototype object must have a property "maxPacketLifeTime" expected true got false +PASS RTCDataChannel interface: attribute maxPacketLifeTime PASS RTCDataChannel interface: attribute maxRetransmits PASS RTCDataChannel interface: attribute protocol PASS RTCDataChannel interface: attribute negotiated @@ -423,7 +423,7 @@ PASS Stringification of new RTCPeerConnection().createDataChannel('') PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "label" with the proper type PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "ordered" with the proper type -FAIL RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "maxPacketLifeTime" with the proper type assert_inherits: property "maxPacketLifeTime" not found in prototype chain +PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "maxPacketLifeTime" with the proper type PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "maxRetransmits" with the proper type PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "protocol" with the proper type PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "negotiated" with the proper type
diff --git a/third_party/blink/web_tests/fast/dom/shadow/content-text-selection-crash.html b/third_party/blink/web_tests/fast/dom/shadow/content-text-selection-crash.html new file mode 100644 index 0000000..4c937e5 --- /dev/null +++ b/third_party/blink/web_tests/fast/dom/shadow/content-text-selection-crash.html
@@ -0,0 +1,14 @@ +<!doctype html> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> +<p>Selecting all text should not crash.</p> +<div id="host"></div> +<script> + test(() => { + const root = host.createShadowRoot(); + root.innerHTML = "<style>content::selection {color:green}</style><content>Fallback</content>"; + const range = document.createRange(); + range.selectNode(document.body); + window.getSelection().addRange(range); + }, "Adding ::selection style on <content> should not crash when rendering fallback."); +</script>
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/webexposed/periodic-background-sync-origin-trial-interfaces-worker.js b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/periodic-background-sync-origin-trial-interfaces-worker.js new file mode 100644 index 0000000..34d0253 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/periodic-background-sync-origin-trial-interfaces-worker.js
@@ -0,0 +1,13 @@ +importScripts('/resources/testharness.js', + '/resources/origin-trials-helper.js'); + +test(t => { + + OriginTrialsHelper.check_properties_exist(this, { + 'ServiceWorkerRegistration': ['periodicSync'], + 'PeriodicSyncManager': ['register', 'getTags', 'unregister'], + 'PeriodicSyncEvent': ['tag'], + }); +}, 'Periodic Background Sync API interfaces and properties in Origin-Trial enabled worker.'); + +done(); \ No newline at end of file
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/webexposed/periodic-background-sync-origin-trial-interfaces.html b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/periodic-background-sync-origin-trial-interfaces.html new file mode 100644 index 0000000..cd9b513 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/periodic-background-sync-origin-trial-interfaces.html
@@ -0,0 +1,23 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<!-- Generate token with the command: +generate_token.py http://127.0.0.1:8000 PeriodicBackgroundSync --expire-timestamp=2000000000 +--> + +<meta http-equiv="origin-trial" content="ArBC4XZnvKrTOwjYpe4wXy6t+PrIdFoyqLkTNBVamdBgdFTxwMc9xfEJonBUlsX1LLLTzzLKhFZujvwwZrbPog8AAABeeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiUGVyaW9kaWNCYWNrZ3JvdW5kU3luYyIsICJleHBpcnkiOiAyMDAwMDAwMDAwfQ==" /> +<title>Periodic Background Sync API - interfaces exposed by origin trial</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/origin-trials-helper.js"></script> +<script src="/serviceworker/resources/test-helpers.js"></script> + +<script> +test(t => { + OriginTrialsHelper.check_properties_exist(this, { + 'PeriodicSyncManager': ['register', 'getTags', 'unregister'], + 'ServiceWorkerRegistration': ['periodicSync'], + }); +}, 'Periodic Background Sync API interfaces and properties in Origin-Trial enabled document.'); + +service_worker_test('resources/periodic-background-sync-origin-trial-interfaces-worker.php'); +</script> \ No newline at end of file
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/webexposed/resources/periodic-background-sync-origin-trial-interfaces-worker.php b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/resources/periodic-background-sync-origin-trial-interfaces-worker.php new file mode 100644 index 0000000..d22a86a --- /dev/null +++ b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/resources/periodic-background-sync-origin-trial-interfaces-worker.php
@@ -0,0 +1,19 @@ +<?php +// Generate token with the command: +// generate_token.py http://127.0.0.1:8000 PeriodicBackgroundSync --expire-timestamp=2000000000 +header("Origin-Trial: ArBC4XZnvKrTOwjYpe4wXy6t+PrIdFoyqLkTNBVamdBgdFTxwMc9xfEJonBUlsX1LLLTzzLKhFZujvwwZrbPog8AAABeeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiUGVyaW9kaWNCYWNrZ3JvdW5kU3luYyIsICJleHBpcnkiOiAyMDAwMDAwMDAwfQ=="); +header('Content-Type: application/javascript'); +?> + +importScripts('/resources/testharness.js', + '/resources/origin-trials-helper.js'); + +test(t => { + OriginTrialsHelper.check_properties_exist(this, { + 'ServiceWorkerRegistration': ['periodicSync'], + 'PeriodicSyncManager': ['register', 'getTags', 'unregister'], + 'PeriodicSyncEvent': ['tag'], + }); +}, 'Periodic Background Sync API interfaces and properties in Origin-Trial enabled worker.'); + +done(); \ No newline at end of file
diff --git a/third_party/blink/web_tests/nfc/resources/nfc-helpers.js b/third_party/blink/web_tests/nfc/resources/nfc-helpers.js index f419701..46575a4a 100644 --- a/third_party/blink/web_tests/nfc/resources/nfc-helpers.js +++ b/third_party/blink/web_tests/nfc/resources/nfc-helpers.js
@@ -106,7 +106,7 @@ return device.mojom.NDEFCompatibility.ANY; } -// Converts between NDEFMessage https://w3c.github.io/web-nfc/#dom-ndefmessage +// Converts between NDEFMessageInit https://w3c.github.io/web-nfc/#dom-ndefmessage // and mojom.NDEFMessage structure, so that nfc.watch function can be tested. function toMojoNDEFMessage(message) { let ndefMessage = new device.mojom.NDEFMessage(); @@ -141,8 +141,8 @@ return byteArray; } -// Compares NDEFMessage that was provided to the API -// (e.g. navigator.nfc.push), and NDEFMessage that was received by the +// Compares NDEFMessageSource that was provided to the API +// (e.g. navigator.nfc.push), and mojom NDEFMessage that was received by the // mock NFC service. function assertNDEFMessagesEqual(providedMessage, receivedMessage) { // If simple data type is passed, e.g. String or ArrayBuffer, convert it @@ -173,7 +173,6 @@ let recordB = b.records[i]; assert_equals(recordA.recordType, recordB.recordType); assert_equals(recordA.mediaType, recordB.mediaType); - if (recordA.data instanceof ArrayBuffer) { assert_array_equals(new Uint8Array(recordA.data), new Uint8Array(recordB.data));
diff --git a/third_party/blink/web_tests/nfc/watch.html b/third_party/blink/web_tests/nfc/watch.html index c54db47..f2d42509 100644 --- a/third_party/blink/web_tests/nfc/watch.html +++ b/third_party/blink/web_tests/nfc/watch.html
@@ -62,7 +62,7 @@ let messageCallback; let promise = new Promise(resolve => { messageCallback = receivedMessage => { - assertWebNDEFMessagesEqual(message, receivedMessage); + assertWebNDEFMessagesEqual(new NDEFMessage(message), receivedMessage); resolve(); } });
diff --git a/third_party/blink/web_tests/platform/linux/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/platform/linux/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index 023d6be..0000000 --- a/third_party/blink/web_tests/platform/linux/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index 023d6be..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.11/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index 023d6be..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.11/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.12/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index 023d6be..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.12/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac-retina/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/platform/mac-retina/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index 023d6be..0000000 --- a/third_party/blink/web_tests/platform/mac-retina/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index 023d6be..0000000 --- a/third_party/blink/web_tests/platform/mac/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/win/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/platform/win/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index 023d6be..0000000 --- a/third_party/blink/web_tests/platform/win/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/win7/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt b/third_party/blink/web_tests/platform/win7/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt deleted file mode 100644 index 023d6be..0000000 --- a/third_party/blink/web_tests/platform/win7/external/wpt/web-nfc/NFCReadingEvent_constructor.https-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL NFCReadingEvent constructor without init dict NFCReadingEvent is not defined -FAIL NFCReadingEvent constructor with valid parameters NFCReadingEvent is not defined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/virtual/cascade/README.md b/third_party/blink/web_tests/virtual/cascade/README.md new file mode 100644 index 0000000..e33581a --- /dev/null +++ b/third_party/blink/web_tests/virtual/cascade/README.md
@@ -0,0 +1,5 @@ +This is a virtual test suite for the Cascade Project. + +Flag: CSSCascade + +https://crbug.com/947004
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt index 482a59c..b259fa20 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -4967,7 +4967,7 @@ getter bufferedAmountLowThreshold getter id getter label - getter maxRetransmitTime + getter maxPacketLifeTime getter maxRetransmits getter negotiated getter onbufferedamountlow
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt index 52843dc..d210c65 100644 --- a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 508 tests; 399 PASS, 109 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 508 tests; 401 PASS, 107 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Test driver for asyncInitCertificate FAIL Test driver for asyncInitTransports assert_unreached: Failed to run asyncInitTransports: Error: assert_true: Expect pc.sctp to be instance of RTCSctpTransport expected true got false Reached unreachable code @@ -398,7 +398,7 @@ PASS RTCDataChannel interface: existence and properties of interface prototype object's @@unscopables property PASS RTCDataChannel interface: attribute label PASS RTCDataChannel interface: attribute ordered -FAIL RTCDataChannel interface: attribute maxPacketLifeTime assert_true: The prototype object must have a property "maxPacketLifeTime" expected true got false +PASS RTCDataChannel interface: attribute maxPacketLifeTime PASS RTCDataChannel interface: attribute maxRetransmits PASS RTCDataChannel interface: attribute protocol PASS RTCDataChannel interface: attribute negotiated @@ -423,7 +423,7 @@ PASS Stringification of new RTCPeerConnection().createDataChannel('') PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "label" with the proper type PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "ordered" with the proper type -FAIL RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "maxPacketLifeTime" with the proper type assert_inherits: property "maxPacketLifeTime" not found in prototype chain +PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "maxPacketLifeTime" with the proper type PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "maxRetransmits" with the proper type PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "protocol" with the proper type PASS RTCDataChannel interface: new RTCPeerConnection().createDataChannel('') must inherit property "negotiated" with the proper type
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index 9df98cd0..c38208eb8 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -594,8 +594,10 @@ setter onmessage setter onmessageerror interface ByteLengthQueuingStrategy + attribute @@toStringTag + getter highWaterMark + getter size method constructor - method size interface CDATASection : Text attribute @@toStringTag method constructor @@ -1174,8 +1176,10 @@ method set setter onchange interface CountQueuingStrategy + attribute @@toStringTag + getter highWaterMark + getter size method constructor - method size interface Credential attribute @@toStringTag getter id @@ -4912,6 +4916,17 @@ getter target getter type method constructor +interface NDEFMessage + attribute @@toStringTag + getter records + getter url + method constructor +interface NDEFRecord + attribute @@toStringTag + getter mediaType + getter recordType + method constructor + method data interface NFC attribute @@toStringTag method cancelPush @@ -4923,6 +4938,11 @@ attribute @@toStringTag getter error method constructor +interface NFCReadingEvent : Event + attribute @@toStringTag + getter message + getter serialNumber + method constructor interface NFCWriter attribute @@toStringTag method constructor @@ -5766,7 +5786,7 @@ getter bufferedAmountLowThreshold getter id getter label - getter maxRetransmitTime + getter maxPacketLifeTime getter maxRetransmits getter negotiated getter onbufferedamountlow
diff --git a/third_party/blink/web_tests/webgpu/fence.html b/third_party/blink/web_tests/webgpu/fence.html index 3f69e560..4e08d8d68 100644 --- a/third_party/blink/web_tests/webgpu/fence.html +++ b/third_party/blink/web_tests/webgpu/fence.html
@@ -11,7 +11,7 @@ { // Test default initial value. - const fence = queue.createFence({}); + const fence = queue.createFence(); assert_equals(fence.getCompletedValue(), 0); } { @@ -22,21 +22,21 @@ { // Promise resolves when onCompletion value is less than signal value. - const fence = queue.createFence({}); + const fence = queue.createFence(); queue.signal(fence, 2); await fence.onCompletion(1); assert_equals(fence.getCompletedValue(), 2); } { // Promise resolves when onCompletion value is equal to signal value. - const fence = queue.createFence({}); + const fence = queue.createFence(); queue.signal(fence, 2); await fence.onCompletion(2); assert_equals(fence.getCompletedValue(), 2); } { // Promise resolves when signal is called multiple times. - const fence = queue.createFence({}); + const fence = queue.createFence(); queue.signal(fence, 1); queue.signal(fence, 2); await fence.onCompletion(2); @@ -44,7 +44,7 @@ } { // Promise resolves if fence has already completed. - const fence = queue.createFence({}); + const fence = queue.createFence(); queue.signal(fence, 2); // Wait for value to update. @@ -63,7 +63,7 @@ // Test dropping references to the fence and onCompletion promise does not // crash. { - const fence = queue.createFence({}); + const fence = queue.createFence(); queue.signal(fence, 2); fence.onCompletion(2); } @@ -74,7 +74,7 @@ // crash. let promise; { - const fence = queue.createFence({}); + const fence = queue.createFence(); queue.signal(fence, 2); promise = fence.onCompletion(2); } @@ -83,7 +83,7 @@ } { // Test many calls to signal and wait on fence values one at a time. - const fence = queue.createFence({}); + const fence = queue.createFence(); for (let i = 1; i <= 20; ++i) { queue.signal(fence, i); await fence.onCompletion(i); @@ -92,7 +92,7 @@ } { // Test many calls to signal and wait on all fence values. - const fence = queue.createFence({}); + const fence = queue.createFence(); const promises = []; for (let i = 1; i <= 20; ++i) { queue.signal(fence, i); @@ -105,7 +105,7 @@ } { // Test it is illegal to wait on a fence without signaling the value. - const fence = queue.createFence({}); + const fence = queue.createFence(); const promise = fence.onCompletion(2); await promise_rejects( @@ -113,7 +113,7 @@ } { // Test it is illegal to wait on a fence before it is signaled. - const fence = queue.createFence({}); + const fence = queue.createFence(); const promise = fence.onCompletion(2); queue.signal(fence, 2); @@ -122,7 +122,7 @@ } { // Test it is illegal to wait on a value greater than the signaled value. - const fence = queue.createFence({}); + const fence = queue.createFence(); queue.signal(fence, 2); const promise = fence.onCompletion(3);
diff --git a/tools/binary_size/diagnose_bloat.py b/tools/binary_size/diagnose_bloat.py index 1d8149d4..b6c328b 100755 --- a/tools/binary_size/diagnose_bloat.py +++ b/tools/binary_size/diagnose_bloat.py
@@ -328,6 +328,9 @@ # Variables often become unused when experimenting with macros to reduce # size, so don't fail on warnings. gn_args += ' treat_warnings_as_errors=false' + # Speed things up a bit by skipping lint & errorprone. + gn_args += ' disable_android_lint=true' + gn_args += ' use_errorprone_java_compiler=false' gn_args += ' use_goma=%s' % str(self.use_goma).lower() gn_args += ' target_os="%s"' % self.target_os if self.IsAndroid():
diff --git a/tools/binary_size/libsupersize/archive.py b/tools/binary_size/libsupersize/archive.py index de605d6..e518dd5 100644 --- a/tools/binary_size/libsupersize/archive.py +++ b/tools/binary_size/libsupersize/archive.py
@@ -52,6 +52,13 @@ 'thin_archives', ]) +# When ensuring matching section sizes between .elf and .map files, these +# sections should be ignored. When lld creates a combined library with +# partitions, some sections (like .text) exist in each partition, but the ones +# below are common. At library splitting time, llvm-objcopy pulls what's needed +# from these sections into the new libraries. Hence, the ELF sections will end +# up smaller than the combined .map file sections. +_SECTION_SIZE_BLACKLIST = ['.symtab', '.shstrtab', '.strtab'] # Tunable "knobs" for CreateSectionSizesAndSymbols(). class SectionSizeKnobs(object): @@ -857,7 +864,7 @@ logging.info('Parsing Linker Map') with _OpenMaybeGz(map_path) as map_file: - section_sizes, raw_symbols, linker_map_extras = ( + map_section_sizes, raw_symbols, linker_map_extras = ( linker_map_parser.MapFileParser().Parse(linker_name, map_file)) if outdir_context and outdir_context.thin_archives: @@ -866,12 +873,17 @@ if elf_path: logging.debug('Validating section sizes') elf_section_sizes = _SectionSizesFromElf(elf_path, tool_prefix) + differing_elf_section_sizes = {} + differing_map_section_sizes = {} for k, v in elf_section_sizes.iteritems(): - if v != section_sizes.get(k): - logging.error('ELF file and .map file do not agree on section sizes.') - logging.error('.map file: %r', section_sizes) - logging.error('readelf: %r', elf_section_sizes) - sys.exit(1) + if k not in _SECTION_SIZE_BLACKLIST and v != map_section_sizes.get(k): + differing_map_section_sizes[k] = map_section_sizes.get(k) + differing_elf_section_sizes[k] = v + if differing_map_section_sizes: + logging.error('ELF file and .map file do not agree on section sizes.') + logging.error('readelf: %r', differing_elf_section_sizes) + logging.error('.map file: %r', differing_map_section_sizes) + sys.exit(1) if elf_path and outdir_context: missed_object_paths = _DiscoverMissedObjectPaths( @@ -937,7 +949,10 @@ linker_map_parser.DeduceObjectPathsFromThinMap(raw_symbols, linker_map_extras) - return section_sizes, raw_symbols, object_paths_by_name + # If we have an ELF file, use its sizes as the source of truth, since some + # sections can differ from the .map. + return (elf_section_sizes if elf_path else map_section_sizes, raw_symbols, + object_paths_by_name) def _ComputePakFileSymbols( @@ -1506,7 +1521,7 @@ def _ElfInfoFromApk(apk_path, apk_so_path, tool_prefix): - """Returns a tuple of (build_id, section_sizes).""" + """Returns a tuple of (build_id, section_sizes, elf_overhead_size).""" with zipfile.ZipFile(apk_path) as apk, \ tempfile.NamedTemporaryFile() as f: f.write(apk.read(apk_so_path))
diff --git a/tools/binary_size/libsupersize/linker_map_parser.py b/tools/binary_size/libsupersize/linker_map_parser.py index 6f7f8a8..dc3988aa 100755 --- a/tools/binary_size/libsupersize/linker_map_parser.py +++ b/tools/binary_size/libsupersize/linker_map_parser.py
@@ -485,6 +485,7 @@ tokenizer = self.Tokenize(lines) + in_partitions = False in_jump_table = False jump_tables_count = 0 jump_entries_count = 0 @@ -493,15 +494,32 @@ # Level 1 data match the "Out" column. They specify sections or # PROVIDE_HIDDEN lines. if level == 1: - if not tok.startswith('PROVIDE_HIDDEN'): - self._section_sizes[tok] = size - cur_section = tok - # E.g., Want to convert "(.text._name)" -> "_name" later. - mangled_start_idx = len(cur_section) + 2 - cur_section_is_useful = (cur_section in models.BSS_SECTIONS - or cur_section in (models.SECTION_RODATA, - models.SECTION_TEXT) - or cur_section.startswith(models.SECTION_DATA)) + # Ignore sections that belong to feature library partitions. Seeing a + # library name is an indicator that we've entered a list of feature + # partitions. After these, a single .part.end section will follow to + # reserve memory at runtime. Seeing the .part.end section also marks the + # end of partition sections in the map file. + if tok.startswith('lib') and tok.endswith('.so'): + in_partitions = True + elif tok == '.part.end': + # Note that we want to retain .part.end section, so it's fine to + # restart processing on this section, rather than the next one. + in_partitions = False + + if in_partitions: + # For now, completely ignore feature partitions. + cur_section = None + cur_section_is_useful = False + else: + if not tok.startswith('PROVIDE_HIDDEN'): + self._section_sizes[tok] = size + cur_section = tok + # E.g., Want to convert "(.text._name)" -> "_name" later. + mangled_start_idx = len(cur_section) + 2 + cur_section_is_useful = ( + cur_section in models.BSS_SECTIONS + or cur_section in (models.SECTION_RODATA, models.SECTION_TEXT) + or cur_section.startswith(models.SECTION_DATA)) elif cur_section_is_useful: # Level 2 data match the "In" column. They specify object paths and
diff --git a/tools/binary_size/libsupersize/testdata/linker_map_parser/Parser.golden b/tools/binary_size/libsupersize/testdata/linker_map_parser/Parser.golden index 0b95b3c..0c3fbb435 100644 --- a/tools/binary_size/libsupersize/testdata/linker_map_parser/Parser.golden +++ b/tools/binary_size/libsupersize/testdata/linker_map_parser/Parser.golden
@@ -20,6 +20,7 @@ .note.android.ident 152 .note.crashpad.info 28 .note.gnu.build-id 36 +.part.end 4096 .plt 6096 .rel.dyn 184789 .rel.plt 3032 @@ -124,3 +125,4 @@ .bss@2f56000(size_without_padding=4,padding=0,full_name=WebRtcSpl_CrossCorrelation,object_path=,source_path=,flags={},num_aliases=1,component=) .bss@2f56004(size_without_padding=4,padding=0,full_name=WebRtcSpl_DownsampleFast,object_path=,source_path=,flags={},num_aliases=1,component=) .bss@2f56008(size_without_padding=4,padding=0,full_name=WebRtcSpl_MaxAbsValueW16,object_path=,source_path=,flags={},num_aliases=1,component=) +.part.end@0(size_without_padding=4096,padding=0,full_name=** ,object_path=,source_path=,flags={},num_aliases=1,component=)
diff --git a/tools/binary_size/libsupersize/testdata/linker_map_parser/Tokenize.golden b/tools/binary_size/libsupersize/testdata/linker_map_parser/Tokenize.golden index e9e5225..cc142f5 100644 --- a/tools/binary_size/libsupersize/testdata/linker_map_parser/Tokenize.golden +++ b/tools/binary_size/libsupersize/testdata/linker_map_parser/Tokenize.golden
@@ -226,6 +226,40 @@ 2F56008 4 (3) 0 WebRtcSpl_MaxAbsValueW16 2F56008 4 (3) 0 WebRtcSpl_MaxAbsValueW16 2F56008 4 (3) 4 WebRtcSpl_MaxAbsValueW16 + 34BE000 34 (1) -------- libvr.so + 34BE000 34 (2) -------- <internal>:(libvr.so) + 34BE034 140 (1) -------- .phdrs + 34BE034 140 (2) -------- <internal>:(.phdrs) + 34BE174 13 (1) -------- .interp + 34BE174 13 (2) -------- <internal>:(.interp) + 34BE188 1C (1) -------- .note.crashpad.info + 34BE188 1C (2) -------- obj/third_party/crashpad/crashpad/client/libclient.a(client/crashpad_info_note.o):(.note.crashpad.info) + 34BE1A4 98 (1) -------- .note.android.ident + 34BE1A4 98 (2) -------- ../../third_party/android_ndk/platforms/android-16/arch-arm/usr/lib/crtbegin_so.o:(.note.android.ident) + 34BE23C 24 (1) -------- .note.gnu.build-id + 34BE23C 24 (2) -------- <internal>:(.note.gnu.build-id) + 34BE260 20 (1) -------- .dynsym + 34BE260 20 (2) -------- <internal>:(.dynsym) + 34BE280 4 (1) -------- .gnu.version + 34BE280 4 (2) -------- <internal>:(.gnu.version) + 34BE284 60 (1) -------- .gnu.version_r + 34BE284 60 (2) -------- <internal>:(.gnu.version_r) + 34BE2E4 1C (1) -------- .gnu.hash + 34BE2E4 1C (2) -------- <internal>:(.gnu.hash) + 34BE300 6C (1) -------- .dynstr + 34BE300 6C (2) -------- <internal>:(.dynstr) + 34BE36C 257 (1) -------- .rel.dyn + 34BE36C 257 (2) -------- <internal>:(.rel.dyn) + 34BE5C4 10 (1) -------- .ARM.exidx + 34BE5C4 10 (2) -------- <internal>:(.ARM.exidx) + 34BE5D8 2428 (1) -------- .rodata + 34BE5D8 10 (2) -------- thinlto-cache/Thin-5e976b.tmp.o:(.rodata._ZN2vrL17kRepositionIconIdE) + 34BE5D8 10 (3) 10 vr::kRepositionIconId + 34C0A00 2C9EC (1) -------- .text + 34C0A00 18 (2) -------- thinlto-cache/Thin-ec84a4.tmp.o:(.text._ZN6SkFont7setSizeEf) + 34C0A00 18 (3) 18 SkFont::setSize(float) + 0 1000 (1) -------- .part.end + 0 1000 (2) -------- <internal>:(.part.end) 0 23 (1) -------- .ARM.attributes 0 23 (2) -------- obj/third_party/boringssl/boringssl_asm/chacha-armv4.o:(.ARM.attributes) 0 A8 (1) -------- .comment
diff --git a/tools/binary_size/libsupersize/testdata/linker_map_parser/test_lld-lto_v1.map b/tools/binary_size/libsupersize/testdata/linker_map_parser/test_lld-lto_v1.map index b7f1b937..ff0713f 100644 --- a/tools/binary_size/libsupersize/testdata/linker_map_parser/test_lld-lto_v1.map +++ b/tools/binary_size/libsupersize/testdata/linker_map_parser/test_lld-lto_v1.map
@@ -351,6 +351,46 @@ 2f56008 2f56008 4 1 WebRtcSpl_MaxAbsValueW16 2f56008 2f56008 4 1 WebRtcSpl_MaxAbsValueW16 +# Partitions should be ignored at this point. Otherwise, their .text, .rodata, +# etc. sections will overwrite those of the main partition. + 34be000 34be000 34 1 libvr.so + 34be000 34be000 34 1 <internal>:(libvr.so) + 34be034 34be034 140 1 .phdrs + 34be034 34be034 140 1 <internal>:(.phdrs) + 34be174 34be174 13 1 .interp + 34be174 34be174 13 1 <internal>:(.interp) + 34be188 34be188 1c 4 .note.crashpad.info + 34be188 34be188 1c 4 obj/third_party/crashpad/crashpad/client/libclient.a(client/crashpad_info_note.o):(.note.crashpad.info) + 34be1a4 34be1a4 98 4 .note.android.ident + 34be1a4 34be1a4 98 4 ../../third_party/android_ndk/platforms/android-16/arch-arm/usr/lib/crtbegin_so.o:(.note.android.ident) + 34be23c 34be23c 24 4 .note.gnu.build-id + 34be23c 34be23c 24 4 <internal>:(.note.gnu.build-id) + 34be260 34be260 20 4 .dynsym + 34be260 34be260 20 4 <internal>:(.dynsym) + 34be280 34be280 4 2 .gnu.version + 34be280 34be280 4 2 <internal>:(.gnu.version) + 34be284 34be284 60 4 .gnu.version_r + 34be284 34be284 60 4 <internal>:(.gnu.version_r) + 34be2e4 34be2e4 1c 4 .gnu.hash + 34be2e4 34be2e4 1c 4 <internal>:(.gnu.hash) + 34be300 34be300 6c 1 .dynstr + 34be300 34be300 6c 1 <internal>:(.dynstr) + 34be36c 34be36c 257 4 .rel.dyn + 34be36c 34be36c 257 4 <internal>:(.rel.dyn) + 34be5c4 34be5c4 10 4 .ARM.exidx + 34be5c4 34be5c4 10 4 <internal>:(.ARM.exidx) + 34be5d8 34be5d8 2428 8 .rodata + 34be5d8 34be5d8 10 1 thinlto-cache/Thin-5e976b.tmp.o:(.rodata._ZN2vrL17kRepositionIconIdE) + 34be5d8 34be5d8 10 1 vr::kRepositionIconId + 34c0a00 34c0a00 2c9ec 16 .text + 34c0a00 34c0a00 18 4 thinlto-cache/Thin-ec84a4.tmp.o:(.text._ZN6SkFont7setSizeEf) + 34c0a00 34c0a00 0 1 $t.11 + 34c0a01 34c0a01 18 1 SkFont::setSize(float) + 34c0a14 34c0a14 0 1 $d.12 +# .part.end is unique, even if multiple lib*.so, .phdrs, etc. exist. + 0 0 1000 1 .part.end + 0 0 1000 1 <internal>:(.part.end) + # Various .debug sections can exist, but they're omitted for simplicity. # Size-only sections.
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 1a44933b..3120c030 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -12352,6 +12352,15 @@ </description> </action> +<action name="MobileNTPPaused"> + <owner>skym@chromium.org</owner> + <owner>carloks@chromium.org</owner> + <owner>twellington@chromium.org</owner> + <description> + The New Tab Page (NTP) was open when Chrome was backgrounded by the user. + </description> +</action> + <action name="MobileNTPRecentlyClosed"> <obsolete> Deprecated as of 01/2017. Replaced with
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index f17c789..dc95f3c 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -891,6 +891,17 @@ <int value="3" label="Account Corruption Detected"/> </enum> +<enum name="AccountReconcilorInconsistencyReason"> + <int value="0" label="Consistent"/> + <int value="1" label="Sync cookie missing"/> + <int value="2" label="Sync account auth error"/> + <int value="3" label="First web account token missing"/> + <int value="4" label="Secondary cookie missing"/> + <int value="5" label="Secondary token missing"/> + <int value="6" label="Cookie Token mismatch"/> + <int value="7" label="Sync cookie not first"/> +</enum> + <enum name="AccountRelation"> <int value="0" label="Empty cookie jar"/> <int value="1" label="No signed in, single signed out match"/> @@ -6127,6 +6138,9 @@ </enum> <enum name="BooleanIsUseRelinker"> + <obsolete> + Removed in 2019-07. + </obsolete> <int value="0" label="Didn't use relinker"/> <int value="1" label="Used relinker"/> </enum> @@ -17480,6 +17494,7 @@ <int value="573" label="SelectToSpeakEnabled"/> <int value="574" label="BrowserGuestModeEnforced"/> <int value="575" label="BuiltinCertificateVerifierEnabled"/> + <int value="576" label="CrostiniRootAccessAllowed"/> </enum> <enum name="EnterprisePolicyInvalidations"> @@ -29674,6 +29689,9 @@ </enum> <enum name="HttpServerPropertiesUpdatePrefsLocation"> + <obsolete> + Deprecated as of July 2019. + </obsolete> <int value="0" label="SUPPORTS_SPDY"/> <int value="1" label="HTTP_11_REQUIRED"/> <int value="2" label="SET_ALTERNATIVE_SERVICE"/> @@ -48564,6 +48582,110 @@ <int value="14" label="NACL_BROKER_PROCESS"/> </enum> +<enum name="Profile"> + <int value="0" label="Guest Profile"/> + <int value="1" label="Profile 1"/> + <int value="2" label="Profile 2"/> + <int value="3" label="Profile 3"/> + <int value="4" label="Profile 4"/> + <int value="5" label="Profile 5"/> + <int value="6" label="Profile 6"/> + <int value="7" label="Profile 7"/> + <int value="8" label="Profile 8"/> + <int value="9" label="Profile 9"/> + <int value="10" label="Profile 10"/> + <int value="11" label="Profile 11"/> + <int value="12" label="Profile 12"/> + <int value="13" label="Profile 13"/> + <int value="14" label="Profile 14"/> + <int value="15" label="Profile 15"/> + <int value="16" label="Profile 16"/> + <int value="17" label="Profile 17"/> + <int value="18" label="Profile 18"/> + <int value="19" label="Profile 19"/> + <int value="20" label="Profile 20"/> + <int value="21" label="Profile 21"/> + <int value="22" label="Profile 22"/> + <int value="23" label="Profile 23"/> + <int value="24" label="Profile 24"/> + <int value="25" label="Profile 25"/> + <int value="26" label="Profile 26"/> + <int value="27" label="Profile 27"/> + <int value="28" label="Profile 28"/> + <int value="29" label="Profile 29"/> + <int value="30" label="Profile 30"/> + <int value="31" label="Profile 31"/> + <int value="32" label="Profile 32"/> + <int value="33" label="Profile 33"/> + <int value="34" label="Profile 34"/> + <int value="35" label="Profile 35"/> + <int value="36" label="Profile 36"/> + <int value="37" label="Profile 37"/> + <int value="38" label="Profile 38"/> + <int value="39" label="Profile 39"/> + <int value="40" label="Profile 40"/> + <int value="41" label="Profile 41"/> + <int value="42" label="Profile 42"/> + <int value="43" label="Profile 43"/> + <int value="44" label="Profile 44"/> + <int value="45" label="Profile 45"/> + <int value="46" label="Profile 46"/> + <int value="47" label="Profile 47"/> + <int value="48" label="Profile 48"/> + <int value="49" label="Profile 49"/> + <int value="50" label="Profile 50"/> + <int value="51" label="Profile 51"/> + <int value="52" label="Profile 52"/> + <int value="53" label="Profile 53"/> + <int value="54" label="Profile 54"/> + <int value="55" label="Profile 55"/> + <int value="56" label="Profile 56"/> + <int value="57" label="Profile 57"/> + <int value="58" label="Profile 58"/> + <int value="59" label="Profile 59"/> + <int value="60" label="Profile 60"/> + <int value="61" label="Profile 61"/> + <int value="62" label="Profile 62"/> + <int value="63" label="Profile 63"/> + <int value="64" label="Profile 64"/> + <int value="65" label="Profile 65"/> + <int value="66" label="Profile 66"/> + <int value="67" label="Profile 67"/> + <int value="68" label="Profile 68"/> + <int value="69" label="Profile 69"/> + <int value="70" label="Profile 70"/> + <int value="71" label="Profile 71"/> + <int value="72" label="Profile 72"/> + <int value="73" label="Profile 73"/> + <int value="74" label="Profile 74"/> + <int value="75" label="Profile 75"/> + <int value="76" label="Profile 76"/> + <int value="77" label="Profile 77"/> + <int value="78" label="Profile 78"/> + <int value="79" label="Profile 79"/> + <int value="80" label="Profile 80"/> + <int value="81" label="Profile 81"/> + <int value="82" label="Profile 82"/> + <int value="83" label="Profile 83"/> + <int value="84" label="Profile 84"/> + <int value="85" label="Profile 85"/> + <int value="86" label="Profile 86"/> + <int value="87" label="Profile 87"/> + <int value="88" label="Profile 88"/> + <int value="89" label="Profile 89"/> + <int value="90" label="Profile 90"/> + <int value="91" label="Profile 91"/> + <int value="92" label="Profile 92"/> + <int value="93" label="Profile 93"/> + <int value="94" label="Profile 94"/> + <int value="95" label="Profile 95"/> + <int value="96" label="Profile 96"/> + <int value="97" label="Profile 97"/> + <int value="98" label="Profile 98"/> + <int value="99" label="Profile 99"/> + <int value="100" label="Profile 100"/> +</enum> + <enum name="ProfileAddNewUser"> <int value="0" label="Add new user from icon menu"/> <int value="1" label="Add new user from title bar menu"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 4bea61c4..17be21c 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -18877,6 +18877,9 @@ <histogram name="ChromiumAndroidLinker.RelinkerFallbackCount" enum="BooleanIsUseRelinker"> + <obsolete> + Deprecated 2019-07 in crbug.com/981599. + </obsolete> <owner>agrieve@chromium.org</owner> <owner>yfriedman@chromium.org</owner> <summary> @@ -50537,21 +50540,22 @@ </histogram> <histogram name="InputMethod.AutoCorrectLevel" enum="IMECorrectionLevel" - expires_after="M77"> - <owner>shuchen@chromium.org</owner> + expires_after="2020-04-01"> + <owner>essential-inputs-team@google.com</owner> <summary>The auto-correction level for suggestion engine.</summary> </histogram> -<histogram name="InputMethod.Category" enum="InputMethodCategory"> - <owner>shuchen@chromium.org</owner> +<histogram name="InputMethod.Category" enum="InputMethodCategory" + expires_after="2020-04-01"> + <owner>essential-inputs-team@google.com</owner> <summary> The breakdown of input method usage by input method category. Recorded when the system changes the current input method. </summary> </histogram> -<histogram name="InputMethod.Commit.Index" expires_after="M77"> - <owner>shuchen@chromium.org</owner> +<histogram name="InputMethod.Commit.Index" expires_after="2020-04-01"> + <owner>essential-inputs-team@google.com</owner> <summary> The suggestion index (1-based) of the suggestion list item which user chooses to commit. @@ -50651,7 +50655,7 @@ </histogram> <histogram name="InputMethod.Mojo.Extension.ActivateIMELatency" units="ms" - expires_after="2019-06-30"> + expires_after="2019-12-30"> <owner>googleo@chromium.org</owner> <owner>shuchen@chromium.org</owner> <summary> @@ -50662,16 +50666,15 @@ </summary> </histogram> -<histogram name="InputMethod.Mojo.Extension.Event" enum="IMEExtensionMojoEvent"> - <owner>googleo@chromium.org</owner> - <owner>shuchen@chromium.org</owner> +<histogram name="InputMethod.Mojo.Extension.Event" enum="IMEExtensionMojoEvent" + expires_after="2020-04-01"> + <owner>essential-inputs-team@google.com</owner> <summary>The events of Mojo service in the IME Extension.</summary> </histogram> <histogram name="InputMethod.Mojo.Extension.Rulebased.ProcessLatency" - units="ms" expires_after="2019-06-30"> - <owner>googleo@chromium.org</owner> - <owner>shuchen@chromium.org</owner> + units="ms" expires_after="2019-12-31"> + <owner>essential-inputs-team@google.com</owner> <summary> The time taken to process a rulebased request via the IME Mojo service inside the IME extension. @@ -50679,9 +50682,8 @@ </histogram> <histogram name="InputMethod.Mojo.Extension.ServiceInitLatency" units="ms" - expires_after="2019-06-30"> - <owner>googleo@chromium.org</owner> - <owner>shuchen@chromium.org</owner> + expires_after="2019-12-31"> + <owner>essential-inputs-team@google.com</owner> <summary> The time taken to initialize the IME Mojo service in the IME extension. It's from the IME extension starts loading a private Mojo bundle for making a @@ -50690,8 +50692,8 @@ </summary> </histogram> -<histogram name="InputMethod.PkCommit.Index" expires_after="M78"> - <owner>shuchen@chromium.org</owner> +<histogram name="InputMethod.PkCommit.Index" expires_after="2020-04-01"> + <owner>essential-inputs-team@google.com</owner> <summary> The suggestion index (1-based) of the suggestion list item which user chooses to commit for physical keyboard autocorrect. @@ -72336,6 +72338,9 @@ <histogram name="Net.HttpServerProperties.UpdatePrefs" enum="HttpServerPropertiesUpdatePrefsLocation" expires_after="2018-08-30"> + <obsolete> + Deprecated as of July 2019. + </obsolete> <owner>rch@chromium.org</owner> <summary> The location in http_server_properties_manager.cc where UpdatePrefs was @@ -91368,7 +91373,7 @@ </histogram> <histogram name="PageLoad.Clients.ThirdParty.Origins.Read" units="Count" - expires_after="2019-07-01"> + expires_after="2021-07-01"> <owner>jkarlin@chromium.org</owner> <summary> The number of third party origins on a page that read cookies either via @@ -91377,7 +91382,7 @@ </histogram> <histogram name="PageLoad.Clients.ThirdParty.Origins.Write" units="Count" - expires_after="2019-07-01"> + expires_after="2021-07-01"> <owner>jkarlin@chromium.org</owner> <summary> The number of third party origins on a page that changed cookies either via @@ -92254,6 +92259,9 @@ <histogram base="true" name="PageLoad.FrameCounts.AdFrames.PerFrame.SizeIntervention" enum="AdFrameSizeInterventionStatus" expires_after="2020-01-29"> + <obsolete> + Deprecated July 2019 in Issue 962616. + </obsolete> <owner>johnidel@chromium.org</owner> <owner>jkarlin@chromium.org</owner> <summary> @@ -92268,6 +92276,9 @@ <histogram base="true" name="PageLoad.FrameCounts.AdFrames.PerFrame.SizeIntervention.MediaStatus" enum="AdFrameMediaStatus" expires_after="2020-02-22"> + <obsolete> + Deprecated July 2019 in Issue 962616. + </obsolete> <owner>johnidel@chromium.org</owner> <owner>jkarlin@chromium.org</owner> <summary> @@ -105814,7 +105825,7 @@ <summary>Size of the bookmarks database.</summary> </histogram> -<histogram name="Profile.BrowserActive.PerProfile" units="Profile ID" +<histogram name="Profile.BrowserActive.PerProfile" enum="Profile" expires_after="2020-06-30"> <owner>msarda@chromium.org</owner> <owner>tangltom@chromium.org</owner> @@ -106311,6 +106322,28 @@ </summary> </histogram> +<histogram name="Profile.SessionDuration.PerProfile" enum="Profile" + expires_after="2020-06-30"> + <owner>msarda@chromium.org</owner> + <owner>tangltom@chromium.org</owner> + <summary> + Browsing session duration in minutes, recorded per profile. Each profile on + a client is assigned a unique bucket. + + Recorded when the user switches profiles, after some time of + inactivity(usually 5 minutes) or at browser shutdown. + + Example: A user has 2 profiles. They open a browser window of profile 1 and + interact with the browser for 8 minutes. Then they open a browser window of + profile 2 and interact with the browser for 3 minutes. Then they do nothing + (=stay inactive) for while. The recorded values will be: (bucket 1: 8), + (bucket 2: 3). + + Note: The guest profile has bucket 0. Regular profiles start at bucket 1. + Incognito profiles count towards the original profile. + </summary> +</histogram> + <histogram name="Profile.SupervisedProfileCreateError" enum="GoogleServiceAuthError" expires_after="2019-02-12"> <obsolete> @@ -124273,6 +124306,17 @@ </summary> </histogram> +<histogram name="Sharing.ClickToCallDialIntent" enum="BooleanEmpty" + expires_after="2020-02-02"> + <owner>mvanouwerkerk@chromium.org</owner> + <owner>knollr@chromium.org</owner> + <summary> + Logged when a user taps a Click to Call notification and a dial intent is + fired to open the dialer. Distinguishes between empty string (no phone + number) and not empty. Android only. + </summary> +</histogram> + <histogram name="Sharing.ClickToCallSelectedAppIndex" units="index" expires_after="2020-02-02"> <!-- Name completed by histogram_suffixes name="SharingClickToCallUi" --> @@ -124317,6 +124361,15 @@ </summary> </histogram> +<histogram name="Sharing.MessageAckTime" units="ms" expires_after="2020-02-02"> + <owner>mvanouwerkerk@chromium.org</owner> + <owner>knollr@chromium.org</owner> + <summary> + The time from sending a FCM message from the Sharing service until an ack + message is received for it. + </summary> +</histogram> + <histogram name="Sharing.MessageReceivedType" enum="SharingMessageType" expires_after="2020-02-02"> <owner>mvanouwerkerk@chromium.org</owner> @@ -124908,6 +124961,16 @@ </summary> </histogram> +<histogram base="true" name="Signin.DiceMigrationNotReady.Reason" + enum="AccountReconcilorInconsistencyReason" expires_after="2020-01-12"> + <owner>msalama@chromium.org</owner> + <owner>msarda@chromium.org</owner> + <summary> + Tracks the reason of why DICE migration is not ready. It is computed by dice + reconcilor delegate on every reconciliation cycle. + </summary> +</histogram> + <histogram name="Signin.DiceMigrationStatus" enum="SigninDiceMigrationStatus"> <owner>droger@chromium.org</owner> <summary> @@ -153338,6 +153401,14 @@ <affected-histogram name="AccountManager.Migrations.StepResult"/> </histogram_suffixes> +<histogram_suffixes name="AccountReconcilorExecution" separator="."> + <owner>msalama@chromium.org</owner> + <owner>msarda@chromium.org</owner> + <suffix name="FirstExecution" label="The first Reconcilor execution"/> + <suffix name="NotFirstExecution" label="Not the first Reconcilor execution"/> + <affected-histogram name="Signin.DiceMigrationNotReady.Reason"/> +</histogram_suffixes> + <histogram_suffixes name="ActiveNetworkState" separator="_"> <suffix name="Offline" label="network manager thinks that the active network is offline"/>
diff --git a/tools/perf/core/find_dependencies.py b/tools/perf/core/find_dependencies.py index 0e6746d..8724370 100644 --- a/tools/perf/core/find_dependencies.py +++ b/tools/perf/core/find_dependencies.py
@@ -5,18 +5,14 @@ import fnmatch import imp import logging -import optparse import os import sys import zipfile -from telemetry import benchmark from telemetry.internal.util import command_line from telemetry.internal.util import path from telemetry.internal.util import path_set -from py_utils import discover - try: from modulegraph import modulegraph # pylint: disable=import-error except ImportError as err: @@ -93,35 +89,6 @@ sys.path = sys_path -def FindPageSetDependencies(base_dir): - logging.info('Finding page sets in %s', base_dir) - - # Add base_dir to path so our imports relative to base_dir will work. - sys.path.append(base_dir) - tests = discover.DiscoverClasses(base_dir, base_dir, benchmark.Benchmark, - index_by_class_name=True) - - for test_class in tests.itervalues(): - test_obj = test_class() - - # Ensure the test's default options are set if needed. - parser = optparse.OptionParser() - test_obj.AddCommandLineArgs(parser, None) - options = optparse.Values() - for k, v in parser.get_default_values().__dict__.iteritems(): - options.ensure_value(k, v) - - # Page set paths are relative to their runner script, not relative to us. - path.GetBaseDir = lambda: base_dir - # TODO: Loading the page set will automatically download its Cloud Storage - # deps. This is really expensive, and we don't want to do this by default. - story_set = test_obj.CreateStorySet(options) - - # Add all of its serving_dirs as dependencies. - for serving_dir in story_set.serving_dirs: - yield serving_dir - - def FindExcludedFiles(files, options): # Define some filters for files. def IsHidden(path_string): @@ -182,8 +149,6 @@ dependencies.add(base_dir) dependencies |= FindBootstrapDependencies(base_dir) dependencies |= FindPythonDependencies(target_path) - if options.include_page_set_data: - dependencies |= FindPageSetDependencies(base_dir) # Remove excluded files. dependencies -= FindExcludedFiles(set(dependencies), options) @@ -231,10 +196,6 @@ help='Increase verbosity level (repeat as needed).') parser.add_option( - '-p', '--include-page-set-data', action='store_true', default=False, - help='Scan tests for page set data and include them.') - - parser.add_option( '-e', '--exclude', action='append', default=[], help='Exclude paths matching EXCLUDE. Can be used multiple times.')
diff --git a/tools/perf/scripts_smoke_unittest.py b/tools/perf/scripts_smoke_unittest.py index 89607a9..d08bff42 100644 --- a/tools/perf/scripts_smoke_unittest.py +++ b/tools/perf/scripts_smoke_unittest.py
@@ -33,19 +33,23 @@ return_code = proc.returncode return return_code, stdout + # TODO(crbug.com/985712): Re-enable after new command line interface lands. + @decorators.Disabled('all') def testRunBenchmarkHelp(self): - return_code, stdout = self.RunPerfScript('run_benchmark help') + return_code, stdout = self.RunPerfScript('run_benchmark --help') self.assertEquals(return_code, 0, stdout) - self.assertIn('Available commands are', stdout) + self.assertIn('usage: run_benchmark', stdout) def testRunBenchmarkRunListsOutBenchmarks(self): return_code, stdout = self.RunPerfScript('run_benchmark run') self.assertIn('Pass --browser to list benchmarks', stdout) self.assertNotEquals(return_code, 0) + # TODO(crbug.com/985712): Re-enable after new command line interface lands. + @decorators.Disabled('all') def testRunBenchmarkRunNonExistingBenchmark(self): return_code, stdout = self.RunPerfScript('run_benchmark foo') - self.assertIn('No benchmark named "foo"', stdout) + self.assertIn('no such benchmark: foo', stdout) self.assertNotEquals(return_code, 0) def testRunRecordWprHelp(self):
diff --git a/ui/file_manager/file_manager/foreground/css/file_manager.css b/ui/file_manager/file_manager/foreground/css/file_manager.css index 4d80fe6f..d17d720 100644 --- a/ui/file_manager/file_manager/foreground/css/file_manager.css +++ b/ui/file_manager/file_manager/foreground/css/file_manager.css
@@ -166,13 +166,14 @@ text-overflow: ellipsis; } -.tree-item > .ejectable { +#directory-tree .tree-item > .tree-row.ejectable { position: inherit; } -.ejectable > span.label { +#directory-tree .tree-row.ejectable > .label { left: 48px; position: absolute; + right: 48px; width: calc(100% - 48px - 40px - 3px); } @@ -227,8 +228,9 @@ cursor: pointer; flex: none; height: 40px; + left: calc(100% - 40px - 3px); position: absolute; - right: 3px; + right: calc(100% - 40px - 3px); width: 40px; z-index: 1; /* Make sure the icon is on upper layer than paper-ripple. */ }
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index fd72f31..b1855bfe 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -307,7 +307,6 @@ "gl_wgl_api_implementation.h", "swap_chain_presenter.cc", "swap_chain_presenter.h", - "vsync_observer.h", "vsync_provider_win.cc", "vsync_provider_win.h", "vsync_thread_win.cc",
diff --git a/ui/gl/direct_composition_child_surface_win.cc b/ui/gl/direct_composition_child_surface_win.cc index 06721e59..15cfd1fa 100644 --- a/ui/gl/direct_composition_child_surface_win.cc +++ b/ui/gl/direct_composition_child_surface_win.cc
@@ -107,9 +107,7 @@ return base::FeatureList::IsEnabled(features::kSwapChainFrameStatistics); } -DirectCompositionChildSurfaceWin::DirectCompositionChildSurfaceWin( - gfx::VSyncProvider* vsync_provider) - : vsync_provider_(vsync_provider) {} +DirectCompositionChildSurfaceWin::DirectCompositionChildSurfaceWin() {} DirectCompositionChildSurfaceWin::~DirectCompositionChildSurfaceWin() { Destroy(); @@ -260,8 +258,6 @@ bool succeeded = ReleaseDrawTexture(false /* will_discard */); if (UseSwapChainFrameStatistics()) { - vsync_provider_->GetVSyncParametersIfAvailable(&last_vsync_time_, - &last_vsync_interval_); CheckPendingFrames(); // Enqueue callback after retiring previous callbacks so that it's called // after SwapBuffers() returns. @@ -507,6 +503,17 @@ return true; } +void DirectCompositionChildSurfaceWin::UpdateVSyncParameters( + base::TimeTicks vsync_time, + base::TimeDelta vsync_interval) { + last_vsync_time_ = vsync_time; + last_vsync_interval_ = vsync_interval; +} + +bool DirectCompositionChildSurfaceWin::HasPendingFrames() const { + return !pending_frames_.empty(); +} + void DirectCompositionChildSurfaceWin::CheckPendingFrames() { DCHECK(UseSwapChainFrameStatistics());
diff --git a/ui/gl/direct_composition_child_surface_win.h b/ui/gl/direct_composition_child_surface_win.h index 3f84f9fa02..34a847f 100644 --- a/ui/gl/direct_composition_child_surface_win.h +++ b/ui/gl/direct_composition_child_surface_win.h
@@ -12,15 +12,11 @@ #include "ui/gl/gl_surface_egl.h" -namespace gfx { -class VSyncProvider; -} // namespace gfx - namespace gl { class DirectCompositionChildSurfaceWin : public GLSurfaceEGL { public: - explicit DirectCompositionChildSurfaceWin(gfx::VSyncProvider* vsync_provider); + DirectCompositionChildSurfaceWin(); static bool UseSwapChainFrameStatistics(); @@ -44,6 +40,11 @@ bool has_alpha) override; bool SetEnableDCLayers(bool enable) override; + void UpdateVSyncParameters(base::TimeTicks vsync_time, + base::TimeDelta vsync_interval); + bool HasPendingFrames() const; + void CheckPendingFrames(); + const Microsoft::WRL::ComPtr<IDCompositionSurface>& dcomp_surface() const { return dcomp_surface_; } @@ -75,7 +76,6 @@ // Presentation callback enqueued in SwapBuffers(). PresentationCallback callback; }; - void CheckPendingFrames(); void EnqueuePendingFrame(PresentationCallback callback); void ClearPendingFrames(); @@ -109,7 +109,6 @@ // be called on the device. uint64_t dcomp_surface_serial_ = 0; - gfx::VSyncProvider* const vsync_provider_; base::TimeTicks last_vsync_time_; base::TimeDelta last_vsync_interval_ = base::TimeDelta::FromSecondsD(1. / 60);
diff --git a/ui/gl/direct_composition_surface_win.cc b/ui/gl/direct_composition_surface_win.cc index 22587ec..0522acc8 100644 --- a/ui/gl/direct_composition_surface_win.cc +++ b/ui/gl/direct_composition_surface_win.cc
@@ -172,14 +172,15 @@ : GLSurfaceEGL(), child_window_(parent_window), task_runner_(base::ThreadTaskRunnerHandle::Get()), - root_surface_(new DirectCompositionChildSurfaceWin(vsync_provider.get())), + root_surface_(new DirectCompositionChildSurfaceWin()), layer_tree_(std::make_unique<DCLayerTree>( settings.disable_nv12_dynamic_textures, settings.disable_larger_than_screen_overlays)), - presentation_helper_( - std::make_unique<GLSurfacePresentationHelper>(vsync_provider.get())), vsync_provider_(std::move(vsync_provider)), - vsync_callback_(std::move(vsync_callback)) {} + vsync_callback_(std::move(vsync_callback)), + presentation_helper_( + std::make_unique<GLSurfacePresentationHelper>(vsync_provider_.get())), + weak_ptr_factory_(this) {} DirectCompositionSurfaceWin::~DirectCompositionSurfaceWin() { Destroy(); @@ -395,17 +396,27 @@ if (!root_surface_->Initialize(GLSurfaceFormat())) return false; - if (SupportsGpuVSync() && vsync_callback_) - vsync_thread_ = VSyncThreadWin::GetInstance(); + if (root_surface_->UseSwapChainFrameStatistics()) { + // Save weak ptr on main thread before any use on vsync thread. + main_thread_vsync_callback_ = base::BindRepeating( + &DirectCompositionSurfaceWin::HandleVSyncOnMainThread, + weak_ptr_factory_.GetWeakPtr()); + } + + if ((SupportsGpuVSync() && vsync_callback_) || main_thread_vsync_callback_) { + vsync_thread_ = std::make_unique<VSyncThreadWin>( + window_, d3d11_device_, + base::BindRepeating( + &DirectCompositionSurfaceWin::HandleVSyncOnVSyncThread, + base::Unretained(this))); + } return true; } void DirectCompositionSurfaceWin::Destroy() { - if (vsync_thread_) { - vsync_thread_->RemoveObserver(this); - vsync_thread_ = nullptr; - } + // Destroy vsync thread because joining it could issue callbacks. + vsync_thread_ = nullptr; // Destroy presentation helper first because its dtor calls GetHandle. presentation_helper_ = nullptr; root_surface_->Destroy(); @@ -448,11 +459,14 @@ callback.Reset(); } - gfx::SwapResult swap_result; - if (root_surface_->SwapBuffers(std::move(callback)) == - gfx::SwapResult::SWAP_ACK && + gfx::SwapResult swap_result = root_surface_->SwapBuffers(std::move(callback)); + + if (swap_result == gfx::SwapResult::SWAP_ACK && layer_tree_->CommitAndClearPendingOverlays(root_surface_.get())) { - swap_result = gfx::SwapResult::SWAP_ACK; + if (vsync_thread_) { + vsync_thread_->SetEnabled(root_surface_->HasPendingFrames() || + vsync_callback_enabled_); + } } else { swap_result = gfx::SwapResult::SWAP_FAILED; } @@ -533,17 +547,34 @@ void DirectCompositionSurfaceWin::SetGpuVSyncEnabled(bool enabled) { DCHECK(vsync_thread_); - if (enabled) { - vsync_thread_->AddObserver(this); - } else { - vsync_thread_->RemoveObserver(this); + if (vsync_callback_enabled_ == enabled) + return; + vsync_callback_enabled_ = enabled; + vsync_thread_->SetEnabled(root_surface_->HasPendingFrames() || + vsync_callback_enabled_); +} + +void DirectCompositionSurfaceWin::HandleVSyncOnVSyncThread( + base::TimeTicks vsync_time, + base::TimeDelta vsync_interval) { + if (vsync_callback_) + vsync_callback_.Run(vsync_time, vsync_interval); + + if (main_thread_vsync_callback_) { + task_runner_->PostTask( + FROM_HERE, base::BindOnce(main_thread_vsync_callback_, vsync_time, + vsync_interval)); } } -void DirectCompositionSurfaceWin::OnVSync(base::TimeTicks vsync_time, - base::TimeDelta interval) { - DCHECK(vsync_callback_); - vsync_callback_.Run(vsync_time, interval); +void DirectCompositionSurfaceWin::HandleVSyncOnMainThread( + base::TimeTicks vsync_time, + base::TimeDelta vsync_interval) { + // Check pending frames in root surface in case client stops issuing swaps. + root_surface_->UpdateVSyncParameters(vsync_time, vsync_interval); + root_surface_->CheckPendingFrames(); + vsync_thread_->SetEnabled(root_surface_->HasPendingFrames() || + vsync_callback_enabled_); } scoped_refptr<base::TaskRunner>
diff --git a/ui/gl/direct_composition_surface_win.h b/ui/gl/direct_composition_surface_win.h index 62c07e1..1c65a78 100644 --- a/ui/gl/direct_composition_surface_win.h +++ b/ui/gl/direct_composition_surface_win.h
@@ -16,7 +16,6 @@ #include "ui/gl/child_window_win.h" #include "ui/gl/gl_export.h" #include "ui/gl/gl_surface_egl.h" -#include "ui/gl/vsync_observer.h" namespace gl { class DCLayerTree; @@ -24,8 +23,7 @@ class GLSurfacePresentationHelper; class VSyncThreadWin; -class GL_EXPORT DirectCompositionSurfaceWin : public GLSurfaceEGL, - public VSyncObserver { +class GL_EXPORT DirectCompositionSurfaceWin : public GLSurfaceEGL { public: using VSyncCallback = base::RepeatingCallback<void(base::TimeTicks, base::TimeDelta)>; @@ -107,6 +105,7 @@ gfx::Vector2d GetDrawOffset() const override; bool SupportsGpuVSync() const override; void SetGpuVSyncEnabled(bool enabled) override; + // This schedules an overlay plane to be displayed on the next SwapBuffers // or PostSubBuffer call. Overlay planes must be scheduled before every swap // to remain in the layer tree. This surface's backbuffer doesn't have to be @@ -114,9 +113,6 @@ // tree at z-order 0. bool ScheduleDCLayer(const ui::DCRendererLayerParams& params) override; - // VSyncObserver implementation. - void OnVSync(base::TimeTicks vsync_time, base::TimeDelta interval) override; - HWND window() const { return window_; } scoped_refptr<base::TaskRunner> GetWindowTaskRunnerForTesting(); @@ -131,21 +127,33 @@ ~DirectCompositionSurfaceWin() override; private: + void HandleVSyncOnVSyncThread(base::TimeTicks vsync_time, + base::TimeDelta vsync_interval); + + void HandleVSyncOnMainThread(base::TimeTicks vsync_time, + base::TimeDelta vsync_interval); + HWND window_ = nullptr; ChildWindowWin child_window_; scoped_refptr<base::SequencedTaskRunner> task_runner_; scoped_refptr<DirectCompositionChildSurfaceWin> root_surface_; std::unique_ptr<DCLayerTree> layer_tree_; - std::unique_ptr<GLSurfacePresentationHelper> presentation_helper_; + std::unique_ptr<VSyncThreadWin> vsync_thread_; std::unique_ptr<gfx::VSyncProvider> vsync_provider_; + const VSyncCallback vsync_callback_; - VSyncThreadWin* vsync_thread_; + bool vsync_callback_enabled_ = false; + + std::unique_ptr<GLSurfacePresentationHelper> presentation_helper_; Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_; Microsoft::WRL::ComPtr<IDCompositionDevice2> dcomp_device_; + VSyncCallback main_thread_vsync_callback_; + base::WeakPtrFactory<DirectCompositionSurfaceWin> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(DirectCompositionSurfaceWin); };
diff --git a/ui/gl/init/gl_factory_ozone.cc b/ui/gl/init/gl_factory_ozone.cc index faba8ea6..2adf488 100644 --- a/ui/gl/init/gl_factory_ozone.cc +++ b/ui/gl/init/gl_factory_ozone.cc
@@ -50,6 +50,8 @@ stub_context->SetUseStubApi(true); return stub_context; } + case kGLImplementationDisabled: + return nullptr; default: NOTREACHED() << "Expected Mock or Stub, actual:" << GetGLImplementation(); }
diff --git a/ui/gl/vsync_observer.h b/ui/gl/vsync_observer.h deleted file mode 100644 index 5d0fe964..0000000 --- a/ui/gl/vsync_observer.h +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_GL_VSYNC_OBSERVER_H_ -#define UI_GL_VSYNC_OBSERVER_H_ - -namespace gl { -class GL_EXPORT VSyncObserver { - public: - // Called on vsync thread. - virtual void OnVSync(base::TimeTicks vsync_time, - base::TimeDelta interval) = 0; - - protected: - virtual ~VSyncObserver() {} -}; -} // namespace gl - -#endif // UI_GL_VSYNC_OBSERVER_H_
diff --git a/ui/gl/vsync_thread_win.cc b/ui/gl/vsync_thread_win.cc index 9502606..a9e341573 100644 --- a/ui/gl/vsync_thread_win.cc +++ b/ui/gl/vsync_thread_win.cc
@@ -5,10 +5,6 @@ #include "ui/gl/vsync_thread_win.h" #include "base/bind.h" -#include "base/memory/singleton.h" -#include "base/stl_util.h" -#include "ui/gl/gl_angle_util_win.h" -#include "ui/gl/vsync_observer.h" namespace gl { namespace { @@ -47,51 +43,45 @@ } } // namespace -// static -VSyncThreadWin* VSyncThreadWin::GetInstance() { - return base::Singleton<VSyncThreadWin>::get(); -} - -VSyncThreadWin::VSyncThreadWin() +VSyncThreadWin::VSyncThreadWin( + HWND window, + Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device, + VSyncCallback callback) : vsync_thread_("GpuVSyncThread"), - d3d11_device_(QueryD3D11DeviceObjectFromANGLE()) { - DCHECK(d3d11_device_); + window_(window), + d3d11_device_(std::move(d3d11_device)), + callback_(std::move(callback)) { + DCHECK(window_); + DCHECK(callback_); base::Thread::Options options; - options.priority = base::ThreadPriority::DISPLAY; + // Inherit priority from GPU main thread which depends on finch flags. + options.priority = base::PlatformThread::GetCurrentThreadPriority(); vsync_thread_.StartWithOptions(std::move(options)); } VSyncThreadWin::~VSyncThreadWin() { - { - base::AutoLock auto_lock(lock_); - observers_.clear(); - } + SetEnabled(false); vsync_thread_.Stop(); } -void VSyncThreadWin::AddObserver(VSyncObserver* obs) { +void VSyncThreadWin::SetEnabled(bool enabled) { base::AutoLock auto_lock(lock_); - observers_.insert(obs); - if (is_idle_) { - is_idle_ = false; + if (enabled_ == enabled) + return; + enabled_ = enabled; + if (enabled_ && !started_) { + started_ = true; vsync_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce(&VSyncThreadWin::WaitForVSync, base::Unretained(this))); } } -void VSyncThreadWin::RemoveObserver(VSyncObserver* obs) { - base::AutoLock auto_lock(lock_); - observers_.erase(obs); -} - void VSyncThreadWin::WaitForVSync() { - // From Raymond Chen's blog "How do I get a handle to the primary monitor?" - // https://devblogs.microsoft.com/oldnewthing/20141106-00/?p=43683 - HMONITOR monitor = MonitorFromWindow(nullptr, MONITOR_DEFAULTTOPRIMARY); - if (primary_monitor_ != monitor) { - primary_monitor_ = monitor; - primary_output_ = DXGIOutputFromMonitor(monitor, d3d11_device_); + HMONITOR monitor = MonitorFromWindow(window_, MONITOR_DEFAULTTONEAREST); + if (window_monitor_ != monitor) { + window_monitor_ = monitor; + window_output_ = DXGIOutputFromMonitor(monitor, d3d11_device_); } base::TimeDelta interval = base::TimeDelta::FromSecondsD(1.0 / 60); @@ -112,13 +102,13 @@ base::TimeTicks wait_for_vblank_start_time = base::TimeTicks::Now(); bool wait_for_vblank_succeeded = - primary_output_ && SUCCEEDED(primary_output_->WaitForVBlank()); + window_output_ && SUCCEEDED(window_output_->WaitForVBlank()); // WaitForVBlank returns very early instead of waiting until vblank when the // monitor goes to sleep. We use 1ms as a threshold for the duration of // WaitForVBlank and fallback to Sleep() if it returns before that. This // could happen during normal operation for the first call after the vsync - // thread becomes non-idle, but it shouldn't happen often. + // callback is enabled, but it shouldn't happen often. const auto kVBlankIntervalThreshold = base::TimeDelta::FromMilliseconds(1); base::TimeDelta wait_for_vblank_elapsed_time = base::TimeTicks::Now() - wait_for_vblank_start_time; @@ -129,15 +119,17 @@ } base::AutoLock auto_lock(lock_); - if (!observers_.empty()) { + DCHECK(started_); + if (enabled_) { vsync_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce(&VSyncThreadWin::WaitForVSync, base::Unretained(this))); - base::TimeTicks vsync_time = base::TimeTicks::Now(); - for (auto* obs : observers_) - obs->OnVSync(vsync_time, interval); + // Release lock before running callback to guard against any reentracny + // deadlock. + base::AutoUnlock auto_unlock(lock_); + callback_.Run(base::TimeTicks::Now(), interval); } else { - is_idle_ = true; + started_ = false; } }
diff --git a/ui/gl/vsync_thread_win.h b/ui/gl/vsync_thread_win.h index d148353..f540f75 100644 --- a/ui/gl/vsync_thread_win.h +++ b/ui/gl/vsync_thread_win.h
@@ -9,53 +9,48 @@ #include <windows.h> #include <wrl/client.h> -#include "base/containers/flat_set.h" #include "base/threading/thread.h" #include "ui/gl/gl_export.h" -namespace base { -template <typename T> -struct DefaultSingletonTraits; -} // namespace base - namespace gl { -class VSyncObserver; -// Helper singleton that wraps a thread for calling IDXGIOutput::WaitForVBlank() -// for the primary monitor, and notifies observers on the same thread. Observers -// can be added or removed on the main thread, and the vsync thread goes to -// sleep if there are no observers. This is used by DirectCompositionSurfaceWin -// to plumb vsync signal back to the display compositor's BeginFrameSource. + +// Helper class that manages a thread for calling IDXGIOutput::WaitForVBlank() +// for the output corresponding to the given |window|, and runs |callback| on +// the same thread. The callback can be enabled or disabled via SetEnabled(). +// This is used by DirectCompositionSurfaceWin to plumb vsync signal back to the +// display compositor's BeginFrameSource. class GL_EXPORT VSyncThreadWin { public: - static VSyncThreadWin* GetInstance(); - - // These methods are not rentrancy safe, and shouldn't be called inside - // VSyncObserver::OnVSync. It's safe to assume that these can be called only - // from the main thread. - void AddObserver(VSyncObserver* obs); - void RemoveObserver(VSyncObserver* obs); - - private: - friend struct base::DefaultSingletonTraits<VSyncThreadWin>; - - VSyncThreadWin(); + using VSyncCallback = + base::RepeatingCallback<void(base::TimeTicks, base::TimeDelta)>; + VSyncThreadWin(HWND window, + Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device, + VSyncCallback callback); ~VSyncThreadWin(); + void SetEnabled(bool enabled); + + private: void WaitForVSync(); base::Thread vsync_thread_; // Used on vsync thread only after initialization. + const HWND window_; const Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_; - HMONITOR primary_monitor_ = nullptr; - Microsoft::WRL::ComPtr<IDXGIOutput> primary_output_; + const VSyncCallback callback_; + + // Used on vsync thread exclusively. + HMONITOR window_monitor_ = nullptr; + Microsoft::WRL::ComPtr<IDXGIOutput> window_output_; base::Lock lock_; - bool GUARDED_BY(lock_) is_idle_ = true; - base::flat_set<VSyncObserver*> GUARDED_BY(lock_) observers_; + bool GUARDED_BY(lock_) enabled_ = false; + bool GUARDED_BY(lock_) started_ = false; DISALLOW_COPY_AND_ASSIGN(VSyncThreadWin); }; + } // namespace gl #endif // UI_GL_VSYNC_THREAD_WIN_H_