diff --git a/DEPS b/DEPS index fcd7ddeb..42e9143 100644 --- a/DEPS +++ b/DEPS
@@ -221,7 +221,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': 'adc9033be9174ca30e65ddd3f8986ddad60de60f', + 'angle_revision': '18c9aa0dc36e879386290bf0cf47f6b6f5674733', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -280,7 +280,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': '1ae270e66814fe4d968ec699f21b75205e2d7a83', + 'catapult_revision': '5185110bf9f5852831a64eb149ee4d1a1ff7db71', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -328,7 +328,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': 'c63ac30826671e49173d18afdb9ae4b31bdaa6be', + 'dawn_revision': 'd98b3076f580098c27421f5643d20a72a50fcda3', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -573,7 +573,7 @@ }, 'src/ios/third_party/material_components_ios/src': { - 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + 'f7a90670fcf2f080b669a86f501273bba0178539', + 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + '85cdcadbec83ea2514f871cb1ed2a44b8368ad7a', 'condition': 'checkout_ios', }, @@ -966,7 +966,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '75229247494ecf31997b68bf143264e1537f92e0', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'a84eaf515f9dd4f199425e0cfc46f3e1b2b0984a', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1338,7 +1338,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '9d7fd31b50330f79a861d00bdb3f9d429300300f', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'b1a6a6e1ae3696a8330c33258f10be4e6c552c38', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1613,7 +1613,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@48aeba5a7e1ef4b213c51d909971831d3278d23a', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@ea2aa6c9a4e4c91d2cd50101ed9f69455bb031c7', 'condition': 'checkout_src_internal', },
diff --git a/ash/wm/full_restore/full_restore_controller.cc b/ash/wm/full_restore/full_restore_controller.cc index 141380b7..3452583a 100644 --- a/ash/wm/full_restore/full_restore_controller.cc +++ b/ash/wm/full_restore/full_restore_controller.cc
@@ -6,6 +6,7 @@ #include <cstdint> +#include "ash/app_list/app_list_controller_impl.h" #include "ash/public/cpp/app_types.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" @@ -243,6 +244,30 @@ window->ClearProperty(full_restore::kActivationIndexKey); } +void FullRestoreController::OnWindowVisibilityChanged(aura::Window* window, + bool visible) { + if (!windows_observation_.IsObservingSource(window)) + return; + + // Early return if `window` isn't visible, we're not in tablet mode, or the + // app list is null. + aura::Window* app_list_window = + Shell::Get()->app_list_controller()->GetWindow(); + if (!visible || !Shell::Get()->tablet_mode_controller()->InTabletMode() || + !app_list_window) { + return; + } + + // Because windows are shown inactive, they don't take focus/activation. This + // can lead to situations in tablet mode where the app list is active and + // visibly below restored windows. This causes the hotseat widget to not be + // hidden, so deactivate the app list. See crbug.com/1202923. + auto* app_list_widget = + views::Widget::GetWidgetForNativeWindow(app_list_window); + if (app_list_widget->IsActive() && WindowState::Get(window)->IsMaximized()) + app_list_widget->Deactivate(); +} + void FullRestoreController::OnWindowDestroying(aura::Window* window) { DCHECK(windows_observation_.IsObservingSource(window)); windows_observation_.RemoveObservation(window);
diff --git a/ash/wm/full_restore/full_restore_controller.h b/ash/wm/full_restore/full_restore_controller.h index 37df417..eea834e 100644 --- a/ash/wm/full_restore/full_restore_controller.h +++ b/ash/wm/full_restore/full_restore_controller.h
@@ -73,6 +73,7 @@ // aura::WindowObserver: void OnWindowStackingChanged(aura::Window* window) override; + void OnWindowVisibilityChanged(aura::Window* window, bool visible) override; void OnWindowDestroying(aura::Window* window) override; bool is_restoring_snap_state() const { return is_restoring_snap_state_; }
diff --git a/ash/wm/full_restore/full_restore_controller_unittest.cc b/ash/wm/full_restore/full_restore_controller_unittest.cc index c60ca69..227839b 100644 --- a/ash/wm/full_restore/full_restore_controller_unittest.cc +++ b/ash/wm/full_restore/full_restore_controller_unittest.cc
@@ -7,6 +7,8 @@ #include "ash/accelerators/accelerator_controller_impl.h" #include "ash/public/cpp/ash_features.h" #include "ash/screen_util.h" +#include "ash/shelf/hotseat_widget.h" +#include "ash/shelf/shelf.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/test/test_widget_builder.h" @@ -859,4 +861,23 @@ EXPECT_EQ(expected_bounds, window->GetBoundsInScreen()); } +// Tests that when windows are restored in tablet mode the hotseat is hidden. +// See crbug.com/1202923. +TEST_F(FullRestoreControllerTest, HotseatIsHiddenOnRestoration) { + // Enter tablet mode and check that the hotseat is not hidden. + TabletModeControllerTestApi().EnterTabletMode(); + HotseatWidget* hotseat_widget = GetPrimaryShelf()->hotseat_widget(); + EXPECT_EQ(HotseatState::kShownHomeLauncher, hotseat_widget->state()); + + // Add an entry and restore it. The widget should be visible and the hotseat + // should now be hidden. + AddEntryToFakeFile(/*restore_window_id=*/1, gfx::Rect(200, 200), + chromeos::WindowStateType::kNormal); + views::Widget* restored_widget = + CreateTestFullRestoredWidgetFromRestoreId(/*restore_window_id=*/1); + EXPECT_TRUE(restored_widget->IsVisible()); + EXPECT_EQ(HotseatState::kHidden, hotseat_widget->state()); + // TODO(chinsenj|sammiequon): Ensure that the app list is deactivated here. +} + } // namespace ash
diff --git a/base/trace_event/log_message.h b/base/trace_event/log_message.h index 30da1e1..e0cfade7 100644 --- a/base/trace_event/log_message.h +++ b/base/trace_event/log_message.h
@@ -7,17 +7,13 @@ #include <stddef.h> -#include <memory> #include <string> -#include <vector> #include "base/strings/string_piece.h" #include "base/trace_event/trace_event_impl.h" namespace base { -class Value; - namespace trace_event { class BASE_EXPORT LogMessage : public ConvertableToTraceFormat {
diff --git a/base/trace_event/trace_event.h b/base/trace_event/trace_event.h index 9e3f747..0d6b3c9c 100644 --- a/base/trace_event/trace_event.h +++ b/base/trace_event/trace_event.h
@@ -13,10 +13,10 @@ #include <stdint.h> #include <memory> -#include <string> #include <utility> #include "base/atomicops.h" +#include "base/base_export.h" #include "base/debug/debugging_buildflags.h" #include "base/time/time.h" #include "base/time/time_override.h" @@ -452,32 +452,33 @@ unsigned int id_flags_ = TRACE_EVENT_FLAG_HAS_ID; }; - TraceID(const void* raw_id) : raw_id_(static_cast<unsigned long long>( - reinterpret_cast<uintptr_t>(raw_id))) { + explicit TraceID(const void* raw_id) + : raw_id_(static_cast<unsigned long long>( + reinterpret_cast<uintptr_t>(raw_id))) { id_flags_ = TRACE_EVENT_FLAG_HAS_LOCAL_ID; } - TraceID(unsigned long long raw_id) : raw_id_(raw_id) {} - TraceID(unsigned long raw_id) : raw_id_(raw_id) {} - TraceID(unsigned int raw_id) : raw_id_(raw_id) {} - TraceID(unsigned short raw_id) : raw_id_(raw_id) {} - TraceID(unsigned char raw_id) : raw_id_(raw_id) {} - TraceID(long long raw_id) + explicit TraceID(unsigned long long raw_id) : raw_id_(raw_id) {} + explicit TraceID(unsigned long raw_id) : raw_id_(raw_id) {} + explicit TraceID(unsigned int raw_id) : raw_id_(raw_id) {} + explicit TraceID(unsigned short raw_id) : raw_id_(raw_id) {} + explicit TraceID(unsigned char raw_id) : raw_id_(raw_id) {} + explicit TraceID(long long raw_id) : raw_id_(static_cast<unsigned long long>(raw_id)) {} - TraceID(long raw_id) + explicit TraceID(long raw_id) : raw_id_(static_cast<unsigned long long>(raw_id)) {} - TraceID(int raw_id) + explicit TraceID(int raw_id) : raw_id_(static_cast<unsigned long long>(raw_id)) {} - TraceID(short raw_id) + explicit TraceID(short raw_id) : raw_id_(static_cast<unsigned long long>(raw_id)) {} - TraceID(signed char raw_id) + explicit TraceID(signed char raw_id) : raw_id_(static_cast<unsigned long long>(raw_id)) {} - TraceID(LocalId raw_id) : raw_id_(raw_id.raw_id()) { + explicit TraceID(LocalId raw_id) : raw_id_(raw_id.raw_id()) { id_flags_ = TRACE_EVENT_FLAG_HAS_LOCAL_ID; } - TraceID(GlobalId raw_id) : raw_id_(raw_id.raw_id()) { + explicit TraceID(GlobalId raw_id) : raw_id_(raw_id.raw_id()) { id_flags_ = TRACE_EVENT_FLAG_HAS_GLOBAL_ID; } - TraceID(WithScope scoped_id) + explicit TraceID(WithScope scoped_id) : scope_(scoped_id.scope()), raw_id_(scoped_id.raw_id()), id_flags_(scoped_id.id_flags()) {} @@ -587,7 +588,7 @@ // These AddTraceEvent and AddTraceEventWithThreadIdAndTimestamp template // functions are defined here instead of in the macro, because the arg_values -// could be temporary objects, such as std::string. In order to store +// could be temporary objects, such as `std::string`. In order to store // pointers to the internal c_str and pass through to the tracing API, // the arg_values must live throughout these procedures.
diff --git a/base/values.h b/base/values.h index 282bb28..0903e82 100644 --- a/base/values.h +++ b/base/values.h
@@ -98,7 +98,7 @@ // // Migrating code will require conversions on API boundaries. This can be done // cheaply by making use of overloaded base::Value constructors and the -// Value::TakeList() and Value::TakeDict() APIs. +// `Value::TakeList()` and `Value::TakeDict()` APIs. class BASE_EXPORT Value { public: using BlobStorage = std::vector<uint8_t>; @@ -177,7 +177,7 @@ ~Value(); - // Returns the name for a given |type|. + // Returns the name for a given `type`. static const char* GetTypeName(Type type); // Returns the type of the value stored by the current Value object. @@ -211,18 +211,18 @@ // Returns the Values in a list as a view. The mutable overload allows for // modification of the underlying values, but does not allow changing the - // structure of the list. If this is desired, use TakeList(), perform the + // structure of the list. If this is desired, use `TakeList()`, perform the // operations, and return the list back to the Value via move assignment. ListView GetList(); ConstListView GetList() const; // Transfers ownership of the underlying list to the caller. Subsequent - // calls to GetList() will return an empty list. - // Note: This requires that type() is Type::LIST. + // calls to `GetList()` will return an empty list. + // Note: This requires that `type()` is Type::LIST. ListStorage TakeList(); - // Appends |value| to the end of the list. - // Note: These CHECK that type() is Type::LIST. + // Appends `value` to the end of the list. + // Note: These CHECK that `type()` is Type::LIST. void Append(bool value); void Append(int value); void Append(double value); @@ -232,7 +232,7 @@ void Append(std::string&& value); void Append(const char16_t* value); - // Disable Append() from other pointers, so that there is no silent + // Disable `Append()` from other pointers, so that there is no silent // conversion to bool. template <typename T, typename = std::enable_if_t< @@ -243,67 +243,67 @@ void Append(StringPiece16 value); void Append(Value&& value); - // Inserts |value| before |pos|. - // Note: This CHECK that type() is Type::LIST. + // Inserts `value` before `pos`. + // Note: This CHECK that `type()` is Type::LIST. CheckedContiguousIterator<Value> Insert( CheckedContiguousConstIterator<Value> pos, Value&& value); - // Erases the Value pointed to by |iter|. Returns false if |iter| is out of + // Erases the Value pointed to by `iter`. Returns false if `iter` is out of // bounds. - // Note: This requires that type() is Type::LIST. + // Note: This requires that `type()` is Type::LIST. bool EraseListIter(CheckedContiguousConstIterator<Value> iter); - // Erases all Values that compare equal to |val|. Returns the number of + // Erases all Values that compare equal to `val`. Returns the number of // deleted Values. - // Note: This requires that type() is Type::LIST. + // Note: This requires that `type()` is Type::LIST. size_t EraseListValue(const Value& val); - // Erases all Values for which |pred| returns true. Returns the number of + // Erases all Values for which `pred` returns true. Returns the number of // deleted Values. - // Note: This requires that type() is Type::LIST. + // Note: This requires that `type()` is Type::LIST. template <typename Predicate> size_t EraseListValueIf(Predicate pred) { return base::EraseIf(list(), pred); } // Erases all Values from the list. - // Note: This requires that type() is Type::LIST. + // Note: This requires that `type()` is Type::LIST. void ClearList(); - // |FindKey| looks up |key| in the underlying dictionary. If found, it returns + // `FindKey` looks up `key` in the underlying dictionary. If found, it returns // a pointer to the element. Otherwise it returns nullptr. // returned. Callers are expected to perform a check against null before using // the pointer. - // Note: This requires that type() is Type::DICTIONARY. + // Note: This requires that `type()` is Type::DICTIONARY. // // Example: // auto* found = FindKey("foo"); Value* FindKey(StringPiece key); const Value* FindKey(StringPiece key) const; - // |FindKeyOfType| is similar to |FindKey|, but it also requires the found - // value to have type |type|. If no type is found, or the found value is of a + // `FindKeyOfType` is similar to `FindKey`, but it also requires the found + // value to have type `type`. If no type is found, or the found value is of a // different type nullptr is returned. // Callers are expected to perform a check against null before using the // pointer. - // Note: This requires that type() is Type::DICTIONARY. + // Note: This requires that `type()` is Type::DICTIONARY. // // Example: // auto* found = FindKey("foo", Type::DOUBLE); Value* FindKeyOfType(StringPiece key, Type type); const Value* FindKeyOfType(StringPiece key, Type type) const; - // These are convenience forms of |FindKey|. They return |base::nullopt| if + // These are convenience forms of `FindKey`. They return `base`:nullopt| if // the value is not found or doesn't have the type specified in the // function's name. base::Optional<bool> FindBoolKey(StringPiece key) const; base::Optional<int> FindIntKey(StringPiece key) const; - // Note FindDoubleKey() will auto-convert INTEGER keys to their double - // value, for consistency with GetDouble(). + // Note `FindDoubleKey()` will auto-convert INTEGER keys to their double + // value, for consistency with `GetDouble()`. base::Optional<double> FindDoubleKey(StringPiece key) const; - // |FindStringKey| returns |nullptr| if value is not found or not a string. + // `FindStringKey` returns `nullptr` if value is not found or not a string. const std::string* FindStringKey(StringPiece key) const; std::string* FindStringKey(StringPiece key); @@ -318,11 +318,11 @@ const Value* FindListKey(StringPiece key) const; Value* FindListKey(StringPiece key); - // |SetKey| looks up |key| in the underlying dictionary and sets the mapped - // value to |value|. If |key| could not be found, a new element is inserted. + // `SetKey` looks up `key` in the underlying dictionary and sets the mapped + // value to `value`. If `key` could not be found, a new element is inserted. // A pointer to the modified item is returned. - // Note: This requires that type() is Type::DICTIONARY. - // Note: Prefer Set<Type>Key() for simple values. + // Note: This requires that `type()` is Type::DICTIONARY. + // Note: Prefer `Set<Type>Key()` for simple values. // // Example: // SetKey("foo", std::move(myvalue)); @@ -332,9 +332,9 @@ // This overload is necessary to avoid ambiguity for const char* arguments. Value* SetKey(const char* key, Value&& value); - // |Set<Type>Key| looks up |key| in the underlying dictionary and associates - // a corresponding Value() constructed from the second parameter. Compared - // to SetKey(), this avoids un-necessary temporary Value() creation, as well + // `Set`Type>Key` looks up `key` in the underlying dictionary and associates a + // corresponding Value() constructed from the second parameter. Compared to + // `SetKey()`, this avoids un-necessary temporary `Value()` creation, as well // ambiguities in the value type. Value* SetBoolKey(StringPiece key, bool val); Value* SetIntKey(StringPiece key, int val); @@ -346,21 +346,21 @@ Value* SetStringKey(StringPiece key, const char* val); Value* SetStringKey(StringPiece key, std::string&& val); - // This attempts to remove the value associated with |key|. In case of + // This attempts to remove the value associated with `key`. In case of // failure, e.g. the key does not exist, false is returned and the underlying - // dictionary is not changed. In case of success, |key| is deleted from the + // dictionary is not changed. In case of success, `key` is deleted from the // dictionary and the method returns true. - // Note: This requires that type() is Type::DICTIONARY. + // Note: This requires that `type()` is Type::DICTIONARY. // // Example: // bool success = dict.RemoveKey("foo"); bool RemoveKey(StringPiece key); - // This attempts to extract the value associated with |key|. In case of + // This attempts to extract the value associated with `key`. In case of // failure, e.g. the key does not exist, nullopt is returned and the - // underlying dictionary is not changed. In case of success, |key| is deleted + // underlying dictionary is not changed. In case of success, `key` is deleted // from the dictionary and the method returns the extracted Value. - // Note: This requires that type() is Type::DICTIONARY. + // Note: This requires that `type()` is Type::DICTIONARY. // // Example: // Optional<Value> maybe_value = dict.ExtractKey("foo"); @@ -388,7 +388,7 @@ // span<const StringPiece>. The latter is useful to use a // std::vector<std::string> as a parameter but creates huge dynamic // allocations and should be avoided! - // Note: If there is only one component in the path, use FindKey() instead. + // Note: If there is only one component in the path, use `FindKey()` instead. // // Example: // std::vector<StringPiece> components = ... @@ -400,9 +400,9 @@ // Like FindPath() but will only return the value if the leaf Value type // matches the given type. Will return nullptr otherwise. - // Note: Prefer Find<Type>Path() for simple values. + // Note: Prefer `Find<Type>Path()` for simple values. // - // Note: If there is only one component in the path, use FindKeyOfType() + // Note: If there is only one component in the path, use `FindKeyOfType()` // instead for slightly better performance. Value* FindPathOfType(StringPiece path, Type type); const Value* FindPathOfType(StringPiece path, Type type) const; @@ -440,8 +440,8 @@ // Example: // value.SetPath("foo.bar", std::move(myvalue)); // - // Note: If there is only one component in the path, use SetKey() instead. - // Note: Using Set<Type>Path() might be more convenient and efficient. + // Note: If there is only one component in the path, use `SetKey()` instead. + // Note: Using `Set<Type>Path()` might be more convenient and efficient. Value* SetPath(StringPiece path, Value&& value); // These setters are more convenient and efficient than the corresponding @@ -454,7 +454,7 @@ Value* SetStringPath(StringPiece path, std::string&& value); Value* SetStringPath(StringPiece path, StringPiece16 value); - // Deprecated: use the ones that take a StringPiece path parameter instead. + // Deprecated: use the `SetPath(StringPiece, ...)` methods above instead. Value* SetPath(std::initializer_list<StringPiece> path, Value&& value); Value* SetPath(span<const StringPiece> path, Value&& value); @@ -462,9 +462,10 @@ // // If the current value is not a dictionary or any path component does not // exist, this operation fails, leaves underlying Values untouched and returns - // |false|. In case intermediate dictionaries become empty as a result of this + // `false`. In case intermediate dictionaries become empty as a result of this // path removal, they will be removed as well. - // Note: If there is only one component in the path, use ExtractKey() instead. + // Note: If there is only one component in the path, use `ExtractKey()` + // instead. // // Example: // bool success = value.RemovePath("foo.bar"); @@ -477,7 +478,8 @@ // nullopt. In case intermediate dictionaries become empty as a result of this // path removal, they will be removed as well. Returns the extracted value on // success. - // Note: If there is only one component in the path, use ExtractKey() instead. + // Note: If there is only one component in the path, use `ExtractKey()` + // instead. // // Example: // Optional<Value> maybe_value = value.ExtractPath("foo.bar"); @@ -486,58 +488,59 @@ using dict_iterator_proxy = detail::dict_iterator_proxy; using const_dict_iterator_proxy = detail::const_dict_iterator_proxy; - // |DictItems| returns a proxy object that exposes iterators to the underlying + // `DictItems` returns a proxy object that exposes iterators to the underlying // dictionary. These are intended for iteration over all items in the // dictionary and are compatible with for-each loops and standard library // algorithms. // - // Unlike with std::map, a range-for over the non-const version of DictItems() - // will range over items of type pair<const std::string&, Value&>, so code of - // the form + // Unlike with std::map, a range-for over the non-const version of + // `DictItems()` will range over items of type + // `pair<const std::string&, Value&>`, so code of the form // for (auto kv : my_value.DictItems()) // Mutate(kv.second); - // will actually alter |my_value| in place (if it isn't const). + // will actually alter `my_value` in place (if it isn't const). // - // Note: These CHECK that type() is Type::DICTIONARY. + // Note: These CHECK that `type()` is Type::DICTIONARY. dict_iterator_proxy DictItems(); const_dict_iterator_proxy DictItems() const; // Transfers ownership of the underlying dict to the caller. Subsequent // calls to DictItems() will return an empty dict. - // Note: This requires that type() is Type::DICTIONARY. + // Note: This requires that `type()` is Type::DICTIONARY. DictStorage TakeDict(); // Returns the size of the dictionary, if the dictionary is empty, and clears - // the dictionary. Note: These CHECK that type() is Type::DICTIONARY. + // the dictionary. Note: These CHECK that `type()` is Type::DICTIONARY. size_t DictSize() const; bool DictEmpty() const; void DictClear(); - // Merge |dictionary| into this value. This is done recursively, i.e. any + // Merge `dictionary` into this value. This is done recursively, i.e. any // sub-dictionaries will be merged as well. In case of key collisions, the // passed in dictionary takes precedence and data already present will be - // replaced. Values within |dictionary| are deep-copied, so |dictionary| may + // replaced. Values within `dictionary` are deep-copied, so `dictionary` may // be freed any time after this call. - // Note: This requires that type() and dictionary->type() is Type::DICTIONARY. + // Note: This requires that `type()` and `dictionary->type()` is + // Type::DICTIONARY. void MergeDictionary(const Value* dictionary); // These methods allow the convenient retrieval of the contents of the Value. // If the current object can be converted into the given type, the value is - // returned through the |out_value| parameter and true is returned; - // otherwise, false is returned and |out_value| is unchanged. - // DEPRECATED, use GetIfBool() instead. + // returned through the `out_value` parameter and true is returned; + // otherwise, false is returned and `out_value` is unchanged. + // DEPRECATED, use `GetIfBool()` instead. bool GetAsBoolean(bool* out_value) const; - // DEPRECATED, use GetIfInt() instead. + // DEPRECATED, use `GetIfInt()` instead. bool GetAsInteger(int* out_value) const; - // DEPRECATED, use GetIfDouble() instead. + // DEPRECATED, use `GetIfDouble()` instead. bool GetAsDouble(double* out_value) const; - // DEPRECATED, use GetIfString() instead. + // DEPRECATED, use `GetIfString()` instead. bool GetAsString(std::string* out_value) const; bool GetAsString(std::u16string* out_value) const; bool GetAsString(const Value** out_value) const; bool GetAsString(StringPiece* out_value) const; // ListValue::From is the equivalent for std::unique_ptr conversions. - // DEPRECATED, use is_list() instead. + // DEPRECATED, use `is_list()` instead. bool GetAsList(ListValue** out_value); bool GetAsList(const ListValue** out_value) const; // DictionaryValue::From is the equivalent for std::unique_ptr conversions. @@ -549,10 +552,10 @@ // to the copy. The caller gets ownership of the copy, of course. // Subclasses return their own type directly in their overrides; // this works because C++ supports covariant return types. - // DEPRECATED, use Value::Clone() instead. + // DEPRECATED, use `Value::Clone()` instead. // TODO(crbug.com/646113): Delete this and migrate callsites. Value* DeepCopy() const; - // DEPRECATED, use Value::Clone() instead. + // DEPRECATED, use `Value::Clone()` instead. // TODO(crbug.com/646113): Delete this and migrate callsites. std::unique_ptr<Value> CreateDeepCopy() const; @@ -566,7 +569,7 @@ BASE_EXPORT friend bool operator>=(const Value& lhs, const Value& rhs); // Compares if two Value objects have equal contents. - // DEPRECATED, use operator==(const Value& lhs, const Value& rhs) instead. + // DEPRECATED, use `operator==(const Value& lhs, const Value& rhs)` instead. // TODO(crbug.com/646113): Delete this and migrate callsites. bool Equals(const Value* other) const; @@ -632,13 +635,13 @@ // DictionaryValue provides a key-value dictionary with (optional) "path" // parsing for recursive access; see the comment at the top of the file. Keys -// are |std::string|s and should be UTF-8 encoded. +// are `std`:string|s and should be UTF-8 encoded. class BASE_EXPORT DictionaryValue : public Value { public: using const_iterator = LegacyDictStorage::const_iterator; using iterator = LegacyDictStorage::iterator; - // Returns |value| if it is a dictionary, nullptr otherwise. + // Returns `value` if it is a dictionary, nullptr otherwise. static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value); DictionaryValue(); @@ -646,7 +649,7 @@ explicit DictionaryValue(LegacyDictStorage&& in_dict) noexcept; // Returns true if the current dictionary has a value for the given key. - // DEPRECATED, use Value::FindKey(key) instead. + // DEPRECATED, use `Value::FindKey(key)` instead. bool HasKey(StringPiece key) const; // Returns the number of Values in this dictionary. @@ -656,7 +659,7 @@ bool empty() const { return dict().empty(); } // Clears any current contents of this dictionary. - // DEPRECATED, use Value::DictClear() instead. + // DEPRECATED, use `Value::DictClear()` instead. void Clear(); // Sets the Value associated with the given path starting from this object. @@ -665,32 +668,32 @@ // within a key, but there are no other restrictions on keys. // If the key at any step of the way doesn't exist, or exists but isn't // a DictionaryValue, a new DictionaryValue will be created and attached - // to the path in that location. |in_value| must be non-null. + // to the path in that location. `in_value` must be non-null. // Returns a pointer to the inserted value. - // DEPRECATED, use Value::SetPath(path, value) instead. + // DEPRECATED, use `Value::SetPath(path, value)` instead. Value* Set(StringPiece path, std::unique_ptr<Value> in_value); // Convenience forms of Set(). These methods will replace any existing // value at that path, even if it has a different type. - // DEPRECATED, use Value::SetBoolKey() or Value::SetBoolPath(). + // DEPRECATED, use `Value::SetBoolKey()` or `Value::SetBoolPath()`. Value* SetBoolean(StringPiece path, bool in_value); - // DEPRECATED, use Value::SetIntPath(). + // DEPRECATED, use `Value::SetIntPath()`. Value* SetInteger(StringPiece path, int in_value); - // DEPRECATED, use Value::SetDoublePath(). + // DEPRECATED, use `Value::SetDoublePath()`. Value* SetDouble(StringPiece path, double in_value); - // DEPRECATED, use Value::SetStringPath(). + // DEPRECATED, use `Value::SetStringPath()`. Value* SetString(StringPiece path, StringPiece in_value); - // DEPRECATED, use Value::SetStringPath(). + // DEPRECATED, use `Value::SetStringPath()`. Value* SetString(StringPiece path, const std::u16string& in_value); - // DEPRECATED, use Value::SetPath(). + // DEPRECATED, use `Value::SetPath()`. DictionaryValue* SetDictionary(StringPiece path, std::unique_ptr<DictionaryValue> in_value); - // DEPRECATED, use Value::SetPath(). + // DEPRECATED, use `Value::SetPath()`. ListValue* SetList(StringPiece path, std::unique_ptr<ListValue> in_value); // Like Set(), but without special treatment of '.'. This allows e.g. URLs to // be used as paths. - // DEPRECATED, use Value::SetKey(key, value) instead. + // DEPRECATED, use `Value::SetKey(key, value)` instead. Value* SetWithoutPathExpansion(StringPiece key, std::unique_ptr<Value> in_value); @@ -698,111 +701,114 @@ // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes // into the next DictionaryValue down. If the path can be resolved // successfully, the value for the last key in the path will be returned - // through the |out_value| parameter, and the function will return true. - // Otherwise, it will return false and |out_value| will be untouched. + // through the `out_value` parameter, and the function will return true. + // Otherwise, it will return false and `out_value` will be untouched. // Note that the dictionary always owns the value that's returned. - // |out_value| is optional and will only be set if non-NULL. - // DEPRECATED, use Value::FindPath(path) instead. + // `out_value` is optional and will only be set if non-NULL. + // DEPRECATED, use `Value::FindPath(path)` instead. bool Get(StringPiece path, const Value** out_value) const; - // DEPRECATED, use Value::FindPath(path) instead. + // DEPRECATED, use `Value::FindPath(path)` instead. bool Get(StringPiece path, Value** out_value); - // These are convenience forms of Get(). The value will be retrieved + // These are convenience forms of `Get()`. The value will be retrieved // and the return value will be true if the path is valid and the value at // the end of the path can be returned in the form specified. - // |out_value| is optional and will only be set if non-NULL. - // DEPRECATED, use Value::FindBoolPath(path) instead. + // `out_value` is optional and will only be set if non-NULL. + // DEPRECATED, use `Value::FindBoolPath(path)` instead. bool GetBoolean(StringPiece path, bool* out_value) const; - // DEPRECATED, use Value::FindIntPath(path) instead. + // DEPRECATED, use `Value::FindIntPath(path)` instead. bool GetInteger(StringPiece path, int* out_value) const; // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as // doubles. - // DEPRECATED, use Value::FindDoublePath(path). + // DEPRECATED, use `Value::FindDoublePath(path)`. bool GetDouble(StringPiece path, double* out_value) const; - // DEPRECATED, use Value::FindStringPath(path) instead. + // DEPRECATED, use `Value::FindStringPath(path)` instead. bool GetString(StringPiece path, std::string* out_value) const; - // DEPRECATED, use Value::FindStringPath(path) instead. + // DEPRECATED, use `Value::FindStringPath(path)` instead. bool GetString(StringPiece path, std::u16string* out_value) const; - // DEPRECATED, use Value::FindString(path) and IsAsciiString() instead. + // DEPRECATED, use `Value::FindString(path)` and `IsAsciiString()` instead. bool GetStringASCII(StringPiece path, std::string* out_value) const; - // DEPRECATED, use Value::FindBlobPath(path) instead. + // DEPRECATED, use `Value::FindBlobPath(path)` instead. bool GetBinary(StringPiece path, const Value** out_value) const; - // DEPRECATED, use Value::FindBlobPath(path) instead. + // DEPRECATED, use `Value::FindBlobPath(path)` instead. bool GetBinary(StringPiece path, Value** out_value); - // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead. + // DEPRECATED, use `Value::FindPath(path)` and Value's Dictionary API + // instead. bool GetDictionary(StringPiece path, const DictionaryValue** out_value) const; - // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead. + // DEPRECATED, use `Value::FindPath(path)` and Value's Dictionary API + // instead. bool GetDictionary(StringPiece path, DictionaryValue** out_value); - // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead. + // DEPRECATED, use `Value::FindPath(path)` and `Value::GetList()` instead. bool GetList(StringPiece path, const ListValue** out_value) const; - // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead. + // DEPRECATED, use `Value::FindPath(path)` and `Value::GetList()` instead. bool GetList(StringPiece path, ListValue** out_value); - // Like Get(), but without special treatment of '.'. This allows e.g. URLs to - // be used as paths. - // DEPRECATED, use Value::FindKey(key) instead. + // Like `Get()`, but without special treatment of '.'. This allows e.g. URLs + // to be used as paths. + // DEPRECATED, use `Value::FindKey(key)` instead. bool GetWithoutPathExpansion(StringPiece key, const Value** out_value) const; - // DEPRECATED, use Value::FindKey(key) instead. + // DEPRECATED, use `Value::FindKey(key)` instead. bool GetWithoutPathExpansion(StringPiece key, Value** out_value); - // DEPRECATED, use Value::FindBoolKey(key) instead. + // DEPRECATED, use `Value::FindBoolKey(key)` instead. bool GetBooleanWithoutPathExpansion(StringPiece key, bool* out_value) const; - // DEPRECATED, use Value::FindIntKey(key) instead. + // DEPRECATED, use `Value::FindIntKey(key)` instead. bool GetIntegerWithoutPathExpansion(StringPiece key, int* out_value) const; - // DEPRECATED, use Value::FindDoubleKey(key) instead. + // DEPRECATED, use `Value::FindDoubleKey(key)` instead. bool GetDoubleWithoutPathExpansion(StringPiece key, double* out_value) const; - // DEPRECATED, use Value::FindStringKey(key) instead. + // DEPRECATED, use `Value::FindStringKey(key)` instead. bool GetStringWithoutPathExpansion(StringPiece key, std::string* out_value) const; - // DEPRECATED, use Value::FindStringKey(key) and UTF8ToUTF16() instead. + // DEPRECATED, use `Value::FindStringKey(key)` and UTF8ToUTF16() instead. bool GetStringWithoutPathExpansion(StringPiece key, std::u16string* out_value) const; - // DEPRECATED, use Value::FindDictKey(key) instead. + // DEPRECATED, use `Value::FindDictKey(key)` instead. bool GetDictionaryWithoutPathExpansion( StringPiece key, const DictionaryValue** out_value) const; - // DEPRECATED, use Value::FindDictKey(key) instead. + // DEPRECATED, use `Value::FindDictKey(key)` instead. bool GetDictionaryWithoutPathExpansion(StringPiece key, DictionaryValue** out_value); - // DEPRECATED, use Value::FindListKey(key) instead. + // DEPRECATED, use `Value::FindListKey(key)` instead. bool GetListWithoutPathExpansion(StringPiece key, const ListValue** out_value) const; - // DEPRECATED, use Value::FindListKey(key) instead. + // DEPRECATED, use `Value::FindListKey(key)` instead. bool GetListWithoutPathExpansion(StringPiece key, ListValue** out_value); // Removes the Value with the specified path from this dictionary (or one // of its child dictionaries, if the path is more than just a local key). - // If |out_value| is non-NULL, the removed Value will be passed out via - // |out_value|. If |out_value| is NULL, the removed value will be deleted. - // This method returns true if |path| is a valid path; otherwise it will + // If `out_value` is non-NULL, the removed Value will be passed out via + // `out_value`. If `out_value` is NULL, the removed value will be deleted. + // This method returns true if `path` is a valid path; otherwise it will // return false and the DictionaryValue object will be unchanged. - // DEPRECATED, use Value::RemovePath(path) or Value::ExtractPath(path) + // DEPRECATED, use `Value::RemovePath(path)` or `Value::ExtractPath(path)` // instead. bool Remove(StringPiece path, std::unique_ptr<Value>* out_value); // Like Remove(), but without special treatment of '.'. This allows e.g. URLs // to be used as paths. - // DEPRECATED, use Value::RemoveKey(key) or Value::ExtractKey(key) instead. + // DEPRECATED, use `Value::RemoveKey(key)` or `Value::ExtractKey(key)` + // instead. bool RemoveWithoutPathExpansion(StringPiece key, std::unique_ptr<Value>* out_value); - // Removes a path, clearing out all dictionaries on |path| that remain empty - // after removing the value at |path|. - // DEPRECATED, use Value::RemovePath(path) or Value::ExtractPath(path) + // Removes a path, clearing out all dictionaries on `path` that remain empty + // after removing the value at `path`. + // DEPRECATED, use `Value::RemovePath(path)` or `Value::ExtractPath(path)` // instead. bool RemovePath(StringPiece path, std::unique_ptr<Value>* out_value); using Value::RemovePath; // DictionaryValue::RemovePath shadows otherwise. - // Makes a copy of |this| but doesn't include empty dictionaries and lists in - // the copy. This never returns NULL, even if |this| itself is empty. + // Makes a copy of `this` but doesn't include empty dictionaries and lists in + // the copy. This never returns NULL, even if `this` itself is empty. std::unique_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const; - // Swaps contents with the |other| dictionary. + // Swaps contents with the `other` dictionary. void Swap(DictionaryValue* other); // This class provides an iterator over both keys and values in the // dictionary. It can't be used to modify the dictionary. - // DEPRECATED, use Value::DictItems() instead. + // DEPRECATED, use `Value::DictItems()` instead. class BASE_EXPORT Iterator { public: explicit Iterator(const DictionaryValue& target); @@ -821,18 +827,18 @@ }; // Iteration. - // DEPRECATED, use Value::DictItems() instead. + // DEPRECATED, use `Value::DictItems()` instead. iterator begin() { return dict().begin(); } iterator end() { return dict().end(); } - // DEPRECATED, use Value::DictItems() instead. + // DEPRECATED, use `Value::DictItems()` instead. const_iterator begin() const { return dict().begin(); } const_iterator end() const { return dict().end(); } - // DEPRECATED, use Value::Clone() instead. + // DEPRECATED, use `Value::Clone()` instead. // TODO(crbug.com/646113): Delete this and migrate callsites. DictionaryValue* DeepCopy() const; - // DEPRECATED, use Value::Clone() instead. + // DEPRECATED, use `Value::Clone()` instead. // TODO(crbug.com/646113): Delete this and migrate callsites. std::unique_ptr<DictionaryValue> CreateDeepCopy() const; }; @@ -844,7 +850,7 @@ using const_iterator = ListView::const_iterator; using iterator = ListView::iterator; - // Returns |value| if it is a list, nullptr otherwise. + // Returns `value` if it is a list, nullptr otherwise. static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value); ListValue(); @@ -852,15 +858,15 @@ explicit ListValue(ListStorage&& in_list) noexcept; // Clears the contents of this ListValue - // DEPRECATED, use ClearList() instead. + // DEPRECATED, use `ClearList()` instead. void Clear(); // Returns the number of Values in this list. - // DEPRECATED, use GetList()::size() instead. + // DEPRECATED, use `GetList()::size()` instead. size_t GetSize() const { return list().size(); } // Returns whether the list is empty. - // DEPRECATED, use GetList()::empty() instead. + // DEPRECATED, use `GetList()::empty()` instead. bool empty() const { return list().empty(); } // Sets the list item at the given index to be the Value specified by @@ -868,30 +874,30 @@ // Values will be used to pad out the list. // Returns true if successful, or false if the index was negative or // the value is a null pointer. - // DEPRECATED, use GetList()::operator[] instead. + // DEPRECATED, use `GetList()::operator[] instead. bool Set(size_t index, std::unique_ptr<Value> in_value); - // Gets the Value at the given index. Modifies |out_value| (and returns true) + // Gets the Value at the given index. Modifies `out_value` (and returns true) // only if the index falls within the current list range. - // Note that the list always owns the Value passed out via |out_value|. - // |out_value| is optional and will only be set if non-NULL. - // DEPRECATED, use GetList()::operator[] instead. + // Note that the list always owns the Value passed out via `out_value`. + // `out_value` is optional and will only be set if non-NULL. + // DEPRECATED, use `GetList()::operator[] instead. bool Get(size_t index, const Value** out_value) const; bool Get(size_t index, Value** out_value); - // Convenience forms of Get(). Modifies |out_value| (and returns true) + // Convenience forms of `Get()`. Modifies `out_value` (and returns true) // only if the index is valid and the Value at that index can be returned // in the specified form. - // |out_value| is optional and will only be set if non-NULL. - // DEPRECATED, use GetList()::operator[]::GetBool() instead. + // `out_value` is optional and will only be set if non-NULL. + // DEPRECATED, use `GetList()::operator[]::GetBool()` instead. bool GetBoolean(size_t index, bool* out_value) const; - // DEPRECATED, use GetList()::operator[]::GetInt() instead. + // DEPRECATED, use `GetList()::operator[]::GetInt()` instead. bool GetInteger(size_t index, int* out_value) const; // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as // doubles. - // DEPRECATED, use GetList()::operator[]::GetDouble() instead. + // DEPRECATED, use `GetList()::operator[]::GetDouble()` instead. bool GetDouble(size_t index, double* out_value) const; - // DEPRECATED, use GetList()::operator[]::GetString() instead. + // DEPRECATED, use `GetList()::operator[]::GetString()` instead. bool GetString(size_t index, std::string* out_value) const; bool GetString(size_t index, std::u16string* out_value) const; @@ -899,82 +905,82 @@ bool GetDictionary(size_t index, DictionaryValue** out_value); using Value::GetList; - // DEPRECATED, use GetList()::operator[]::GetList() instead. + // DEPRECATED, use `GetList()::operator[]::GetList()` instead. bool GetList(size_t index, const ListValue** out_value) const; bool GetList(size_t index, ListValue** out_value); // Removes the Value with the specified index from this list. - // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be - // passed out via |out_value|. If |out_value| is NULL, the removed value will - // be deleted. This method returns true if |index| is valid; otherwise + // If `out_value` is non-NULL, the removed Value AND ITS OWNERSHIP will be + // passed out via `out_value`. If `out_value` is NULL, the removed value will + // be deleted. This method returns true if `index` is valid; otherwise // it will return false and the ListValue object will be unchanged. - // DEPRECATED, use GetList()::erase() instead. + // DEPRECATED, use `GetList()::erase()` instead. bool Remove(size_t index, std::unique_ptr<Value>* out_value); - // Removes the first instance of |value| found in the list, if any, and - // deletes it. |index| is the location where |value| was found. Returns false + // Removes the first instance of `value` found in the list, if any, and + // deletes it. `index` is the location where `value` was found. Returns false // if not found. - // DEPRECATED, use GetList()::erase() instead. + // DEPRECATED, use `GetList()::erase()` instead. bool Remove(const Value& value, size_t* index); - // Removes the element at |iter|. If |out_value| is NULL, the value will be + // Removes the element at `iter`. If `out_value` is NULL, the value will be // deleted, otherwise ownership of the value is passed back to the caller. // Returns an iterator pointing to the location of the element that // followed the erased element. - // DEPRECATED, use GetList()::erase() instead. + // DEPRECATED, use `GetList()::erase()` instead. iterator Erase(iterator iter, std::unique_ptr<Value>* out_value); using Value::Append; // Appends a Value to the end of the list. - // DEPRECATED, use Value::Append() instead. + // DEPRECATED, use `Value::Append()` instead. void Append(std::unique_ptr<Value> in_value); // Convenience forms of Append. - // DEPRECATED, use Value::Append() instead. + // DEPRECATED, use `Value::Append()` instead. void AppendBoolean(bool in_value); void AppendInteger(int in_value); void AppendDouble(double in_value); void AppendString(StringPiece in_value); void AppendString(const std::u16string& in_value); - // DEPRECATED, use Value::Append() in a loop instead. + // DEPRECATED, use `Value::Append()` in a loop instead. void AppendStrings(const std::vector<std::string>& in_values); // Appends a Value if it's not already present. Returns true if successful, // or false if the value was already - // DEPRECATED, use std::find() with Value::Append() instead. + // DEPRECATED, use `std::find()` with `Value::Append()` instead. bool AppendIfNotPresent(std::unique_ptr<Value> in_value); using Value::Insert; // Insert a Value at index. // Returns true if successful, or false if the index was out of range. - // DEPRECATED, use Value::Insert() instead. + // DEPRECATED, use `Value::Insert()` instead. bool Insert(size_t index, std::unique_ptr<Value> in_value); - // Searches for the first instance of |value| in the list using the Equals + // Searches for the first instance of `value` in the list using the Equals // method of the Value type. // Returns a const_iterator to the found item or to end() if none exists. - // DEPRECATED, use std::find() instead. + // DEPRECATED, use `std::find()` instead. const_iterator Find(const Value& value) const; - // Swaps contents with the |other| list. - // DEPRECATED, use GetList()::swap() instead. + // Swaps contents with the `other` list. + // DEPRECATED, use `GetList()::swap()` instead. void Swap(ListValue* other); // Iteration. - // DEPRECATED, use GetList()::begin() instead. + // DEPRECATED, use `GetList()::begin()` instead. iterator begin() { return GetList().begin(); } - // DEPRECATED, use GetList()::end() instead. + // DEPRECATED, use `GetList()::end()` instead. iterator end() { return GetList().end(); } - // DEPRECATED, use GetList()::begin() instead. + // DEPRECATED, use `GetList()::begin()` instead. const_iterator begin() const { return GetList().begin(); } - // DEPRECATED, use GetList()::end() instead. + // DEPRECATED, use `GetList()::end()` instead. const_iterator end() const { return GetList().end(); } - // DEPRECATED, use Value::Clone() instead. + // DEPRECATED, use `Value::Clone()` instead. // TODO(crbug.com/646113): Delete this and migrate callsites. ListValue* DeepCopy() const; - // DEPRECATED, use Value::Clone() instead. + // DEPRECATED, use `Value::Clone()` instead. // TODO(crbug.com/646113): Delete this and migrate callsites. std::unique_ptr<ListValue> CreateDeepCopy() const; }; @@ -998,11 +1004,11 @@ // If the return value is non-NULL, the caller takes ownership of returned // Value. // - // If the return value is nullptr, and if |error_code| is non-nullptr, - // |*error_code| will be set to an integer value representing the underlying + // If the return value is nullptr, and if `error_code` is non-nullptr, + // `*error_code` will be set to an integer value representing the underlying // error. See "enum ErrorCode" below for more detail about the integer value. // - // If |error_message| is non-nullptr, it will be filled in with a formatted + // If `error_message` is non-nullptr, it will be filled in with a formatted // error message including the location of the error if appropriate. virtual std::unique_ptr<Value> Deserialize(int* error_code, std::string* error_message) = 0; @@ -1025,7 +1031,7 @@ kErrorCodeFirstMetadataError = 1000, }; - // The |error_code| argument can be one of the ErrorCode values, but it is + // The `error_code` argument can be one of the ErrorCode values, but it is // not restricted to only being 0, 1 or 1000. Subclasses of ValueDeserializer // can define their own error code values. static inline bool ErrorCodeIsDataError(int error_code) {
diff --git a/build/android/docs/coverage.md b/build/android/docs/coverage.md index 17c83c6..ed24100 100644 --- a/build/android/docs/coverage.md +++ b/build/android/docs/coverage.md
@@ -29,6 +29,10 @@ 3. The coverage results of JUnit and instrumentation tests will be merged automatically if they are in the same directory. +4. If generating coverage and there are duplicate class files, as can happen + when generating coverage for downstream targets, use the + --include-substr-filter option to choose jars in the desired directory. + ## How to generate coverage report 1. Now we have generated .exec files already. We can create a JaCoCo HTML/XML/CSV
diff --git a/build/android/generate_jacoco_report.py b/build/android/generate_jacoco_report.py index d0a9987..b8c4a97 100755 --- a/build/android/generate_jacoco_report.py +++ b/build/android/generate_jacoco_report.py
@@ -40,22 +40,27 @@ _HOST_CLASS_EXCLUDE_SUFFIX = 'device_filter.jar' -def _CreateClassfileArgs(class_files, exclude_suffix=None): - """Returns a list of files that don't have a given suffix. +def _CreateClassfileArgs(class_files, exclude_suffix=None, include_substr=None): + """Returns a filtered list of files with classfile option. Args: class_files: A list of class files. exclude_suffix: Suffix to look for to exclude. + include_substr: A substring that must be present to include the file. + exclude_suffix takes precedence over this. Returns: A list of files that don't use the suffix. """ result_class_files = [] for f in class_files: - if exclude_suffix: - if not f.endswith(exclude_suffix): - result_class_files += ['--classfiles', f] - else: + include_file = True + if exclude_suffix and f.endswith(exclude_suffix): + include_file = False + # Exclude overrides include. + if include_file and include_substr and include_substr not in f: + include_file = False + if include_file: result_class_files += ['--classfiles', f] return result_class_files @@ -68,7 +73,8 @@ elif report_type == 'host': class_jar_exclude = _HOST_CLASS_EXCLUDE_SUFFIX - cmd = _CreateClassfileArgs(class_files, class_jar_exclude) + cmd = _CreateClassfileArgs(class_files, class_jar_exclude, + args.include_substr_filter) if args.format == 'html': report_dir = os.path.join(args.output_dir, report_type) if not os.path.exists(report_dir): @@ -141,6 +147,10 @@ 'host classpath files. Host would typically be used for junit tests ' ' and device for tests that run on the device. Only used for xml and csv' ' reports.') + parser.add_argument('--include-substr-filter', + help='Substring that must be included in classjars.', + type=str, + default='') parser.add_argument('--output-dir', help='html report output directory.') parser.add_argument('--output-file', help='xml file to write device coverage results.') @@ -241,6 +251,7 @@ # report and we wouldn't know which one a developer needed. device_cmd = cmd + _GenerateReportOutputArgs(args, class_files, 'device') host_cmd = cmd + _GenerateReportOutputArgs(args, class_files, 'host') + device_exit_code = cmd_helper.RunCmd(device_cmd) host_exit_code = cmd_helper.RunCmd(host_cmd) exit_code = device_exit_code or host_exit_code
diff --git a/build/toolchain/apple/toolchain.gni b/build/toolchain/apple/toolchain.gni index 4191f9bf..7210cc20f 100644 --- a/build/toolchain/apple/toolchain.gni +++ b/build/toolchain/apple/toolchain.gni
@@ -494,7 +494,7 @@ } command = - "$_env_vars $_tool -module-name {{module_name}} " + + "$_env_vars $python_path $_tool -module-name {{module_name}} " + "-object-dir $_objects_dir " + "-module-path {{target_gen_dir}}/{{module_name}}.swiftmodule " + "-header-path {{target_gen_dir}}/{{module_name}}.h " +
diff --git a/build/toolchain/ios/swiftc.py b/build/toolchain/ios/swiftc.py old mode 100755 new mode 100644 index 2f4bb58d..a08dc8d --- a/build/toolchain/ios/swiftc.py +++ b/build/toolchain/ios/swiftc.py
@@ -1,5 +1,3 @@ -#!/usr/bin/python3 - # Copyright 2020 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.
diff --git a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/v2/FeedStream.java b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/v2/FeedStream.java index 1afbca9..5fb5949 100644 --- a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/v2/FeedStream.java +++ b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/v2/FeedStream.java
@@ -573,6 +573,9 @@ notifyContentChange(); } + // Dismiss bottomsheet if any is shown. + dismissBottomSheet(); + mContentManager.setHandlers(new HashMap<>()); mContentManager = null;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/page_info/ChromePageInfoControllerDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/page_info/ChromePageInfoControllerDelegate.java index 106deeb..9ec49e88 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/page_info/ChromePageInfoControllerDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/page_info/ChromePageInfoControllerDelegate.java
@@ -23,15 +23,12 @@ import org.chromium.base.supplier.Supplier; import org.chromium.chrome.R; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; -import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.instantapps.InstantAppsHandler; import org.chromium.chrome.browser.offlinepages.OfflinePageItem; import org.chromium.chrome.browser.offlinepages.OfflinePageUtils; import org.chromium.chrome.browser.offlinepages.OfflinePageUtils.OfflinePageLoadUrlDelegate; import org.chromium.chrome.browser.omnibox.ChromeAutocompleteSchemeClassifier; import org.chromium.chrome.browser.paint_preview.TabbedPaintPreview; -import org.chromium.chrome.browser.performance_hints.PerformanceHintsObserver; -import org.chromium.chrome.browser.performance_hints.PerformanceHintsObserver.PerformanceClass; import org.chromium.chrome.browser.previews.PreviewsAndroidBridge; import org.chromium.chrome.browser.previews.PreviewsUma; import org.chromium.chrome.browser.profiles.Profile; @@ -218,20 +215,6 @@ * {@inheritDoc} */ @Override - public boolean shouldShowPerformanceBadge(GURL url) { - if (!ChromeFeatureList.isEnabled(ChromeFeatureList.PAGE_INFO_PERFORMANCE_HINTS)) { - return false; - } - @PerformanceClass - int pagePerformanceClass = - PerformanceHintsObserver.getPerformanceClassForURL(mWebContents, url); - return pagePerformanceClass == PerformanceClass.PERFORMANCE_FAST; - } - - /** - * {@inheritDoc} - */ - @Override public void showSiteSettings(String url) { SiteSettingsHelper.showSiteSettings(mContext, url); }
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index eec795b..4e1c64b 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -307,7 +307,7 @@ Profile has been added successfully. This connection will be available to all users of this device. </message> <message name="IDS_CELLULAR_SETUP_ESIM_FINAL_PAGE_ERROR_MESSAGE" desc="Message displayed under title in final screen of eSIM cellular setup when ChromeOS encountered an error installing eSIM profiles."> - Unable to connect to a mobile network. For technical support, please contact your carrier. + Couldn't install eSIM profile. For help, please contact your carrier. </message> <message name="IDS_CELLULAR_SETUP_ESIM_PROFILE_DETECT_MESSAGE" desc="Message displayed during loading page in eSIM setup flow when looking for eSIM profiles."> Looking for available profiles...
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CELLULAR_SETUP_ESIM_FINAL_PAGE_ERROR_MESSAGE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CELLULAR_SETUP_ESIM_FINAL_PAGE_ERROR_MESSAGE.png.sha1 index ce97f7b..5c5b74af 100644 --- a/chrome/app/chromeos_strings_grdp/IDS_CELLULAR_SETUP_ESIM_FINAL_PAGE_ERROR_MESSAGE.png.sha1 +++ b/chrome/app/chromeos_strings_grdp/IDS_CELLULAR_SETUP_ESIM_FINAL_PAGE_ERROR_MESSAGE.png.sha1
@@ -1 +1 @@ -57b82e94e5ee46431fd4796fe0a7fb9aa101625a \ No newline at end of file +2aa097dcae4eb864d9ab85bfbac16164bd1a9e33 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings.grdp b/chrome/app/os_settings_strings.grdp index d9276cf4..8b8daaa 100644 --- a/chrome/app/os_settings_strings.grdp +++ b/chrome/app/os_settings_strings.grdp
@@ -2391,6 +2391,9 @@ <message name="IDS_SETTINGS_INTERNET_NETWORK_RENAME_INPUT_CHARACTER_COUNT" desc="Settings > Internet > Network details >Rename profile dialog: The Label for the dialog input that renames an eSIM cellular network, informing the user the number of characters they have inputted compared to the maximum number of characters allowed."> <ph name="CURRENT_CHARACTER_COUNT">$1<ex>15</ex></ph>/<ph name="MAX_CHARACTER_COUNT">$2<ex>20</ex></ph> </message> + <message name="IDS_SETTINGS_INTERNET_NETWORK_RENAME_DONE_BUTTON_A11Y_LABEL" desc="Settings > Internet > Network details >Rename profile dialog: The accessibility label for done button in the rename profile dialog."> + Rename profile to <ph name="PROFILE_NAME">$1<ex>Verizon</ex></ph> + </message> <message name="IDS_SETTINGS_INTERNET_NETWORK_RENAME_INPUT_A11Y_LABEL" desc="Settings > Internet > Network details >Rename profile dialog: The a11y label for the dialog input that renames an eSIM cellular network, informing the user that letters, numbers and special characters are allowed, as well as the maximum number of characters permitted."> Name can use letters, numbers, and special characters, and must be <ph name="MAX_CHARACTER_COUNT">$1<ex>20</ex></ph> characters or fewer </message>
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_INTERNET_NETWORK_RENAME_DONE_BUTTON_A11Y_LABEL.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_INTERNET_NETWORK_RENAME_DONE_BUTTON_A11Y_LABEL.png.sha1 new file mode 100644 index 0000000..791a3621 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_INTERNET_NETWORK_RENAME_DONE_BUTTON_A11Y_LABEL.png.sha1
@@ -0,0 +1 @@ +bf8e48875beec7d3acae86df2760b73f4aadfcc0 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 89d08e3..c0ba410 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -311,6 +311,8 @@ "component_updater/chrome_component_updater_configurator.h", "component_updater/chrome_origin_trials_component_installer.cc", "component_updater/chrome_origin_trials_component_installer.h", + "component_updater/client_side_phishing_component_installer.cc", + "component_updater/client_side_phishing_component_installer.h", "component_updater/component_updater_prefs.cc", "component_updater/component_updater_prefs.h", "component_updater/component_updater_utils.cc", @@ -2162,6 +2164,7 @@ "//components/reputation/core:proto", "//components/resources", "//components/safe_browsing/content/browser", + "//components/safe_browsing/content/browser:client_side_detection", "//components/safe_browsing/content/password_protection", "//components/safe_browsing/core:download_file_types_proto", "//components/safe_browsing/core:features",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 2b547d5f..d4ec0a1 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3204,6 +3204,9 @@ FEATURE_WITH_PARAMS_VALUE_TYPE(language::kOverrideTranslateTriggerInIndia, kTranslateForceTriggerOnEnglishVariations, "OverrideTranslateTriggerInIndia")}, + {"translate-intent", flag_descriptions::kTranslateIntentName, + flag_descriptions::kTranslateIntentDescription, kOsAndroid, + FEATURE_VALUE_TYPE(language::kTranslateIntent)}, #endif // OS_ANDROID {"override-language-prefs-for-href-translate", @@ -3924,8 +3927,8 @@ flag_descriptions::kExperimentalAccessibilityDictationListeningName, flag_descriptions::kExperimentalAccessibilityDictationListeningDescription, kOsCrOS, - SINGLE_VALUE_TYPE( - ::switches::kEnableExperimentalAccessibilityDictationListening)}, + FEATURE_VALUE_TYPE( + features::kExperimentalAccessibilityDictationListening)}, {"enable-experimental-accessibility-dictation-offline", flag_descriptions::kExperimentalAccessibilityDictationOfflineName, flag_descriptions::kExperimentalAccessibilityDictationOfflineDescription, @@ -6314,14 +6317,6 @@ #endif // !defined(OS_ANDROID) #if defined(OS_ANDROID) - {"page-info-performance-hints", - flag_descriptions::kPageInfoPerformanceHintsName, - flag_descriptions::kPageInfoPerformanceHintsDescription, kOsAndroid, - FEATURE_VALUE_TYPE( - performance_hints::features::kPageInfoPerformanceHints)}, -#endif // !defined(OS_ANDROID) - -#if defined(OS_ANDROID) {"page-info-version-2", flag_descriptions::kPageInfoV2Name, flag_descriptions::kPageInfoV2Description, kOsAndroid, FEATURE_VALUE_TYPE(page_info::kPageInfoV2)},
diff --git a/chrome/browser/apps/app_service/webapk/webapk_install_task.cc b/chrome/browser/apps/app_service/webapk/webapk_install_task.cc index 75e90b8b..e995ed1 100644 --- a/chrome/browser/apps/app_service/webapk/webapk_install_task.cc +++ b/chrome/browser/apps/app_service/webapk/webapk_install_task.cc
@@ -24,6 +24,7 @@ #include "components/arc/arc_service_manager.h" #include "components/arc/mojom/webapk.mojom.h" #include "components/arc/session/arc_bridge_service.h" +#include "components/services/app_service/public/cpp/share_target.h" #include "components/version_info/version_info.h" #include "components/webapk/webapk.pb.h" #include "content/public/browser/browser_context.h" @@ -124,7 +125,10 @@ auto& registrar = web_app_provider_->registrar(); - if (!registrar.IsInstalled(app_id_)) { + // This is already checked in WebApkManager, check again in case anything + // changed while the install request was queued. + if (!registrar.IsInstalled(app_id_) || + !registrar.GetAppShareTarget(app_id_)) { std::move(callback).Run(false); return; } @@ -171,7 +175,34 @@ web_app_manifest->set_start_url(registrar.GetAppStartUrl(app_id_).spec()); web_app_manifest->add_scopes(registrar.GetAppScope(app_id_).spec()); - // TODO(crbug.com/1198433): Fill in Share Target. + auto* share_target = registrar.GetAppShareTarget(app_id_); + webapk::ShareTarget* proto_share_target = + web_app_manifest->add_share_targets(); + proto_share_target->set_action(share_target->action.spec()); + proto_share_target->set_method( + apps::ShareTarget::MethodToString(share_target->method)); + proto_share_target->set_enctype( + apps::ShareTarget::EnctypeToString(share_target->enctype)); + + webapk::ShareTargetParams* proto_params = + proto_share_target->mutable_params(); + if (!share_target->params.title.empty()) { + proto_params->set_title(share_target->params.title); + } + if (!share_target->params.text.empty()) { + proto_params->set_text(share_target->params.text); + } + if (!share_target->params.url.empty()) { + proto_params->set_url(share_target->params.url); + } + + for (const auto& file : share_target->params.files) { + webapk::ShareTargetParamsFile* proto_file = proto_params->add_files(); + proto_file->set_name(file.name); + for (const auto& accept_type : file.accept) { + proto_file->add_accept(accept_type); + } + } webapk::Image* image = web_app_manifest->add_icons(); image->set_src(std::move(icon_url));
diff --git a/chrome/browser/apps/app_service/webapk/webapk_install_task_unittest.cc b/chrome/browser/apps/app_service/webapk/webapk_install_task_unittest.cc index 8187705..be2a99d7 100644 --- a/chrome/browser/apps/app_service/webapk/webapk_install_task_unittest.cc +++ b/chrome/browser/apps/app_service/webapk/webapk_install_task_unittest.cc
@@ -31,8 +31,10 @@ namespace { constexpr char kTestAppUrl[] = "https://www.example.com/"; +constexpr char kTestAppActionUrl[] = "https://www.example.com/share"; constexpr char kTestAppIcon[] = "https://www.example.com/icon.png"; constexpr char kTestManifestUrl[] = "https://www.example.com/manifest.json"; +constexpr char kTestShareTextParam[] = "share_text"; const std::u16string kTestAppTitle = u"Test App"; constexpr char kServerPath[] = "/webapk"; @@ -62,7 +64,7 @@ return response; } -std::unique_ptr<WebApplicationInfo> BuildWebAppInfo() { +std::unique_ptr<WebApplicationInfo> BuildDefaultWebAppInfo() { auto app_info = std::make_unique<WebApplicationInfo>(); app_info->start_url = GURL(kTestAppUrl); app_info->scope = GURL(kTestAppUrl); @@ -74,8 +76,16 @@ icon.url = GURL(kTestAppIcon); app_info->icon_infos.push_back(icon); + apps::ShareTarget target; + target.action = GURL(kTestAppActionUrl); + target.method = apps::ShareTarget::Method::kPost; + target.enctype = apps::ShareTarget::Enctype::kMultipartFormData; + target.params.text = kTestShareTextParam; + app_info->share_target = target; + return app_info; } + } // namespace class WebApkInstallTaskTest : public testing::Test { @@ -171,7 +181,8 @@ }; TEST_F(WebApkInstallTaskTest, SuccessfulInstall) { - auto app_id = web_app::test::InstallWebApp(profile(), BuildWebAppInfo()); + auto app_id = + web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo()); SetWebApkResponse(base::BindRepeating(&BuildValidWebApkResponse, "org.chromium.webapk.some_package")); @@ -180,16 +191,53 @@ ASSERT_EQ(last_webapk_request()->manifest_url(), kTestManifestUrl); const webapk::WebAppManifest& manifest = last_webapk_request()->manifest(); - ASSERT_EQ(manifest.short_name(), "Test App"); - ASSERT_EQ(manifest.start_url(), kTestAppUrl); - ASSERT_EQ(manifest.icons(0).src(), kTestAppIcon); + EXPECT_EQ(manifest.short_name(), "Test App"); + EXPECT_EQ(manifest.start_url(), kTestAppUrl); + EXPECT_EQ(manifest.icons(0).src(), kTestAppIcon); ASSERT_EQ(fake_webapk_instance()->handled_packages().size(), 1); ASSERT_EQ(fake_webapk_instance()->handled_packages()[0], "org.chromium.webapk.some_package"); } -TEST_F(WebApkInstallTaskTest, InvalidManifest) { +TEST_F(WebApkInstallTaskTest, ShareTarget) { + auto web_app_info = BuildDefaultWebAppInfo(); + + apps::ShareTarget share_target; + share_target.action = GURL("https://www.example.com/new"); + share_target.method = apps::ShareTarget::Method::kPost; + share_target.enctype = apps::ShareTarget::Enctype::kFormUrlEncoded; + share_target.params.text = "share_text"; + share_target.params.url = "share_url"; + apps::ShareTarget::Files files1; + files1.name = "images"; + files1.accept = {"image/*"}; + apps::ShareTarget::Files files2; + files2.name = "videos"; + files2.accept = {"video/mp4", "video/quicktime"}; + share_target.params.files = {files1, files2}; + web_app_info->share_target = share_target; + + auto app_id = + web_app::test::InstallWebApp(profile(), std::move(web_app_info)); + + SetWebApkResponse(base::BindRepeating(&BuildValidWebApkResponse, + "org.chromium.webapk.some_package")); + + EXPECT_TRUE(InstallWebApk(app_id)); + + const webapk::WebAppManifest& manifest = last_webapk_request()->manifest(); + EXPECT_EQ(manifest.share_targets(0).action(), "https://www.example.com/new"); + EXPECT_EQ(manifest.share_targets(0).params().text(), "share_text"); + EXPECT_EQ(manifest.share_targets(0).params().url(), "share_url"); + EXPECT_FALSE(manifest.share_targets(0).params().has_title()); + EXPECT_EQ(manifest.share_targets(0).params().files(0).name(), "images"); + EXPECT_EQ(manifest.share_targets(0).params().files(0).accept_size(), 1); + EXPECT_EQ(manifest.share_targets(0).params().files(0).accept(0), "image/*"); + EXPECT_EQ(manifest.share_targets(0).params().files(1).accept_size(), 2); +} + +TEST_F(WebApkInstallTaskTest, NoIconInManifest) { auto app_info = std::make_unique<WebApplicationInfo>(); app_info->start_url = GURL(kTestAppUrl); app_info->scope = GURL(kTestAppUrl); @@ -201,7 +249,8 @@ } TEST_F(WebApkInstallTaskTest, FailedServerCall) { - auto app_id = web_app::test::InstallWebApp(profile(), BuildWebAppInfo()); + auto app_id = + web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo()); SetWebApkResponse(base::BindRepeating(&BuildFailedResponse)); @@ -211,7 +260,8 @@ } TEST_F(WebApkInstallTaskTest, FailedArcInstall) { - auto app_id = web_app::test::InstallWebApp(profile(), BuildWebAppInfo()); + auto app_id = + web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo()); SetWebApkResponse(base::BindRepeating(&BuildValidWebApkResponse, "org.chromium.webapk.some_package"));
diff --git a/chrome/browser/ash/accessibility/dictation.cc b/chrome/browser/ash/accessibility/dictation.cc index 9f529f0..e431ee2 100644 --- a/chrome/browser/ash/accessibility/dictation.cc +++ b/chrome/browser/ash/accessibility/dictation.cc
@@ -18,6 +18,7 @@ #include "content/public/browser/storage_partition.h" #include "services/audio/public/cpp/sounds/sounds_manager.h" #include "services/network/public/cpp/shared_url_loader_factory.h" +#include "ui/accessibility/accessibility_features.h" #include "ui/accessibility/accessibility_switches.h" #include "ui/base/ime/chromeos/extension_ime_util.h" #include "ui/base/ime/chromeos/ime_bridge.h" @@ -116,7 +117,7 @@ base::UmaHistogramBoolean("Accessibility.CrosDictation.UsedOnDeviceSpeech", false); no_speech_timeout_ = - switches::IsExperimentalAccessibilityDictationListeningEnabled() + features::IsExperimentalAccessibilityDictationListeningEnabled() ? kDeviceNoSpeechTimeout : kNetworkNoSpeechTimeout; no_new_speech_timeout_ = kNetworkNoNewSpeechTimeout; @@ -149,7 +150,7 @@ StartSpeechTimeout(no_speech_timeout_); } else { StartSpeechTimeout( - switches::IsExperimentalAccessibilityDictationListeningEnabled() + features::IsExperimentalAccessibilityDictationListeningEnabled() ? no_speech_timeout_ : no_new_speech_timeout_); // If ChromeVox is enabled, we don't want to show intermediate results @@ -161,7 +162,7 @@ input_context->UpdateCompositionText(*composition_, 0, true); return; } - if (switches::IsExperimentalAccessibilityDictationListeningEnabled()) { + if (features::IsExperimentalAccessibilityDictationListeningEnabled()) { CommitCurrentText(); } else { // Turn off after finalized speech.
diff --git a/chrome/browser/ash/accessibility/dictation_browsertest.cc b/chrome/browser/ash/accessibility/dictation_browsertest.cc index e3d2e69b..8254b10 100644 --- a/chrome/browser/ash/accessibility/dictation_browsertest.cc +++ b/chrome/browser/ash/accessibility/dictation_browsertest.cc
@@ -19,6 +19,7 @@ #include "content/public/test/browser_test.h" #include "content/public/test/fake_speech_recognition_manager.h" #include "media/mojo/mojom/speech_recognition_service.mojom.h" +#include "ui/accessibility/accessibility_features.h" #include "ui/accessibility/accessibility_switches.h" #include "ui/base/ime/chromeos/ime_bridge.h" #include "ui/base/ime/chromeos/mock_ime_input_context_handler.h" @@ -84,8 +85,11 @@ void SetUpCommandLine(base::CommandLine* command_line) override { if (GetParam().first == kTestWithLongerListening) { - command_line->AppendSwitch( - switches::kEnableExperimentalAccessibilityDictationListening); + scoped_feature_list_.InitAndEnableFeature( + features::kExperimentalAccessibilityDictationListening); + } else { + scoped_feature_list_.InitAndDisableFeature( + features::kExperimentalAccessibilityDictationListening); } if (GetParam().second == kOnDeviceRecognition) { command_line->AppendSwitch( @@ -222,6 +226,8 @@ // For on-device recognition. // Unowned. speech::FakeSpeechRecognitionService* fake_service_; + + base::test::ScopedFeatureList scoped_feature_list_; }; INSTANTIATE_TEST_SUITE_P(
diff --git a/chrome/browser/ash/login/users/avatar/user_image_manager.h b/chrome/browser/ash/login/users/avatar/user_image_manager.h index 9f384a09..23f03e99 100644 --- a/chrome/browser/ash/login/users/avatar/user_image_manager.h +++ b/chrome/browser/ash/login/users/avatar/user_image_manager.h
@@ -31,6 +31,9 @@ // There is an instance of this class for each user in the system. class UserImageManager { public: + // Converts `image_index` to UMA histogram value. + static int ImageIndexToHistogramIndex(int image_index); + // Registers user image manager preferences. static void RegisterPrefs(PrefRegistrySimple* registry);
diff --git a/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc b/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc index e66bd7f..258de39 100644 --- a/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc +++ b/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc
@@ -50,33 +50,17 @@ namespace { -// Delay betweeen user login and attempt to update user's profile data. +// Delay between user login and attempt to update user's profile data. const int kProfileDataDownloadDelaySec = 10; -// Interval betweeen retries to update user's profile data. +// Interval between retries to update user's profile data. const int kProfileDataDownloadRetryIntervalSec = 300; -// Delay betweeen subsequent profile refresh attempts (24 hrs). +// Delay between subsequent profile refresh attempts (24 hrs). const int kProfileRefreshIntervalSec = 24 * 3600; static bool g_ignore_profile_data_download_delay_ = false; -// Converts `image_index` to UMA histogram value. -int ImageIndexToHistogramIndex(int image_index) { - switch (image_index) { - case user_manager::User::USER_IMAGE_EXTERNAL: - return default_user_image::kHistogramImageExternal; - case user_manager::User::USER_IMAGE_PROFILE: - return default_user_image::kHistogramImageFromProfile; - default: - // Create a gap in histogram values for - // [kHistogramImageExternal and kHistogramImageFromProfile] block to fit. - if (image_index < default_user_image::kHistogramImageExternal) - return image_index; - return image_index + default_user_image::kHistogramSpecialImagesCount; - } -} - // Saves `image_bytes` at `image_path`, and delete the old file at // `old_image_path` if needed. bool SaveAndDeleteImage(scoped_refptr<base::RefCountedBytes> image_bytes, @@ -131,6 +115,22 @@ const char UserImageManagerImpl::kImageURLNodeName[] = "url"; // static +int UserImageManager::ImageIndexToHistogramIndex(int image_index) { + switch (image_index) { + case user_manager::User::USER_IMAGE_EXTERNAL: + return default_user_image::kHistogramImageExternal; + case user_manager::User::USER_IMAGE_PROFILE: + return default_user_image::kHistogramImageFromProfile; + default: + // Create a gap in histogram values for + // [kHistogramImageExternal and kHistogramImageFromProfile] block to fit. + if (image_index < default_user_image::kHistogramImageExternal) + return image_index; + return image_index + default_user_image::kHistogramSpecialImagesCount; + } +} + +// static void UserImageManager::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(UserImageManagerImpl::kUserImageProperties); }
diff --git a/chrome/browser/ash/web_applications/help_app/help_app_integration_browsertest.cc b/chrome/browser/ash/web_applications/help_app/help_app_integration_browsertest.cc index 7fad635d..f59658e 100644 --- a/chrome/browser/ash/web_applications/help_app/help_app_integration_browsertest.cc +++ b/chrome/browser/ash/web_applications/help_app/help_app_integration_browsertest.cc
@@ -6,10 +6,13 @@ #include <vector> #include "ash/constants/ash_features.h" +#include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/metrics/user_action_tester.h" #include "base/test/scoped_feature_list.h" +#include "base/time/time.h" +#include "base/timer/timer.h" #include "build/branding_buildflags.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -44,6 +47,8 @@ #include "content/public/test/browser_test.h" #include "content/public/test/test_navigation_observer.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/idle/idle.h" +#include "ui/base/idle/scoped_set_idle_state.h" #include "ui/display/screen.h" #include "ui/display/types/display_constants.h" #include "ui/events/keycodes/keyboard_codes.h" @@ -442,6 +447,88 @@ run_loop.Run(); } +// Test that the Help App background task works. +// It should open and update the index for launcher search, then close. +IN_PROC_BROWSER_TEST_P(HelpAppIntegrationTest, + HelpAppV2BackgroundTaskUpdatesLauncherSearchIndex) { + WaitForTestSystemAppInstall(); + ui::ScopedSetIdleState idle(ui::IDLE_STATE_IDLE); + + const GURL bg_task_url("chrome://help-app/background"); + content::TestNavigationObserver navigation_observer(bg_task_url); + navigation_observer.StartWatchingNewWebContents(); + + // Wait for system apps background tasks to start. + base::RunLoop run_loop; + web_app::WebAppProvider::Get(browser()->profile()) + ->system_web_app_manager() + .on_tasks_started() + .Post(FROM_HERE, run_loop.QuitClosure()); + run_loop.Run(); + + auto& tasks = GetManager().GetBackgroundTasksForTesting(); + + // Find the help app's background task. + const auto& help_task = std::find_if( + tasks.begin(), tasks.end(), + [&bg_task_url]( + const std::unique_ptr<web_app::SystemAppBackgroundTask>& x) { + return x->url_for_testing() == bg_task_url; + }); + ASSERT_NE(help_task, tasks.end()); + + auto* timer = help_task->get()->get_timer_for_testing(); + EXPECT_EQ(web_app::SystemAppBackgroundTask::INITIAL_WAIT, + help_task->get()->get_state_for_testing()); + // The "Immediate" timer waits for several minutes, and it's hard to mock time + // properly in a browser test, so just fire the timer now. We're not testing + // that base::Timer works. + timer->FireNow(); + + navigation_observer.Wait(); + + // Wait until the background page closes. It's closed when the web contents + // becomes null. + // TODO(b/186819234): Add a way to wait for the task instead of polling. + base::RunLoop bg_page_run_loop; + base::RepeatingTimer check_timer; + check_timer.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(10), + base::BindLambdaForTesting([&]() { + if (help_task->get()->web_contents_for_testing()) + return; + bg_page_run_loop.QuitClosure().Run(); + })); + bg_page_run_loop.Run(); + + EXPECT_EQ(help_task->get()->opened_count_for_testing(), 1u); + +// TODO(b/187231134): Replace this with a single build flag. +#if !BUILDFLAG(IS_CHROMEOS_ASH) || !BUILDFLAG(GOOGLE_CHROME_BRANDING) + // This part only works in non-branded builds because it uses fake data added + // by the mock app. + // Search using the search handler to confirm that the update happened. + base::RunLoop search_run_loop; + chromeos::help_app::HelpAppManagerFactory::GetForBrowserContext(profile()) + ->search_handler() + ->Search(u"verycomplicatedsearchquery", + /*max_num_results=*/1u, + base::BindLambdaForTesting( + [&](std::vector<chromeos::help_app::mojom::SearchResultPtr> + search_results) { + ASSERT_EQ(search_results.size(), 1u); + EXPECT_EQ(search_results[0]->id, "mock-app-test-id"); + EXPECT_EQ(search_results[0]->title, u"Title"); + EXPECT_EQ(search_results[0]->main_category, u"Help"); + EXPECT_EQ(search_results[0]->locale, ""); + EXPECT_EQ(search_results[0]->url_path_with_parameters, + "help/sub/3399763/"); + EXPECT_GT(search_results[0]->relevance_score, 0.01); + search_run_loop.QuitClosure().Run(); + })); + search_run_loop.Run(); +#endif +} + // Test that the Help App opens when Gesture help requested. IN_PROC_BROWSER_TEST_P(HelpAppAllProfilesIntegrationTest, HelpAppOpenGestures) { WaitForTestSystemAppInstall();
diff --git a/chrome/browser/cart/cart_handler.cc b/chrome/browser/cart/cart_handler.cc index 5162448..ea9dc57 100644 --- a/chrome/browser/cart/cart_handler.cc +++ b/chrome/browser/cart/cart_handler.cc
@@ -65,6 +65,7 @@ bool success, std::vector<CartDB::KeyAndValue> res) { std::vector<chrome_cart::mojom::MerchantCartPtr> carts; + bool show_discount = cart_service_->IsCartDiscountEnabled(); for (CartDB::KeyAndValue proto_pair : res) { auto cart = chrome_cart::mojom::MerchantCart::New(); cart->merchant = std::move(proto_pair.second.merchant()); @@ -75,8 +76,10 @@ for (std::string image_url : proto_pair.second.product_image_urls()) { cart->product_image_urls.emplace_back(std::move(image_url)); } - cart->discount_text = - std::move(proto_pair.second.discount_info().discount_text()); + if (show_discount) { + cart->discount_text = + std::move(proto_pair.second.discount_info().discount_text()); + } } carts.push_back(std::move(cart)); }
diff --git a/chrome/browser/cart/cart_handler_unittest.cc b/chrome/browser/cart/cart_handler_unittest.cc index 2a117194..a3baecf 100644 --- a/chrome/browser/cart/cart_handler_unittest.cc +++ b/chrome/browser/cart/cart_handler_unittest.cc
@@ -390,8 +390,8 @@ run_loop[run_loop_index++].Run(); } -// Verifies discount data fetching. -TEST_F(CartHandlerNtpModuleTest, TestDiscountDataFetching) { +// Verifies discount data not showing with RBD disabled. +TEST_F(CartHandlerNtpModuleTest, TestDiscountDataWithoutFeature) { base::RunLoop run_loop[7]; int run_loop_index = 0; // Add a cart with discount. @@ -401,29 +401,17 @@ service_->AddCart(kMockMerchantBKey, base::nullopt, merchant_proto); task_environment_.RunUntilIdle(); - // Discount should not show in welcome surface. + // Skip the welcome surface stage as discount is not showing for welcome + // surface. for (int i = 0; i < CartService::kWelcomSurfaceShowLimit; i++) { - // Build a callback result without discount. - auto expect_cart = chrome_cart::mojom::MerchantCart::New(); - expect_cart->merchant = kMockMerchantB; - expect_cart->cart_url = GURL(kMockMerchantURLB); - std::vector<chrome_cart::mojom::MerchantCartPtr> carts; - carts.push_back(std::move(expect_cart)); - handler_->GetWarmWelcomeVisible(base::BindOnce( - &CartHandlerTest::GetEvaluationBoolResult, base::Unretained(this), - run_loop[run_loop_index].QuitClosure(), true)); - run_loop[run_loop_index++].Run(); - handler_->GetMerchantCarts(base::BindOnce( - &GetEvaluationMerchantCarts, run_loop[run_loop_index].QuitClosure(), - std::move(carts))); - run_loop[run_loop_index++].Run(); + service_->IncreaseWelcomeSurfaceCounter(); } + ASSERT_FALSE(service_->ShouldShowWelcomeSurface()); - // Discount should show in normal cart module. + // Discount should not show in normal cart module with RBD disabled. auto expect_cart = chrome_cart::mojom::MerchantCart::New(); expect_cart->merchant = kMockMerchantB; expect_cart->cart_url = GURL(kMockMerchantURLB); - expect_cart->discount_text = "15% off"; std::vector<chrome_cart::mojom::MerchantCartPtr> carts; carts.push_back(std::move(expect_cart)); handler_->GetMerchantCarts( @@ -514,3 +502,49 @@ handler_->SetDiscountEnabled(false); ASSERT_FALSE(service_->IsCartDiscountEnabled()); } + +// Verifies discount data showing with RBD enabled. +TEST_F(CartHandlerNtpModuleDiscountTest, TestDiscountDataWithFeature) { + base::RunLoop run_loop[7]; + int run_loop_index = 0; + // Add a cart with discount. Mock that welcome surface hasn't shown and RBD is + // enabled. + cart_db::ChromeCartContentProto merchant_proto = + BuildProto(kMockMerchantBKey, kMockMerchantB, kMockMerchantURLB); + merchant_proto.mutable_discount_info()->set_discount_text("15% off"); + service_->AddCart(kMockMerchantBKey, base::nullopt, merchant_proto); + task_environment_.RunUntilIdle(); + profile_.GetPrefs()->SetInteger(prefs::kCartModuleWelcomeSurfaceShownTimes, + 0); + profile_.GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, true); + + // Discount should not show in welcome surface. + for (int i = 0; i < CartService::kWelcomSurfaceShowLimit; i++) { + // Build a callback result without discount. + auto expect_cart = chrome_cart::mojom::MerchantCart::New(); + expect_cart->merchant = kMockMerchantB; + expect_cart->cart_url = GURL(kMockMerchantURLB); + std::vector<chrome_cart::mojom::MerchantCartPtr> carts; + carts.push_back(std::move(expect_cart)); + handler_->GetWarmWelcomeVisible(base::BindOnce( + &CartHandlerTest::GetEvaluationBoolResult, base::Unretained(this), + run_loop[run_loop_index].QuitClosure(), true)); + run_loop[run_loop_index++].Run(); + handler_->GetMerchantCarts(base::BindOnce( + &GetEvaluationMerchantCarts, run_loop[run_loop_index].QuitClosure(), + std::move(carts))); + run_loop[run_loop_index++].Run(); + } + + // Discount should show in normal cart module with RBD enabled. + auto expect_cart = chrome_cart::mojom::MerchantCart::New(); + expect_cart->merchant = kMockMerchantB; + expect_cart->cart_url = GURL(kMockMerchantURLB); + expect_cart->discount_text = "15% off"; + std::vector<chrome_cart::mojom::MerchantCartPtr> carts; + carts.push_back(std::move(expect_cart)); + handler_->GetMerchantCarts( + base::BindOnce(&GetEvaluationMerchantCarts, + run_loop[run_loop_index].QuitClosure(), std::move(carts))); + run_loop[run_loop_index++].Run(); +}
diff --git a/chrome/browser/chromeos/chromebox_for_meetings/device_info/device_info_service.cc b/chrome/browser/chromeos/chromebox_for_meetings/device_info/device_info_service.cc index 2c2dbba..a34df7c 100644 --- a/chrome/browser/chromeos/chromebox_for_meetings/device_info/device_info_service.cc +++ b/chrome/browser/chromeos/chromebox_for_meetings/device_info/device_info_service.cc
@@ -126,8 +126,8 @@ policy_info->timestamp_ms = policy_data->timestamp(); } - if (policy_data->has_device_id()) { - policy_info->device_id = policy_data->device_id(); + if (policy_data->has_directory_api_id()) { + policy_info->device_id = policy_data->directory_api_id(); } if (policy_data->has_service_account_identity()) { @@ -140,6 +140,10 @@ &policy_info->service_account_gaia_id); } + if (policy_data->has_device_id()) { + policy_info->cros_device_id = policy_data->device_id(); + } + if (current_policy_info_.Equals(policy_info)) { return; }
diff --git a/chrome/browser/chromeos/chromebox_for_meetings/device_info/device_info_service_unittest.cc b/chrome/browser/chromeos/chromebox_for_meetings/device_info/device_info_service_unittest.cc index e0e5327..1891c33 100644 --- a/chrome/browser/chromeos/chromebox_for_meetings/device_info/device_info_service_unittest.cc +++ b/chrome/browser/chromeos/chromebox_for_meetings/device_info/device_info_service_unittest.cc
@@ -71,14 +71,16 @@ } void UpdatePolicyInfo(int64_t timestamp, - std::string device_id, + std::string directory_api_id, std::string service_account_id, - int64_t gaia_id) { + int64_t gaia_id, + std::string cros_device_id) { device_policy_.policy_data().set_timestamp(timestamp); - device_policy_.policy_data().set_device_id(device_id); + device_policy_.policy_data().set_directory_api_id(directory_api_id); device_policy_.policy_data().set_service_account_identity( service_account_id); device_policy_.policy_data().set_gaia_id(base::NumberToString(gaia_id)); + device_policy_.policy_data().set_device_id(cros_device_id); device_policy_.Build(); session_manager_client_.set_device_policy(device_policy_.GetBlob()); ash::DeviceSettingsService::Get()->Load(); @@ -166,19 +168,22 @@ run_loop.RunUntilIdle(); int64_t timestamp = 10; - std::string device_id = "device_id"; + std::string directory_api_id = "device_id"; std::string service_account_id = "service_account_id"; int64_t gaia_id = 20; - UpdatePolicyInfo(timestamp, device_id, service_account_id, gaia_id); + std::string cros_device_id = "cros_device_id"; + UpdatePolicyInfo(timestamp, directory_api_id, service_account_id, gaia_id, + cros_device_id); base::RunLoop mojo_loop; details_remote->GetPolicyInfo( base::BindLambdaForTesting([&](mojom::PolicyInfoPtr policy_ptr) { ASSERT_EQ(timestamp, policy_ptr->timestamp_ms); - ASSERT_EQ(device_id, policy_ptr->device_id); + ASSERT_EQ(directory_api_id, policy_ptr->device_id); ASSERT_EQ(service_account_id, policy_ptr->service_account_email_address); ASSERT_EQ(gaia_id, policy_ptr->service_account_gaia_id); + ASSERT_EQ(cros_device_id, policy_ptr->cros_device_id); mojo_loop.Quit(); })); mojo_loop.Run();
diff --git a/chrome/browser/chromeos/full_restore/app_launch_handler_browsertest.cc b/chrome/browser/chromeos/full_restore/app_launch_handler_browsertest.cc index 6b0a47d..6a857481 100644 --- a/chrome/browser/chromeos/full_restore/app_launch_handler_browsertest.cc +++ b/chrome/browser/chromeos/full_restore/app_launch_handler_browsertest.cc
@@ -41,7 +41,12 @@ #include "components/arc/mojom/app.mojom.h" #include "components/arc/session/arc_bridge_service.h" #include "components/arc/test/fake_app_instance.h" +#include "components/exo/buffer.h" #include "components/exo/shell_surface_util.h" +#include "components/exo/surface.h" +#include "components/exo/test/exo_test_helper.h" +#include "components/exo/wm_helper.h" +#include "components/exo/wm_helper_chromeos.h" #include "components/full_restore/app_launch_info.h" #include "components/full_restore/full_restore_info.h" #include "components/full_restore/full_restore_read_handler.h" @@ -56,6 +61,7 @@ #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/base/window_open_disposition.h" +#include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/display/types/display_constants.h" #include "ui/wm/core/window_util.h" @@ -94,6 +100,17 @@ constexpr chromeos::WindowStateType kWindowStateType = chromeos::WindowStateType::kLeftSnapped; +void RemoveInactiveDesks() { + // Removes all the inactive desks and waits for their async operations to + // complete. + while (true) { + base::RunLoop run_loop; + if (!ash::AutotestDesksApi().RemoveActiveDesk(run_loop.QuitClosure())) + break; + run_loop.Run(); + } +} + class TestFullRestoreInfoObserver : public ::full_restore::FullRestoreInfo::Observer { public: @@ -160,6 +177,7 @@ ::full_restore::WindowInfo window_info; window_info.window = window; window_info.activation_index = activation_index; + window_info.desk_id = kDeskId; window_info.current_bounds = kCurrentBounds; window_info.window_state_type = window_state_type; ::full_restore::SaveWindowInfo(window_info); @@ -243,7 +261,9 @@ class AppLaunchHandlerBrowserTest : public extensions::PlatformAppBrowserTest { public: - AppLaunchHandlerBrowserTest() { + AppLaunchHandlerBrowserTest() + : faster_animations_( + ui::ScopedAnimationDurationScaleMode::ZERO_DURATION) { scoped_feature_list_.InitAndEnableFeature(ash::features::kFullRestore); } ~AppLaunchHandlerBrowserTest() override = default; @@ -285,6 +305,7 @@ private: base::test::ScopedFeatureList scoped_feature_list_; + ui::ScopedAnimationDurationScaleMode faster_animations_; }; IN_PROC_BROWSER_TEST_F(AppLaunchHandlerBrowserTest, NotLaunchBrowser) { @@ -624,12 +645,7 @@ ASSERT_FALSE(GetWindowInfo(restore_window_id)); // Remove the added desks. - while (true) { - base::RunLoop run_loop; - if (!ash::AutotestDesksApi().RemoveActiveDesk(run_loop.QuitClosure())) - break; - run_loop.Run(); - } + RemoveInactiveDesks(); } IN_PROC_BROWSER_TEST_F(AppLaunchHandlerBrowserTest, RestoreMinimizedChromeApp) { @@ -1024,15 +1040,17 @@ int32_t kTaskId1 = 100; CreateTask(app_id1, kTaskId1, session_id1); - // Create the window for the app1. + // Create the window for the app1 and store its bounds. views::Widget* widget1 = CreateExoWindow("org.chromium.arc.100"); aura::Window* window1 = widget1->GetNativeWindow(); + gfx::Rect pre_restore_bounds_1 = window1->GetBoundsInScreen(); - // Create the window for the app2. The task id needs to match the - // |window_app_id| arg of CreateExoWindow. + // Create the window for the app2 and store its bounds. The task id needs to + // match the |window_app_id| arg of CreateExoWindow. int32_t kTaskId2 = 101; views::Widget* widget2 = CreateExoWindow("org.chromium.arc.101"); aura::Window* window2 = widget2->GetNativeWindow(); + gfx::Rect pre_restore_bounds_2 = window2->GetBoundsInScreen(); // Simulate creating kTaskId2. CreateTask(app_id2, kTaskId2, session_id2); @@ -1076,6 +1094,7 @@ VerifyWindowProperty(window1, kTaskId3, ::full_restore::kParentToHiddenContainer, /*hidden=*/true); + EXPECT_EQ(pre_restore_bounds_1, window1->GetBoundsInScreen()); // Simulate creating tasks for apps. CreateTask(app_id1, kTaskId3, session_id3); @@ -1086,6 +1105,7 @@ // Create the window to simulate the restoration for the app2. widget2 = CreateExoWindow("org.chromium.arc.202"); window2 = widget2->GetNativeWindow(); + EXPECT_EQ(pre_restore_bounds_2, window2->GetBoundsInScreen()); VerifyObserver(window1, /*launch_count=*/1, /*init_count=*/2); VerifyObserver(window2, /*launch_count=*/1, /*init_count=*/1); @@ -1108,6 +1128,102 @@ StopInstance(); } +// Tests that an ARC app's properties are restored when its surface is created. +IN_PROC_BROWSER_TEST_F(AppLaunchHandlerArcAppBrowserTest, + RestoreArcAppWindowProperties) { + constexpr int32_t kPreRestoreTaskId = 100; + const int32_t kPreRestoreSessionId = + ::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId(); + constexpr char kPreRestoreWindowAppId[] = "org.chromium.arc.100"; + + constexpr int32_t kRestoreTaskId = 200; + constexpr int32_t kRestoreSessionId = + ::full_restore::kArcSessionIdOffsetForRestoredLaunching + 1; + constexpr char kRestoreWindowAppId[] = "org.chromium.arc.200"; + + // Create four desks in total. + ash::AutotestDesksApi().CreateNewDesk(); + ash::AutotestDesksApi().CreateNewDesk(); + ash::AutotestDesksApi().CreateNewDesk(); + + // Setup ARC app. + SetProfile(); + InstallTestApps(kTestAppPackage, false); + const std::string kAppId = GetTestApp1Id(kTestAppPackage); + ::full_restore::FullRestoreInfo::GetInstance()->AddObserver( + test_full_restore_info_observer()); + SaveAppLaunchInfo(kAppId, kPreRestoreSessionId); + + // Create the arc app. + views::Widget* arc_widget = CreateExoWindow(kPreRestoreWindowAppId); + aura::Window* arc_window = arc_widget->GetNativeWindow(); + VerifyObserver(arc_window, /*launch_count=*/0, /*init_count=*/0); + VerifyWindowProperty(arc_window, kPreRestoreTaskId, /*restore_window_id=*/0, + /*hidden=*/false); + + // Simulate creating the task. + CreateTask(kAppId, kPreRestoreTaskId, kPreRestoreSessionId); + VerifyObserver(arc_window, /*launch_count=*/1, /*init_count=*/0); + + // Save the arc app as left snapped. + SaveWindowInfo(arc_window, kActivationIndex, kWindowStateType); + WaitForAppLaunchInfoSaved(); + + // Close the widget, simulating logging off. + Restore(); + arc_widget->CloseNow(); + app_host()->OnTaskDestroyed(kPreRestoreTaskId); + + // Recreate the window, simulating its restoration. Task id needs to match the + // `kWindowAppId` arg of `CreateArcApp()`. + arc_widget = CreateExoWindow(kRestoreWindowAppId); + arc_window = arc_widget->GetNativeWindow(); + + // Recreate the task. + CreateTask(kAppId, kRestoreTaskId, kRestoreSessionId); + VerifyObserver(arc_window, /*launch_count=*/1, /*init_count=*/2); + VerifyWindowProperty(arc_window, kRestoreTaskId, kPreRestoreTaskId, + /*hidden=*/false); + VerifyWindowInfo(arc_window, kActivationIndex, kWindowStateType); + + // Create a `ClientControlledShellSurface` for this task. + exo::test::ExoTestHelper exo_test_helper; + std::unique_ptr<exo::WMHelper> wm_helper = + std::make_unique<exo::WMHelperChromeOS>(); + wm_helper->RegisterAppPropertyResolver( + std::make_unique<ExoAppTypeResolver>()); + auto surface = std::make_unique<exo::Surface>(); + auto shell_surface = + exo_test_helper.CreateClientControlledShellSurface(surface.get()); + shell_surface->SetApplicationId(kRestoreWindowAppId); + auto surface_buffer = std::make_unique<exo::Buffer>( + exo_test_helper.CreateGpuMemoryBuffer(gfx::Size(256, 256))); + surface->Attach(surface_buffer.get()); + surface->Commit(); + + // Check if the surface properly restores desk state and activation index. + arc_window = shell_surface->GetWidget()->GetNativeWindow(); + EXPECT_TRUE(arc_window); + EXPECT_EQ(kDeskId, + arc_window->GetProperty(aura::client::kWindowWorkspaceKey)); + int32_t* index = arc_window->GetProperty(::full_restore::kActivationIndexKey); + ASSERT_TRUE(index); + EXPECT_EQ(kActivationIndex, *index); + + // Destroy the task and close the window. + app_host()->OnTaskDestroyed(kRestoreTaskId); + arc_widget->CloseNow(); + + ASSERT_FALSE(GetWindowInfo(kPreRestoreTaskId)); + + // Remove the added desks. + RemoveInactiveDesks(); + + ::full_restore::FullRestoreInfo::GetInstance()->RemoveObserver( + test_full_restore_info_observer()); + StopInstance(); +} + class AppLaunchHandlerNoBrowserBrowserTest : public AppLaunchHandlerBrowserTest { public:
diff --git a/chrome/browser/commerce/merchant_viewer/android/javatests/src/org/chromium/chrome/browser/merchant_viewer/MerchantTrustSignalsCoordinatorTest.java b/chrome/browser/commerce/merchant_viewer/android/javatests/src/org/chromium/chrome/browser/merchant_viewer/MerchantTrustSignalsCoordinatorTest.java index 9b9e68b..daefaed 100644 --- a/chrome/browser/commerce/merchant_viewer/android/javatests/src/org/chromium/chrome/browser/merchant_viewer/MerchantTrustSignalsCoordinatorTest.java +++ b/chrome/browser/commerce/merchant_viewer/android/javatests/src/org/chromium/chrome/browser/merchant_viewer/MerchantTrustSignalsCoordinatorTest.java
@@ -39,6 +39,7 @@ import org.chromium.base.test.UiThreadTest; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisableIf; +import org.chromium.base.test.util.DisabledTest; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.merchant_viewer.MerchantTrustMetrics.MessageClearReason; @@ -73,6 +74,7 @@ Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, "force-fieldtrials=Study/Group"}) @DisableIf.Build(sdk_is_less_than = Build.VERSION_CODES.M) @DisableIf.Device(type = {UiDisableIf.TABLET}) +@DisabledTest(message = "crbug.com/1205485") public class MerchantTrustSignalsCoordinatorTest { @Rule public final ChromeBrowserTestRule mBrowserTestRule = new ChromeBrowserTestRule();
diff --git a/chrome/browser/component_updater/client_side_phishing_component_installer.cc b/chrome/browser/component_updater/client_side_phishing_component_installer.cc new file mode 100644 index 0000000..c073d02 --- /dev/null +++ b/chrome/browser/component_updater/client_side_phishing_component_installer.cc
@@ -0,0 +1,133 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/component_updater/client_side_phishing_component_installer.h" + +#include "base/bind.h" +#include "base/callback_forward.h" +#include "base/feature_list.h" +#include "base/files/file_util.h" +#include "base/location.h" +#include "base/task/post_task.h" +#include "base/task/task_traits.h" +#include "base/task/thread_pool.h" +#include "components/safe_browsing/content/browser/client_side_phishing_model.h" +#include "components/safe_browsing/core/features.h" +#include "components/variations/variations_associated_data.h" + +using component_updater::ComponentUpdateService; + +namespace { + +const base::FilePath::CharType kClientModelBinaryPbFileName[] = + FILE_PATH_LITERAL("client_model.pb"); + +// The SHA256 of the SubjectPublicKeyInfo used to sign the extension. +// The extension id is: imefjhfbkmcmebodilednhmaccmincoa +const uint8_t kClientSidePhishingPublicKeySHA256[32] = { + 0x8c, 0x45, 0x97, 0x51, 0xac, 0x2c, 0x41, 0xe3, 0x8b, 0x43, 0xd7, + 0xc0, 0x22, 0xc8, 0xd2, 0xe0, 0xe3, 0xe2, 0x33, 0x88, 0x1f, 0x09, + 0x6d, 0xde, 0x65, 0x6a, 0x83, 0x32, 0x71, 0x52, 0x6e, 0x77}; + +const char kClientSidePhishingManifestName[] = "Client Side Phishing Detection"; + +void LoadFromDisk(const base::FilePath& pb_path) { + if (pb_path.empty()) + return; + + std::string binary_pb; + if (!base::ReadFileToString(pb_path, &binary_pb)) + return; + + safe_browsing::ClientSidePhishingModel::GetInstance() + ->PopulateFromDynamicUpdate(binary_pb); +} + +} // namespace + +namespace component_updater { + +bool ClientSidePhishingComponentInstallerPolicy:: + SupportsGroupPolicyEnabledComponentUpdates() const { + return false; +} + +bool ClientSidePhishingComponentInstallerPolicy::RequiresNetworkEncryption() + const { + return false; +} + +update_client::CrxInstaller::Result +ClientSidePhishingComponentInstallerPolicy::OnCustomInstall( + const base::DictionaryValue& manifest, + const base::FilePath& install_dir) { + return update_client::CrxInstaller::Result(0); // Nothing custom here. +} + +void ClientSidePhishingComponentInstallerPolicy::OnCustomUninstall() {} + +base::FilePath ClientSidePhishingComponentInstallerPolicy::GetInstalledPath( + const base::FilePath& base) { + return base.Append(kClientModelBinaryPbFileName); +} + +void ClientSidePhishingComponentInstallerPolicy::ComponentReady( + const base::Version& version, + const base::FilePath& install_dir, + std::unique_ptr<base::DictionaryValue> manifest) { + base::ThreadPool::PostTask( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::BindOnce(&LoadFromDisk, GetInstalledPath(install_dir))); +} + +// Called during startup and installation before ComponentReady(). +bool ClientSidePhishingComponentInstallerPolicy::VerifyInstallation( + const base::DictionaryValue& manifest, + const base::FilePath& install_dir) const { + // No need to actually validate the proto here, since we'll do the checking + // in PopulateFromDynamicUpdate(). + return base::PathExists(GetInstalledPath(install_dir)); +} + +base::FilePath +ClientSidePhishingComponentInstallerPolicy::GetRelativeInstallDir() const { + return base::FilePath(FILE_PATH_LITERAL("ClientSidePhishing")); +} + +void ClientSidePhishingComponentInstallerPolicy::GetHash( + std::vector<uint8_t>* hash) const { + hash->assign(kClientSidePhishingPublicKeySHA256, + kClientSidePhishingPublicKeySHA256 + + base::size(kClientSidePhishingPublicKeySHA256)); +} + +std::string ClientSidePhishingComponentInstallerPolicy::GetName() const { + return kClientSidePhishingManifestName; +} + +update_client::InstallerAttributes +ClientSidePhishingComponentInstallerPolicy::GetInstallerAttributes() const { + update_client::InstallerAttributes attributes; + + // Pass the tag parameter to the installer as the "tag" attribute; it will + // be used to choose which binary is downloaded. + constexpr char kTagParamName[] = "reporter_omaha_tag"; + std::string tag_value = "default"; + if (base::FeatureList::IsEnabled( + safe_browsing::kClientSideDetectionModelTag)) { + tag_value = variations::GetVariationParamValueByFeature( + safe_browsing::kClientSideDetectionModelTag, kTagParamName); + } + + attributes["tag"] = tag_value; + return update_client::InstallerAttributes(); +} + +void RegisterClientSidePhishingComponent(ComponentUpdateService* cus) { + auto installer = base::MakeRefCounted<ComponentInstaller>( + std::make_unique<ClientSidePhishingComponentInstallerPolicy>()); + installer->Register(cus, base::OnceClosure()); +} + +} // namespace component_updater
diff --git a/chrome/browser/component_updater/client_side_phishing_component_installer.h b/chrome/browser/component_updater/client_side_phishing_component_installer.h new file mode 100644 index 0000000..77158fa --- /dev/null +++ b/chrome/browser/component_updater/client_side_phishing_component_installer.h
@@ -0,0 +1,62 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_COMPONENT_UPDATER_CLIENT_SIDE_PHISHING_COMPONENT_INSTALLER_H_ +#define CHROME_BROWSER_COMPONENT_UPDATER_CLIENT_SIDE_PHISHING_COMPONENT_INSTALLER_H_ + +#include <stdint.h> +#include <memory> +#include <string> +#include <vector> + +#include "base/files/file_path.h" +#include "base/macros.h" +#include "base/values.h" +#include "base/version.h" +#include "components/component_updater/component_installer.h" + +namespace base { +class FilePath; +} // namespace base + +namespace component_updater { + +class ComponentUpdateService; + +class ClientSidePhishingComponentInstallerPolicy + : public ComponentInstallerPolicy { + public: + ClientSidePhishingComponentInstallerPolicy() = default; + ~ClientSidePhishingComponentInstallerPolicy() override = default; + + private: + // The following methods override ComponentInstallerPolicy. + bool SupportsGroupPolicyEnabledComponentUpdates() const override; + bool RequiresNetworkEncryption() const override; + update_client::CrxInstaller::Result OnCustomInstall( + const base::DictionaryValue& manifest, + const base::FilePath& install_dir) override; + void OnCustomUninstall() override; + bool VerifyInstallation(const base::DictionaryValue& manifest, + const base::FilePath& install_dir) const override; + void ComponentReady(const base::Version& version, + const base::FilePath& install_dir, + std::unique_ptr<base::DictionaryValue> manifest) override; + base::FilePath GetRelativeInstallDir() const override; + void GetHash(std::vector<uint8_t>* hash) const override; + std::string GetName() const override; + update_client::InstallerAttributes GetInstallerAttributes() const override; + + static base::FilePath GetInstalledPath(const base::FilePath& base); + + DISALLOW_COPY_AND_ASSIGN(ClientSidePhishingComponentInstallerPolicy); +}; + +// Call once during startup to make the component update service aware of +// the Client Side Phishing component. +void RegisterClientSidePhishingComponent(ComponentUpdateService* cus); + +} // namespace component_updater + +#endif // CHROME_BROWSER_COMPONENT_UPDATER_CLIENT_SIDE_PHISHING_COMPONENT_INSTALLER_H_
diff --git a/chrome/browser/component_updater/registration.cc b/chrome/browser/component_updater/registration.cc index 9af6c2f..3d7402a1 100644 --- a/chrome/browser/component_updater/registration.cc +++ b/chrome/browser/component_updater/registration.cc
@@ -14,6 +14,7 @@ #include "chrome/browser/buildflags.h" #include "chrome/browser/component_updater/autofill_regex_component_installer.h" #include "chrome/browser/component_updater/chrome_origin_trials_component_installer.h" +#include "chrome/browser/component_updater/client_side_phishing_component_installer.h" #include "chrome/browser/component_updater/crl_set_component_installer.h" #include "chrome/browser/component_updater/crowd_deny_component_installer.h" #include "chrome/browser/component_updater/desktop_sharing_hub_component_installer.h" @@ -186,6 +187,8 @@ RegisterAutofillStatesComponent(cus, g_browser_process->local_state()); RegisterAutofillRegexComponent(cus); + + RegisterClientSidePhishingComponent(cus); } } // namespace component_updater
diff --git a/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc b/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc index f104c2d..8ff4f9a4 100644 --- a/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
@@ -4391,7 +4391,7 @@ base::BindOnce(&OnDangerPromptCreated); DownloadsAcceptDangerFunction::OnPromptCreatedForTesting( &callback); - ExtensionActionTestHelper::Create(current_browser())->Press(0); + ExtensionActionTestHelper::Create(current_browser())->Press(GetExtensionId()); observer->WaitForFinished(); }
diff --git a/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc b/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc index 342a5ba..f2719e6 100644 --- a/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc +++ b/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc
@@ -300,7 +300,7 @@ profile(), extension, GetBrowserAction(browser(), *extension), nullptr); // Test that there is a browser action in the toolbar. ASSERT_EQ(1, GetBrowserActionsBar()->NumberOfBrowserActions()); - EXPECT_TRUE(GetBrowserActionsBar()->HasIcon(0)); + EXPECT_TRUE(GetBrowserActionsBar()->HasIcon(extension->id())); gfx::Image action_icon = icon_factory.GetIcon(0); uint32_t action_icon_last_id = action_icon.ToSkBitmap()->getGenerationID(); @@ -309,9 +309,9 @@ ASSERT_EQ(action_icon_last_id, icon_factory.GetIcon(0).ToSkBitmap()->getGenerationID()); - gfx::Image last_bar_icon = GetBrowserActionsBar()->GetIcon(0); - EXPECT_TRUE(gfx::test::AreImagesEqual(last_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); + gfx::Image last_bar_icon = GetBrowserActionsBar()->GetIcon(extension->id()); + EXPECT_TRUE(gfx::test::AreImagesEqual( + last_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); // The reason we don't test more standard scales (like 1x, 2x, etc.) is that // these may be generated from the provided scales. @@ -322,12 +322,12 @@ // Tell the extension to update the icon using ImageData object. ResultCatcher catcher; - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); - EXPECT_FALSE(gfx::test::AreImagesEqual(last_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); - last_bar_icon = GetBrowserActionsBar()->GetIcon(0); + EXPECT_FALSE(gfx::test::AreImagesEqual( + last_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); + last_bar_icon = GetBrowserActionsBar()->GetIcon(extension->id()); action_icon = icon_factory.GetIcon(0); uint32_t action_icon_current_id = action_icon.ToSkBitmap()->getGenerationID(); @@ -340,13 +340,13 @@ EXPECT_FALSE(action_icon.ToImageSkia()->HasRepresentation(kLargeIconScale)); // Tell the extension to update the icon using path. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); // Make sure the browser action bar updated. - EXPECT_FALSE(gfx::test::AreImagesEqual(last_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); - last_bar_icon = GetBrowserActionsBar()->GetIcon(0); + EXPECT_FALSE(gfx::test::AreImagesEqual( + last_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); + last_bar_icon = GetBrowserActionsBar()->GetIcon(extension->id()); action_icon = icon_factory.GetIcon(0); action_icon_current_id = action_icon.ToSkBitmap()->getGenerationID(); @@ -360,12 +360,12 @@ // Tell the extension to update the icon using dictionary of ImageData // objects. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); - EXPECT_FALSE(gfx::test::AreImagesEqual(last_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); - last_bar_icon = GetBrowserActionsBar()->GetIcon(0); + EXPECT_FALSE(gfx::test::AreImagesEqual( + last_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); + last_bar_icon = GetBrowserActionsBar()->GetIcon(extension->id()); action_icon = icon_factory.GetIcon(0); action_icon_current_id = action_icon.ToSkBitmap()->getGenerationID(); @@ -378,12 +378,12 @@ EXPECT_TRUE(action_icon.AsImageSkia().HasRepresentation(kLargeIconScale)); // Tell the extension to update the icon using dictionary of paths. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); - EXPECT_FALSE(gfx::test::AreImagesEqual(last_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); - last_bar_icon = GetBrowserActionsBar()->GetIcon(0); + EXPECT_FALSE(gfx::test::AreImagesEqual( + last_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); + last_bar_icon = GetBrowserActionsBar()->GetIcon(extension->id()); action_icon = icon_factory.GetIcon(0); action_icon_current_id = action_icon.ToSkBitmap()->getGenerationID(); @@ -397,12 +397,12 @@ // Tell the extension to update the icon using dictionary of ImageData // objects, but setting only one size. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); - EXPECT_FALSE(gfx::test::AreImagesEqual(last_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); - last_bar_icon = GetBrowserActionsBar()->GetIcon(0); + EXPECT_FALSE(gfx::test::AreImagesEqual( + last_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); + last_bar_icon = GetBrowserActionsBar()->GetIcon(extension->id()); action_icon = icon_factory.GetIcon(0); action_icon_current_id = action_icon.ToSkBitmap()->getGenerationID(); @@ -416,12 +416,12 @@ // Tell the extension to update the icon using dictionary of paths, but // setting only one size. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); - EXPECT_FALSE(gfx::test::AreImagesEqual(last_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); - last_bar_icon = GetBrowserActionsBar()->GetIcon(0); + EXPECT_FALSE(gfx::test::AreImagesEqual( + last_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); + last_bar_icon = GetBrowserActionsBar()->GetIcon(extension->id()); action_icon = icon_factory.GetIcon(0); action_icon_current_id = action_icon.ToSkBitmap()->getGenerationID(); @@ -435,12 +435,12 @@ // Tell the extension to update the icon using dictionary of ImageData // objects, but setting only size 42. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); - EXPECT_FALSE(gfx::test::AreImagesEqual(last_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); - last_bar_icon = GetBrowserActionsBar()->GetIcon(0); + EXPECT_FALSE(gfx::test::AreImagesEqual( + last_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); + last_bar_icon = GetBrowserActionsBar()->GetIcon(extension->id()); action_icon = icon_factory.GetIcon(0); action_icon_current_id = action_icon.ToSkBitmap()->getGenerationID(); @@ -452,12 +452,12 @@ EXPECT_TRUE(action_icon.AsImageSkia().HasRepresentation(kLargeIconScale)); // Try setting icon with empty dictionary of ImageData objects. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_FALSE(catcher.GetNextResult()); EXPECT_EQ(kEmptyImageDataError, catcher.message()); // Try setting icon with empty dictionary of path objects. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_FALSE(catcher.GetNextResult()); EXPECT_EQ(kEmptyPathError, catcher.message()); } @@ -472,8 +472,9 @@ // Test there is a browser action in the toolbar. ASSERT_EQ(1, GetBrowserActionsBar()->NumberOfBrowserActions()); - EXPECT_TRUE(GetBrowserActionsBar()->HasIcon(0)); - gfx::Image initial_bar_icon = GetBrowserActionsBar()->GetIcon(0); + EXPECT_TRUE(GetBrowserActionsBar()->HasIcon(extension->id())); + gfx::Image initial_bar_icon = + GetBrowserActionsBar()->GetIcon(extension->id()); ExtensionHost* background_page = ProcessManager::Get(profile())->GetBackgroundHostForExtension( @@ -497,8 +498,8 @@ base::StringPrintf(kScript, "invisibleImageData"), &result)); EXPECT_EQ("Icon not sufficiently visible.", result); // The icon should not have changed. - EXPECT_TRUE(gfx::test::AreImagesEqual(initial_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); + EXPECT_TRUE(gfx::test::AreImagesEqual( + initial_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); EXPECT_THAT(histogram_tester.GetAllSamples(histogram_name), testing::ElementsAre(base::Bucket(0, 1))); EXPECT_THAT(histogram_tester.GetAllSamples(new_histogram_name), @@ -513,8 +514,8 @@ base::StringPrintf(kScript, "visibleImageData"), &result)); EXPECT_EQ("", result); // The icon should have changed. - EXPECT_FALSE(gfx::test::AreImagesEqual(initial_bar_icon, - GetBrowserActionsBar()->GetIcon(0))); + EXPECT_FALSE(gfx::test::AreImagesEqual( + initial_bar_icon, GetBrowserActionsBar()->GetIcon(extension->id()))); EXPECT_THAT(histogram_tester.GetAllSamples(histogram_name), testing::ElementsAre(base::Bucket(1, 1))); EXPECT_THAT(histogram_tester.GetAllSamples(new_histogram_name), @@ -531,26 +532,28 @@ // Test that there is a browser action in the toolbar and that it has an icon. ASSERT_EQ(1, GetBrowserActionsBar()->NumberOfBrowserActions()); - EXPECT_TRUE(GetBrowserActionsBar()->HasIcon(0)); + EXPECT_TRUE(GetBrowserActionsBar()->HasIcon(extension->id())); // Execute the action, its title should change. ResultCatcher catcher; - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); - EXPECT_EQ("Showing icon 2", GetBrowserActionsBar()->GetTooltip(0)); + EXPECT_EQ("Showing icon 2", + GetBrowserActionsBar()->GetTooltip(extension->id())); // Open a new tab, the title should go back. chrome::NewTab(browser()); - EXPECT_EQ("hi!", GetBrowserActionsBar()->GetTooltip(0)); + EXPECT_EQ("hi!", GetBrowserActionsBar()->GetTooltip(extension->id())); // Go back to first tab, changed title should reappear. browser()->tab_strip_model()->ActivateTabAt( 0, {TabStripModel::GestureType::kOther}); - EXPECT_EQ("Showing icon 2", GetBrowserActionsBar()->GetTooltip(0)); + EXPECT_EQ("Showing icon 2", + GetBrowserActionsBar()->GetTooltip(extension->id())); // Reload that tab, default title should come back. ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); - EXPECT_EQ("hi!", GetBrowserActionsBar()->GetTooltip(0)); + EXPECT_EQ("hi!", GetBrowserActionsBar()->GetTooltip(extension->id())); } // Test that calling chrome.browserAction.setIcon() can set the icon for @@ -575,7 +578,7 @@ // call setIcon(). { ResultCatcher catcher; - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); } @@ -608,7 +611,7 @@ // will add a popup. { ResultCatcher catcher; - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()); } @@ -959,7 +962,7 @@ // Simulate a click on the browser action icon. { ResultCatcher catcher; - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); EXPECT_TRUE(catcher.GetNextResult()); } @@ -989,7 +992,7 @@ // gfx::Image. TestIconImageObserver::WaitForExtensionActionIcon(extension, profile()); - gfx::Image first_icon = GetBrowserActionsBar()->GetIcon(0); + gfx::Image first_icon = GetBrowserActionsBar()->GetIcon(extension->id()); ASSERT_FALSE(first_icon.IsEmpty()); TestExtensionActionAPIObserver observer(profile(), extension->id()); @@ -999,7 +1002,7 @@ // Wait for extension action to be updated. observer.Wait(); - gfx::Image next_icon = GetBrowserActionsBar()->GetIcon(0); + gfx::Image next_icon = GetBrowserActionsBar()->GetIcon(extension->id()); ASSERT_FALSE(next_icon.IsEmpty()); EXPECT_FALSE(gfx::test::AreImagesEqual(first_icon, next_icon)); } @@ -1037,12 +1040,12 @@ // Click on the browser action icon to enter Picture-in-Picture. ResultCatcher catcher; - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); EXPECT_TRUE(catcher.GetNextResult()); EXPECT_TRUE(window_controller->GetWindowForTesting()->IsVisible()); // Click on the browser action icon to exit Picture-in-Picture. - GetBrowserActionsBar()->Press(0); + GetBrowserActionsBar()->Press(extension->id()); EXPECT_TRUE(catcher.GetNextResult()); EXPECT_FALSE(window_controller->GetWindowForTesting()->IsVisible()); }
diff --git a/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc b/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc index b761f25..9a1b771 100644 --- a/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc +++ b/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc
@@ -167,12 +167,14 @@ EnsurePopupActive(); } - // Open an extension popup by clicking the browser action button. - content::WebContents* OpenPopupViaToolbar() { + // Open an extension popup by clicking the browser action button associated + // with `id`. + content::WebContents* OpenPopupViaToolbar(const std::string& id) { + EXPECT_FALSE(id.empty()); content::WindowedNotificationObserver popup_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press(id); popup_observer.Wait(); EnsurePopupActive(); const auto& source = @@ -321,10 +323,9 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, TestOpenPopupDoesNotCloseOtherPopups) { // Load a first extension that can open a popup. - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( - "browser_action/popup"))); - const Extension* extension = GetSingleLoadedExtension(); - ASSERT_TRUE(extension) << message_; + const Extension* first_extension = + LoadExtension(test_data_dir_.AppendASCII("browser_action/popup")); + ASSERT_TRUE(first_extension) << message_; ExtensionTestMessageListener listener("ready", true); // Load the test extension which will do nothing except notifyPass() to @@ -333,9 +334,12 @@ .page_url = "open_popup_fails.html"})) << message_; EXPECT_TRUE(listener.WaitUntilSatisfied()); - OpenPopupViaToolbar(); + + // Open a popup with the first extension. + OpenPopupViaToolbar(first_extension->id()); ResultCatcher catcher; - // Return control to javascript to validate that opening a popup fails now. + // Now, try to open a popup with the second extension. It should fail since + // there's an active popup. listener.Reply("show another"); ASSERT_TRUE(catcher.GetNextResult()) << message_; EXPECT_TRUE(ClosePopup()); @@ -372,7 +376,7 @@ "browser_action/popup"))); const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; - OpenPopupViaToolbar(); + OpenPopupViaToolbar(extension->id()); ClosePopupViaFocusLoss(); } @@ -446,7 +450,7 @@ content::WindowedNotificationObserver popup_observer( NOTIFICATION_EXTENSION_HOST_CREATED, content::NotificationService::AllSources()); - OpenPopupViaToolbar(); + OpenPopupViaToolbar(extension->id()); popup_observer.Wait(); ExtensionHost* extension_host = content::Details<ExtensionHost>(popup_observer.details()).ptr(); @@ -508,7 +512,7 @@ content::WindowedNotificationObserver frame_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); - ExtensionActionTestHelper::Create(browser())->InspectPopup(0); + ExtensionActionTestHelper::Create(browser())->InspectPopup(extension->id()); frame_observer.Wait(); EXPECT_TRUE(ExtensionActionTestHelper::Create(browser())->HasPopup()); @@ -591,12 +595,12 @@ const gfx::Size kExpectedSizes[] = {minSize, middleSize, maxSize}; for (size_t i = 0; i < base::size(kExpectedSizes); i++) { content::WebContentsAddedObserver popup_observer; - actions_bar->Press(0); + actions_bar->Press(extension->id()); content::WebContents* popup = popup_observer.GetWebContents(); actions_bar->WaitForExtensionsContainerLayout(); gfx::Size max_available_size = - actions_bar->GetMaxAvailableSizeToFitBubbleOnScreen(0); + actions_bar->GetMaxAvailableSizeToFitBubbleOnScreen(extension->id()); // Take the screen boundaries into account for calculating the size of the // displayed popup @@ -649,7 +653,7 @@ content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL); // Simulate a click on the browser action to open the popup. - content::WebContents* popup = OpenPopupViaToolbar(); + content::WebContents* popup = OpenPopupViaToolbar(extension->id()); ASSERT_TRUE(popup); content::ExecuteScriptAsync(popup, "run_tests()"); @@ -735,7 +739,7 @@ ASSERT_TRUE(extension) << message_; // Simulate a click on the browser action to open the popup. - ASSERT_TRUE(OpenPopupViaToolbar()); + ASSERT_TRUE(OpenPopupViaToolbar(extension->id())); // Find the RenderFrameHost associated with the iframe in the popup. content::RenderFrameHost* frame_host = nullptr; @@ -834,12 +838,12 @@ std::unique_ptr<ExtensionActionTestHelper> action_bar_helper = ExtensionActionTestHelper::Create(browser()); ASSERT_EQ(2, action_bar_helper->NumberOfBrowserActions()); - ASSERT_EQ(popup_extension().id(), action_bar_helper->GetExtensionId(0)); - ASSERT_EQ(other_extension().id(), action_bar_helper->GetExtensionId(1)); + EXPECT_TRUE(action_bar_helper->HasAction(popup_extension().id())); + EXPECT_TRUE(action_bar_helper->HasAction(other_extension().id())); } // Simulate a click on the browser action to open the popup. - content::WebContents* popup = OpenPopupViaToolbar(); + content::WebContents* popup = OpenPopupViaToolbar(popup_extension().id()); ASSERT_TRUE(popup); GURL popup_url = popup_extension().GetResourceURL("popup.html"); EXPECT_EQ(popup_url, popup->GetLastCommittedURL());
diff --git a/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc b/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc index b0f50a31..408ae9e 100644 --- a/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc +++ b/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc
@@ -467,7 +467,7 @@ ASSERT_TRUE(extension); ASSERT_TRUE(listener.WaitUntilSatisfied()); ASSERT_EQ(1, toolbar_helper->NumberOfBrowserActions()); - EXPECT_EQ(extension->id(), toolbar_helper->GetExtensionId(0)); + EXPECT_TRUE(toolbar_helper->HasAction(extension->id())); ExtensionAction* action = GetExtensionAction(*extension); ASSERT_TRUE(action); @@ -478,7 +478,7 @@ EXPECT_FALSE(action->HasPopup(tab_id)); ResultCatcher result_catcher; - toolbar_helper->Press(0); + toolbar_helper->Press(extension->id()); ASSERT_TRUE(result_catcher.GetNextResult()) << result_catcher.message(); } @@ -524,7 +524,7 @@ EXPECT_TRUE(action->HasPopup(tab_id)); ResultCatcher result_catcher; - toolbar_helper->Press(0); + toolbar_helper->Press(extension->id()); EXPECT_TRUE(result_catcher.GetNextResult()) << result_catcher.message(); ProcessManager* process_manager = ProcessManager::Get(profile()); @@ -598,7 +598,7 @@ EXPECT_TRUE(action->HasPopup(tab_id)); ResultCatcher result_catcher; - toolbar_helper->Press(0); + toolbar_helper->Press(extension->id()); EXPECT_TRUE(result_catcher.GetNextResult()) << result_catcher.message(); ProcessManager* process_manager = ProcessManager::Get(profile()); @@ -629,7 +629,7 @@ EXPECT_EQ(0u, frames.size()); // Open the popup again. - toolbar_helper->Press(0); + toolbar_helper->Press(extension->id()); EXPECT_TRUE(result_catcher.GetNextResult()) << result_catcher.message(); frames = process_manager->GetRenderFrameHostsForExtension(extension->id()); @@ -766,9 +766,9 @@ ExtensionActionTestHelper::Create(browser()); ASSERT_EQ(1, toolbar_helper->NumberOfBrowserActions()); - EXPECT_EQ(extension->id(), toolbar_helper->GetExtensionId(0)); + EXPECT_TRUE(toolbar_helper->HasAction(extension->id())); - gfx::Image default_icon = toolbar_helper->GetIcon(0); + gfx::Image default_icon = toolbar_helper->GetIcon(extension->id()); EXPECT_FALSE(default_icon.IsEmpty()); // Check the midpoint. All these icons are solid, but the rendered icon @@ -800,7 +800,7 @@ EnsureActionIsEnabledOnActiveTab(action); // The new tab should still have the same icon (the default). - gfx::Image new_tab_icon = toolbar_helper->GetIcon(0); + gfx::Image new_tab_icon = toolbar_helper->GetIcon(extension->id()); EXPECT_FALSE(default_icon.IsEmpty()); EXPECT_EQ(SK_ColorRED, default_icon.AsBitmap().getColor(mid_x, mid_y)); @@ -810,7 +810,7 @@ base::StringPrintf("setIcon({tabId: %d, path: 'blue_icon.png'});", new_tab_id)); - new_tab_icon = toolbar_helper->GetIcon(0); + new_tab_icon = toolbar_helper->GetIcon(extension->id()); EXPECT_FALSE(new_tab_icon.IsEmpty()); EXPECT_EQ(SK_ColorBLUE, new_tab_icon.AsBitmap().getColor(mid_x, mid_y)); @@ -830,14 +830,14 @@ RunTestAndWaitForSuccess( web_contents, base::StringPrintf(kSetIconFromImageData, new_tab_id)); - new_tab_icon = toolbar_helper->GetIcon(0); + new_tab_icon = toolbar_helper->GetIcon(extension->id()); EXPECT_FALSE(new_tab_icon.IsEmpty()); EXPECT_EQ(SK_ColorGREEN, new_tab_icon.AsBitmap().getColor(mid_x, mid_y)); // Switch back to the first tab. The icon should still be red, since the other // changes were for specific tabs. browser()->tab_strip_model()->ActivateTabAt(0); - gfx::Image first_tab_icon = toolbar_helper->GetIcon(0); + gfx::Image first_tab_icon = toolbar_helper->GetIcon(extension->id()); EXPECT_FALSE(first_tab_icon.IsEmpty()); EXPECT_EQ(SK_ColorRED, first_tab_icon.AsBitmap().getColor(mid_x, mid_y)); @@ -1340,7 +1340,7 @@ auto get_response = [extension, toolbar_helper = toolbar_helper.get()]() { ExtensionTestMessageListener listener(/*will_reply=*/false); listener.set_extension_id(extension->id()); - toolbar_helper->Press(0); + toolbar_helper->Press(extension->id()); EXPECT_TRUE(listener.WaitUntilSatisfied()); return listener.message(); };
diff --git a/chrome/browser/extensions/api/preference/preference_api.cc b/chrome/browser/extensions/api/preference/preference_api.cc index 98887c8e..c576b0e 100644 --- a/chrome/browser/extensions/api/preference/preference_api.cc +++ b/chrome/browser/extensions/api/preference/preference_api.cc
@@ -188,13 +188,13 @@ const base::Value* extension_pref, std::string* error, bool* bad_message) override { - return extension_pref->CreateDeepCopy(); + return base::Value::ToUniquePtrValue(extension_pref->Clone()); } std::unique_ptr<base::Value> BrowserToExtensionPref( const base::Value* browser_pref, bool is_incognito_profile) override { - return browser_pref->CreateDeepCopy(); + return base::Value::ToUniquePtrValue(browser_pref->Clone()); } }; @@ -492,7 +492,8 @@ extension_id, scope_string); auto preference = update.Create(); - preference->SetWithoutPathExpansion(pref_key, value.CreateDeepCopy()); + preference->SetWithoutPathExpansion( + pref_key, base::Value::ToUniquePtrValue(value.Clone())); } extension_pref_value_map()->SetExtensionPref(extension_id, pref_key, scope, std::move(value));
diff --git a/chrome/browser/extensions/api/storage/policy_value_store.cc b/chrome/browser/extensions/api/storage/policy_value_store.cc index e349670f..431f560 100644 --- a/chrome/browser/extensions/api/storage/policy_value_store.cc +++ b/chrome/browser/extensions/api/storage/policy_value_store.cc
@@ -40,10 +40,9 @@ // Convert |policy| to a dictionary value. Only include mandatory policies // for now. base::DictionaryValue current_policy; - for (auto it = policy.begin(); it != policy.end(); ++it) { - if (it->second.level == policy::POLICY_LEVEL_MANDATORY) { - current_policy.SetWithoutPathExpansion( - it->first, it->second.value()->CreateDeepCopy()); + for (const auto& it : policy) { + if (it.second.level == policy::POLICY_LEVEL_MANDATORY) { + current_policy.SetKey(it.first, it.second.value()->Clone()); } }
diff --git a/chrome/browser/extensions/api/storage/syncable_settings_storage.cc b/chrome/browser/extensions/api/storage/syncable_settings_storage.cc index c5b1d4a0..cc19a7a 100644 --- a/chrome/browser/extensions/api/storage/syncable_settings_storage.cc +++ b/chrome/browser/extensions/api/storage/syncable_settings_storage.cc
@@ -217,7 +217,7 @@ it.Advance()) { std::unique_ptr<base::Value> sync_value; if (sync_state->RemoveWithoutPathExpansion(it.key(), &sync_value)) { - if (sync_value->Equals(&it.value())) { + if (*sync_value == it.value()) { // Sync and local values are the same, no changes to send. } else { // Sync value is different, update local setting with new value.
diff --git a/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc b/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc index baf89d6d..c8cc3765 100644 --- a/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc +++ b/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc
@@ -504,7 +504,7 @@ ASSERT_TRUE(RunExtensionTest("webnavigation/history")) << message_; } -IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcess) { +IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, CrossProcess) { ASSERT_TRUE(StartEmbeddedTestServer()); LoadExtension(test_data_dir_.AppendASCII("webnavigation").AppendASCII("app")); @@ -519,7 +519,7 @@ "empty.html"); call_script_user_gesture.set_has_user_gesture(true); - ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcess")) << message_; + ASSERT_TRUE(RunTest("webnavigation/crossProcess")) << message_; } // crbug.com/708139. @@ -540,7 +540,8 @@ << message_; } -IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcessHistory) { +IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, + CrossProcessHistory) { ASSERT_TRUE(StartEmbeddedTestServer()); // See crossProcessHistory/e.html. @@ -558,14 +559,14 @@ browser(), embedded_test_server()->GetURL("/test6"), "updateHistory()", "empty.html"); - ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessHistory")) - << message_; + ASSERT_TRUE(RunTest("webnavigation/crossProcessHistory")) << message_; } -IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcessIframe) { +IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, + CrossProcessIframe) { content::IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess()); ASSERT_TRUE(StartEmbeddedTestServer()); - ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessIframe")) << message_; + ASSERT_TRUE(RunTest("webnavigation/crossProcessIframe")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, PendingDeletion) {
diff --git a/chrome/browser/extensions/autoplay_browsertest.cc b/chrome/browser/extensions/autoplay_browsertest.cc index 84a04d8..c38cc25 100644 --- a/chrome/browser/extensions/autoplay_browsertest.cc +++ b/chrome/browser/extensions/autoplay_browsertest.cc
@@ -54,7 +54,7 @@ content::WindowedNotificationObserver popup_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); - browser_action_test_util->Press(0); + browser_action_test_util->Press(extension->id()); popup_observer.Wait(); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); }
diff --git a/chrome/browser/extensions/back_forward_cache_browsertest.cc b/chrome/browser/extensions/back_forward_cache_browsertest.cc index 0259b1cd..1b0a53a6 100644 --- a/chrome/browser/extensions/back_forward_cache_browsertest.cc +++ b/chrome/browser/extensions/back_forward_cache_browsertest.cc
@@ -4,10 +4,13 @@ #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/back_forward_cache/back_forward_cache_disable.h" +#include "content/public/browser/back_forward_cache.h" #include "content/public/common/content_features.h" #include "content/public/test/browser_test.h" #include "extensions/common/extension.h" #include "net/dns/mock_host_resolver.h" +#include "third_party/blink/public/common/scheduler/web_scheduler_tracked_feature.h" namespace extensions { @@ -34,6 +37,55 @@ ExtensionBrowserTest::SetUpOnMainThread(); } + void RunChromeRuntimeTest(const std::string& action) { + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("back_forward_cache") + .AppendASCII("content_script"))); + + 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")); + + // 1) Navigate to A. + content::RenderFrameHost* rfh_a = + ui_test_utils::NavigateToURL(browser(), url_a); + content::RenderFrameDeletedObserver delete_observer_rfh_a(rfh_a); + + constexpr int kMessagingBucket = + (static_cast<int>(content::BackForwardCache::DisabledSource::kEmbedder) + << 16) + + static_cast<int>( + back_forward_cache::DisabledReasonId::kExtensionMessaging); + + EXPECT_TRUE(ExecJs(rfh_a, action)); + + EXPECT_EQ(0, histogram_tester_.GetBucketCount( + "BackForwardCache.HistoryNavigationOutcome." + "DisabledForRenderFrameHostReason2", + kMessagingBucket)); + // 2) Navigate to B. + ui_test_utils::NavigateToURL(browser(), url_b); + + // Expect that `rfh_a` is destroyed as it wouldn't be placed in the cache + // since it uses the chrome.runtime API. + delete_observer_rfh_a.WaitUntilDeleted(); + + // 3) Go back to A. + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + web_contents->GetController().GoBack(); + EXPECT_TRUE(WaitForLoadStop(web_contents)); + + // Validate that the not restored reason is `ExtensionMessaging` due to the + // chrome.runtime usage. + EXPECT_EQ(1, histogram_tester_.GetBucketCount( + "BackForwardCache.HistoryNavigationOutcome." + "DisabledForRenderFrameHostReason2", + kMessagingBucket)); + } + + protected: + base::HistogramTester histogram_tester_; + private: base::test::ScopedFeatureList feature_list_; }; @@ -236,7 +288,6 @@ // 2) Navigate to B. content::RenderFrameHost* rfh_b = ui_test_utils::NavigateToURL(browser(), url_b); - content::RenderFrameDeletedObserver delete_observer_rfh_b(rfh_b); // Ensure that `rfh_a` is in the cache. EXPECT_FALSE(delete_observer_rfh_a.deleted()); @@ -252,4 +303,38 @@ delete_observer_rfh_a.WaitUntilDeleted(); } +// Test if the chrome.runtime.connect API is called, the page is prevented from +// entering bfcache. +IN_PROC_BROWSER_TEST_F(ExtensionBackForwardCacheBrowserTest, + ChromeRuntimeConnectUsage) { + RunChromeRuntimeTest( + "chrome.runtime.connect('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');"); +} + +// Test if the chrome.runtime.sendMessage API is called, the page is prevented +// from entering bfcache. +IN_PROC_BROWSER_TEST_F(ExtensionBackForwardCacheBrowserTest, + ChromeRuntimeSendMessageUsage) { + RunChromeRuntimeTest( + "chrome.runtime.sendMessage('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'some " + "message');"); +} + +// Test if the chrome.runtime.connect API is called, the page is prevented from +// entering bfcache. +IN_PROC_BROWSER_TEST_F( + ExtensionBackForwardCacheContentScriptDisabledBrowserTest, + ChromeRuntimeConnectUsage) { + RunChromeRuntimeTest( + "chrome.runtime.connect('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');"); + + // Validate also that the not restored reason is `IsolatedWorldScript` due to + // the extension injecting a content script. + EXPECT_EQ( + 1, + histogram_tester_.GetBucketCount( + "BackForwardCache.HistoryNavigationOutcome.BlocklistedFeature", + blink::scheduler::WebSchedulerTrackedFeature::kIsolatedWorldScript)); +} + } // namespace extensions
diff --git a/chrome/browser/extensions/crx_installer.cc b/chrome/browser/extensions/crx_installer.cc index fb8fff7..ea397a6 100644 --- a/chrome/browser/extensions/crx_installer.cc +++ b/chrome/browser/extensions/crx_installer.cc
@@ -380,7 +380,7 @@ valid = true; } } else { - valid = expected_manifest_->Equals(original_manifest_.get()); + valid = *expected_manifest_ == *original_manifest_; if (!valid && expected_manifest_check_level_ == WebstoreInstaller::MANIFEST_CHECK_LEVEL_LOOSE) { std::string error;
diff --git a/chrome/browser/extensions/extension_bindings_apitest.cc b/chrome/browser/extensions/extension_bindings_apitest.cc index 89dc061..05d7537cd 100644 --- a/chrome/browser/extensions/extension_bindings_apitest.cc +++ b/chrome/browser/extensions/extension_bindings_apitest.cc
@@ -151,14 +151,8 @@ // Tests that we don't override events when bindings are re-injected. // Regression test for http://crbug.com/269149. // Regression test for http://crbug.com/436593. -// Flaky on Mac. http://crbug.com/733064. -// Flaky on Chrome OS. http://crbug.com/1181768 -#if (defined(OS_MAC) || defined(OS_CHROMEOS)) -#define MAYBE_EventOverriding DISABLED_EventOverriding -#else -#define MAYBE_EventOverriding EventOverriding -#endif -IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, MAYBE_EventOverriding) { +// Flaky http://crbug.com/733064. +IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, DISABLED_EventOverriding) { ASSERT_TRUE(RunExtensionTest("bindings/event_overriding")) << message_; // The extension test removes a window and, during window removal, sends the // success message. Make sure we flush all pending tasks.
diff --git a/chrome/browser/extensions/extension_incognito_apitest.cc b/chrome/browser/extensions/extension_incognito_apitest.cc index 56248992..449929f8 100644 --- a/chrome/browser/extensions/extension_incognito_apitest.cc +++ b/chrome/browser/extensions/extension_incognito_apitest.cc
@@ -169,9 +169,10 @@ IN_PROC_BROWSER_TEST_F(IncognitoApiTest, DISABLED_IncognitoPopup) { ResultCatcher catcher; - ASSERT_TRUE(LoadExtension( + const extensions::Extension* const extension = LoadExtension( test_data_dir_.AppendASCII("incognito").AppendASCII("popup"), - {.allow_in_incognito = true})); + {.allow_in_incognito = true}); + ASSERT_TRUE(extension); // Open incognito window and navigate to test page. Browser* incognito_browser = OpenURLOffTheRecord( @@ -179,7 +180,7 @@ embedded_test_server()->GetURL("/extensions/test_file.html")); // Simulate the incognito's browser action being clicked. - ExtensionActionTestHelper::Create(incognito_browser)->Press(0); + ExtensionActionTestHelper::Create(incognito_browser)->Press(extension->id()); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); }
diff --git a/chrome/browser/extensions/lazy_background_page_apitest.cc b/chrome/browser/extensions/lazy_background_page_apitest.cc index 8028c8e7..afc40e0 100644 --- a/chrome/browser/extensions/lazy_background_page_apitest.cc +++ b/chrome/browser/extensions/lazy_background_page_apitest.cc
@@ -173,7 +173,8 @@ // Observe background page being created and closed after // the browser action is clicked. LazyBackgroundObserver page_complete; - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press( + last_loaded_extension_id()); page_complete.Wait(); // Background page created a new tab before it closed. @@ -197,7 +198,8 @@ // Observe background page being created and closed after // the browser action is clicked. LazyBackgroundObserver page_complete; - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press( + last_loaded_extension_id()); page_complete.Wait(); // Background page is closed after creating a new tab. @@ -409,7 +411,8 @@ { ExtensionTestMessageListener nacl_module_loaded("nacl_module_loaded", false); - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press( + last_loaded_extension_id()); EXPECT_TRUE(nacl_module_loaded.WaitUntilSatisfied()); content::RunAllTasksUntilIdle(); EXPECT_TRUE(IsBackgroundPageAlive(last_loaded_extension_id())); @@ -419,7 +422,8 @@ // down. { LazyBackgroundObserver page_complete; - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press( + last_loaded_extension_id()); page_complete.WaitUntilClosed(); } @@ -530,7 +534,8 @@ ExtensionTestMessageListener listener_incognito("waiting_incognito", false); LazyBackgroundObserver page_complete(browser()->profile()); - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press( + last_loaded_extension_id()); page_complete.Wait(); // Only the original event page received the message. @@ -613,7 +618,7 @@ // The browser action has a new title. auto browser_action = ExtensionActionTestHelper::Create(browser()); ASSERT_EQ(1, browser_action->NumberOfBrowserActions()); - EXPECT_EQ("Success", browser_action->GetTooltip(0)); + EXPECT_EQ("Success", browser_action->GetTooltip(last_loaded_extension_id())); } // Tests that both a regular page and an event page will receive events when @@ -730,7 +735,7 @@ // Click on the browser action icon to load video. { ExtensionTestMessageListener video_loaded("video_loaded", false); - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press(extension->id()); EXPECT_TRUE(video_loaded.WaitUntilSatisfied()); } @@ -744,7 +749,7 @@ testing::Not(testing::Contains(pip_activity))); ExtensionTestMessageListener entered_pip("entered_pip", false); - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press(extension->id()); EXPECT_TRUE(entered_pip.WaitUntilSatisfied()); EXPECT_THAT(pm->GetLazyKeepaliveActivities(extension), testing::Contains(pip_activity)); @@ -754,7 +759,7 @@ // Background Page shuts down. { LazyBackgroundObserver page_complete; - ExtensionActionTestHelper::Create(browser())->Press(0); + ExtensionActionTestHelper::Create(browser())->Press(extension->id()); page_complete.WaitUntilClosed(); EXPECT_FALSE(IsBackgroundPageAlive(extension->id())); }
diff --git a/chrome/browser/extensions/manifest_v3_browsertest.cc b/chrome/browser/extensions/manifest_v3_browsertest.cc index fb9631e..f6b5c41 100644 --- a/chrome/browser/extensions/manifest_v3_browsertest.cc +++ b/chrome/browser/extensions/manifest_v3_browsertest.cc
@@ -138,7 +138,7 @@ std::unique_ptr<ExtensionActionTestHelper> action_test_util = ExtensionActionTestHelper::Create(browser()); ASSERT_EQ(1, action_test_util->NumberOfBrowserActions()); - EXPECT_EQ(extension->id(), action_test_util->GetExtensionId(0)); + EXPECT_TRUE(action_test_util->HasAction(extension->id())); ExtensionAction* const action = ExtensionActionManager::Get(profile())->GetExtensionAction(*extension); @@ -146,7 +146,7 @@ EXPECT_FALSE(action->HasIcon(ExtensionAction::kDefaultTabId)); ResultCatcher catcher; - action_test_util->Press(0); + action_test_util->Press(extension->id()); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); EXPECT_TRUE(action->HasIcon(ExtensionAction::kDefaultTabId));
diff --git a/chrome/browser/extensions/process_manager_browsertest.cc b/chrome/browser/extensions/process_manager_browsertest.cc index 699fd09..cda32ff7 100644 --- a/chrome/browser/extensions/process_manager_browsertest.cc +++ b/chrome/browser/extensions/process_manager_browsertest.cc
@@ -427,7 +427,7 @@ content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); // Open popup in the first extension. - test_util->Press(0); + test_util->Press(popup->id()); frame_observer.Wait(); ASSERT_TRUE(test_util->HasPopup());
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index b0b5c82..d62fc9e8 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -5053,6 +5053,11 @@ "expiry_milestone": 95 }, { + "name": "translate-intent", + "owners": [ "jds", "basiaz", "chrome-language@google.com" ], + "expiry_milestone": 94 + }, + { "name": "treat-unsafe-downloads-as-active-content", "owners": [ "jdeblasio", "cthomp" ], "expiry_milestone": 89
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 41ff5b4..bc0375b 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -2503,6 +2503,11 @@ const char kTraceUploadUrlChoiceQa[] = "QA"; const char kTraceUploadUrlChoiceTesting[] = "Testing"; +const char kTranslateBubbleUIName[] = + "Select which UI to use for translate bubble"; +const char kTranslateBubbleUIDescription[] = + "Three bubble options to choose. Existing UI is selected by default"; + const char kTranslateForceTriggerOnEnglishName[] = "Select which language model to use to trigger translate on English " "content"; @@ -2510,10 +2515,10 @@ "Force the Translate Triggering on English pages experiment to be enabled " "with the selected language model active."; -const char kTranslateBubbleUIName[] = - "Select which UI to use for translate bubble"; -const char kTranslateBubbleUIDescription[] = - "Three bubble options to choose. Existing UI is selected by default"; +const char kTranslateIntentName[] = "Translate intent"; +const char kTranslateIntentDescription[] = + "Enables an intent that allows Assistant to initiate a translation of the " + "foreground tab."; const char kTreatInsecureOriginAsSecureName[] = "Insecure origins treated as secure"; @@ -3199,10 +3204,6 @@ "Enable a history sub page to the page info menu, and a button to forget " "a site, removing all preferences and history."; -const char kPageInfoPerformanceHintsName[] = "Page info performance hints"; -const char kPageInfoPerformanceHintsDescription[] = - "Show site performance information in the page info menu."; - const char kPageInfoV2Name[] = "Page info version two"; const char kPageInfoV2Description[] = "Enable the second version of the page info menu.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index bd60cc7..42478a0e 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -1451,11 +1451,14 @@ extern const char kTraceUploadUrlChoiceQa[]; extern const char kTraceUploadUrlChoiceTesting[]; +extern const char kTranslateBubbleUIName[]; +extern const char kTranslateBubbleUIDescription[]; + extern const char kTranslateForceTriggerOnEnglishName[]; extern const char kTranslateForceTriggerOnEnglishDescription[]; -extern const char kTranslateBubbleUIName[]; -extern const char kTranslateBubbleUIDescription[]; +extern const char kTranslateIntentName[]; +extern const char kTranslateIntentDescription[]; extern const char kTreatInsecureOriginAsSecureName[]; extern const char kTreatInsecureOriginAsSecureDescription[]; @@ -1854,9 +1857,6 @@ extern const char kPageInfoHistoryName[]; extern const char kPageInfoHistoryDescription[]; -extern const char kPageInfoPerformanceHintsName[]; -extern const char kPageInfoPerformanceHintsDescription[]; - extern const char kPageInfoV2Name[]; extern const char kPageInfoV2Description[];
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index 7e79456f..762731af 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -296,7 +296,6 @@ &password_manager::features::kPasswordScriptsFetching, &password_manager::features::kRecoverFromNeverSaveAndroid, &performance_hints::features::kContextMenuPerformanceInfo, - &performance_hints::features::kPageInfoPerformanceHints, &query_tiles::features::kQueryTilesGeoFilter, &query_tiles::features::kQueryTiles, &query_tiles::features::kQueryTilesInNTP,
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java index c5b52ab..64b5908d 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java
@@ -402,7 +402,6 @@ "OptimizationGuidePushNotifications"; public static final String OVERLAY_NEW_LAYOUT = "OverlayNewLayout"; public static final String PAGE_ANNOTATIONS_SERVICE = "PageAnnotationsService"; - public static final String PAGE_INFO_PERFORMANCE_HINTS = "PageInfoPerformanceHints"; public static final String PAINT_PREVIEW_DEMO = "PaintPreviewDemo"; public static final String PAINT_PREVIEW_SHOW_ON_STARTUP = "PaintPreviewShowOnStartup"; public static final String PASSWORD_SCRIPTS_FETCHING = "PasswordScriptsFetching";
diff --git a/chrome/browser/media_galleries/media_galleries_preferences.cc b/chrome/browser/media_galleries/media_galleries_preferences.cc index 64111954..9c83f52c1 100644 --- a/chrome/browser/media_galleries/media_galleries_preferences.cc +++ b/chrome/browser/media_galleries/media_galleries_preferences.cc
@@ -573,13 +573,13 @@ const base::ListValue* list = prefs->GetList( prefs::kMediaGalleriesRememberedGalleries); if (list) { - for (auto it = list->begin(); it != list->end(); ++it) { - const base::DictionaryValue* dict = nullptr; - if (!it->GetAsDictionary(&dict)) + for (const auto& gallery_value : *list) { + if (!gallery_value.is_dict()) continue; MediaGalleryPrefInfo gallery_info; - if (!PopulateGalleryPrefInfoFromDictionary(*dict, &gallery_info)) + if (!PopulateGalleryPrefInfoFromDictionary( + base::Value::AsDictionaryValue(gallery_value), &gallery_info)) continue; known_galleries_[gallery_info.pref_id] = gallery_info; @@ -795,35 +795,41 @@ new ListPrefUpdate(prefs, prefs::kMediaGalleriesRememberedGalleries)); base::ListValue* list = update->Get(); - for (auto list_iter = list->begin(); list_iter != list->end(); - ++list_iter) { - base::DictionaryValue* dict; + for (auto& gallery_value : *list) { MediaGalleryPrefId iter_id; - if (list_iter->GetAsDictionary(&dict) && GetPrefId(*dict, &iter_id) && + if (gallery_value.is_dict() && + GetPrefId(base::Value::AsDictionaryValue(gallery_value), &iter_id) && *pref_id_it == iter_id) { if (update_gallery_type) - dict->SetString(kMediaGalleriesTypeKey, TypeToStringValue(new_type)); + gallery_value.SetStringKey(kMediaGalleriesTypeKey, + TypeToStringValue(new_type)); if (update_gallery_name) - dict->SetString(kMediaGalleriesDisplayNameKey, display_name); + gallery_value.SetStringKey(kMediaGalleriesDisplayNameKey, + display_name); if (update_gallery_metadata) { - dict->SetString(kMediaGalleriesVolumeLabelKey, volume_label); - dict->SetString(kMediaGalleriesVendorNameKey, vendor_name); - dict->SetString(kMediaGalleriesModelNameKey, model_name); - dict->SetDouble(kMediaGalleriesSizeKey, total_size_in_bytes); - dict->SetDouble(kMediaGalleriesLastAttachTimeKey, - last_attach_time.ToInternalValue()); + gallery_value.SetStringKey(kMediaGalleriesVolumeLabelKey, + volume_label); + gallery_value.SetStringKey(kMediaGalleriesVendorNameKey, vendor_name); + gallery_value.SetStringKey(kMediaGalleriesModelNameKey, model_name); + gallery_value.SetDoubleKey(kMediaGalleriesSizeKey, + total_size_in_bytes); + gallery_value.SetDoubleKey(kMediaGalleriesLastAttachTimeKey, + last_attach_time.ToInternalValue()); } if (update_scan_counts) { - dict->SetInteger(kMediaGalleriesScanAudioCountKey, audio_count); - dict->SetInteger(kMediaGalleriesScanImageCountKey, image_count); - dict->SetInteger(kMediaGalleriesScanVideoCountKey, video_count); + gallery_value.SetIntKey(kMediaGalleriesScanAudioCountKey, + audio_count); + gallery_value.SetIntKey(kMediaGalleriesScanImageCountKey, + image_count); + gallery_value.SetIntKey(kMediaGalleriesScanVideoCountKey, + video_count); } if (update_default_gallery_type) { - dict->SetString( + gallery_value.SetStringKey( kMediaGalleriesDefaultGalleryTypeKey, DefaultGalleryTypeToStringValue(default_gallery_type)); } - dict->SetInteger(kMediaGalleriesPrefsVersionKey, prefs_version); + gallery_value.SetIntKey(kMediaGalleriesPrefsVersionKey, prefs_version); break; } } @@ -888,35 +894,35 @@ std::vector<MediaGalleryPrefId> pref_ids; - for (auto iter = list->begin(); iter != list->end(); ++iter) { - base::DictionaryValue* dict; + for (auto& gallery_value : *list) { MediaGalleryPrefId pref_id; - if (!(iter->GetAsDictionary(&dict) && GetPrefId(*dict, &pref_id))) + if (!(gallery_value.is_dict() && + GetPrefId(base::Value::AsDictionaryValue(gallery_value), &pref_id))) continue; - std::string default_gallery_type_string; + std::string* default_gallery_type_string = + gallery_value.FindStringKey(kMediaGalleriesDefaultGalleryTypeKey); - // If the "default gallery type" key is set, just update the paths in place. - // If it's not set, then AddOrUpdateGalleryInternal will take care of - // setting it as part of migration to prefs version 3. - if (dict->GetString(kMediaGalleriesDefaultGalleryTypeKey, - &default_gallery_type_string)) { + // If the "default gallery type" key is set, just update the paths in + // place. If it's not set, then AddOrUpdateGalleryInternal will take + // care of setting it as part of migration to prefs version 3. + if (default_gallery_type_string) { std::string device_id; if (got_music_path && - default_gallery_type_string == + *default_gallery_type_string == kMediaGalleriesDefaultGalleryTypeMusicDefaultValue) { device_id = StorageInfo::MakeDeviceId( StorageInfo::Type::FIXED_MASS_STORAGE, music_path.AsUTF8Unsafe()); } else if (got_pictures_path && - default_gallery_type_string == + *default_gallery_type_string == kMediaGalleriesDefaultGalleryTypePicturesDefaultValue) { device_id = StorageInfo::MakeDeviceId( StorageInfo::Type::FIXED_MASS_STORAGE, pictures_path.AsUTF8Unsafe()); } else if (got_videos_path && - default_gallery_type_string == + *default_gallery_type_string == kMediaGalleriesDefaultGalleryTypeVideosDefaultValue) { device_id = StorageInfo::MakeDeviceId( StorageInfo::Type::FIXED_MASS_STORAGE, @@ -924,7 +930,7 @@ } if (!device_id.empty()) - dict->SetString(kMediaGalleriesDeviceIdKey, device_id); + gallery_value.SetStringKey(kMediaGalleriesDeviceIdKey, device_id); } pref_ids.push_back(pref_id); @@ -984,24 +990,24 @@ return; for (auto iter = list->begin(); iter != list->end(); ++iter) { - base::DictionaryValue* dict; MediaGalleryPrefId iter_id; - if (iter->GetAsDictionary(&dict) && GetPrefId(*dict, &iter_id) && + if (iter->is_dict() && + GetPrefId(base::Value::AsDictionaryValue(*iter), &iter_id) && id == iter_id) { RemoveGalleryPermissionsFromPrefs(id); MediaGalleryPrefInfo::Type type; - if (!erase && GetType(*dict, &type) && + if (!erase && GetType(base::Value::AsDictionaryValue(*iter), &type) && (type == MediaGalleryPrefInfo::kAutoDetected || type == MediaGalleryPrefInfo::kScanResult)) { if (type == MediaGalleryPrefInfo::kAutoDetected) { - dict->SetString(kMediaGalleriesTypeKey, - kMediaGalleriesTypeBlackListedValue); + iter->SetStringKey(kMediaGalleriesTypeKey, + kMediaGalleriesTypeBlackListedValue); } else { - dict->SetString(kMediaGalleriesTypeKey, - kMediaGalleriesTypeRemovedScanValue); - dict->SetInteger(kMediaGalleriesScanAudioCountKey, 0); - dict->SetInteger(kMediaGalleriesScanImageCountKey, 0); - dict->SetInteger(kMediaGalleriesScanVideoCountKey, 0); + iter->SetStringKey(kMediaGalleriesTypeKey, + kMediaGalleriesTypeRemovedScanValue); + iter->SetIntKey(kMediaGalleriesScanAudioCountKey, 0); + iter->SetIntKey(kMediaGalleriesScanImageCountKey, 0); + iter->SetIntKey(kMediaGalleriesScanVideoCountKey, 0); } } else { list->Erase(iter, nullptr); @@ -1161,16 +1167,16 @@ permissions = update.Create(); } else { // If the gallery is already in the list, update the permission... - for (auto iter = permissions->begin(); iter != permissions->end(); ++iter) { - base::DictionaryValue* dict = nullptr; - if (!iter->GetAsDictionary(&dict)) + for (auto& permission : *permissions) { + if (!permission.is_dict()) continue; MediaGalleryPermission perm; - if (!GetMediaGalleryPermissionFromDictionary(dict, &perm)) + if (!GetMediaGalleryPermissionFromDictionary( + &base::Value::AsDictionaryValue(permission), &perm)) continue; if (perm.pref_id == gallery_id) { if (has_access != perm.has_permission) { - dict->SetBoolean(kMediaGalleryHasPermissionKey, has_access); + permission.SetBoolKey(kMediaGalleryHasPermissionKey, has_access); return true; } else { return false; @@ -1198,11 +1204,11 @@ return false; for (auto iter = permissions->begin(); iter != permissions->end(); ++iter) { - const base::DictionaryValue* dict = nullptr; - if (!iter->GetAsDictionary(&dict)) + if (!iter->is_dict()) continue; MediaGalleryPermission perm; - if (!GetMediaGalleryPermissionFromDictionary(dict, &perm)) + if (!GetMediaGalleryPermissionFromDictionary( + &base::Value::AsDictionaryValue(*iter), &perm)) continue; if (perm.pref_id == gallery_id) { permissions->Erase(iter, nullptr); @@ -1224,12 +1230,12 @@ return result; } - for (auto iter = permissions->begin(); iter != permissions->end(); ++iter) { - const base::DictionaryValue* dict = nullptr; - if (!iter->GetAsDictionary(&dict)) + for (const auto& permission : *permissions) { + if (!permission.is_dict()) continue; MediaGalleryPermission perm; - if (!GetMediaGalleryPermissionFromDictionary(dict, &perm)) + if (!GetMediaGalleryPermissionFromDictionary( + &base::Value::AsDictionaryValue(permission), &perm)) continue; result.push_back(perm); }
diff --git a/chrome/browser/performance_hints/performance_hints_features.cc b/chrome/browser/performance_hints/performance_hints_features.cc index 11854023..9085eb4 100644 --- a/chrome/browser/performance_hints/performance_hints_features.cc +++ b/chrome/browser/performance_hints/performance_hints_features.cc
@@ -28,12 +28,9 @@ const base::Feature kContextMenuPerformanceInfo{ "ContextMenuPerformanceInfo", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kPageInfoPerformanceHints{ - "PageInfoPerformanceHints", base::FEATURE_DISABLED_BY_DEFAULT}; bool IsPerformanceHintsObserverEnabled() { - return base::FeatureList::IsEnabled(kPageInfoPerformanceHints) || - IsContextMenuPerformanceInfoEnabled() || + return IsContextMenuPerformanceInfoEnabled() || base::FeatureList::IsEnabled(kPerformanceHintsObserver); }
diff --git a/chrome/browser/performance_hints/performance_hints_features.h b/chrome/browser/performance_hints/performance_hints_features.h index 281272f..c74166b 100644 --- a/chrome/browser/performance_hints/performance_hints_features.h +++ b/chrome/browser/performance_hints/performance_hints_features.h
@@ -12,9 +12,6 @@ namespace performance_hints { namespace features { -// Exposed for chrome://flags. -extern const base::Feature kPageInfoPerformanceHints; - // Exposed for testing. extern const base::Feature kPerformanceHintsObserver; extern const base::Feature kPerformanceHintsTreatUnknownAsFast;
diff --git a/chrome/browser/resources/new_tab_page/BUILD.gn b/chrome/browser/resources/new_tab_page/BUILD.gn index 4d63ef4..e14ae1b 100644 --- a/chrome/browser/resources/new_tab_page/BUILD.gn +++ b/chrome/browser/resources/new_tab_page/BUILD.gn
@@ -158,6 +158,7 @@ js_library("customize_shortcuts") { deps = [ + ":i18n_setup", ":mini_page", ":new_tab_page_proxy", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", @@ -211,6 +212,7 @@ js_library("logo") { deps = [ ":doodle_share_dialog", + ":i18n_setup", ":new_tab_page_proxy", ":window_proxy", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", @@ -220,6 +222,7 @@ js_library("doodle_share_dialog") { deps = [ + ":i18n_setup", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements/cr_button:cr_button.m", "//ui/webui/resources/cr_elements/cr_dialog:cr_dialog.m", @@ -241,7 +244,10 @@ } js_library("i18n_setup") { - deps = [ "//ui/webui/resources/js:load_time_data.m" ] + deps = [ + "//ui/webui/resources/js:i18n_behavior.m", + "//ui/webui/resources/js:load_time_data.m", + ] } html_to_js("web_components_local") {
diff --git a/chrome/browser/resources/new_tab_page/app.html b/chrome/browser/resources/new_tab_page/app.html index f6265f5..8fb0186b 100644 --- a/chrome/browser/resources/new_tab_page/app.html +++ b/chrome/browser/resources/new_tab_page/app.html
@@ -307,16 +307,16 @@ button in container to enfore solid background color. --> <div id="customizeButtonContainer"> <cr-button id="customizeButton" on-click="onCustomizeClick_" - title="$i18n{customizeThisPage}"> + title="[[i18n('customizeThisPage')]]"> <div id="customizeIcon"></div> <div id="customizeText" hidden$="[[showBackgroundImage_]]"> - $i18n{customizeButton} + [[i18n('customizeButton')]] </div> </cr-button> </div> <div id="themeAttribution" hidden$="[[!theme_.backgroundImage.attributionUrl]]"> - <div>$i18n{themeCreatedBy}</div> + <div>[[i18n('themeCreatedBy')]]</div> <img src="[[theme_.backgroundImage.attributionUrl.url]]"><img> </div> </template>
diff --git a/chrome/browser/resources/new_tab_page/app.js b/chrome/browser/resources/new_tab_page/app.js index 9ee086b3..6b62f6c 100644 --- a/chrome/browser/resources/new_tab_page/app.js +++ b/chrome/browser/resources/new_tab_page/app.js
@@ -14,11 +14,11 @@ import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {SkColor} from 'chrome://resources/mojo/skia/public/mojom/skcolor.mojom-webui.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BackgroundManager} from './background_manager.js'; import {BackgroundSelection, BackgroundSelectionType, CustomizeDialogPage} from './customize_dialog_types.js'; -import {loadTimeData} from './i18n_setup.js'; +import {I18nBehavior, loadTimeData} from './i18n_setup.js'; import {recordLoadDuration} from './metrics_utils.js'; import {ModuleRegistry} from './modules/module_registry.js'; import {NewTabPageProxy} from './new_tab_page_proxy.js'; @@ -43,7 +43,12 @@ document.body.appendChild(script); } -class AppElement extends PolymerElement { +/** + * @polymer + * @extends {PolymerElement} + */ +class AppElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-app'; }
diff --git a/chrome/browser/resources/new_tab_page/customize_backgrounds.html b/chrome/browser/resources/new_tab_page/customize_backgrounds.html index 04a0bbb6..e6a5da1 100644 --- a/chrome/browser/resources/new_tab_page/customize_backgrounds.html +++ b/chrome/browser/resources/new_tab_page/customize_backgrounds.html
@@ -164,7 +164,7 @@ </style> <div id="backgroundsDisabled" hidden$="[[!customBackgroundDisabledByPolicy_]]"> <div id="backgroundsDisabledIcon"></div> - <div id="backgroundsDisabledTitle">$i18n{customBackgroundDisabled}</div> + <div id="backgroundsDisabledTitle">[[i18n('customBackgroundDisabled')]]</div> </div> <cr-grid id="collections" columns="3" hidden="[[!showBackgroundSelection_]]"> <div id="uploadFromDevice" class="tile" role="button" @@ -174,7 +174,7 @@ </div> <div id="uploadFromDeviceImage"> <div id="uploadIcon"></div> - <div class="label">$i18n{uploadFromDevice}</div> + <div class="label">[[i18n('uploadFromDevice')]]</div> </div> <div class="selected-circle"></div> <div class="selected-check"></div> @@ -190,7 +190,7 @@ <div class="selected-circle"></div> <div class="selected-check"></div> </div> - <div class="label">$i18n{noBackground}</div> + <div class="label">[[i18n('noBackground')]]</div> </div> <dom-repeat id="collectionsRepeat" items="[[collections_]]"> <template>
diff --git a/chrome/browser/resources/new_tab_page/customize_backgrounds.js b/chrome/browser/resources/new_tab_page/customize_backgrounds.js index 0886937..02327d0 100644 --- a/chrome/browser/resources/new_tab_page/customize_backgrounds.js +++ b/chrome/browser/resources/new_tab_page/customize_backgrounds.js
@@ -7,14 +7,19 @@ import './mini_page.js'; import './iframe.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BackgroundSelection, BackgroundSelectionType} from './customize_dialog_types.js'; -import {loadTimeData} from './i18n_setup.js'; +import {I18nBehavior, loadTimeData} from './i18n_setup.js'; import {NewTabPageProxy} from './new_tab_page_proxy.js'; -/** Element that lets the user configure the background. */ -class CustomizeBackgroundsElement extends PolymerElement { +/** + * Element that lets the user configure the background. + * @polymer + * @extends {PolymerElement} + */ +class CustomizeBackgroundsElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-customize-backgrounds'; }
diff --git a/chrome/browser/resources/new_tab_page/customize_dialog.html b/chrome/browser/resources/new_tab_page/customize_dialog.html index 0a9e44b..afea897 100644 --- a/chrome/browser/resources/new_tab_page/customize_dialog.html +++ b/chrome/browser/resources/new_tab_page/customize_dialog.html
@@ -186,17 +186,17 @@ <div id="leftTitleSpacer"></div> <div id="title"> <div id="titleText" hidden="[[showTitleNavigation_]]"> - $i18n{customizeThisPage} + [[i18n('customizeThisPage')]] </div> <div id="titleNavigation" hidden="[[!showTitleNavigation_]]"> <cr-icon-button id="backButton" class="icon-arrow-back" - on-click="onBackClick_" title="$i18n{backButton}"> + on-click="onBackClick_" title="[[i18n('backButton')]]"> </cr-icon-button> <div id="collectionTitle">[[selectedCollection_.label]]</div> <cr-toggle id="refreshToggle" checked="[[isRefreshToggleChecked_]]" on-change="onBackgroundDailyRefreshToggleChange_"> </cr-toggle> - $i18n{refreshDaily} + [[i18n('refreshDaily')]] </div> </div> </div> @@ -209,21 +209,21 @@ on-keydown="onMenuItemKeyDown_" fallback-selection="backgrounds"> <div class="menu-item" page-name="backgrounds" tabindex="0"> <div id="backgroundsIcon" class="menu-item-icon"></div> - $i18n{backgroundsMenuItem} + [[i18n('backgroundsMenuItem')]] </div> <div class="menu-item" page-name="shortcuts" tabindex="0" hidden$="[[!shortcutsEnabled_]]"> <div id="shortcutsIcon" class="menu-item-icon"></div> - $i18n{shortcutsMenuItem} + [[i18n('shortcutsMenuItem')]] </div> <div class="menu-item" page-name="modules" tabindex="0" hidden$="[[!modulesEnabled_]]"> <div id="modulesIcon" class="menu-item-icon"></div> - $i18n{modulesMenuItem} + [[i18n('modulesMenuItem')]] </div> <div class="menu-item" page-name="themes" tabindex="0"> <div id="themesIcon" class="menu-item-icon"></div> - $i18n{themesMenuItem} + [[i18n('themesMenuItem')]] </div> </iron-selector> </div> @@ -247,10 +247,10 @@ </div> <div slot="button-container"> <cr-button class="cancel-button" on-click="onCancelClick_"> - $i18n{cancelButton} + [[i18n('cancelButton')]] </cr-button> <cr-button class="action-button" on-click="onDoneClick_"> - $i18n{doneButton} + [[i18n('doneButton')]] </cr-button> </div> </cr-dialog>
diff --git a/chrome/browser/resources/new_tab_page/customize_dialog.js b/chrome/browser/resources/new_tab_page/customize_dialog.js index 69dc8744..a256816 100644 --- a/chrome/browser/resources/new_tab_page/customize_dialog.js +++ b/chrome/browser/resources/new_tab_page/customize_dialog.js
@@ -14,18 +14,21 @@ import './customize_modules.js'; import {assert} from 'chrome://resources/js/assert.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BackgroundSelection, BackgroundSelectionType, CustomizeDialogPage} from './customize_dialog_types.js'; -import {loadTimeData} from './i18n_setup.js'; +import {I18nBehavior, loadTimeData} from './i18n_setup.js'; import {NewTabPageProxy} from './new_tab_page_proxy.js'; import {createScrollBorders} from './utils.js'; /** * Dialog that lets the user customize the NTP such as the background color or * image. + * @polymer + * @extends {PolymerElement} */ -class CustomizeDialogElement extends PolymerElement { +class CustomizeDialogElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-customize-dialog'; }
diff --git a/chrome/browser/resources/new_tab_page/customize_modules.html b/chrome/browser/resources/new_tab_page/customize_modules.html index 2c52495..5e6a60a 100644 --- a/chrome/browser/resources/new_tab_page/customize_modules.html +++ b/chrome/browser/resources/new_tab_page/customize_modules.html
@@ -62,10 +62,10 @@ disabled="[[showManagedByPolicy_]]" on-selected-changed="onShowRadioSelectionChanged_"> <cr-radio-button id="hideButton" name="hide"> - $i18n{hideAllCards} + [[i18n('hideAllCards')]] </cr-radio-button> <cr-radio-button id="customizeButton" name="customize"> - $i18n{customizeCards} + [[i18n('customizeCards')]] </cr-radio-button> </cr-radio-group> <cr-policy-indicator indicator-type="devicePolicy" @@ -92,7 +92,7 @@ "[[showDiscountToggle_(item.id, item.checked, discountToggleEligible_)]]"> <div class="discount-toggle-row"> <div class="toggle-name"> - $i18n{modulesCartDiscountConsentAccept} + [[i18n('modulesCartDiscountConsentAccept')]] </div> <cr-toggle checked="{{discountToggle_.enabled}}"></cr-toggle> </div>
diff --git a/chrome/browser/resources/new_tab_page/customize_modules.js b/chrome/browser/resources/new_tab_page/customize_modules.js index 8baddc1..acfa29f 100644 --- a/chrome/browser/resources/new_tab_page/customize_modules.js +++ b/chrome/browser/resources/new_tab_page/customize_modules.js
@@ -10,15 +10,20 @@ import 'chrome://resources/cr_elements/policy/cr_policy_indicator.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from './i18n_setup.js'; +import {I18nBehavior, loadTimeData} from './i18n_setup.js'; import {ChromeCartProxy} from './modules/cart/chrome_cart_proxy.js'; import {ModuleRegistry} from './modules/module_registry.js'; import {NewTabPageProxy} from './new_tab_page_proxy.js'; -/** Element that lets the user configure modules settings. */ -class CustomizeModulesElement extends PolymerElement { +/** + * Element that lets the user configure modules settings. + * @polymer + * @extends {PolymerElement} + */ +class CustomizeModulesElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-customize-modules'; }
diff --git a/chrome/browser/resources/new_tab_page/customize_shortcuts.html b/chrome/browser/resources/new_tab_page/customize_shortcuts.html index ed5451c..4e3c5131 100644 --- a/chrome/browser/resources/new_tab_page/customize_shortcuts.html +++ b/chrome/browser/resources/new_tab_page/customize_shortcuts.html
@@ -244,7 +244,7 @@ <cr-button id="optionCustomLinksButton" class="option-image" tabindex="0" aria-pressed$="[[getCustomLinksAriaPressed_(customLinksEnabled_, hide_)]]" - title="$i18n{myShortcuts}" on-click="onCustomLinksClick_" noink> + title="[[i18n('myShortcuts')]]" on-click="onCustomLinksClick_" noink> <div class="option-icon"></div> <div class="option-mini"> <ntp-mini-page single-colored-logo></ntp-mini-page> @@ -252,15 +252,15 @@ <div class="selected-circle"></div> <div class="selected-check"></div> </cr-button> - <div class="option-title">$i18n{myShortcuts}</div> - <div class="option-description">$i18n{shortcutsCurated}</div> + <div class="option-title">[[i18n('myShortcuts')]]</div> + <div class="option-description">[[i18n('shortcutsCurated')]]</div> </div> <div id="optionMostVisited" class$="option [[getMostVisitedSelected_(customLinksEnabled_, hide_)]]"> <cr-button id="optionMostVisitedButton" class="option-image" tabindex="0" aria-pressed$="[[getMostVisitedAriaPressed_(customLinksEnabled_, hide_)]]" - title="$i18n{mostVisited}" on-click="onMostVisitedClick_" + title="[[i18n('mostVisited')]]" on-click="onMostVisitedClick_" on-keydown="onMostVistedKey" noink> <div class="option-icon"></div> <div class="option-mini"> @@ -269,18 +269,18 @@ <div class="selected-circle"></div> <div class="selected-check"></div> </cr-button> - <div class="option-title">$i18n{mostVisited}</div> - <div class="option-description">$i18n{shortcutsSuggested}</div> + <div class="option-title">[[i18n('mostVisited')]]</div> + <div class="option-description">[[i18n('shortcutsSuggested')]]</div> </div> </div> <div id="hide" class$="[[getHideClass_(hide_)]]"> <div id="hideIcon" class="cr-icon icon-visibility-off"></div> <div id="hideTitleContainer"> - <div id="hideTitle">$i18n{hideShortcuts}</div> + <div id="hideTitle">[[i18n('hideShortcuts')]]</div> <div id="hideDescription" class="option-description"> - $i18n{hideShortcutsDesc} + [[i18n('hideShortcutsDesc')]] </div> </div> - <cr-toggle id="hideToggle" title="$i18n{hideShortcuts}" checked="[[hide_]]" - on-change="onHideChange_"></cr-toggle> + <cr-toggle id="hideToggle" title="[[i18n('hideShortcuts')]]" + checked="[[hide_]]" on-change="onHideChange_"></cr-toggle> </div>
diff --git a/chrome/browser/resources/new_tab_page/customize_shortcuts.js b/chrome/browser/resources/new_tab_page/customize_shortcuts.js index 4192b1eac..5591393a 100644 --- a/chrome/browser/resources/new_tab_page/customize_shortcuts.js +++ b/chrome/browser/resources/new_tab_page/customize_shortcuts.js
@@ -9,12 +9,18 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {I18nBehavior} from './i18n_setup.js'; import {NewTabPageProxy} from './new_tab_page_proxy.js'; -/** Element that lets the user configure shortcut settings. */ -class CustomizeShortcutsElement extends PolymerElement { +/** + * Element that lets the user configure shortcut settings. + * @polymer + * @extends {PolymerElement} + */ +class CustomizeShortcutsElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-customize-shortcuts'; }
diff --git a/chrome/browser/resources/new_tab_page/doodle_share_dialog.html b/chrome/browser/resources/new_tab_page/doodle_share_dialog.html index c41b624..0d1996b 100644 --- a/chrome/browser/resources/new_tab_page/doodle_share_dialog.html +++ b/chrome/browser/resources/new_tab_page/doodle_share_dialog.html
@@ -56,26 +56,26 @@ </div> <div slot="body"> <div id="buttons"> - <cr-button id="facebookButton" title="$i18n{facebook}" + <cr-button id="facebookButton" title="[[i18n('facebook')]]" on-click="onFacebookClick_"> </cr-button> - <cr-button id="twitterButton" title="$i18n{twitter}" + <cr-button id="twitterButton" title="[[i18n('twitter')]]" on-click="onTwitterClick_"> </cr-button> - <cr-button id="emailButton" title="$i18n{email}" + <cr-button id="emailButton" title="[[i18n('email')]]" on-click="onEmailClick_"> </cr-button> </div> - <cr-input readonly label="$i18n{doodleLink}" id="url" + <cr-input readonly label="[[i18n('doodleLink')]]" id="url" value="[[url.url]]"> - <cr-icon-button id="copyButton" slot="suffix" title="$i18n{copyLink}" + <cr-icon-button id="copyButton" slot="suffix" title="[[i18n('copyLink')]]" on-click="onCopyClick_"> </cr-icon-button> </cr-input> </div> <div slot="button-container"> <cr-button id="doneButton" class="action-button" on-click="onCloseClick_"> - $i18n{doneButton} + [[i18n('doneButton')]] </cr-button> </div> </cr-dialog>
diff --git a/chrome/browser/resources/new_tab_page/doodle_share_dialog.js b/chrome/browser/resources/new_tab_page/doodle_share_dialog.js index ea61ff0..c4bd001 100644 --- a/chrome/browser/resources/new_tab_page/doodle_share_dialog.js +++ b/chrome/browser/resources/new_tab_page/doodle_share_dialog.js
@@ -7,7 +7,9 @@ import 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + +import {I18nBehavior} from './i18n_setup.js'; import {WindowProxy} from './window_proxy.js'; /** @@ -16,8 +18,13 @@ */ const FACEBOOK_APP_ID = 738026486351791; -// Dialog that lets the user share the doodle. -class DoodleShareDialogElement extends PolymerElement { +/** + * Dialog that lets the user share the doodle. + * @polymer + * @extends {PolymerElement} + */ +class DoodleShareDialogElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-doodle-share-dialog'; }
diff --git a/chrome/browser/resources/new_tab_page/i18n_setup.js b/chrome/browser/resources/new_tab_page/i18n_setup.js index cd20bad..b109446 100644 --- a/chrome/browser/resources/new_tab_page/i18n_setup.js +++ b/chrome/browser/resources/new_tab_page/i18n_setup.js
@@ -3,4 +3,6 @@ // found in the LICENSE file. import './strings.m.js'; + +export {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js'; export {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
diff --git a/chrome/browser/resources/new_tab_page/logo.html b/chrome/browser/resources/new_tab_page/logo.html index 02ab0a2..31c7fa5 100644 --- a/chrome/browser/resources/new_tab_page/logo.html +++ b/chrome/browser/resources/new_tab_page/logo.html
@@ -118,7 +118,7 @@ <ntp-iframe id="animation" src="[[animationUrl_]]" hidden="[[!showAnimation_]]"> </ntp-iframe> - <cr-button id="shareButton" title="$i18n{shareDoodle}" + <cr-button id="shareButton" title="[[i18n('shareDoodle')]]" on-click="onShareButtonClick_" hidden="[[!imageDoodle_.shareButton]]"> <img id="shareButtonImage"
diff --git a/chrome/browser/resources/new_tab_page/logo.js b/chrome/browser/resources/new_tab_page/logo.js index f965b9d..0049a532 100644 --- a/chrome/browser/resources/new_tab_page/logo.js +++ b/chrome/browser/resources/new_tab_page/logo.js
@@ -10,8 +10,9 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {skColorToRgba} from 'chrome://resources/js/color_utils.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {I18nBehavior} from './i18n_setup.js'; import {NewTabPageProxy} from './new_tab_page_proxy.js'; import {$$} from './utils.js'; import {WindowProxy} from './window_proxy.js'; @@ -19,8 +20,13 @@ /** @type {number} */ const SHARE_BUTTON_SIZE_PX = 26; -// Shows the Google logo or a doodle if available. -class LogoElement extends PolymerElement { +/** + * Shows the Google logo or a doodle if available. + * @polymer + * @extends {PolymerElement} + */ +class LogoElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-logo'; }
diff --git a/chrome/browser/resources/new_tab_page/modules/BUILD.gn b/chrome/browser/resources/new_tab_page/modules/BUILD.gn index 2b36071..bb48c72 100644 --- a/chrome/browser/resources/new_tab_page/modules/BUILD.gn +++ b/chrome/browser/resources/new_tab_page/modules/BUILD.gn
@@ -60,6 +60,7 @@ js_library("module_header") { deps = [ + "..:i18n_setup", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", ] } @@ -74,6 +75,7 @@ js_library("info_dialog") { deps = [ + "..:i18n_setup", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements/cr_button:cr_button.m", "//ui/webui/resources/cr_elements/cr_dialog:cr_dialog.m",
diff --git a/chrome/browser/resources/new_tab_page/modules/cart/BUILD.gn b/chrome/browser/resources/new_tab_page/modules/cart/BUILD.gn index abe25b20..b3975a0 100644 --- a/chrome/browser/resources/new_tab_page/modules/cart/BUILD.gn +++ b/chrome/browser/resources/new_tab_page/modules/cart/BUILD.gn
@@ -15,7 +15,6 @@ "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu.m", "//ui/webui/resources/cr_elements/cr_icon_button:cr_icon_button.m", "//ui/webui/resources/cr_elements/cr_toast:cr_toast.m", - "//ui/webui/resources/js:i18n_behavior.m", ] }
diff --git a/chrome/browser/resources/new_tab_page/modules/cart/module.html b/chrome/browser/resources/new_tab_page/modules/cart/module.html index 542934c..d3cb637 100644 --- a/chrome/browser/resources/new_tab_page/modules/cart/module.html +++ b/chrome/browser/resources/new_tab_page/modules/cart/module.html
@@ -279,7 +279,7 @@ 'modulesCartLower')]]" show-dismiss-button on-dismiss-button-click="onDismissButtonClick_" on-disable-button-click="onDisableButtonClick_"> - $i18n{modulesCartSentence} + [[i18n('modulesCartSentence')]] </ntp-module-header> <div id="moduleContent"> <template is="dom-if" if="[[showLeftScrollButton_]]"> @@ -297,18 +297,18 @@ <div id="consentIcon"></div> </div> <span id="consentContent"> - $i18n{modulesCartDiscountConsentContent} + [[i18n('modulesCartDiscountConsentContent')]] </span> <div id="consentButtonContainer"> <cr-button id="cancelButton" class="cancel-button" on-click="onDisallowDiscount_" on-auxclick="onDisallowDiscount_"> - $i18n{modulesCartDiscountConsentReject} + [[i18n('modulesCartDiscountConsentReject')]] </cr-button> <cr-button id="actionButton" class="action-button" on-click="onAllowDiscount_" on-auxclick="onAllowDiscount_"> - $i18n{modulesCartDiscountConsentAccept} + [[i18n('modulesCartDiscountConsentAccept')]] </cr-button> </div> </div> @@ -321,7 +321,7 @@ <div class="discount-chip">[[item.discountText]]</div> </template> <cr-icon-button class="icon-more-vert" - title="$i18n{moreActions}" on-click="onCartMenuButtonClick_"> + title="[[i18n('moreActions')]]" on-click="onCartMenuButtonClick_"> </cr-icon-button> <img class="favicon-image" is="ntp-img" auto-src="[[getFaviconUrl_(item.cartUrl.url)]]"></img> @@ -379,7 +379,7 @@ </div> <cr-button id="undoDismissCartButton" on-click="onUndoDismissCartButtonClick_"> - $i18n{undo} + [[i18n('undo')]] </cr-button> </cr-toast> <cr-toast id="confirmDiscountConsentToast" duration="10000"> @@ -388,6 +388,6 @@ </div> <cr-button id="confirmDiscountConsentButton" on-click="onConfirmDiscountConsentClick_"> - $i18n{modulesCartDiscountConsentConfirmationDismiss} + [[i18n('modulesCartDiscountConsentConfirmationDismiss')]] </cr-button> </cr-toast>
diff --git a/chrome/browser/resources/new_tab_page/modules/cart/module.js b/chrome/browser/resources/new_tab_page/modules/cart/module.js index 2c853c4..c75aef3 100644 --- a/chrome/browser/resources/new_tab_page/modules/cart/module.js +++ b/chrome/browser/resources/new_tab_page/modules/cart/module.js
@@ -10,10 +10,9 @@ import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.m.js'; import 'chrome://resources/cr_elements/cr_toast/cr_toast.m.js'; -import {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js'; import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from '../../i18n_setup.js'; +import {I18nBehavior, loadTimeData} from '../../i18n_setup.js'; import {$$} from '../../utils.js'; import {ModuleDescriptor} from '../module_descriptor.js';
diff --git a/chrome/browser/resources/new_tab_page/modules/drive/BUILD.gn b/chrome/browser/resources/new_tab_page/modules/drive/BUILD.gn index cd67cb4..90c00ab0 100644 --- a/chrome/browser/resources/new_tab_page/modules/drive/BUILD.gn +++ b/chrome/browser/resources/new_tab_page/modules/drive/BUILD.gn
@@ -13,7 +13,6 @@ "../..:i18n_setup", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements/cr_lazy_render:cr_lazy_render.m", - "//ui/webui/resources/js:i18n_behavior.m", ] }
diff --git a/chrome/browser/resources/new_tab_page/modules/drive/module.html b/chrome/browser/resources/new_tab_page/modules/drive/module.html index 88aa2196..5dc3a62 100644 --- a/chrome/browser/resources/new_tab_page/modules/drive/module.html +++ b/chrome/browser/resources/new_tab_page/modules/drive/module.html
@@ -72,7 +72,7 @@ 'modulesDriveSentence')]]" show-info-button on-info-button-click="onInfoButtonClick_" on-disable-button-click="onDisableButtonClick_"> - $i18n{modulesDriveTitle} + [[i18n('modulesDriveTitle')]] </ntp-module-header> <div id="files"> <template id="fileRepeat" is="dom-repeat" items="[[files]]"> @@ -93,6 +93,7 @@ </div> <cr-lazy-render id="infoDialogRender"> <template> - <ntp-info-dialog>$i18nRaw{modulesDriveInfo}</ntp-info-dialog> + <ntp-info-dialog inner-h-t-m-l="[[i18nAdvanced('modulesDriveInfo')]]"> + </ntp-info-dialog> </template> </cr-lazy-render>
diff --git a/chrome/browser/resources/new_tab_page/modules/drive/module.js b/chrome/browser/resources/new_tab_page/modules/drive/module.js index c2c83f5..b46e52f5 100644 --- a/chrome/browser/resources/new_tab_page/modules/drive/module.js +++ b/chrome/browser/resources/new_tab_page/modules/drive/module.js
@@ -5,10 +5,9 @@ import '../module_header.js'; import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; -import {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js'; import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from '../../i18n_setup.js'; +import {I18nBehavior, loadTimeData} from '../../i18n_setup.js'; import {InfoDialogElement} from '../info_dialog.js'; import {ModuleDescriptor} from '../module_descriptor.js';
diff --git a/chrome/browser/resources/new_tab_page/modules/dummy/BUILD.gn b/chrome/browser/resources/new_tab_page/modules/dummy/BUILD.gn index 0abc4d4..c25f55ed 100644 --- a/chrome/browser/resources/new_tab_page/modules/dummy/BUILD.gn +++ b/chrome/browser/resources/new_tab_page/modules/dummy/BUILD.gn
@@ -13,7 +13,6 @@ "../..:img", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements/cr_grid", - "//ui/webui/resources/js:i18n_behavior.m", ] }
diff --git a/chrome/browser/resources/new_tab_page/modules/dummy/module.js b/chrome/browser/resources/new_tab_page/modules/dummy/module.js index 39e7e1ab..eab0a43 100644 --- a/chrome/browser/resources/new_tab_page/modules/dummy/module.js +++ b/chrome/browser/resources/new_tab_page/modules/dummy/module.js
@@ -7,10 +7,9 @@ import '../../strings.m.js'; import '../module_header.js'; -import {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js'; import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from '../../i18n_setup.js'; +import {I18nBehavior, loadTimeData} from '../../i18n_setup.js'; import {ModuleDescriptor} from '../module_descriptor.js'; import {FooProxy} from './foo_proxy.js';
diff --git a/chrome/browser/resources/new_tab_page/modules/info_dialog.html b/chrome/browser/resources/new_tab_page/modules/info_dialog.html index 730de21..bea3fa2 100644 --- a/chrome/browser/resources/new_tab_page/modules/info_dialog.html +++ b/chrome/browser/resources/new_tab_page/modules/info_dialog.html
@@ -14,13 +14,13 @@ } </style> <cr-dialog id="dialog" consume-keydown-event> - <div slot="title">$i18n{modulesTasksInfoTitle}</div> + <div slot="title">[[i18n('modulesTasksInfoTitle')]]</div> <div slot="body"> <slot></slot> </div> <div slot="button-container"> <cr-button id="closeButton" class="action-button" on-click="onCloseClick_"> - $i18n{modulesTasksInfoClose} + [[i18n('modulesTasksInfoClose')]] </cr-button> </div> </cr-dialog>
diff --git a/chrome/browser/resources/new_tab_page/modules/info_dialog.js b/chrome/browser/resources/new_tab_page/modules/info_dialog.js index b6b765a3..f0499fe 100644 --- a/chrome/browser/resources/new_tab_page/modules/info_dialog.js +++ b/chrome/browser/resources/new_tab_page/modules/info_dialog.js
@@ -5,13 +5,17 @@ import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + +import {I18nBehavior} from '../i18n_setup.js'; /** * Info dialog that can be populated with custom text via slotting. * @polymer + * @extends {PolymerElement} */ -export class InfoDialogElement extends PolymerElement { +export class InfoDialogElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-info-dialog'; }
diff --git a/chrome/browser/resources/new_tab_page/modules/module_header.html b/chrome/browser/resources/new_tab_page/modules/module_header.html index 32b1d73..6aad5dd5 100644 --- a/chrome/browser/resources/new_tab_page/modules/module_header.html +++ b/chrome/browser/resources/new_tab_page/modules/module_header.html
@@ -58,11 +58,11 @@ </template> <div id="headerSpacer"></div> <template is="dom-if" if="[[showInfoButton]]"> - <cr-icon-button id="infoButton" title="$i18n{moduleInfoButtonTitle}" + <cr-icon-button id="infoButton" title="[[i18n('moduleInfoButtonTitle')]]" on-click="onInfoButtonClick_"> </cr-icon-button> </template> - <cr-icon-button id="menuButton" title="$i18n{moreActions}" + <cr-icon-button id="menuButton" title="[[i18n('moreActions')]]" class="icon-more-vert" on-click="onMenuButtonClick_"> </cr-icon-button> </div> @@ -82,6 +82,6 @@ </button> <button id="customizeButton" class="dropdown-item" on-click="onCustomizeButtonClick_"> - $i18n{modulesCustomizeButtonText} + [[i18n('modulesCustomizeButtonText')]] </button> </cr-action-menu>
diff --git a/chrome/browser/resources/new_tab_page/modules/module_header.js b/chrome/browser/resources/new_tab_page/modules/module_header.js index 162e12c..6d75558 100644 --- a/chrome/browser/resources/new_tab_page/modules/module_header.js +++ b/chrome/browser/resources/new_tab_page/modules/module_header.js
@@ -4,11 +4,17 @@ import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -/** @fileoverview Element that displays a header inside a module. */ +import {I18nBehavior} from '../i18n_setup.js'; -export class ModuleHeaderElement extends PolymerElement { +/** + * Element that displays a header inside a module. + * @polymer + * @extends {PolymerElement} + */ +export class ModuleHeaderElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-module-header'; }
diff --git a/chrome/browser/resources/new_tab_page/modules/modules.html b/chrome/browser/resources/new_tab_page/modules/modules.html index e03ac22..bedde0a 100644 --- a/chrome/browser/resources/new_tab_page/modules/modules.html +++ b/chrome/browser/resources/new_tab_page/modules/modules.html
@@ -24,8 +24,8 @@ <cr-toast id="removeModuleToast" duration="10000"> <div id="removeModuleToastMessage">[[removedModuleData_.message]]</div> <cr-button id="undoRemoveModuleButton" - aria-label="$i18n{undoDescription}" + aria-label="[[i18n('undoDescription')]]" on-click="onUndoRemoveModuleButtonClick_"> - $i18n{undo} + [[i18n('undo')]] </cr-button> </cr-toast>
diff --git a/chrome/browser/resources/new_tab_page/modules/modules.js b/chrome/browser/resources/new_tab_page/modules/modules.js index d533f634..90a21d31 100644 --- a/chrome/browser/resources/new_tab_page/modules/modules.js +++ b/chrome/browser/resources/new_tab_page/modules/modules.js
@@ -9,17 +9,22 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; -import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {I18nBehavior, loadTimeData} from '../i18n_setup.js'; import {NewTabPageProxy} from '../new_tab_page_proxy.js'; import {$$} from '../utils.js'; import {Module} from './module_descriptor.js'; import {ModuleRegistry} from './module_registry.js'; -/** Container for the NTP modules. */ -export class ModulesElement extends PolymerElement { +/** + * Container for the NTP modules. + * @polymer + * @extends {PolymerElement} + */ +export class ModulesElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-modules'; }
diff --git a/chrome/browser/resources/new_tab_page/modules/task_module/BUILD.gn b/chrome/browser/resources/new_tab_page/modules/task_module/BUILD.gn index 68d2e03..c4ee839 100644 --- a/chrome/browser/resources/new_tab_page/modules/task_module/BUILD.gn +++ b/chrome/browser/resources/new_tab_page/modules/task_module/BUILD.gn
@@ -15,7 +15,6 @@ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/cr_elements/cr_grid", "//ui/webui/resources/cr_elements/cr_lazy_render:cr_lazy_render.m", - "//ui/webui/resources/js:i18n_behavior.m", ] }
diff --git a/chrome/browser/resources/new_tab_page/modules/task_module/module.html b/chrome/browser/resources/new_tab_page/modules/task_module/module.html index fb5c6a96..80453dd2 100644 --- a/chrome/browser/resources/new_tab_page/modules/task_module/module.html +++ b/chrome/browser/resources/new_tab_page/modules/task_module/module.html
@@ -233,6 +233,7 @@ </div> <cr-lazy-render id="infoDialogRender"> <template> - <ntp-info-dialog>$i18nRaw{modulesTasksInfo}</ntp-info-dialog> + <ntp-info-dialog inner-h-t-m-l="[[i18nAdvanced('modulesTasksInfo')]]"> + </ntp-info-dialog> </template> </cr-lazy-render>
diff --git a/chrome/browser/resources/new_tab_page/modules/task_module/module.js b/chrome/browser/resources/new_tab_page/modules/task_module/module.js index 9d5316d..bb2a37d 100644 --- a/chrome/browser/resources/new_tab_page/modules/task_module/module.js +++ b/chrome/browser/resources/new_tab_page/modules/task_module/module.js
@@ -7,10 +7,9 @@ import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import 'chrome://resources/cr_elements/hidden_style_css.m.js'; -import {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js'; import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from '../../i18n_setup.js'; +import {I18nBehavior, loadTimeData} from '../../i18n_setup.js'; import {InfoDialogElement} from '../info_dialog.js'; import {ModuleDescriptor} from '../module_descriptor.js';
diff --git a/chrome/browser/resources/new_tab_page/most_visited.html b/chrome/browser/resources/new_tab_page/most_visited.html index 0316dda..a6cd63b 100644 --- a/chrome/browser/resources/new_tab_page/most_visited.html +++ b/chrome/browser/resources/new_tab_page/most_visited.html
@@ -207,10 +207,10 @@ on-click="onTileClick_" on-keydown="onTileKeyDown_" query-tile$="[[item.isQueryTile]]"> <cr-icon-button id="actionMenuButton" class="icon-more-vert" - title="$i18n{moreActions}" on-click="onTileActionButtonClick_" + title="[[i18n('moreActions')]]" on-click="onTileActionButtonClick_" tabindex="0" hidden$="[[!customLinksEnabled_]]"></cr-icon-button> <cr-icon-button id="removeButton" class="icon-clear" - title="$i18n{linkRemove}" on-click="onTileRemoveButtonClick_" + title="[[i18n('linkRemove')]]" on-click="onTileRemoveButtonClick_" tabindex="0" hidden$="[[customLinksEnabled_]]"></cr-icon-button> <div class="tile-icon"> <img src$="[[getFaviconUrl_(item.url)]]" draggable="false" @@ -230,15 +230,15 @@ <div id="addShortcutIcon" draggable="false"></div> </div> <div class="tile-title"> - <span>$i18n{addLinkTitle}</span> + <span>[[i18n('addLinkTitle')]]</span> </div> </cr-button> <cr-dialog id="dialog" on-close="onDialogClose_"> <div slot="title">[[dialogTitle_]]</div> <div slot="body"> - <cr-input id="dialogInputName" label="$i18n{nameField}" + <cr-input id="dialogInputName" label="[[i18n('nameField')]]" value="{{dialogTileTitle_}}" spellcheck="false" autofocus></cr-input> - <cr-input id="dialogInputUrl" label="$i18n{urlField}" + <cr-input id="dialogInputUrl" label="[[i18n('urlField')]]" value="{{dialogTileUrl_}}" invalid="[[dialogTileUrlInvalid_]]" error-message="[[dialogTileUrlError_]]" spellcheck="false" type="url" on-blur="onDialogTileUrlBlur_"> @@ -246,20 +246,20 @@ </div> <div slot="button-container"> <cr-button class="cancel-button" on-click="onDialogCancel_"> - $i18n{linkCancel} + [[i18n('linkCancel')]] </cr-button> <cr-button class="action-button" on-click="onSave_" disabled$="[[dialogSaveDisabled_]]"> - $i18n{linkDone} + [[i18n('linkDone')]] </cr-button> </div> </cr-dialog> <cr-action-menu id="actionMenu"> <button id="actionMenuEdit" class="dropdown-item" on-click="onEdit_"> - $i18n{editLinkTitle} + [[i18n('editLinkTitle')]] </button> <button id="actionMenuRemove" class="dropdown-item" on-click="onRemove_"> - $i18n{linkRemove} + [[i18n('linkRemove')]] </button> </cr-action-menu> </div> @@ -267,9 +267,9 @@ <div>[[toastContent_]]</div> <dom-if if="[[showToastButtons_]]"> <template> - <cr-button id="undo" aria-label="$i18n{undoDescription}" + <cr-button id="undo" aria-label="[[i18n('undoDescription')]]" on-click="onUndoClick_"> - $i18n{undo} + [[i18n('undo')]] </cr-button> <cr-button id="restore" aria-label$="[[getRestoreButtonText_(customLinksEnabled_)]]"
diff --git a/chrome/browser/resources/new_tab_page/most_visited.js b/chrome/browser/resources/new_tab_page/most_visited.js index cf97e742..0360945 100644 --- a/chrome/browser/resources/new_tab_page/most_visited.js +++ b/chrome/browser/resources/new_tab_page/most_visited.js
@@ -18,9 +18,9 @@ import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {hasKeyModifiers} from 'chrome://resources/js/util.m.js'; -import {Debouncer, html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from './i18n_setup.js'; +import {I18nBehavior, loadTimeData} from './i18n_setup.js'; import {NewTabPageProxy} from './new_tab_page_proxy.js'; import {WindowProxy} from './window_proxy.js'; @@ -86,7 +86,12 @@ return null; } -class MostVisitedElement extends PolymerElement { +/** + * @polymer + * @extends {PolymerElement} + */ +class MostVisitedElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-most-visited'; }
diff --git a/chrome/browser/resources/new_tab_page/realbox/realbox.html b/chrome/browser/resources/new_tab_page/realbox/realbox.html index 156be8d..d2e6cd2b 100644 --- a/chrome/browser/resources/new_tab_page/realbox/realbox.html +++ b/chrome/browser/resources/new_tab_page/realbox/realbox.html
@@ -105,7 +105,7 @@ on-keydown="onInputWrapperKeydown_"> <input id="input" type="search" autocomplete="off" spellcheck="false" aria-live="[[inputAriaLive_]]" role="combobox" - placeholder="$i18n{searchBoxHint}" + placeholder="[[i18n('searchBoxHint')]]" on-copy="onInputCutCopy_" on-cut="onInputCutCopy_" on-focus="onInputFocus_" on-blur="onInputBlur_" on-input="onInputInput_" on-keydown="onInputKeydown_" on-keyup="onInputKeyup_" @@ -114,7 +114,7 @@ default-icon="[[realboxIcon_]]" in-searchbox> </ntp-realbox-icon> <button id="voiceSearchButton" on-click="onVoiceSearchClick_" - title="$i18n{voiceSearchButtonLabel}"> + title="[[i18n('voiceSearchButtonLabel')]]"> </button> <ntp-realbox-dropdown id="matches" role="listbox" theme="[[theme]]" result="[[result_]]" selected-match-index="{{selectedMatchIndex_}}"
diff --git a/chrome/browser/resources/new_tab_page/realbox/realbox.js b/chrome/browser/resources/new_tab_page/realbox/realbox.js index 4d17c0a..3b548f4 100644 --- a/chrome/browser/resources/new_tab_page/realbox/realbox.js +++ b/chrome/browser/resources/new_tab_page/realbox/realbox.js
@@ -8,9 +8,9 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {skColorToRgba} from 'chrome://resources/js/color_utils.js'; import {hasKeyModifiers} from 'chrome://resources/js/util.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from '../i18n_setup.js'; +import {I18nBehavior, loadTimeData} from '../i18n_setup.js'; import {decodeString16, mojoString16, mojoTimeDelta} from '../utils.js'; import {RealboxBrowserProxy} from './realbox_browser_proxy.js'; @@ -27,8 +27,13 @@ */ let InputUpdate; -// A real search box that behaves just like the Omnibox. -class RealboxElement extends PolymerElement { +/** + * A real search box that behaves just like the Omnibox. + * @polymer + * @extends {PolymerElement} + */ +class RealboxElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-realbox'; }
diff --git a/chrome/browser/resources/new_tab_page/voice_search_overlay.html b/chrome/browser/resources/new_tab_page/voice_search_overlay.html index 040d451..5ca35cc 100644 --- a/chrome/browser/resources/new_tab_page/voice_search_overlay.html +++ b/chrome/browser/resources/new_tab_page/voice_search_overlay.html
@@ -179,17 +179,17 @@ on-keydown="onOverlayKeydown_"> <!-- Purely exists to capture focus upon opening the dialog. --> <div tabindex="-1"></div> - <cr-icon-button id="closeButton" class="icon-clear" title="$i18n{close}"> + <cr-icon-button id="closeButton" class="icon-clear" title="[[i18n('close')]]"> </cr-icon-button> <div id="content"> <iron-selector id="texts" selected="[[getText_(state_)]]" attr-for-selected="text" fallback-selection="none" aria-live="polite" selected-attribute="visible" class="display-stack"> <div text="none"></div> - <div text="waiting">$i18n{waiting}</div> + <div text="waiting">[[i18n('waiting')]]</div> <div text="speak" class="display-stack"> - <div id="speak">$i18n{speak}</div> - <div id="listening">$i18n{listening}</div> + <div id="speak">[[i18n('speak')]]</div> + <div id="listening">[[i18n('listening')]]</div> </div> <div text="result" aria-hidden="true"> <span id="finalResult">[[finalResult_]]</span> @@ -198,28 +198,28 @@ <div text="error"> <iron-pages id="errors" selected="[[getErrorText_(error_)]]" attr-for-selected="error" fallback-selection="other"> - <span error="no-speech">$i18n{noVoice}</span> - <span error="audio-capture">$i18n{audioError}</span> - <span error="network">$i18n{networkError}</span> - <span error="not-allowed">$i18n{permissionError}</span> - <span error="language-not-supported">$i18n{languageError}</span> - <span error="no-match">$i18n{noTranslation}</span> - <span error="other">$i18n{otherError}</span> + <span error="no-speech">[[i18n('noVoice')]]</span> + <span error="audio-capture">[[i18n('audioError')]]</span> + <span error="network">[[i18n('networkError')]]</span> + <span error="not-allowed">[[i18n('permissionError')]]</span> + <span error="language-not-supported">[[i18n('languageError')]]</span> + <span error="no-match">[[i18n('noTranslation')]]</span> + <span error="other">[[i18n('otherError')]]</span> </iron-pages> <iron-pages id="errorLinks" selected="[[getErrorLink_(error_)]]" attr-for-selected="link" fallback-selection="none"> <span link="none"></span> <a link="learn-more" target="_blank" href="[[helpUrl_]]" on-click="onLearnMoreClick_" on-keydown="onLinkKeydown_"><!-- - -->$i18n{learnMore} + -->[[i18n('learnMore')]] </a> <a link="details" target="_blank" href="[[helpUrl_]]" on-keydown="onLinkKeydown_"><!-- - -->$i18n{details} + -->[[i18n('details')]] </a> <a link="try-again" id="retryLink" href="#" on-click="onTryAgainClick_" on-keydown="onLinkKeydown_"><!-- - -->$i18n{tryAgain} + -->[[i18n('tryAgain')]] </a> </iron-pages> </div>
diff --git a/chrome/browser/resources/new_tab_page/voice_search_overlay.js b/chrome/browser/resources/new_tab_page/voice_search_overlay.js index a691919..e36b208 100644 --- a/chrome/browser/resources/new_tab_page/voice_search_overlay.js +++ b/chrome/browser/resources/new_tab_page/voice_search_overlay.js
@@ -7,9 +7,9 @@ import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {loadTimeData} from './i18n_setup.js'; +import {I18nBehavior, loadTimeData} from './i18n_setup.js'; import {NewTabPageProxy} from './new_tab_page_proxy.js'; import {WindowProxy} from './window_proxy.js'; @@ -182,8 +182,13 @@ } } -// Overlay that lats the user perform voice searches. -class VoiceSearchOverlayElement extends PolymerElement { +/** + * Overlay that lats the user perform voice searches. + * @polymer + * @extends {PolymerElement} + */ +class VoiceSearchOverlayElement extends mixinBehaviors +([I18nBehavior], PolymerElement) { static get is() { return 'ntp-voice-search-overlay'; }
diff --git a/chrome/browser/resources/settings/chromeos/internet_page/esim_rename_dialog.html b/chrome/browser/resources/settings/chromeos/internet_page/esim_rename_dialog.html index f8ba1790..c2e52f2 100644 --- a/chrome/browser/resources/settings/chromeos/internet_page/esim_rename_dialog.html +++ b/chrome/browser/resources/settings/chromeos/internet_page/esim_rename_dialog.html
@@ -79,6 +79,7 @@ spellcheck="false" disabled="[[isRenameInProgress_]]" invalid="[[isInputInvalid_]]" + aria-label="[[i18n('eSimRenameProfileDialogLabel')]]" aria-description="[[i18n('eSimRenameProfileInputA11yLabel', MAX_INPUT_LENGTH)]]" error-message="[[i18n('eSimRenameProfileInputA11yLabel', @@ -94,7 +95,7 @@ </div> </div> </template> - <div id="errorMessage" hidden$="[[!errorMessage_]]"> + <div id="errorMessage" aria-live="polite" hidden$="[[!errorMessage_]]"> [[errorMessage_]] </div> </div> @@ -110,6 +111,8 @@ <cr-button id="done" on-click="onRenameDialogDoneTap_" disabled="[[isRenameInProgress_]]" + aria-label$="[[getDoneBtnA11yLabel_(esimProfileName_)]]" + aria-describedby="warningMessage" class="action-button"> $i18n{eSimRenameProfileDialogDone} </cr-button>
diff --git a/chrome/browser/resources/settings/chromeos/internet_page/esim_rename_dialog.js b/chrome/browser/resources/settings/chromeos/internet_page/esim_rename_dialog.js index 72cce6bd..9058b80 100644 --- a/chrome/browser/resources/settings/chromeos/internet_page/esim_rename_dialog.js +++ b/chrome/browser/resources/settings/chromeos/internet_page/esim_rename_dialog.js
@@ -87,6 +87,10 @@ this.errorMessage_ = this.i18n('eSimRenameProfileDialogError'); } this.esimProfileName_ = this.networkState.name; + + if (!this.errorMessage_) { + this.$$('#eSimprofileName').focus(); + } }, /** @@ -193,4 +197,12 @@ /*locales=*/ undefined, {minimumIntegerDigits: 2}), MAX_INPUT_LENGTH.toLocaleString()); }, + + /** + * @param {string} esimProfileName + * @returns {string} + */ + getDoneBtnA11yLabel_(esimProfileName) { + return this.i18n('eSimRenameProfileDoneBtnA11yLabel', esimProfileName); + } });
diff --git a/chrome/browser/safe_browsing/download_protection/download_protection_util.h b/chrome/browser/safe_browsing/download_protection/download_protection_util.h index 052ba7f..2167d68cf 100644 --- a/chrome/browser/safe_browsing/download_protection/download_protection_util.h +++ b/chrome/browser/safe_browsing/download_protection/download_protection_util.h
@@ -82,11 +82,11 @@ // be mixed together based on their values). enum SBStatsType { DOWNLOAD_URL_CHECKS_TOTAL, - DOWNLOAD_URL_CHECKS_CANCELED, + DEPRECATED_DOWNLOAD_URL_CHECKS_CANCELED, DOWNLOAD_URL_CHECKS_MALWARE, - DOWNLOAD_HASH_CHECKS_TOTAL, - DOWNLOAD_HASH_CHECKS_MALWARE, + DEPRECATED_DOWNLOAD_HASH_CHECKS_TOTAL, + DEPRECATED_DOWNLOAD_HASH_CHECKS_MALWARE, // Memory space for histograms is determined by the max. // ALWAYS ADD NEW VALUES BEFORE THIS ONE.
diff --git a/chrome/browser/safe_browsing/safe_browsing_service.cc b/chrome/browser/safe_browsing/safe_browsing_service.cc index d21ed2c..f1180c2 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service.cc +++ b/chrome/browser/safe_browsing/safe_browsing_service.cc
@@ -346,9 +346,6 @@ GetURLLoaderFactory()), std::make_unique<network::CrossThreadPendingSharedURLLoaderFactory>( g_browser_process->shared_url_loader_factory()))); - - ClientSidePhishingModel::GetInstance()->Start( - g_browser_process->shared_url_loader_factory()); } void SafeBrowsingService::Stop(bool shutdown) { @@ -357,7 +354,6 @@ content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&SafeBrowsingService::StopOnIOThread, this, shutdown)); - ClientSidePhishingModel::GetInstance()->Stop(); } void SafeBrowsingService::OnProfileAdded(Profile* profile) {
diff --git a/chrome/browser/safe_browsing/safe_browsing_service_browsertest.cc b/chrome/browser/safe_browsing/safe_browsing_service_browsertest.cc index 335846a..f2c82d0 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service_browsertest.cc +++ b/chrome/browser/safe_browsing/safe_browsing_service_browsertest.cc
@@ -1230,22 +1230,6 @@ } #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) -IN_PROC_BROWSER_TEST_F(V4SafeBrowsingServiceTest, - EnablesClientSidePhishingModelAtStartup) { -#if BUILDFLAG(IS_CHROMEOS_ASH) - // ChromeOS creates a signin profile with Standard Protection enabled. In - // order to test what happens when Standard Protection is enabled/disabled for - // all users, we need to disable Standard Protection for this profile. - SetStandardProtectionPref( - ash::ProfileHelper::GetSigninProfile()->GetOriginalProfile()->GetPrefs(), - false); -#endif - SetStandardProtectionPref(browser()->profile()->GetPrefs(), false); - EXPECT_FALSE(ClientSidePhishingModel::GetInstance()->IsEnabled()); - SetStandardProtectionPref(browser()->profile()->GetPrefs(), true); - EXPECT_TRUE(ClientSidePhishingModel::GetInstance()->IsEnabled()); -} - /////////////////////////////////////////////////////////////////////////////// // END: These tests use SafeBrowsingService::Client to directly interact with // SafeBrowsingService.
diff --git a/chrome/browser/speech/network_speech_recognizer.cc b/chrome/browser/speech/network_speech_recognizer.cc index 066e23b..3f16d20 100644 --- a/chrome/browser/speech/network_speech_recognizer.cc +++ b/chrome/browser/speech/network_speech_recognizer.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/macros.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/speech/speech_recognizer_delegate.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -23,7 +24,10 @@ #include "content/public/common/child_process_host.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "third_party/blink/public/mojom/speech/speech_recognition_error.mojom.h" -#include "ui/accessibility/accessibility_switches.h" + +#if BUILDFLAG(IS_CHROMEOS_ASH) +#include "ui/accessibility/accessibility_features.h" +#endif // Invalid speech session. static const int kInvalidSessionId = -1; @@ -134,10 +138,14 @@ if (session_ != kInvalidSessionId) StopOnIOThread(); +#if BUILDFLAG(IS_CHROMEOS_ASH) // Don't filter profanities if flag is enabled for experimental listening. // This would match desired OnDeviceSpeechRecognizer behavior. bool filter_profanities = - !switches::IsExperimentalAccessibilityDictationListeningEnabled(); + !features::IsExperimentalAccessibilityDictationListeningEnabled(); +#else + bool filter_profanities = true; +#endif content::SpeechRecognitionSessionConfig config; config.language = locale_; config.continuous = true;
diff --git a/chrome/browser/sync/test/integration/extension_settings_helper.cc b/chrome/browser/sync/test/integration/extension_settings_helper.cc index 3d3f6b5..6acddca1 100644 --- a/chrome/browser/sync/test/integration/extension_settings_helper.cc +++ b/chrome/browser/sync/test/integration/extension_settings_helper.cc
@@ -75,7 +75,7 @@ GetAllSettings(expected_profile, id)); std::unique_ptr<base::DictionaryValue> actual( GetAllSettings(actual_profile, id)); - if (!expected->Equals(actual.get())) { + if (*expected != *actual) { ADD_FAILURE() << "Expected " << ToJson(*expected) << " got " << ToJson(*actual); same = false;
diff --git a/chrome/browser/sync/test/integration/preferences_helper.cc b/chrome/browser/sync/test/integration/preferences_helper.cc index c7b48b7..19f7d01 100644 --- a/chrome/browser/sync/test/integration/preferences_helper.cc +++ b/chrome/browser/sync/test/integration/preferences_helper.cc
@@ -130,7 +130,7 @@ bool ListPrefMatches(const char* pref_name) { const base::ListValue* reference_value = GetPrefs(0)->GetList(pref_name); for (int i = 1; i < test()->num_clients(); ++i) { - if (!reference_value->Equals(GetPrefs(i)->GetList(pref_name))) { + if (*reference_value != *GetPrefs(i)->GetList(pref_name)) { DVLOG(1) << "List preference " << pref_name << " mismatched in" << " profile " << i << "."; return false;
diff --git a/chrome/browser/sync/test/integration/single_client_offer_sync_test.cc b/chrome/browser/sync/test/integration/single_client_offer_sync_test.cc index 90b9d3a..26a4e53 100644 --- a/chrome/browser/sync/test/integration/single_client_offer_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_offer_sync_test.cc
@@ -71,7 +71,7 @@ void WaitForNumberOfOffers(size_t expected_count, autofill::PersonalDataManager* pdm) { - while (pdm->GetCreditCardOffers().size() != expected_count || + while (pdm->GetAutofillOffers().size() != expected_count || pdm->HasPendingQueriesForTesting()) { WaitForOnPersonalDataChanged(pdm); } @@ -106,12 +106,12 @@ autofill::PersonalDataManager* pdm = GetPersonalDataManager(0); ASSERT_NE(nullptr, pdm); // Make sure the offer data is in the DB. - ASSERT_EQ(1uL, pdm->GetCreditCardOffers().size()); + ASSERT_EQ(1uL, pdm->GetAutofillOffers().size()); // Disable sync, the offer data should be gone. GetSyncService(0)->StopAndClear(); WaitForNumberOfOffers(0, pdm); - EXPECT_EQ(0uL, pdm->GetCreditCardOffers().size()); + EXPECT_EQ(0uL, pdm->GetAutofillOffers().size()); // Turn sync on again, the data should come back. GetSyncService(0)->GetUserSettings()->SetSyncRequested(true); @@ -121,7 +121,7 @@ kSetSourceFromTest); // Wait until Sync restores the card and it arrives at PDM. WaitForNumberOfOffers(1, pdm); - EXPECT_EQ(1uL, pdm->GetCreditCardOffers().size()); + EXPECT_EQ(1uL, pdm->GetAutofillOffers().size()); } // Ensures that offer data should get cleared from the database when sync is @@ -134,18 +134,18 @@ autofill::PersonalDataManager* pdm = GetPersonalDataManager(0); ASSERT_NE(nullptr, pdm); // Make sure the offer data is in the DB. - ASSERT_EQ(1uL, pdm->GetCreditCardOffers().size()); + ASSERT_EQ(1uL, pdm->GetAutofillOffers().size()); // Stop sync, the offer data should be gone. GetSyncService(0)->GetUserSettings()->SetSyncRequested(false); WaitForNumberOfOffers(0, pdm); - EXPECT_EQ(0uL, pdm->GetCreditCardOffers().size()); + EXPECT_EQ(0uL, pdm->GetAutofillOffers().size()); // Turn sync on again, the data should come back. GetSyncService(0)->GetUserSettings()->SetSyncRequested(true); // Wait until Sync restores the card and it arrives at PDM. WaitForNumberOfOffers(1, pdm); - EXPECT_EQ(1uL, pdm->GetCreditCardOffers().size()); + EXPECT_EQ(1uL, pdm->GetAutofillOffers().size()); } // ChromeOS does not sign out, so the test below does not apply. @@ -157,12 +157,12 @@ autofill::PersonalDataManager* pdm = GetPersonalDataManager(0); ASSERT_NE(nullptr, pdm); // Make sure the data & metadata is in the DB. - ASSERT_EQ(1uL, pdm->GetCreditCardOffers().size()); + ASSERT_EQ(1uL, pdm->GetAutofillOffers().size()); // Signout, the data & metadata should be gone. GetClient(0)->SignOutPrimaryAccount(); WaitForNumberOfOffers(0, pdm); - EXPECT_EQ(0uL, pdm->GetCreditCardOffers().size()); + EXPECT_EQ(0uL, pdm->GetAutofillOffers().size()); } #endif // !BUILDFLAG(IS_CHROMEOS_ASH) @@ -178,7 +178,7 @@ // Make sure the data is in the DB. autofill::PersonalDataManager* pdm = GetPersonalDataManager(0); ASSERT_NE(nullptr, pdm); - std::vector<AutofillOfferData*> offers = pdm->GetCreditCardOffers(); + std::vector<AutofillOfferData*> offers = pdm->GetAutofillOffers(); ASSERT_EQ(1uL, offers.size()); EXPECT_EQ(999, offers[0]->offer_id); @@ -189,7 +189,7 @@ WaitForOnPersonalDataChanged(pdm); // Make sure only the new data is present. - offers = pdm->GetCreditCardOffers(); + offers = pdm->GetAutofillOffers(); ASSERT_EQ(1uL, offers.size()); EXPECT_EQ(888, offers[0]->offer_id); } @@ -206,7 +206,7 @@ // Make sure the card is in the DB. autofill::PersonalDataManager* pdm = GetPersonalDataManager(0); ASSERT_NE(nullptr, pdm); - std::vector<AutofillOfferData*> offers = pdm->GetCreditCardOffers(); + std::vector<AutofillOfferData*> offers = pdm->GetAutofillOffers(); ASSERT_EQ(1uL, offers.size()); EXPECT_EQ(999, offers[0]->offer_id); @@ -231,7 +231,7 @@ } // Make sure the same data is present on the client. - offers = pdm->GetCreditCardOffers(); + offers = pdm->GetAutofillOffers(); ASSERT_EQ(1uL, offers.size()); EXPECT_EQ(999, offers[0]->offer_id); } @@ -249,7 +249,7 @@ // Make sure the card is in the DB. autofill::PersonalDataManager* pdm = GetPersonalDataManager(0); ASSERT_NE(nullptr, pdm); - std::vector<AutofillOfferData*> offers = pdm->GetCreditCardOffers(); + std::vector<AutofillOfferData*> offers = pdm->GetAutofillOffers(); ASSERT_EQ(1uL, offers.size()); EXPECT_EQ(999, offers[0]->offer_id); EXPECT_EQ(1U, offers[0]->eligible_instrument_id.size()); @@ -262,7 +262,7 @@ // Make sure the data is present on the client. pdm = GetPersonalDataManager(0); ASSERT_NE(nullptr, pdm); - offers = pdm->GetCreditCardOffers(); + offers = pdm->GetAutofillOffers(); ASSERT_EQ(1uL, offers.size()); EXPECT_EQ(999, offers[0]->offer_id); EXPECT_EQ(2U, offers[0]->eligible_instrument_id.size()); @@ -277,11 +277,11 @@ autofill::PersonalDataManager* pdm = GetPersonalDataManager(0); ASSERT_NE(nullptr, pdm); // Make sure the data is in the DB. - ASSERT_EQ(1uL, pdm->GetCreditCardOffers().size()); + ASSERT_EQ(1uL, pdm->GetAutofillOffers().size()); // Turn off autofill sync, the data should be gone. ASSERT_TRUE( GetClient(0)->DisableSyncForType(syncer::UserSelectableType::kAutofill)); WaitForNumberOfOffers(0, pdm); - EXPECT_EQ(0uL, pdm->GetCreditCardOffers().size()); + EXPECT_EQ(0uL, pdm->GetAutofillOffers().size()); }
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.cc b/chrome/browser/ui/autofill/chrome_autofill_client.cc index a5eed90..a87a789 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.cc +++ b/chrome/browser/ui/autofill/chrome_autofill_client.cc
@@ -650,20 +650,33 @@ } void ChromeAutofillClient::ShowOfferNotificationIfApplicable( - const std::vector<GURL>& domains_to_display_bubble, - const GURL& offer_details_url, - const CreditCard* card) { + const AutofillOfferData* offer) { + if (!offer) + return; + + // Ensure the card for a card-linked offer is successfully on the device. + CreditCard* card = + offer->eligible_instrument_id.empty() + ? nullptr + : GetPersonalDataManager()->GetCreditCardByInstrumentId( + offer->eligible_instrument_id[0]); + if (offer->IsCardLinkedOffer() && !card) + return; + + // TODO(crbug.com/1203811): Promo code offers should eventually show offer + // details in their own format as well. + if (!offer->IsCardLinkedOffer()) + return; + #if defined(OS_ANDROID) std::unique_ptr<OfferNotificationInfoBarControllerImpl> controller = std::make_unique<OfferNotificationInfoBarControllerImpl>(web_contents()); - controller->ShowIfNecessary(domains_to_display_bubble, offer_details_url, - card); + controller->ShowIfNecessary(offer, card); #else OfferNotificationBubbleControllerImpl::CreateForWebContents(web_contents()); OfferNotificationBubbleControllerImpl* controller = OfferNotificationBubbleControllerImpl::FromWebContents(web_contents()); - controller->ShowOfferNotificationIfApplicable(domains_to_display_bubble, - card); + controller->ShowOfferNotificationIfApplicable(offer, card); #endif }
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.h b/chrome/browser/ui/autofill/chrome_autofill_client.h index c7a33144..f0da781e 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.h +++ b/chrome/browser/ui/autofill/chrome_autofill_client.h
@@ -148,9 +148,7 @@ PopupType popup_type) override; void HideAutofillPopup(PopupHidingReason reason) override; void ShowOfferNotificationIfApplicable( - const std::vector<GURL>& domains_to_display_bubble, - const GURL& offer_details_url, - const CreditCard* card) override; + const AutofillOfferData* offer) override; bool IsAutofillAssistantShowing() override; bool IsAutocompleteEnabled() override; void PropagateAutofillPredictions(
diff --git a/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl.cc b/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl.cc index 379ed2e..1a3525c 100644 --- a/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl.cc +++ b/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl.cc
@@ -13,6 +13,7 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/page_action/page_action_icon_type.h" #include "components/autofill/core/browser/autofill_metrics.h" +#include "components/autofill/core/browser/data_model/autofill_offer_data.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/navigation_handle.h" #include "ui/base/l10n/l10n_util.h" @@ -104,18 +105,20 @@ } void OfferNotificationBubbleControllerImpl::ShowOfferNotificationIfApplicable( - const std::vector<GURL>& origins_to_display_bubble, + const AutofillOfferData* offer, const CreditCard* card) { + DCHECK(offer); // If icon/bubble is already visible, that means we have already shown a // notification for this page. if (IsIconVisible() || bubble_view()) return; origins_to_display_bubble_.clear(); - for (auto origin : origins_to_display_bubble) + for (auto origin : offer->merchant_domain) origins_to_display_bubble_.emplace_back(origin); - card_ = *card; + if (card) + card_ = *card; is_user_gesture_ = false; Show();
diff --git a/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl.h b/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl.h index 9abde37..b257124 100644 --- a/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl.h +++ b/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl.h
@@ -14,6 +14,8 @@ namespace autofill { +struct AutofillOfferData; + // Implementation of per-tab class to control the offer notification bubble and // Omnibox icon. class OfferNotificationBubbleControllerImpl @@ -44,13 +46,11 @@ bool IsIconVisible() const override; void OnBubbleClosed(PaymentsBubbleClosedReason closed_reason) override; - // Displays an offer notification on current page. Populates the value for - // |origins_to_display_bubble_|, since the bubble and icon are sticky over a - // given set of origins. For a card linked offer, The information of the - // |card| will be displayed in the bubble. - void ShowOfferNotificationIfApplicable( - const std::vector<GURL>& origins_to_display_bubble, - const CreditCard* card); + // Displays an offer notification for the given |offer| on the current page. + // The information of the |card|, if present, will be displayed in the bubble + // for a card-linked offer. + void ShowOfferNotificationIfApplicable(const AutofillOfferData* offer, + const CreditCard* card); // Called when user clicks on omnibox icon. void ReshowBubble();
diff --git a/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl_unittest.cc b/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl_unittest.cc index 04e8475..ad3db3a6 100644 --- a/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl_unittest.cc +++ b/chrome/browser/ui/autofill/payments/offer_notification_bubble_controller_impl_unittest.cc
@@ -9,6 +9,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "components/autofill/core/browser/autofill_test_utils.h" +#include "components/autofill/core/browser/data_model/autofill_offer_data.h" #include "content/public/test/mock_navigation_handle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -71,9 +72,8 @@ } protected: - void ShowBubble(const std::vector<GURL> origins_to_display_bubble) { - controller()->ShowOfferNotificationIfApplicable(origins_to_display_bubble, - &card_); + void ShowBubble(const AutofillOfferData* offer) { + controller()->ShowOfferNotificationIfApplicable(offer, &card_); } void CloseBubble(PaymentsBubbleClosedReason closed_reason = @@ -86,6 +86,15 @@ controller()->ReshowBubble(); } + AutofillOfferData CreateTestOfferWithOrigins( + const std::vector<GURL>& merchant_origins) { + // Only adding what the tests need to pass. Feel free to add more populated + // fields as necessary. + AutofillOfferData offer; + offer.merchant_domain = merchant_origins; + return offer; + } + TestOfferNotificationBubbleControllerImpl* controller() { return static_cast<TestOfferNotificationBubbleControllerImpl*>( TestOfferNotificationBubbleControllerImpl::FromWebContents( @@ -98,7 +107,9 @@ TEST_F(OfferNotificationBubbleControllerImplTest, BubbleShown) { // Check that bubble is visible. - ShowBubble({GURL("https://www.example.com/first/").GetOrigin()}); + AutofillOfferData offer = CreateTestOfferWithOrigins( + {GURL("https://www.example.com/first/").GetOrigin()}); + ShowBubble(&offer); EXPECT_TRUE(controller()->GetOfferNotificationBubbleView()); } @@ -117,8 +128,10 @@ for (const auto& test_case : test_cases) { // Set the initial origin that the bubble will be displayed on. NavigateAndCommitActiveTab(GURL("https://www.example.com/first/")); - ShowBubble({GURL("https://www.example.com/first/").GetOrigin(), - GURL("https://www.test.com/first/").GetOrigin()}); + AutofillOfferData offer = CreateTestOfferWithOrigins( + {GURL("https://www.example.com/first/").GetOrigin(), + GURL("https://www.test.com/first/").GetOrigin()}); + ShowBubble(&offer); // Bubble should be visible. EXPECT_TRUE(controller()->GetOfferNotificationBubbleView());
diff --git a/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl.cc b/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl.cc index c6f6032..a15f317 100644 --- a/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl.cc +++ b/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl.cc
@@ -6,6 +6,7 @@ #include "chrome/browser/ui/android/infobars/autofill_offer_notification_infobar.h" #include "chrome/browser/ui/autofill/payments/offer_notification_helper.h" +#include "components/autofill/core/browser/data_model/autofill_offer_data.h" #include "components/autofill/core/browser/payments/autofill_offer_notification_infobar_delegate_mobile.h" #include "components/infobars/content/content_infobar_manager.h" #include "components/infobars/core/infobar.h" @@ -18,19 +19,22 @@ : web_contents_(contents) {} void OfferNotificationInfoBarControllerImpl::ShowIfNecessary( - const std::vector<GURL>& origins_to_display_infobar, - const GURL& offer_details_url, + const AutofillOfferData* offer, const CreditCard* card) { + DCHECK(offer); + OfferNotificationHelper::CreateForWebContents(web_contents_); OfferNotificationHelper* offer_notification_helper = OfferNotificationHelper::FromWebContents(web_contents_); if (offer_notification_helper->OfferNotificationHasAlreadyBeenShown()) return; + + std::vector<GURL> origins_to_display_infobar = offer->merchant_domain; if (card) { infobars::ContentInfoBarManager::FromWebContents(web_contents_) ->AddInfoBar(std::make_unique<AutofillOfferNotificationInfoBar>( std::make_unique<AutofillOfferNotificationInfoBarDelegateMobile>( - offer_details_url, *card))); + offer->offer_details_url, *card))); offer_notification_helper->OnDisplayOfferNotification( origins_to_display_infobar); }
diff --git a/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl.h b/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl.h index 8d835e5..1cbcfe3 100644 --- a/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl.h +++ b/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl.h
@@ -12,6 +12,8 @@ namespace autofill { +struct AutofillOfferData; + // Per-tab controller to control the offer notification infobar displayed on // mobile. class OfferNotificationInfoBarControllerImpl { @@ -27,9 +29,7 @@ // Show the infobar unless it was already shown in the same tab with the same // origin. - void ShowIfNecessary(const std::vector<GURL>& origins_to_display_infobar, - const GURL& offer_details_url, - const CreditCard* card); + void ShowIfNecessary(const AutofillOfferData* offer, const CreditCard* card); private: content::WebContents* web_contents_;
diff --git a/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl_browsertest.cc b/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl_browsertest.cc index ec91bb19..7139a1a 100644 --- a/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl_browsertest.cc +++ b/chrome/browser/ui/autofill/payments/offer_notification_infobar_controller_impl_browsertest.cc
@@ -7,6 +7,7 @@ #include "chrome/test/base/android/android_browser_test.h" #include "chrome/test/base/chrome_test_utils.h" #include "components/autofill/core/browser/autofill_test_utils.h" +#include "components/autofill/core/browser/data_model/autofill_offer_data.h" #include "components/autofill/core/browser/payments/autofill_offer_notification_infobar_delegate_mobile.h" #include "components/infobars/content/content_infobar_manager.h" #include "components/infobars/core/infobar.h" @@ -19,7 +20,6 @@ namespace autofill { const char kHostName[] = "example.com"; -const char kOfferDetailsURL[] = "http://pay.google.com"; class OfferNotificationInfoBarControllerImplBrowserTest : public AndroidBrowserTest { @@ -53,9 +53,17 @@ infobar->delegate()); } - void ShowOfferNotificationInfoBar(const std::vector<GURL>& origins) { - offer_notification_infobar_controller_->ShowIfNecessary( - origins, GURL(kOfferDetailsURL), &card_); + void ShowOfferNotificationInfoBar(const AutofillOfferData* offer) { + offer_notification_infobar_controller_->ShowIfNecessary(offer, &card_); + } + + AutofillOfferData CreateTestOfferWithOrigins( + const std::vector<GURL>& merchant_origins) { + // Only adding what the tests need to pass. Feel free to add more populated + // fields as necessary. + AutofillOfferData offer; + offer.merchant_domain = merchant_origins; + return offer; } void VerifyInfoBarShownCount(int count) { @@ -101,7 +109,9 @@ IN_PROC_BROWSER_TEST_F(OfferNotificationInfoBarControllerImplBrowserTest, ShowInfobarOnlyOncePerDomain) { - ShowOfferNotificationInfoBar({GetInitialUrl().GetOrigin()}); + AutofillOfferData offer = + CreateTestOfferWithOrigins({GetInitialUrl().GetOrigin()}); + ShowOfferNotificationInfoBar(&offer); // Verify that the infobar was shown and logged. infobars::InfoBar* infobar = GetInfoBar(); ASSERT_TRUE(infobar); @@ -114,7 +124,7 @@ GURL secondURL = embedded_test_server()->GetURL(kHostName, "/simple_page.html"); ASSERT_TRUE(content::NavigateToURL(GetWebContents(), secondURL)); - ShowOfferNotificationInfoBar({secondURL.GetOrigin()}); + ShowOfferNotificationInfoBar(&offer); // Verify that the infobar was not shown again because it has already been // shown for this domain. @@ -130,7 +140,9 @@ IN_PROC_BROWSER_TEST_F(OfferNotificationInfoBarControllerImplBrowserTest, ShowInfobarAndAccept) { - ShowOfferNotificationInfoBar({GetInitialUrl().GetOrigin()}); + AutofillOfferData offer = + CreateTestOfferWithOrigins({GetInitialUrl().GetOrigin()}); + ShowOfferNotificationInfoBar(&offer); // Verify that the infobar was shown. infobars::InfoBar* infobar = GetInfoBar(); ASSERT_TRUE(infobar); @@ -149,7 +161,9 @@ IN_PROC_BROWSER_TEST_F(OfferNotificationInfoBarControllerImplBrowserTest, ShowInfobarAndClose) { - ShowOfferNotificationInfoBar({GetInitialUrl().GetOrigin()}); + AutofillOfferData offer = + CreateTestOfferWithOrigins({GetInitialUrl().GetOrigin()}); + ShowOfferNotificationInfoBar(&offer); // Verify that the infobar was shown. infobars::InfoBar* infobar = GetInfoBar(); ASSERT_TRUE(infobar);
diff --git a/chrome/browser/ui/extensions/extension_action_test_helper.h b/chrome/browser/ui/extensions/extension_action_test_helper.h index b4ba9388..8d75591 100644 --- a/chrome/browser/ui/extensions/extension_action_test_helper.h +++ b/chrome/browser/ui/extensions/extension_action_test_helper.h
@@ -11,6 +11,7 @@ #include <string> #include "base/macros.h" +#include "extensions/common/extension_id.h" #include "ui/gfx/native_widget_types.h" class Browser; @@ -22,6 +23,9 @@ class Size; } // namespace gfx +// TODO(https://crbug.com/1197766): A lot of this class can be cleaned up for +// the new toolbar UI. Some of it may also be removable, since we now have +// the platform-abstract ExtensionsContainer class. class ExtensionActionTestHelper { public: // Constructs a ExtensionActionTestHelper which, if |is_real_window| is false, @@ -41,25 +45,25 @@ // calling InProcessBrowserTest::RunScheduledLayouts()) for a browser test. virtual int VisibleBrowserActions() = 0; - // Inspects the extension popup for the action at the given index. - virtual void InspectPopup(int index) = 0; + // Returns true if there is an action for the given `id`. + virtual bool HasAction(const extensions::ExtensionId& id) = 0; - // Returns whether the brownser action at |index| has a non-null icon. Note - // that the icon is loaded asynchronously, in which case you can wait for it - // to load by calling WaitForBrowserActionUpdated. - virtual bool HasIcon(int index) = 0; + // Inspects the extension popup for the action with the given `id`. + virtual void InspectPopup(const extensions::ExtensionId& id) = 0; - // Returns icon for the browser action at |index|. - virtual gfx::Image GetIcon(int index) = 0; + // Returns whether the extension action for the given `id` has a non-null + // icon. Note that the icon is loaded asynchronously, in which case you can + // wait for it to load by calling WaitForBrowserActionUpdated. + virtual bool HasIcon(const extensions::ExtensionId& id) = 0; - // Simulates a user click on the browser action button at |index|. - virtual void Press(int index) = 0; + // Returns icon for the action for the given `id`. + virtual gfx::Image GetIcon(const extensions::ExtensionId& id) = 0; - // Returns the extension id of the extension at |index|. - virtual std::string GetExtensionId(int index) = 0; + // Simulates a user click on the action button for the given `id`. + virtual void Press(const extensions::ExtensionId& id) = 0; - // Returns the current tooltip for the browser action button. - virtual std::string GetTooltip(int index) = 0; + // Returns the current tooltip of the action for the given `id`. + virtual std::string GetTooltip(const extensions::ExtensionId& id) = 0; virtual gfx::NativeView GetPopupNativeView() = 0; @@ -108,9 +112,9 @@ virtual gfx::Size GetMaxPopupSize() = 0; // Returns the maximum available size to place a bubble anchored to - // the browser action at |action_index| on screen. + // the action with the given `id` on screen. virtual gfx::Size GetMaxAvailableSizeToFitBubbleOnScreen( - int action_index) = 0; + const extensions::ExtensionId& id) = 0; protected: ExtensionActionTestHelper() {}
diff --git a/chrome/browser/ui/task_manager/task_manager_table_model.cc b/chrome/browser/ui/task_manager/task_manager_table_model.cc index f1e7a98d..d0416359 100644 --- a/chrome/browser/ui/task_manager/task_manager_table_model.cc +++ b/chrome/browser/ui/task_manager/task_manager_table_model.cc
@@ -15,6 +15,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/values.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/task_manager/task_manager_interface.h" @@ -865,7 +866,8 @@ base::DictionaryValue::Iterator it(*columns_settings_); while (!it.IsAtEnd()) { - dict_update->Set(it.key(), it.value().CreateDeepCopy()); + dict_update->Set(it.key(), + base::Value::ToUniquePtrValue(it.value().Clone())); it.Advance(); }
diff --git a/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_browsertest.cc b/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_browsertest.cc index 471e59c2..5194f12 100644 --- a/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_browsertest.cc +++ b/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_browsertest.cc
@@ -31,7 +31,7 @@ // is invalid (does not have a linked card). IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, InvalidOfferData) { - auto offer_data = CreateOfferDataWithDomains( + auto offer_data = CreateCardLinkedOfferDataWithDomains( {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); offer_data->eligible_instrument_id.clear(); personal_data()->AddOfferDataForTest(std::move(offer_data)); @@ -44,7 +44,7 @@ } IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, OpenNewTab) { - SetUpOfferDataWithDomains( + SetUpCardLinkedOfferDataWithDomains( {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); NavigateTo(chrome::kChromeUINewTabURL); @@ -58,4 +58,19 @@ EXPECT_FALSE(GetOfferNotificationBubbleViews()); } +// Tests that the offer notification bubble will not be shown for a promo code +// offer. +IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, + PromoCodeOffer) { + auto offer_data = CreatePromoCodeOfferDataWithDomains( + {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); + personal_data()->AddOfferDataForTest(std::move(offer_data)); + personal_data()->NotifyPersonalDataObserver(); + + // Neither icon nor bubble should be visible. + NavigateTo("https://www.example.com/first/"); + EXPECT_FALSE(IsIconVisible()); + EXPECT_FALSE(GetOfferNotificationBubbleViews()); +} + } // namespace autofill
diff --git a/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_interactive_uitest.cc b/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_interactive_uitest.cc index eded32ae..62e3610 100644 --- a/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_interactive_uitest.cc +++ b/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_interactive_uitest.cc
@@ -35,7 +35,7 @@ void ShowBubbleAndVerify() { NavigateTo(chrome::kChromeUINewTabURL); // Set the initial origin that the bubble will be displayed on. - SetUpOfferDataWithDomains( + SetUpCardLinkedOfferDataWithDomains( {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); ResetEventWaiterForSequence({DialogEvent::BUBBLE_SHOWN}); NavigateTo("https://www.example.com/first"); @@ -105,7 +105,7 @@ }; // Set the initial origin that the bubble will be displayed on. - SetUpOfferDataWithDomains( + SetUpCardLinkedOfferDataWithDomains( {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); for (const auto& test_case : test_cases) {
diff --git a/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_test_base.cc b/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_test_base.cc index c5255da..9159bb4 100644 --- a/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_test_base.cc +++ b/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_test_base.cc
@@ -44,8 +44,13 @@ } std::unique_ptr<AutofillOfferData> -OfferNotificationBubbleViewsTestBase::CreateOfferDataWithDomains( +OfferNotificationBubbleViewsTestBase::CreateCardLinkedOfferDataWithDomains( const std::vector<GURL>& domains) { + auto card = std::make_unique<CreditCard>(); + card->set_instrument_id(kCreditCardInstrumentId); + personal_data_->AddServerCreditCardForTest(std::move(card)); + personal_data_->NotifyPersonalDataObserver(); + std::unique_ptr<AutofillOfferData> offer_data_entry = std::make_unique<AutofillOfferData>(); offer_data_entry->offer_id = 4444; @@ -60,13 +65,34 @@ return offer_data_entry; } -void OfferNotificationBubbleViewsTestBase::SetUpOfferDataWithDomains( +std::unique_ptr<AutofillOfferData> +OfferNotificationBubbleViewsTestBase::CreatePromoCodeOfferDataWithDomains( + const std::vector<GURL>& domains) { + std::unique_ptr<AutofillOfferData> offer_data_entry = + std::make_unique<AutofillOfferData>(); + offer_data_entry->offer_id = 5555; + offer_data_entry->expiry = + AutofillClock::Now() + base::TimeDelta::FromDays(2); + offer_data_entry->merchant_domain = {}; + for (auto url : domains) + offer_data_entry->merchant_domain.emplace_back(url.GetOrigin()); + offer_data_entry->offer_details_url = GURL("https://www.google.com/"); + offer_data_entry->promo_code = "5PCTOFFSHOES"; + offer_data_entry->display_strings.value_prop_text = + "5% off on shoes. Up to $50."; + offer_data_entry->display_strings.see_details_text = "See details"; + offer_data_entry->display_strings.usage_instructions_text = + "Click the promo code field at checkout to autofill it."; + + return offer_data_entry; +} + +void OfferNotificationBubbleViewsTestBase::SetUpCardLinkedOfferDataWithDomains( const std::vector<GURL>& domains) { personal_data_->ClearAllServerData(); - personal_data_->AddOfferDataForTest(CreateOfferDataWithDomains(domains)); - auto card = std::make_unique<CreditCard>(); - card->set_instrument_id(kCreditCardInstrumentId); - personal_data_->AddServerCreditCardForTest(std::move(card)); + // CreateCardLinkedOfferDataWithDomains(~) will add the necessary card. + personal_data_->AddOfferDataForTest( + CreateCardLinkedOfferDataWithDomains(domains)); personal_data_->NotifyPersonalDataObserver(); }
diff --git a/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_test_base.h b/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_test_base.h index 9dc4af5..4ca1b9d 100644 --- a/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_test_base.h +++ b/chrome/browser/ui/views/autofill/payments/offer_notification_bubble_views_test_base.h
@@ -43,10 +43,15 @@ // OfferNotificationBubbleControllerImpl::ObserverForTest: void OnBubbleShown() override; - std::unique_ptr<AutofillOfferData> CreateOfferDataWithDomains( + // Also creates a credit card for the offer. + std::unique_ptr<AutofillOfferData> CreateCardLinkedOfferDataWithDomains( const std::vector<GURL>& domains); - void SetUpOfferDataWithDomains(const std::vector<GURL>& domains); + std::unique_ptr<AutofillOfferData> CreatePromoCodeOfferDataWithDomains( + const std::vector<GURL>& domains); + + // Also creates a credit card for the offer. + void SetUpCardLinkedOfferDataWithDomains(const std::vector<GURL>& domains); void NavigateTo(const std::string& file_path);
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_test_util.cc b/chrome/browser/ui/views/extensions/extensions_menu_test_util.cc index 9f56eef..c60a941 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_test_util.cc +++ b/chrome/browser/ui/views/extensions/extensions_menu_test_util.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/ui/views/extensions/extensions_menu_test_util.h" #include "base/numerics/safe_conversions.h" +#include "base/ranges/algorithm.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/extensions/extension_action_view_controller.h" @@ -114,30 +115,34 @@ return visible_icons; } -void ExtensionsMenuTestUtil::InspectPopup(int index) { - ExtensionsMenuItemView* view = GetMenuItemViewAtIndex(index); +bool ExtensionsMenuTestUtil::HasAction(const extensions::ExtensionId& id) { + return GetMenuItemViewForId(id) != nullptr; +} + +void ExtensionsMenuTestUtil::InspectPopup(const extensions::ExtensionId& id) { + ExtensionsMenuItemView* view = GetMenuItemViewForId(id); DCHECK(view); static_cast<ExtensionActionViewController*>(view->view_controller()) ->InspectPopup(); } -bool ExtensionsMenuTestUtil::HasIcon(int index) { - ExtensionsMenuItemView* view = GetMenuItemViewAtIndex(index); +bool ExtensionsMenuTestUtil::HasIcon(const extensions::ExtensionId& id) { + ExtensionsMenuItemView* view = GetMenuItemViewForId(id); DCHECK(view); return !view->primary_action_button_for_testing() ->GetImage(views::Button::STATE_NORMAL) .isNull(); } -gfx::Image ExtensionsMenuTestUtil::GetIcon(int index) { - ExtensionsMenuItemView* view = GetMenuItemViewAtIndex(index); +gfx::Image ExtensionsMenuTestUtil::GetIcon(const extensions::ExtensionId& id) { + ExtensionsMenuItemView* view = GetMenuItemViewForId(id); DCHECK(view); return gfx::Image(view->primary_action_button_for_testing()->GetImage( views::Button::STATE_NORMAL)); } -void ExtensionsMenuTestUtil::Press(int index) { - ExtensionsMenuItemView* view = GetMenuItemViewAtIndex(index); +void ExtensionsMenuTestUtil::Press(const extensions::ExtensionId& id) { + ExtensionsMenuItemView* view = GetMenuItemViewForId(id); DCHECK(view); ExtensionsMenuButton* primary_button = view->primary_action_button_for_testing(); @@ -147,14 +152,9 @@ views::test::ButtonTestApi(primary_button).NotifyClick(event); } -std::string ExtensionsMenuTestUtil::GetExtensionId(int index) { - ExtensionsMenuItemView* view = GetMenuItemViewAtIndex(index); - DCHECK(view); - return view->view_controller()->GetId(); -} - -std::string ExtensionsMenuTestUtil::GetTooltip(int index) { - ExtensionsMenuItemView* view = GetMenuItemViewAtIndex(index); +std::string ExtensionsMenuTestUtil::GetTooltip( + const extensions::ExtensionId& id) { + ExtensionsMenuItemView* view = GetMenuItemViewForId(id); DCHECK(view); ExtensionsMenuButton* primary_button = view->primary_action_button_for_testing(); @@ -226,10 +226,10 @@ } gfx::Size ExtensionsMenuTestUtil::GetMaxAvailableSizeToFitBubbleOnScreen( - int action_index) { + const extensions::ExtensionId& id) { auto* view_delegate = static_cast<ToolbarActionViewDelegateViews*>( static_cast<ExtensionActionViewController*>( - extensions_container_->GetActionForId(GetExtensionId(action_index))) + extensions_container_->GetActionForId(id)) ->view_delegate()); return views::BubbleDialogDelegate::GetMaxAvailableScreenSpaceToPlaceBubble( view_delegate->GetReferenceButtonForPopup(), @@ -238,13 +238,17 @@ views::BubbleFrameView::PreferredArrowAdjustment::kMirror); } -ExtensionsMenuItemView* ExtensionsMenuTestUtil::GetMenuItemViewAtIndex( - int index) { +ExtensionsMenuItemView* ExtensionsMenuTestUtil::GetMenuItemViewForId( + const extensions::ExtensionId& id) { std::vector<ExtensionsMenuItemView*> menu_items = menu_view_->extensions_menu_items_for_testing(); - if (index >= base::checked_cast<int>(menu_items.size())) + auto iter = + base::ranges::find_if(menu_items, [id](ExtensionsMenuItemView* view) { + return view->view_controller()->GetId() == id; + }); + if (iter == menu_items.end()) return nullptr; - return menu_items[index]; + return *iter; } // static
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_test_util.h b/chrome/browser/ui/views/extensions/extensions_menu_test_util.h index 4a17c50e..31a12ce 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_test_util.h +++ b/chrome/browser/ui/views/extensions/extensions_menu_test_util.h
@@ -28,12 +28,12 @@ // ExtensionActionTestHelper: int NumberOfBrowserActions() override; int VisibleBrowserActions() override; - void InspectPopup(int index) override; - bool HasIcon(int index) override; - gfx::Image GetIcon(int index) override; - void Press(int index) override; - std::string GetExtensionId(int index) override; - std::string GetTooltip(int index) override; + bool HasAction(const extensions::ExtensionId& id) override; + void InspectPopup(const extensions::ExtensionId& id) override; + bool HasIcon(const extensions::ExtensionId& id) override; + gfx::Image GetIcon(const extensions::ExtensionId& id) override; + void Press(const extensions::ExtensionId& id) override; + std::string GetTooltip(const extensions::ExtensionId& id) override; gfx::NativeView GetPopupNativeView() override; bool HasPopup() override; bool HidePopup() override; @@ -51,15 +51,17 @@ gfx::Size GetMinPopupSize() override; gfx::Size GetMaxPopupSize() override; gfx::Size GetToolbarActionSize() override; - gfx::Size GetMaxAvailableSizeToFitBubbleOnScreen(int action_index) override; + gfx::Size GetMaxAvailableSizeToFitBubbleOnScreen( + const extensions::ExtensionId& id) override; private: class MenuViewObserver; class Wrapper; - // Returns the ExtensionsMenuItemView at the given |index| from the - // |menu_view|. - ExtensionsMenuItemView* GetMenuItemViewAtIndex(int index); + // Returns the ExtensionsMenuItemView for the given `id` from the + // `menu_view`. + ExtensionsMenuItemView* GetMenuItemViewForId( + const extensions::ExtensionId& id); // An override to allow test instances of the ExtensionsMenuView. // This has to be defined before |menu_view_| below.
diff --git a/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc b/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc index 5d53238c..765df2f 100644 --- a/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc +++ b/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc
@@ -57,9 +57,8 @@ quota_manager_->DumpQuotaTable(base::BindOnce( &QuotaInternalsProxy::DidDumpQuotaTable, weak_factory_.GetWeakPtr())); - quota_manager_->DumpOriginInfoTable( - base::BindOnce(&QuotaInternalsProxy::DidDumpOriginInfoTable, - weak_factory_.GetWeakPtr())); + quota_manager_->DumpBucketTable(base::BindOnce( + &QuotaInternalsProxy::DidDumpBucketTable, weak_factory_.GetWeakPtr())); std::map<std::string, std::string> stats = quota_manager_->GetStatistics(); ReportStatistics(stats); @@ -139,16 +138,16 @@ ReportPerHostInfo(host_info); } -void QuotaInternalsProxy::DidDumpOriginInfoTable( - const OriginInfoTableEntries& entries) { +void QuotaInternalsProxy::DidDumpBucketTable( + const BucketTableEntries& entries) { std::vector<PerOriginStorageInfo> origin_info; origin_info.reserve(entries.size()); for (const auto& entry : entries) { PerOriginStorageInfo info(entry.origin.GetURL(), entry.type); - info.set_used_count(entry.used_count); - info.set_last_access_time(entry.last_access_time); - info.set_last_modified_time(entry.last_modified_time); + info.set_used_count(entry.use_count); + info.set_last_access_time(entry.last_accessed); + info.set_last_modified_time(entry.last_modified); origin_info.push_back(info); }
diff --git a/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h b/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h index 8c340baa..b34a188 100644 --- a/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h +++ b/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h
@@ -50,7 +50,7 @@ friend class QuotaInternalsHandler; typedef storage::QuotaManager::QuotaTableEntries QuotaTableEntries; - typedef storage::QuotaManager::OriginInfoTableEntries OriginInfoTableEntries; + typedef storage::QuotaManager::BucketTableEntries BucketTableEntries; virtual ~QuotaInternalsProxy(); @@ -67,7 +67,7 @@ int64_t usage, int64_t unlimited_usage); void DidDumpQuotaTable(const QuotaTableEntries& entries); - void DidDumpOriginInfoTable(const OriginInfoTableEntries& entries); + void DidDumpBucketTable(const BucketTableEntries& entries); void DidGetHostUsage(const std::string& host, blink::mojom::StorageType type, int64_t usage,
diff --git a/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc b/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc index 34d38e9..939e2d3 100644 --- a/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc +++ b/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/command_line.h" +#include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/no_destructor.h" #include "base/path_service.h" @@ -311,6 +312,10 @@ ChromeUserManager::Get()->GetUserImageManager(GetUser()->GetAccountId()); bool waiting_for_camera_photo = false; + // track the index of previous selected message to be compared with the index + // of the new image. + int previous_image_index = GetUser()->image_index(); + if (image_type == "old") { // Previous image (from camera or manually uploaded) re-selected. DCHECK(!previous_image_.isNull()); @@ -352,6 +357,16 @@ NOTREACHED() << "Unexpected image type: " << image_type; } + int image_index = GetUser()->image_index(); + // `previous_image_index` is used instead of `previous_image_index_` as the + // latter has the same value of `image_index` after new image is selected + if (previous_image_index != image_index) { + base::UmaHistogramExactLinear( + "UserImage.Changed", + user_image_manager->ImageIndexToHistogramIndex(image_index), + default_user_image::kHistogramImagesCount + 1); + } + // Ignore the result of the previous decoding if it's no longer needed. if (!waiting_for_camera_photo) ImageDecoder::Cancel(this);
diff --git a/chrome/browser/ui/webui/settings/chromeos/internet_section.cc b/chrome/browser/ui/webui/settings/chromeos/internet_section.cc index 65da08c6..08d5db6 100644 --- a/chrome/browser/ui/webui/settings/chromeos/internet_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/internet_section.cc
@@ -760,6 +760,8 @@ IDS_SETTINGS_INTERNET_NETWORK_RENAME_INPUT_SUBTITLE}, {"eSimRenameProfileInputCharacterCount", IDS_SETTINGS_INTERNET_NETWORK_RENAME_INPUT_CHARACTER_COUNT}, + {"eSimRenameProfileDoneBtnA11yLabel", + IDS_SETTINGS_INTERNET_NETWORK_RENAME_DONE_BUTTON_A11Y_LABEL}, {"eSimRenameProfileInputA11yLabel", IDS_SETTINGS_INTERNET_NETWORK_RENAME_INPUT_A11Y_LABEL}, {"eSimRenameProfileDialogError",
diff --git a/chrome/browser/web_applications/system_web_apps/system_web_app_manager.cc b/chrome/browser/web_applications/system_web_apps/system_web_app_manager.cc index 51f5721..cb40bf15 100644 --- a/chrome/browser/web_applications/system_web_apps/system_web_app_manager.cc +++ b/chrome/browser/web_applications/system_web_apps/system_web_app_manager.cc
@@ -195,6 +195,12 @@ IDS_GENIUS_APP_NAME, IDS_HELP_APP_PERKS, IDS_HELP_APP_OFFERS}; infos.at(SystemAppType::HELP).minimum_window_size = {600, 320}; infos.at(SystemAppType::HELP).capture_navigations = true; + if (base::FeatureList::IsEnabled( + chromeos::features::kHelpAppLauncherSearch)) { + infos.at(SystemAppType::HELP).timer_info = SystemAppBackgroundTaskInfo( + base::nullopt, GURL("chrome://help-app/background"), + /*open_immediately=*/true); + } } if (SystemWebAppManager::IsAppEnabled(SystemAppType::MEDIA)) {
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 2a7be777..958a96b 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-master-1620226734-d8c61dfceebb448f59c384822e9494e9858c2e85.profdata +chrome-win32-master-1620237542-044eea13d49909536a8cf0df3ae49a914c612303.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index ec12e657..4f80b82 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-master-1620226734-f43a2a9eee8868818ee022f83a610a4f6a63a530.profdata +chrome-win64-master-1620237542-f391bec9654af9316e0e955e41fc3b8f6abd13cc.profdata
diff --git a/chrome/common/extensions/api/tabs.json b/chrome/common/extensions/api/tabs.json index a4de1fc..67f179b 100644 --- a/chrome/common/extensions/api/tabs.json +++ b/chrome/common/extensions/api/tabs.json
@@ -142,7 +142,7 @@ ], "properties": { "MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND": { - "value": 1, + "value": 2, "description": "The maximum number of times that $(ref:captureVisibleTab) can be called per second. $(ref:captureVisibleTab) is expensive and should not be called too often." }, "TAB_ID_NONE": {
diff --git a/chrome/common/media/cdm_registration.cc b/chrome/common/media/cdm_registration.cc index ea0c793..5c4155e 100644 --- a/chrome/common/media/cdm_registration.cc +++ b/chrome/common/media/cdm_registration.cc
@@ -242,7 +242,10 @@ capability.encryption_schemes.insert(media::EncryptionScheme::kCenc); capability.encryption_schemes.insert(media::EncryptionScheme::kCbcs); - // TODO(xhwang): Add supported session types. + // Both temporary and persistent sessions are supported on ChromeOS. + capability.session_types.insert(media::CdmSessionType::kTemporary); + capability.session_types.insert(media::CdmSessionType::kPersistentLicense); + // TODO(xhwang): Specify kChromeOsCdmFileSystemId here and update // MediaInterfaceProxy to use it.
diff --git a/chrome/renderer/cart/commerce_hint_agent_browsertest.cc b/chrome/renderer/cart/commerce_hint_agent_browsertest.cc index feba8c4..069d980 100644 --- a/chrome/renderer/cart/commerce_hint_agent_browsertest.cc +++ b/chrome/renderer/cart/commerce_hint_agent_browsertest.cc
@@ -144,9 +144,10 @@ class CommerceHintAgentTest : public PlatformBrowserTest { public: void SetUpInProcessBrowserTestFixture() override { - scoped_feature_list_.InitAndEnableFeatureWithParameters( - ntp_features::kNtpChromeCartModule, - {{"product-skip-pattern", "(^|\\W)(?i)(skipped)(\\W|$)"}}); + scoped_feature_list_.InitWithFeaturesAndParameters( + {{ntp_features::kNtpChromeCartModule, + {{"product-skip-pattern", "(^|\\W)(?i)(skipped)(\\W|$)"}}}}, + {optimization_guide::features::kOptimizationHints}); } void SetUpCommandLine(base::CommandLine* command_line) override { @@ -522,10 +523,11 @@ class CommerceHintProductInfoTest : public CommerceHintAgentTest { public: void SetUpInProcessBrowserTestFixture() override { - scoped_feature_list_.InitAndEnableFeatureWithParameters( - ntp_features::kNtpChromeCartModule, - {{"partner-merchant-pattern", "(guitarcenter.com)"}, - {"product-skip-pattern", "(^|\\W)(?i)(skipped)(\\W|$)"}}); + scoped_feature_list_.InitWithFeaturesAndParameters( + {{ntp_features::kNtpChromeCartModule, + {{"partner-merchant-pattern", "(guitarcenter.com)"}, + {"product-skip-pattern", "(^|\\W)(?i)(skipped)(\\W|$)"}}}}, + {optimization_guide::features::kOptimizationHints}); } private:
diff --git a/chrome/renderer/media/chrome_key_systems.cc b/chrome/renderer/media/chrome_key_systems.cc index 6a539eb..0ccd581 100644 --- a/chrome/renderer/media/chrome_key_systems.cc +++ b/chrome/renderer/media/chrome_key_systems.cc
@@ -10,6 +10,7 @@ #include <vector> #include "base/containers/contains.h" +#include "base/containers/flat_set.h" #include "base/logging.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" @@ -259,13 +260,43 @@ } // Codecs and encryption schemes. - auto codecs = GetSupportedCodecs(capability->video_codecs, - /*is_secure=*/false); - const auto& encryption_schemes = capability->encryption_schemes; - auto hw_secure_codecs = GetSupportedCodecs(capability->hw_secure_video_codecs, - /*is_secure=*/true); - const auto& hw_secure_encryption_schemes = - capability->hw_secure_encryption_schemes; + SupportedCodecs codecs = media::EME_CODEC_NONE; + SupportedCodecs hw_secure_codecs = media::EME_CODEC_NONE; + base::flat_set<::media::EncryptionScheme> encryption_schemes; + base::flat_set<::media::EncryptionScheme> hw_secure_encryption_schemes; + bool cdm_supports_persistent_license = false; + + if (capability->sw_secure_capability) { + codecs = GetSupportedCodecs(capability->sw_secure_capability->video_codecs, + /*is_secure=*/false); + encryption_schemes = capability->sw_secure_capability->encryption_schemes; + if (!base::Contains(capability->sw_secure_capability->session_types, + media::CdmSessionType::kTemporary)) { + DVLOG(1) << "Temporary sessions must be supported."; + return; + } + + cdm_supports_persistent_license = + base::Contains(capability->sw_secure_capability->session_types, + media::CdmSessionType::kPersistentLicense); + } + + if (capability->hw_secure_capability) { + hw_secure_codecs = GetSupportedCodecs( + capability->hw_secure_capability->video_codecs, /*is_secure=*/true); + hw_secure_encryption_schemes = + capability->hw_secure_capability->encryption_schemes; + if (!base::Contains(capability->hw_secure_capability->session_types, + media::CdmSessionType::kTemporary)) { + DVLOG(1) << "Temporary sessions must be supported."; + return; + } + + // TODO(b/186035558): With a single flag we can't distinguish persistent + // session support between software and hardware CDMs. This should be + // fixed so that if there is both a software and a hardware CDM, persistent + // session support can be different between the versions. + } // Robustness. using Robustness = cdm::WidevineKeySystemProperties::Robustness; @@ -284,16 +315,6 @@ } #endif - // Session types. - bool cdm_supports_temporary_session = base::Contains( - capability->session_types, media::CdmSessionType::kTemporary); - if (!cdm_supports_temporary_session) { - DVLOG(1) << "Temporary session must be supported."; - return; - } - - bool cdm_supports_persistent_license = base::Contains( - capability->session_types, media::CdmSessionType::kPersistentLicense); auto persistent_license_support = GetPersistentLicenseSupport(cdm_supports_persistent_license);
diff --git a/chrome/renderer/supervised_user/supervised_user_error_page_controller.cc b/chrome/renderer/supervised_user/supervised_user_error_page_controller.cc index d6f3f1c..dcaf79e 100644 --- a/chrome/renderer/supervised_user/supervised_user_error_page_controller.cc +++ b/chrome/renderer/supervised_user/supervised_user_error_page_controller.cc
@@ -22,6 +22,8 @@ base::WeakPtr<SupervisedUserErrorPageControllerDelegate> delegate) { v8::Isolate* isolate = blink::MainThreadIsolate(); v8::HandleScope handle_scope(isolate); + v8::MicrotasksScope microtasks_scope( + isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Context> context = render_frame->GetWebFrame()->MainWorldScriptContext(); if (context.IsEmpty())
diff --git a/chrome/service/cloud_print/cloud_print_proxy.cc b/chrome/service/cloud_print/cloud_print_proxy.cc index c11d29f..70d8842 100644 --- a/chrome/service/cloud_print/cloud_print_proxy.cc +++ b/chrome/service/cloud_print/cloud_print_proxy.cc
@@ -89,8 +89,9 @@ // Keep only proxy id; service_prefs_->SetString(prefs::kCloudPrintProxyId, proxy_id); } - service_prefs_->SetValue(prefs::kCloudPrintUserSettings, - user_settings.CreateDeepCopy()); + service_prefs_->SetValue( + prefs::kCloudPrintUserSettings, + base::Value::ToUniquePtrValue(user_settings.Clone())); service_prefs_->WritePrefs(); if (!CreateBackend())
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcess/manifest.json b/chrome/test/data/extensions/api_test/webnavigation/crossProcess/manifest.json index b8c665c5..50c38590 100644 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcess/manifest.json +++ b/chrome/test/data/extensions/api_test/webnavigation/crossProcess/manifest.json
@@ -4,7 +4,8 @@ "manifest_version": 2, "description": "Tests the webNavigation API events - crossProcess.", "background": { - "page": "test_crossProcess.html" + "scripts": ["test_crossProcess.js"], + "persistent": true }, "permissions": ["webNavigation", "tabs"] }
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcess/test_crossProcess.html b/chrome/test/data/extensions/api_test/webnavigation/crossProcess/test_crossProcess.html deleted file mode 100644 index ed6003d..0000000 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcess/test_crossProcess.html +++ /dev/null
@@ -1,2 +0,0 @@ -<script src="_test_resources/api_test/webnavigation/framework.js"></script> -<script src="test_crossProcess.js"></script>
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcess/test_crossProcess.js b/chrome/test/data/extensions/api_test/webnavigation/crossProcess/test_crossProcess.js index ffd14891..41bed4d 100644 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcess/test_crossProcess.js +++ b/chrome/test/data/extensions/api_test/webnavigation/crossProcess/test_crossProcess.js
@@ -2,7 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -onload = async function() { +const scriptUrl = '_test_resources/api_test/webnavigation/framework.js'; +let loadScript = chrome.test.loadScript(scriptUrl); + +loadScript.then(async function() { let tab = await promise(chrome.tabs.create, {"url": "about:blank"}); let config = await promise(chrome.test.getConfig); let port = config.testServer.port; @@ -466,4 +469,4 @@ chrome.tabs.update(tab.id, {url: getURL('d.html?' + port + "/test2")}); }, ]); -}; +});
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/manifest.json b/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/manifest.json index aaeded7..b6acf79 100644 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/manifest.json +++ b/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/manifest.json
@@ -4,7 +4,8 @@ "manifest_version": 2, "description": "Tests the webNavigation API events - crossProcessHistory.", "background": { - "page": "test_crossProcessHistory.html" + "scripts": ["test_crossProcessHistory.js"], + "persistent": true }, "permissions": ["webNavigation", "tabs"] }
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/test_crossProcessHistory.html b/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/test_crossProcessHistory.html deleted file mode 100644 index 1437012..0000000 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/test_crossProcessHistory.html +++ /dev/null
@@ -1,2 +0,0 @@ -<script src="_test_resources/api_test/webnavigation/framework.js"></script> -<script src="test_crossProcessHistory.js"></script>
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/test_crossProcessHistory.js b/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/test_crossProcessHistory.js index 1ec8a45..ed56c7e 100644 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/test_crossProcessHistory.js +++ b/chrome/test/data/extensions/api_test/webnavigation/crossProcessHistory/test_crossProcessHistory.js
@@ -2,7 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -onload = async function() { +const scriptUrl = '_test_resources/api_test/webnavigation/framework.js'; +let loadScript = chrome.test.loadScript(scriptUrl); + +loadScript.then(async function() { var getURL = chrome.extension.getURL; let config = await promise(chrome.test.getConfig); let port = config.testServer.port; @@ -360,4 +363,4 @@ chrome.tabs.update(tab.id, {url: getURL('i.html?' + port)}); }, ]); -}; +});
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/manifest.json b/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/manifest.json index 81a3ff1..c2b5408 100644 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/manifest.json +++ b/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/manifest.json
@@ -4,7 +4,8 @@ "manifest_version": 2, "description": "Tests the webNavigation API events - crossProcessIframe.", "background": { - "page": "test_crossProcessIframe.html" + "scripts": ["test_crossProcessIframe.js"], + "persistent": true }, "permissions": ["webNavigation", "tabs"] }
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/test_crossProcessIframe.html b/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/test_crossProcessIframe.html deleted file mode 100644 index c01ad6b..0000000 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/test_crossProcessIframe.html +++ /dev/null
@@ -1,2 +0,0 @@ -<script src="_test_resources/api_test/webnavigation/framework.js"></script> -<script src="test_crossProcessIframe.js"></script>
diff --git a/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/test_crossProcessIframe.js b/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/test_crossProcessIframe.js index b0a38b6..1dcf530 100644 --- a/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/test_crossProcessIframe.js +++ b/chrome/test/data/extensions/api_test/webnavigation/crossProcessIframe/test_crossProcessIframe.js
@@ -2,7 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -onload = async function() { +const scriptUrl = '_test_resources/api_test/webnavigation/framework.js'; +let loadScript = chrome.test.loadScript(scriptUrl); + +loadScript.then(async function() { debug = true; let getURL = chrome.extension.getURL; let tab = await promise(chrome.tabs.create, {"url": "about:blank"}); @@ -173,4 +176,4 @@ }, ]); -}; +});
diff --git a/chrome/test/data/extensions/back_forward_cache/content_script/manifest.json b/chrome/test/data/extensions/back_forward_cache/content_script/manifest.json index 369cf50..789ee9d4 100644 --- a/chrome/test/data/extensions/back_forward_cache/content_script/manifest.json +++ b/chrome/test/data/extensions/back_forward_cache/content_script/manifest.json
@@ -4,6 +4,9 @@ "manifest_version": 2, "description": "Checks that content scripts do prevent back forward cache.", "permissions": ["http://*/*", "https://*/*"], + "externally_connectable": { + "matches": ["*://a.com/*"] + }, "content_scripts": [ { "matches": ["http://*/*", "https://*/*"],
diff --git a/chrome/test/data/webui/settings/chromeos/esim_rename_dialog_test.js b/chrome/test/data/webui/settings/chromeos/esim_rename_dialog_test.js index 241fe2d3..0d48bc5 100644 --- a/chrome/test/data/webui/settings/chromeos/esim_rename_dialog_test.js +++ b/chrome/test/data/webui/settings/chromeos/esim_rename_dialog_test.js
@@ -13,6 +13,7 @@ // #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; // #import {assertEquals, assertTrue} from '../../chai_assert.js'; // #import {eventToPromise} from 'chrome://test/test_util.m.js'; +// #import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; // clang-format on suite('EsimRenameDialog', function() { @@ -38,7 +39,11 @@ esimRenameDialog.networkState = response.result; document.body.appendChild(esimRenameDialog); assertTrue(!!esimRenameDialog); - Polymer.dom.flush(); + await flushAsync(); + assertEquals( + esimRenameDialog.$$('#eSimprofileName') + .shadowRoot.querySelector('input'), + getDeepActiveElement()); } /** @@ -91,7 +96,7 @@ eSimManagerRemote.addEuiccForTest(1); addEsimCellularNetwork(TEST_CELLULAR_GUID, '1'); await flushAsync(); - init(); + await init(); return flushAsync().then(async () => { const inputBox = esimRenameDialog.$$('#eSimprofileName'); @@ -149,7 +154,7 @@ eSimManagerRemote.addEuiccForTest(1); addEsimCellularNetwork(TEST_CELLULAR_GUID, '1'); await flushAsync(); - init(); + await init(); return flushAsync().then(async () => { const inputBox = esimRenameDialog.$$('#eSimprofileName'); @@ -222,7 +227,7 @@ eSimManagerRemote.addEuiccForTest(1); addEsimCellularNetwork(TEST_CELLULAR_GUID, '1'); await flushAsync(); - init(); + await init(); await flushAsync(); const inputBox = esimRenameDialog.$$('#eSimprofileName');
diff --git a/chromecast/cast_core/BUILD.gn b/chromecast/cast_core/BUILD.gn index 7486332f..4547ee7 100644 --- a/chromecast/cast_core/BUILD.gn +++ b/chromecast/cast_core/BUILD.gn
@@ -10,8 +10,14 @@ "cast_runtime_service.h", ] + if (!enable_cast_media_runtime) { + sources += [ "cast_runtime_service_simple.cc" ] + } + deps = [ - "//chromecast/media/cma/backend/proxy:headers", + "//base", "//chromecast/service", ] + + public_deps = [ "//chromecast/media/cma/backend/proxy:headers" ] }
diff --git a/chromecast/cast_core/cast_runtime_service.h b/chromecast/cast_core/cast_runtime_service.h index 4666b12..da3caec 100644 --- a/chromecast/cast_core/cast_runtime_service.h +++ b/chromecast/cast_core/cast_runtime_service.h
@@ -30,9 +30,6 @@ public media::CastRuntimeAudioChannelEndpointManager { public: // Returns current instance of CastRuntimeService in the browser process. - // TODO(rwkeane): After dependent repos have implemented this interface, - // implement it in public Chromium as-well. Do not implement before then, to - // ensure that integration cross-repo remains relatively simple. static CastRuntimeService* GetInstance(); CastRuntimeService();
diff --git a/chromecast/cast_core/cast_runtime_service_simple.cc b/chromecast/cast_core/cast_runtime_service_simple.cc new file mode 100644 index 0000000..53cee410 --- /dev/null +++ b/chromecast/cast_core/cast_runtime_service_simple.cc
@@ -0,0 +1,43 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/no_destructor.h" +#include "chromecast/cast_core/cast_runtime_service.h" + +namespace chromecast { +namespace { + +class CastRuntimeServiceSimple : public CastRuntimeService { + public: + CastRuntimeServiceSimple() = default; + ~CastRuntimeServiceSimple() override = default; + + private: + // CastRuntimeService overrides. + WebCryptoServer* GetWebCryptoServer() override { return nullptr; } + receiver::MediaManager* GetMediaManager() override { return nullptr; } + + // CastService overrides. + void InitializeInternal() override {} + void FinalizeInternal() override {} + void StartInternal() override {} + void StopInternal() override {} + + // CastRuntimeAudioChannelEndpointManager overrides. + const std::string& GetAudioChannelEndpoint() override { return endpoint_; } + + const std::string endpoint_ = ""; +}; + +} // namespace + +// static +CastRuntimeService* CastRuntimeService::GetInstance() { + // TODO(b/186668532): Instead use the CastService singleton instead of + // creating a new one with NoDestructor. + static base::NoDestructor<CastRuntimeServiceSimple> g_instance; + return g_instance.get(); +} + +} // namespace chromecast
diff --git a/chromecast/chromecast.gni b/chromecast/chromecast.gni index aa42f94..3e5c83b 100644 --- a/chromecast/chromecast.gni +++ b/chromecast/chromecast.gni
@@ -129,6 +129,9 @@ # True to use the Chromium runtime for cast rendering. enable_chromium_runtime_cast_renderer = false + + # True to link in alternate build targets for the Cast Media Runtime. + enable_cast_media_runtime = false } declare_args() {
diff --git a/chromeos/components/help_app_ui/resources/mock/app_bin.js b/chromeos/components/help_app_ui/resources/mock/app_bin.js index 9df8da88..827c4cb 100644 --- a/chromeos/components/help_app_ui/resources/mock/app_bin.js +++ b/chromeos/components/help_app_ui/resources/mock/app_bin.js
@@ -54,7 +54,33 @@ window.customElements.define('showoff-app', ShowoffApp); document.addEventListener('DOMContentLoaded', () => { + if (document.location.pathname === '/background') { + // In the background page, don't render the app. + doBackgroundTasks(); + return; + } + // The "real" app first loads translations for populating strings in the app // for the initial load, then does this. document.body.appendChild(new ShowoffApp()); }); + +/** + * Do the background processing and then close the page. + * Based on the internal version: go/help-app-internal-dobackgroundtasks. This + * function's implementation should be kept up to date with the internal + * version. + */ +async function doBackgroundTasks() { + if (window.customLaunchData.delegate) { + await window.customLaunchData.delegate.updateLauncherSearchIndex([{ + id: 'mock-app-test-id', + title: 'Title', + mainCategoryName: 'Help', + tags: ['verycomplicatedsearchquery'], + urlPathWithParameters: 'help/sub/3399763/', + locale: '' + }]); + window.customLaunchData.delegate.closeBackgroundPage(); + } +}
diff --git a/chromeos/services/chromebox_for_meetings/public/mojom/meet_devices_info.mojom b/chromeos/services/chromebox_for_meetings/public/mojom/meet_devices_info.mojom index 7ee9ee92..61a8c6f 100644 --- a/chromeos/services/chromebox_for_meetings/public/mojom/meet_devices_info.mojom +++ b/chromeos/services/chromebox_for_meetings/public/mojom/meet_devices_info.mojom
@@ -33,7 +33,7 @@ // From DMServer when server issued response (Java time) int64 timestamp_ms@0; - // PolicyData::DeviceID + // PolicyData::DirectoryApiId string? device_id@1; // PolicyData::ServiceAccountIdentity @@ -41,6 +41,9 @@ // PolicyData::GaiaId int64 service_account_gaia_id@3; + + // PolicyData::DeviceID + string? cros_device_id@4; }; // Basic system information
diff --git a/chromeos/services/libassistant/chromium_api_delegate.h b/chromeos/services/libassistant/chromium_api_delegate.h index bb70ee3d..2990b59 100644 --- a/chromeos/services/libassistant/chromium_api_delegate.h +++ b/chromeos/services/libassistant/chromium_api_delegate.h
@@ -23,7 +23,7 @@ class ChromiumHttpConnectionFactory; -class ChromiumApiDelegate : public assistant_client::FuchsiaApiDelegate { +class ChromiumApiDelegate : public assistant_client::ChromeOSApiDelegate { public: explicit ChromiumApiDelegate( std::unique_ptr<network::PendingSharedURLLoaderFactory>
diff --git a/chromeos/services/libassistant/service_controller.cc b/chromeos/services/libassistant/service_controller.cc index 1ca11ba..e452385 100644 --- a/chromeos/services/libassistant/service_controller.cc +++ b/chromeos/services/libassistant/service_controller.cc
@@ -327,7 +327,7 @@ assistant_manager_internal() ->GetFuchsiaApiHelperOrDie() - ->SetFuchsiaApiDelegate(chromium_api_delegate_.get()); + ->SetChromeOSApiDelegate(chromium_api_delegate_.get()); } void ServiceController::CreateChromiumApiDelegate(
diff --git a/components/BUILD.gn b/components/BUILD.gn index 1b04c26b..13d84b4a 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -501,7 +501,7 @@ if (safe_browsing_mode == 1) { deps += [ - "//components/safe_browsing/content/browser:client_side_model_loader_unittest", + "//components/safe_browsing/content/browser:unit_tests", "//components/safe_browsing/content/renderer/phishing_classifier:unit_tests", ] }
diff --git a/components/arc/metrics/arc_metrics_service.cc b/components/arc/metrics/arc_metrics_service.cc index 3d581c4..282e2968 100644 --- a/components/arc/metrics/arc_metrics_service.cc +++ b/components/arc/metrics/arc_metrics_service.cc
@@ -159,6 +159,8 @@ void ArcMetricsService::RecordArcUserInteraction(UserInteractionType type) { UMA_HISTOGRAM_ENUMERATION("Arc.UserInteraction", type); + for (auto& obs : user_interaction_observers_) + obs.OnUserInteraction(type); } void ArcMetricsService::SetHistogramNamer(HistogramNamer histogram_namer) { @@ -431,6 +433,18 @@ app_kill_observers_.RemoveObserver(obs); } +void ArcMetricsService::AddUserInteractionObserver( + UserInteractionObserver* obs) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + user_interaction_observers_.AddObserver(obs); +} + +void ArcMetricsService::RemoveUserInteractionObserver( + UserInteractionObserver* obs) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + user_interaction_observers_.RemoveObserver(obs); +} + base::Optional<base::TimeTicks> ArcMetricsService::GetArcStartTimeFromEvents( std::vector<mojom::BootProgressEventPtr>& events) { mojom::BootProgressEventPtr arc_upgraded_event;
diff --git a/components/arc/metrics/arc_metrics_service.h b/components/arc/metrics/arc_metrics_service.h index fc969f5..c3e6f4f2 100644 --- a/components/arc/metrics/arc_metrics_service.h +++ b/components/arc/metrics/arc_metrics_service.h
@@ -61,6 +61,11 @@ virtual void OnArcMetricsServiceDestroyed() {} }; + class UserInteractionObserver : public base::CheckedObserver { + public: + virtual void OnUserInteraction(UserInteractionType type) = 0; + }; + // Returns singleton instance for the given BrowserContext, // or nullptr if the browser |context| is not allowed to use ARC. static ArcMetricsService* GetForBrowserContext( @@ -124,6 +129,9 @@ void AddAppKillObserver(AppKillObserver* obs); void RemoveAppKillObserver(AppKillObserver* obs); + void AddUserInteractionObserver(UserInteractionObserver* obs); + void RemoveUserInteractionObserver(UserInteractionObserver* obs); + // Finds the boot_progress_arc_upgraded event, removes it from |events|, and // returns the event time. If the boot_progress_arc_upgraded event is not // found, base::nullopt is returned. This function is public for testing @@ -238,6 +246,7 @@ bool gamepad_interaction_recorded_ = false; base::ObserverList<AppKillObserver> app_kill_observers_; + base::ObserverList<UserInteractionObserver> user_interaction_observers_; // Always keep this the last member of this class to make sure it's the // first thing to be destructed.
diff --git a/components/arc/metrics/arc_metrics_service_unittest.cc b/components/arc/metrics/arc_metrics_service_unittest.cc index e648162..817641d 100644 --- a/components/arc/metrics/arc_metrics_service_unittest.cc +++ b/components/arc/metrics/arc_metrics_service_unittest.cc
@@ -10,6 +10,7 @@ #include "ash/public/cpp/app_types.h" #include "base/metrics/histogram_samples.h" +#include "base/optional.h" #include "base/run_loop.h" #include "base/test/metrics/histogram_tester.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" @@ -321,5 +322,27 @@ EXPECT_FALSE(arc_start_time.has_value()); } +TEST_F(ArcMetricsServiceTest, UserInteractionObserver) { + class Observer : public ArcMetricsService::UserInteractionObserver { + public: + void OnUserInteraction(UserInteractionType type) override { + this->type = type; + } + base::Optional<UserInteractionType> type; + } observer; + + service()->AddUserInteractionObserver(&observer); + + // This calls RecordArcUserInteraction() with APP_CONTENT_WINDOW_INTERACTION. + service()->OnWindowActivated( + wm::ActivationChangeObserver::ActivationReason::INPUT_EVENT, + fake_arc_window(), nullptr); + ASSERT_TRUE(observer.type); + EXPECT_EQ(UserInteractionType::APP_CONTENT_WINDOW_INTERACTION, + *observer.type); + + service()->RemoveUserInteractionObserver(&observer); +} + } // namespace } // namespace arc
diff --git a/components/autofill/content/browser/content_autofill_driver.cc b/components/autofill/content/browser/content_autofill_driver.cc index 48e42cfa..d351025 100644 --- a/components/autofill/content/browser/content_autofill_driver.cc +++ b/components/autofill/content/browser/content_autofill_driver.cc
@@ -516,18 +516,20 @@ // Try to show offer notification when the last committed URL has the domain // that an offer is applicable for. - std::tuple<std::vector<GURL>, GURL, CreditCard*> result = - offer_manager->GetEligibleDomainsAndCardForOfferForUrl(url); - std::vector<GURL>& domains = std::get<0>(result); - GURL offer_details_url = std::get<1>(result); - CreditCard* card = std::get<2>(result); - // TODO(crbug.com/1093057): Update return condition once we introduce the - // promo offers. - if (domains.empty() || !card) - return; + // TODO(crbug.com/1203811): GetOfferForUrl needs to know whether to give + // precedence to card-linked offers or promo code offers. Eventually, promo + // code offers should take precedence if a bubble is shown. Currently, if a + // url has both types of offers and the promo code offer is selected, no + // bubble will end up being shown (due to not yet being implemented). + AutofillOfferData* offer = offer_manager->GetOfferForUrl(url); - browser_autofill_manager_->client()->ShowOfferNotificationIfApplicable( - domains, offer_details_url, card); + if (!offer || offer->merchant_domain.empty() || + (offer->IsCardLinkedOffer() && offer->eligible_instrument_id.empty()) || + (offer->IsPromoCodeOffer() && offer->promo_code.empty())) { + return; + } + + browser_autofill_manager_->client()->ShowOfferNotificationIfApplicable(offer); } } // namespace autofill
diff --git a/components/autofill/core/browser/autofill_client.cc b/components/autofill/core/browser/autofill_client.cc index 1f72eb15..e24227e 100644 --- a/components/autofill/core/browser/autofill_client.cc +++ b/components/autofill/core/browser/autofill_client.cc
@@ -59,11 +59,9 @@ #endif void AutofillClient::ShowOfferNotificationIfApplicable( - const std::vector<GURL>& domains_to_display_bubble, - const GURL& offer_details_url, - const CreditCard* card) { + const AutofillOfferData* offer) { // This is overridden by platform subclasses. Currently only - // ChromeAutofillClient (Chrome Desktop and Clank) implement this. + // ChromeAutofillClient (Chrome Desktop and Clank) implements this. } bool AutofillClient::IsAutofillAssistantShowing() {
diff --git a/components/autofill/core/browser/autofill_client.h b/components/autofill/core/browser/autofill_client.h index c5c8d4aa..a92b6615 100644 --- a/components/autofill/core/browser/autofill_client.h +++ b/components/autofill/core/browser/autofill_client.h
@@ -72,6 +72,7 @@ class StrikeDatabase; enum class WebauthnDialogCallbackType; enum class WebauthnDialogState; +struct AutofillOfferData; struct Suggestion; namespace payments { @@ -515,14 +516,9 @@ // Will show a bubble or infobar indicating that the current web domain has an // eligible offer or reward if no other notification bubble is currently // visible. See bubble controller for details. The bubble is sticky over a set - // of domains given in |domains_to_display_bubble|. The bubble displays the - // information of the |card| if the offer is card-related. On mobile, the - // bubble also shows the |offer_details_url| as a link which has more - // information about the offer. + // of domains given in the offer. virtual void ShowOfferNotificationIfApplicable( - const std::vector<GURL>& domains_to_display_bubble, - const GURL& offer_details_url, - const CreditCard* card); + const AutofillOfferData* offer); // Returns true if the Autofill Assistant UI is currently being shown. virtual bool IsAutofillAssistantShowing();
diff --git a/components/autofill/core/browser/autofill_metrics_unittest.cc b/components/autofill/core/browser/autofill_metrics_unittest.cc index 6d500f8b..1d2cb507 100644 --- a/components/autofill/core/browser/autofill_metrics_unittest.cc +++ b/components/autofill/core/browser/autofill_metrics_unittest.cc
@@ -580,7 +580,7 @@ offer_data.merchant_domain = {url}; offer_data.eligible_instrument_id = { masked_server_credit_card.instrument_id()}; - personal_data_->AddCreditCardOfferData(offer_data); + personal_data_->AddAutofillOfferData(offer_data); personal_data_->Refresh(); }
diff --git a/components/autofill/core/browser/data_model/autofill_offer_data.cc b/components/autofill/core/browser/data_model/autofill_offer_data.cc index 58f13acf..9fba505f 100644 --- a/components/autofill/core/browser/data_model/autofill_offer_data.cc +++ b/components/autofill/core/browser/data_model/autofill_offer_data.cc
@@ -93,4 +93,14 @@ return 0; } +bool AutofillOfferData::IsCardLinkedOffer() const { + // Card-linked offers have at least one |eligible_instrument_id|. + return !eligible_instrument_id.empty(); +} + +bool AutofillOfferData::IsPromoCodeOffer() const { + // Promo code offers have the promo code field populated. + return !promo_code.empty(); +} + } // namespace autofill
diff --git a/components/autofill/core/browser/data_model/autofill_offer_data.h b/components/autofill/core/browser/data_model/autofill_offer_data.h index 1a3b2fff..99d084a3 100644 --- a/components/autofill/core/browser/data_model/autofill_offer_data.h +++ b/components/autofill/core/browser/data_model/autofill_offer_data.h
@@ -44,6 +44,12 @@ // result of first found difference. int Compare(const AutofillOfferData& other_offer_data) const; + // Returns true if the current offer is a card-linked offer. + bool IsCardLinkedOffer() const; + + // Returns true if the current offer is a promo code offer. + bool IsPromoCodeOffer() const; + // The unique server ID for this offer data. int64_t offer_id;
diff --git a/components/autofill/core/browser/data_model/autofill_profile_comparator.cc b/components/autofill/core/browser/data_model/autofill_profile_comparator.cc index cee9d68b..3224e41 100644 --- a/components/autofill/core/browser/data_model/autofill_profile_comparator.cc +++ b/components/autofill/core/browser/data_model/autofill_profile_comparator.cc
@@ -244,14 +244,15 @@ AutofillProfileComparator::~AutofillProfileComparator() = default; std::vector<ProfileValueDifference> -AutofillProfileComparator::GetSettingsVisibleProfileDifference( +AutofillProfileComparator::GetProfileDifference( const AutofillProfile& first_profile, const AutofillProfile& second_profile, + ServerFieldTypeSet types, const std::string& app_locale) { std::vector<ProfileValueDifference> difference; - difference.reserve(GetUserVisibleTypes().size()); + difference.reserve(types.size()); - for (auto type : GetUserVisibleTypes()) { + for (auto type : types) { const std::u16string& first_value = first_profile.GetInfo(type, app_locale); const std::u16string& second_value = second_profile.GetInfo(type, app_locale); @@ -264,19 +265,18 @@ } base::flat_map<ServerFieldType, std::pair<std::u16string, std::u16string>> -AutofillProfileComparator::GetSettingsVisibleProfileDifferenceMap( +AutofillProfileComparator::GetProfileDifferenceMap( const AutofillProfile& first_profile, const AutofillProfile& second_profile, + ServerFieldTypeSet types, const std::string& app_locale) { std::vector< std::pair<ServerFieldType, std::pair<std::u16string, std::u16string>>> result; + result.reserve(types.size()); - result.reserve(GetUserVisibleTypes().size()); - - for (auto& diff : - AutofillProfileComparator::GetSettingsVisibleProfileDifference( - first_profile, second_profile, app_locale)) { + for (auto& diff : AutofillProfileComparator::GetProfileDifference( + first_profile, second_profile, types, app_locale)) { result.push_back( {diff.type, {std::move(diff.first_value), std::move(diff.second_value)}}); @@ -286,6 +286,24 @@ std::move(result)); } +std::vector<ProfileValueDifference> +AutofillProfileComparator::GetSettingsVisibleProfileDifference( + const AutofillProfile& first_profile, + const AutofillProfile& second_profile, + const std::string& app_locale) { + return GetProfileDifference(first_profile, second_profile, + GetUserVisibleTypes(), app_locale); +} + +base::flat_map<ServerFieldType, std::pair<std::u16string, std::u16string>> +AutofillProfileComparator::GetSettingsVisibleProfileDifferenceMap( + const AutofillProfile& first_profile, + const AutofillProfile& second_profile, + const std::string& app_locale) { + return GetProfileDifferenceMap(first_profile, second_profile, + GetUserVisibleTypes(), app_locale); +} + bool AutofillProfileComparator::Compare(base::StringPiece16 text1, base::StringPiece16 text2, WhitespaceSpec whitespace_spec) const {
diff --git a/components/autofill/core/browser/data_model/autofill_profile_comparator.h b/components/autofill/core/browser/data_model/autofill_profile_comparator.h index 8228091d..34c75984 100644 --- a/components/autofill/core/browser/data_model/autofill_profile_comparator.h +++ b/components/autofill/core/browser/data_model/autofill_profile_comparator.h
@@ -79,6 +79,24 @@ // character is skippable if it is punctuation or white space. bool HasOnlySkippableCharacters(base::StringPiece16 text) const; + // Get the difference in 'types' of two profiles. The difference is determined + // with respect to the provided `app_locale`. + static std::vector<ProfileValueDifference> GetProfileDifference( + const AutofillProfile& first_profile, + const AutofillProfile& second_profile, + ServerFieldTypeSet types, + const std::string& app_locale); + + // Same as `GetProfileDifference()` but returns a map that maps the type to a + // pair of strings that contain the corresponding value from the first and + // second profile. + static base::flat_map<ServerFieldType, + std::pair<std::u16string, std::u16string>> + GetProfileDifferenceMap(const AutofillProfile& first_profile, + const AutofillProfile& second_profile, + ServerFieldTypeSet types, + const std::string& app_locale); + // Get the difference of two profiles for settings-visible values. // The difference is determined with respect to the provided `app_locale`. static std::vector<ProfileValueDifference>
diff --git a/components/autofill/core/browser/data_model/autofill_profile_comparator_unittest.cc b/components/autofill/core/browser/data_model/autofill_profile_comparator_unittest.cc index 7eeadea7..28e56cb 100644 --- a/components/autofill/core/browser/data_model/autofill_profile_comparator_unittest.cc +++ b/components/autofill/core/browser/data_model/autofill_profile_comparator_unittest.cc
@@ -1442,6 +1442,61 @@ existing_profile, new_profile)); } +TEST_P(AutofillProfileComparatorTest, GetProfileDifference) { + AutofillProfile existing_profile(base::GenerateGUID(), + "http://www.example.com/"); + autofill::test::SetProfileInfo( + &existing_profile, "firstName", "middleName", "lastName", "mail@mail.com", + "company", "line1", "line2", "city", "state", "zip", "US", "phone"); + + // Change the zip code of the second profile. + AutofillProfile second_existing_profile = existing_profile; + second_existing_profile.SetRawInfo(ADDRESS_HOME_ZIP, u"another_zip"); + + // There should be no difference in NAME_FULL type. + EXPECT_TRUE( + AutofillProfileComparator::GetProfileDifference( + existing_profile, second_existing_profile, {NAME_FULL}, kLocale) + .empty()); + + // But there should be difference in ADDRESS_HOME_ZIP type. + std::vector<autofill::ProfileValueDifference> expected_difference = { + {ADDRESS_HOME_ZIP, u"zip", u"another_zip"}}; + + EXPECT_EQ(AutofillProfileComparator::GetProfileDifference( + existing_profile, second_existing_profile, {ADDRESS_HOME_ZIP}, + kLocale), + expected_difference); +} + +TEST_P(AutofillProfileComparatorTest, GetProfileDifferenceMap) { + AutofillProfile existing_profile(base::GenerateGUID(), + "http://www.example.com/"); + autofill::test::SetProfileInfo( + &existing_profile, "firstName", "middleName", "lastName", "mail@mail.com", + "company", "line1", "line2", "city", "state", "zip", "US", "phone"); + + // Change the zip code of the second profile. + AutofillProfile second_existing_profile = existing_profile; + second_existing_profile.SetRawInfo(ADDRESS_HOME_ZIP, u"another_zip"); + + // There should be no difference in NAME_FULL type. + EXPECT_TRUE( + AutofillProfileComparator::GetProfileDifferenceMap( + existing_profile, second_existing_profile, {NAME_FULL}, kLocale) + .empty()); + + // But there should be difference in ADDRESS_HOME_ZIP type. + base::flat_map<ServerFieldType, std::pair<std::u16string, std::u16string>> + expected_difference; + expected_difference.insert({ADDRESS_HOME_ZIP, {u"zip", u"another_zip"}}); + + EXPECT_EQ(AutofillProfileComparator::GetProfileDifferenceMap( + existing_profile, second_existing_profile, {ADDRESS_HOME_ZIP}, + kLocale), + expected_difference); +} + TEST_P(AutofillProfileComparatorTest, GetSettingsVisibleProfileDifference) { AutofillProfile existing_profile(base::GenerateGUID(), "http://www.example.com/");
diff --git a/components/autofill/core/browser/payments/autofill_offer_manager.cc b/components/autofill/core/browser/payments/autofill_offer_manager.cc index 595d946..e9fc38da 100644 --- a/components/autofill/core/browser/payments/autofill_offer_manager.cc +++ b/components/autofill/core/browser/payments/autofill_offer_manager.cc
@@ -58,7 +58,7 @@ } AutofillOfferManager::OffersMap eligible_offers_map = - CreateOffersMap(last_committed_url_origin); + CreateCardLinkedOffersMap(last_committed_url_origin); // Update |offer_label| for each suggestion. for (auto& suggestion : suggestions) { @@ -91,46 +91,19 @@ eligible_merchant_domains_.count(last_committed_url.GetOrigin()); } -std::tuple<std::vector<GURL>, GURL, CreditCard*> -AutofillOfferManager::GetEligibleDomainsAndCardForOfferForUrl( +AutofillOfferData* AutofillOfferManager::GetOfferForUrl( const GURL& last_committed_url) { - std::vector<GURL> linked_domains; - std::vector<AutofillOfferData*> offers = - personal_data_->GetCreditCardOffers(); - CreditCard* card = nullptr; - // Initialize to an empty url. - GURL offer_details_url = GURL(); - - // Check which offer is eligible on current domain, then return the full set - // of domains for that offer. - for (auto* offer : offers) { + for (AutofillOfferData* offer : personal_data_->GetAutofillOffers()) { if (IsOfferEligible(*offer, last_committed_url.GetOrigin())) { - for (auto& domain : offer->merchant_domain) { - linked_domains.emplace_back(domain); - } - // Pick first card in the vector. The UI shows only one card's - // information. - card = offer->eligible_instrument_id.empty() - ? nullptr - : personal_data_->GetCreditCardByInstrumentId( - offer->eligible_instrument_id[0]); - offer_details_url = GURL(offer->offer_details_url); - break; + return offer; } } - - // Remove duplicates in domains. - base::ranges::sort(linked_domains); - linked_domains.erase(base::ranges::unique(linked_domains), - linked_domains.end()); - - return std::make_tuple(linked_domains, offer_details_url, card); + return nullptr; } void AutofillOfferManager::UpdateEligibleMerchantDomains() { eligible_merchant_domains_.clear(); - std::vector<AutofillOfferData*> offers = - personal_data_->GetCreditCardOffers(); + std::vector<AutofillOfferData*> offers = personal_data_->GetAutofillOffers(); for (auto* offer : offers) { for (auto& domain : offer->merchant_domain) { @@ -139,12 +112,11 @@ } } -AutofillOfferManager::OffersMap AutofillOfferManager::CreateOffersMap( +AutofillOfferManager::OffersMap AutofillOfferManager::CreateCardLinkedOffersMap( const GURL& last_committed_url_origin) const { AutofillOfferManager::OffersMap offers_map; - std::vector<AutofillOfferData*> offers = - personal_data_->GetCreditCardOffers(); + std::vector<AutofillOfferData*> offers = personal_data_->GetAutofillOffers(); std::vector<CreditCard*> cards = personal_data_->GetCreditCards(); for (auto* offer : offers) { @@ -152,6 +124,10 @@ if (!IsOfferEligible(*offer, last_committed_url_origin)) { continue; } + // Ensure the offer is a card-linked offer. + if (!offer->IsCardLinkedOffer()) { + continue; + } // Find card with corresponding instrument ID and add its guid to the map. for (const auto* card : cards) {
diff --git a/components/autofill/core/browser/payments/autofill_offer_manager.h b/components/autofill/core/browser/payments/autofill_offer_manager.h index ee21328..33910a5f 100644 --- a/components/autofill/core/browser/payments/autofill_offer_manager.h +++ b/components/autofill/core/browser/payments/autofill_offer_manager.h
@@ -22,8 +22,6 @@ namespace autofill { -class CreditCard; - // Manages all Autofill related offers. One per frame; owned by the // BrowserAutofillManager. class AutofillOfferManager : public KeyedService, @@ -47,23 +45,23 @@ // Returns true only if the domain of |last_committed_url| has an offer. bool IsUrlEligible(const GURL& last_committed_url); - // Returns the set of domains and the card linked to a specific offer that - // contains the domain of |last_committed_url|. Also return the - // offer_details_url which redirects to a GPay surface with more details about - // the offer. - std::tuple<std::vector<GURL>, GURL, CreditCard*> - GetEligibleDomainsAndCardForOfferForUrl(const GURL& last_committed_url); + // Returns the offer that contains the domain of |last_committed_url|. + AutofillOfferData* GetOfferForUrl(const GURL& last_committed_url); private: + FRIEND_TEST_ALL_PREFIXES( + AutofillOfferManagerTest, + CreateCardLinkedOffersMap_ReturnsOnlyCardLinkedOffers); FRIEND_TEST_ALL_PREFIXES(AutofillOfferManagerTest, IsUrlEligible); // Queries |personal_data_| to reset the elements of // |eligible_merchant_domains_| void UpdateEligibleMerchantDomains(); - // Creates a mapping from Suggestion Backend ID's to eligible Credit Card - // Offers. - OffersMap CreateOffersMap(const GURL& last_committed_url_origin) const; + // Creates a mapping from Suggestion Backend ID's to eligible card-linked + // offers. + OffersMap CreateCardLinkedOffersMap( + const GURL& last_committed_url_origin) const; PersonalDataManager* personal_data_; std::set<GURL> eligible_merchant_domains_ = {};
diff --git a/components/autofill/core/browser/payments/autofill_offer_manager_unittest.cc b/components/autofill/core/browser/payments/autofill_offer_manager_unittest.cc index 1964110..ad2e02d 100644 --- a/components/autofill/core/browser/payments/autofill_offer_manager_unittest.cc +++ b/components/autofill/core/browser/payments/autofill_offer_manager_unittest.cc
@@ -90,6 +90,21 @@ return offer_data; } + AutofillOfferData CreatePromoCodeOffer(std::vector<GURL> domains = { + GURL(kTestUrl)}) { + AutofillOfferData offer_data; + offer_data.offer_id = 5555; + offer_data.expiry = AutofillClock::Now() + base::TimeDelta::FromDays(2); + offer_data.merchant_domain = std::move(domains); + offer_data.offer_details_url = GURL(kOfferDetailsUrl); + offer_data.promo_code = "5PCTOFFSHOES"; + offer_data.display_strings.value_prop_text = "5% off on shoes. Up to $50."; + offer_data.display_strings.see_details_text = "See details"; + offer_data.display_strings.usage_instructions_text = + "Click the promo code field at checkout to autofill it."; + return offer_data; + } + protected: base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; @@ -102,7 +117,7 @@ TEST_F(AutofillOfferManagerTest, UpdateSuggestionsWithOffers_EligibleCashback) { CreditCard card = CreateCreditCard(kTestGuid); - personal_data_manager_.AddCreditCardOfferData( + personal_data_manager_.AddAutofillOfferData( CreateCreditCardOfferForCard(card, "5%")); std::vector<Suggestion> suggestions = {Suggestion()}; @@ -116,7 +131,7 @@ TEST_F(AutofillOfferManagerTest, UpdateSuggestionsWithOffers_ExpiredOffer) { CreditCard card = CreateCreditCard(kTestGuid); - personal_data_manager_.AddCreditCardOfferData( + personal_data_manager_.AddAutofillOfferData( CreateCreditCardOfferForCard(card, "5%", /*expired=*/true)); std::vector<Suggestion> suggestions = {Suggestion()}; @@ -129,7 +144,7 @@ TEST_F(AutofillOfferManagerTest, UpdateSuggestionsWithOffers_WrongUrl) { CreditCard card = CreateCreditCard(kTestGuid); - personal_data_manager_.AddCreditCardOfferData( + personal_data_manager_.AddAutofillOfferData( CreateCreditCardOfferForCard(card, "5%")); std::vector<Suggestion> suggestions = {Suggestion()}; @@ -145,7 +160,7 @@ CreditCard cardWithoutOffer = CreateCreditCard(kTestGuid); CreditCard cardWithOffer = CreateCreditCard(kTestGuid2, "4111111111111111", 100); - personal_data_manager_.AddCreditCardOfferData( + personal_data_manager_.AddAutofillOfferData( CreateCreditCardOfferForCard(cardWithOffer, "5%")); std::vector<Suggestion> suggestions = {Suggestion(), Suggestion()}; @@ -170,7 +185,7 @@ CreditCard cardWithoutOffer = CreateCreditCard(kTestGuid); CreditCard cardWithOffer = CreateCreditCard(kTestGuid2, "4111111111111111", 100); - personal_data_manager_.AddCreditCardOfferData( + personal_data_manager_.AddAutofillOfferData( CreateCreditCardOfferForCard(cardWithOffer, "5%")); std::vector<Suggestion> suggestions = {Suggestion(), Suggestion()}; @@ -191,9 +206,9 @@ UpdateSuggestionsWithOffer_SuggestionsNotSortedIfAllCardsHaveOffers) { CreditCard card1 = CreateCreditCard(kTestGuid, kTestNumber, 100); CreditCard card2 = CreateCreditCard(kTestGuid2, "4111111111111111", 101); - personal_data_manager_.AddCreditCardOfferData( + personal_data_manager_.AddAutofillOfferData( CreateCreditCardOfferForCard(card1, "5%")); - personal_data_manager_.AddCreditCardOfferData( + personal_data_manager_.AddAutofillOfferData( CreateCreditCardOfferForCard(card2, "5%")); std::vector<Suggestion> suggestions = {Suggestion(), Suggestion()}; @@ -209,10 +224,10 @@ TEST_F(AutofillOfferManagerTest, IsUrlEligible) { CreditCard card1 = CreateCreditCard(kTestGuid, kTestNumber, 100); CreditCard card2 = CreateCreditCard(kTestGuid2, "4111111111111111", 101); - personal_data_manager_.AddCreditCardOfferData(CreateCreditCardOfferForCard( + personal_data_manager_.AddAutofillOfferData(CreateCreditCardOfferForCard( card1, "5%", /*expired=*/false, {GURL("http://www.google.com"), GURL("http://www.youtube.com")})); - personal_data_manager_.AddCreditCardOfferData(CreateCreditCardOfferForCard( + personal_data_manager_.AddAutofillOfferData(CreateCreditCardOfferForCard( card2, "10%", /*expired=*/false, {GURL("http://maps.google.com")})); autofill_offer_manager_->UpdateEligibleMerchantDomains(); @@ -224,66 +239,63 @@ autofill_offer_manager_->IsUrlEligible(GURL("http://maps.google.com"))); } -TEST_F(AutofillOfferManagerTest, - GetEligibleDomainsAndCardForOfferForUrl_ReturnNothingWhenFindNoMatch) { +TEST_F(AutofillOfferManagerTest, GetOfferForUrl_ReturnNothingWhenFindNoMatch) { CreditCard card1 = CreateCreditCard(kTestGuid, kTestNumber, 100); - personal_data_manager_.AddCreditCardOfferData(CreateCreditCardOfferForCard( + personal_data_manager_.AddAutofillOfferData(CreateCreditCardOfferForCard( card1, "5%", /*expired=*/false, {GURL("http://www.google.com"), GURL("http://www.youtube.com")})); - auto result = - autofill_offer_manager_->GetEligibleDomainsAndCardForOfferForUrl( - GURL("http://www.example.com")); - EXPECT_EQ(0U, std::get<0>(result).size()); - EXPECT_EQ(GURL(), std::get<1>(result)); - EXPECT_EQ(nullptr, std::get<2>(result)); + AutofillOfferData* result = + autofill_offer_manager_->GetOfferForUrl(GURL("http://www.example.com")); + EXPECT_EQ(nullptr, result); } TEST_F(AutofillOfferManagerTest, - GetEligibleDomainsAndCardForOfferForUrl_ReturnCorrectSetWhenFindMatch) { + GetOfferForUrl_ReturnCorrectOfferWhenFindMatch) { CreditCard card1 = CreateCreditCard(kTestGuid, kTestNumber, 100); CreditCard card2 = CreateCreditCard(kTestGuid2, "4111111111111111", 101); - personal_data_manager_.AddCreditCardOfferData(CreateCreditCardOfferForCard( + AutofillOfferData offer1 = CreateCreditCardOfferForCard( card1, "5%", /*expired=*/false, /*domains=*/ - {GURL("http://www.google.com"), GURL("http://www.youtube.com")})); - personal_data_manager_.AddCreditCardOfferData(CreateCreditCardOfferForCard( - card2, "5%", /*expired=*/false, + {GURL("http://www.google.com"), GURL("http://www.youtube.com")}); + AutofillOfferData offer2 = CreateCreditCardOfferForCard( + card2, "10%", /*expired=*/false, /*domains=*/ - {GURL("http://www.example.com"), GURL("http://www.example2.com")})); + {GURL("http://www.example.com"), GURL("http://www.example2.com")}); + personal_data_manager_.AddAutofillOfferData(offer1); + personal_data_manager_.AddAutofillOfferData(offer2); - auto result = - autofill_offer_manager_->GetEligibleDomainsAndCardForOfferForUrl( - GURL("http://www.example.com")); - std::vector<GURL> eligible_domain = std::get<0>(result); - EXPECT_EQ(2U, eligible_domain.size()); - EXPECT_NE(eligible_domain.end(), - std::find(eligible_domain.begin(), eligible_domain.end(), - GURL("http://www.example.com"))); - EXPECT_NE(eligible_domain.end(), - std::find(eligible_domain.begin(), eligible_domain.end(), - GURL("http://www.example2.com"))); - EXPECT_EQ(GURL(kOfferDetailsUrl), std::get<1>(result)); - EXPECT_EQ(101, std::get<2>(result)->instrument_id()); + AutofillOfferData* result = + autofill_offer_manager_->GetOfferForUrl(GURL("http://www.example.com")); + EXPECT_EQ(offer2, *result); } -TEST_F( - AutofillOfferManagerTest, - GetEligibleDomainsAndCardForOfferForUrl_ReturnNoCardWhenFindNoMatchedCardData) { +TEST_F(AutofillOfferManagerTest, + CreateCardLinkedOffersMap_ReturnsOnlyCardLinkedOffers) { CreditCard card1 = CreateCreditCard(kTestGuid, kTestNumber, 100); - AutofillOfferData offer_data1 = CreateCreditCardOfferForCard( - card1, "5%", /*expired=*/false, - {GURL("http://www.google.com"), GURL("http://www.youtube.com")}); - offer_data1.eligible_instrument_id.clear(); - personal_data_manager_.AddCreditCardOfferData(offer_data1); + CreditCard card2 = CreateCreditCard(kTestGuid2, "4111111111111111", 101); - auto result = - autofill_offer_manager_->GetEligibleDomainsAndCardForOfferForUrl( - GURL("http://www.google.com")); - EXPECT_EQ(2U, std::get<0>(result).size()); - EXPECT_EQ(GURL(kOfferDetailsUrl), std::get<1>(result)); - EXPECT_EQ(nullptr, std::get<2>(result)); + AutofillOfferData offer1 = CreateCreditCardOfferForCard( + card1, "5%", /*expired=*/false, + /*domains=*/ + {GURL("http://www.google.com"), GURL("http://www.youtube.com")}); + AutofillOfferData offer2 = CreateCreditCardOfferForCard( + card2, "10%", /*expired=*/false, + /*domains=*/ + {GURL("http://www.example.com"), GURL("http://www.example2.com")}); + AutofillOfferData offer3 = + CreatePromoCodeOffer(/*domains=*/ + {GURL("http://www.example.com"), + GURL("http://www.example2.com")}); + personal_data_manager_.AddAutofillOfferData(offer1); + personal_data_manager_.AddAutofillOfferData(offer2); + personal_data_manager_.AddAutofillOfferData(offer3); + + auto result = autofill_offer_manager_->CreateCardLinkedOffersMap( + GURL("http://www.example.com")); + EXPECT_EQ(result.size(), 1UL); + EXPECT_EQ(*result[card2.guid()], offer2); } } // namespace autofill
diff --git a/components/autofill/core/browser/personal_data_manager.cc b/components/autofill/core/browser/personal_data_manager.cc index 63bcc5b..dd462f2 100644 --- a/components/autofill/core/browser/personal_data_manager.cc +++ b/components/autofill/core/browser/personal_data_manager.cc
@@ -1161,8 +1161,7 @@ return result; } -std::vector<AutofillOfferData*> PersonalDataManager::GetCreditCardOffers() - const { +std::vector<AutofillOfferData*> PersonalDataManager::GetAutofillOffers() const { if (!IsAutofillWalletImportEnabled()) return {}; @@ -1179,7 +1178,7 @@ LoadCreditCardCloudTokenData(); LoadPaymentsCustomerData(); LoadUpiIds(); - LoadCreditCardOffers(); + LoadAutofillOffers(); } std::vector<AutofillProfile*> PersonalDataManager::GetProfilesToSuggest() @@ -1691,14 +1690,14 @@ database_helper_->GetLocalDatabase()->GetAllUpiIds(this); } -void PersonalDataManager::LoadCreditCardOffers() { +void PersonalDataManager::LoadAutofillOffers() { if (!database_helper_->GetServerDatabase()) return; CancelPendingServerQuery(&pending_offer_data_query_); pending_offer_data_query_ = - database_helper_->GetServerDatabase()->GetCreditCardOffers(this); + database_helper_->GetServerDatabase()->GetAutofillOffers(this); } void PersonalDataManager::CancelPendingLocalQuery(
diff --git a/components/autofill/core/browser/personal_data_manager.h b/components/autofill/core/browser/personal_data_manager.h index c05a29a..11e4a472 100644 --- a/components/autofill/core/browser/personal_data_manager.h +++ b/components/autofill/core/browser/personal_data_manager.h
@@ -276,8 +276,8 @@ virtual std::vector<CreditCardCloudTokenData*> GetCreditCardCloudTokenData() const; - // Returns the credit card offer data. - virtual std::vector<AutofillOfferData*> GetCreditCardOffers() const; + // Returns autofill offer data, including card-linked and promo code offers. + virtual std::vector<AutofillOfferData*> GetAutofillOffers() const; // Updates the validity states of |profiles| according to server validity map. void UpdateProfilesServerValidityMapsIfNeeded( @@ -559,8 +559,8 @@ // Loads the saved UPI IDs from the web database. virtual void LoadUpiIds(); - // Loads the offer data from the web database. - virtual void LoadCreditCardOffers(); + // Loads the autofill offer data from the web database. + virtual void LoadAutofillOffers(); // Cancels a pending query to the local web database. |handle| is a pointer // to the query handle.
diff --git a/components/autofill/core/browser/test_personal_data_manager.cc b/components/autofill/core/browser/test_personal_data_manager.cc index 0913a4a2..a294d2a 100644 --- a/components/autofill/core/browser/test_personal_data_manager.cc +++ b/components/autofill/core/browser/test_personal_data_manager.cc
@@ -340,7 +340,7 @@ NotifyPersonalDataObserver(); } -void TestPersonalDataManager::AddCreditCardOfferData( +void TestPersonalDataManager::AddAutofillOfferData( const AutofillOfferData& offer_data) { std::unique_ptr<AutofillOfferData> data = std::make_unique<AutofillOfferData>(offer_data);
diff --git a/components/autofill/core/browser/test_personal_data_manager.h b/components/autofill/core/browser/test_personal_data_manager.h index 6524c6b..6acbf596 100644 --- a/components/autofill/core/browser/test_personal_data_manager.h +++ b/components/autofill/core/browser/test_personal_data_manager.h
@@ -93,7 +93,7 @@ void AddCloudTokenData(const CreditCardCloudTokenData& cloud_token_data); // Adds offer data to |autofill_offer_data_|. - void AddCreditCardOfferData(const AutofillOfferData& offer_data); + void AddAutofillOfferData(const AutofillOfferData& offer_data); // Sets a local/server card's nickname based on the provided |guid|. void SetNicknameForCardWithGUID(const char* guid,
diff --git a/components/autofill/core/browser/webdata/autofill_table.cc b/components/autofill/core/browser/webdata/autofill_table.cc index 2c0895b..c60f08bf 100644 --- a/components/autofill/core/browser/webdata/autofill_table.cc +++ b/components/autofill/core/browser/webdata/autofill_table.cc
@@ -2116,7 +2116,7 @@ return s.Succeeded(); } -void AutofillTable::SetCreditCardOffers( +void AutofillTable::SetAutofillOffers( const std::vector<AutofillOfferData>& autofill_offer_data) { sql::Transaction transaction(db_); if (!transaction.Begin()) @@ -2189,7 +2189,7 @@ transaction.Commit(); } -bool AutofillTable::GetCreditCardOffers( +bool AutofillTable::GetAutofillOffers( std::vector<std::unique_ptr<AutofillOfferData>>* autofill_offer_data) { autofill_offer_data->clear();
diff --git a/components/autofill/core/browser/webdata/autofill_table.h b/components/autofill/core/browser/webdata/autofill_table.h index f72a8413..223991c 100644 --- a/components/autofill/core/browser/webdata/autofill_table.h +++ b/components/autofill/core/browser/webdata/autofill_table.h
@@ -612,9 +612,9 @@ // |autofill_offer_data| must include all existing offers, since table will // be completely overwritten. - void SetCreditCardOffers( + void SetAutofillOffers( const std::vector<AutofillOfferData>& autofill_offer_data); - bool GetCreditCardOffers( + bool GetAutofillOffers( std::vector<std::unique_ptr<AutofillOfferData>>* autofill_offer_data); // Adds |upi_id| to the saved UPI IDs.
diff --git a/components/autofill/core/browser/webdata/autofill_table_unittest.cc b/components/autofill/core/browser/webdata/autofill_table_unittest.cc index 21528f61..1afd694 100644 --- a/components/autofill/core/browser/webdata/autofill_table_unittest.cc +++ b/components/autofill/core/browser/webdata/autofill_table_unittest.cc
@@ -3722,11 +3722,11 @@ autofill_offer_data.push_back(credit_card_offer_2); autofill_offer_data.push_back(credit_card_offer_3); - table_->SetCreditCardOffers(autofill_offer_data); + table_->SetAutofillOffers(autofill_offer_data); std::vector<std::unique_ptr<AutofillOfferData>> output_offer_data; - EXPECT_TRUE(table_->GetCreditCardOffers(&output_offer_data)); + EXPECT_TRUE(table_->GetAutofillOffers(&output_offer_data)); EXPECT_EQ(autofill_offer_data.size(), output_offer_data.size()); for (const auto& data : autofill_offer_data) {
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_offer_sync_bridge.cc b/components/autofill/core/browser/webdata/autofill_wallet_offer_sync_bridge.cc index 36a70eb..8f85561 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_offer_sync_bridge.cc +++ b/components/autofill/core/browser/webdata/autofill_wallet_offer_sync_bridge.cc
@@ -147,7 +147,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::vector<std::unique_ptr<AutofillOfferData>> offers; - if (!GetAutofillTable()->GetCreditCardOffers(&offers)) { + if (!GetAutofillTable()->GetAutofillOffers(&offers)) { change_processor()->ReportError( {FROM_HERE, "Failed to load offer data from table."}); return; @@ -189,11 +189,11 @@ // Only do a write operation if there is any difference between server data // and local data. std::vector<std::unique_ptr<AutofillOfferData>> existing_offers; - table->GetCreditCardOffers(&existing_offers); + table->GetAutofillOffers(&existing_offers); bool offer_data_changed = AreAnyItemsDifferent(existing_offers, offer_data); if (offer_data_changed) { - table->SetCreditCardOffers(offer_data); + table->SetAutofillOffers(offer_data); } // Commit the transaction to make sure the data and the metadata with the
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_offer_sync_bridge_unittest.cc b/components/autofill/core/browser/webdata/autofill_wallet_offer_sync_bridge_unittest.cc index 67ac9f17..62b092e2 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_offer_sync_bridge_unittest.cc +++ b/components/autofill/core/browser/webdata/autofill_wallet_offer_sync_bridge_unittest.cc
@@ -254,7 +254,7 @@ TEST_F(AutofillWalletOfferSyncBridgeTest, MergeSyncData_NewData) { // Create one offer data in the client table. AutofillOfferData old_data = test::GetCardLinkedOfferData1(); - table()->SetCreditCardOffers({old_data}); + table()->SetAutofillOffers({old_data}); // Create a different one on the server. AutofillOfferSpecifics offer_specifics; @@ -275,7 +275,7 @@ TEST_F(AutofillWalletOfferSyncBridgeTest, MergeSyncData_NoData) { // Create one offer data in the client table. AutofillOfferData client_data = test::GetCardLinkedOfferData1(); - table()->SetCreditCardOffers({client_data}); + table()->SetAutofillOffers({client_data}); EXPECT_CALL(*backend(), CommitChanges()); EXPECT_CALL(*backend(), NotifyOfMultipleAutofillChanges()); @@ -310,7 +310,7 @@ TEST_F(AutofillWalletOfferSyncBridgeTest, ApplyStopSyncChanges_ClearAllData) { // Create one offer data in the client table. AutofillOfferData client_data = test::GetCardLinkedOfferData1(); - table()->SetCreditCardOffers({client_data}); + table()->SetAutofillOffers({client_data}); EXPECT_CALL(*backend(), CommitChanges()); EXPECT_CALL(*backend(), NotifyOfMultipleAutofillChanges()); @@ -329,7 +329,7 @@ TEST_F(AutofillWalletOfferSyncBridgeTest, ApplyStopSyncChanges_KeepAllData) { // Create one offer data in the client table. AutofillOfferData client_data = test::GetCardLinkedOfferData1(); - table()->SetCreditCardOffers({client_data}); + table()->SetAutofillOffers({client_data}); // We do not write to DB at all, so we should not commit any changes. EXPECT_CALL(*backend(), CommitChanges()).Times(0);
diff --git a/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc b/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc index f713cf1..d3fbed7 100644 --- a/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc +++ b/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc
@@ -570,11 +570,11 @@ AUTOFILL_CLOUDTOKEN_RESULT, std::move(cloud_token_data)); } -std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetCreditCardOffers( +std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetAutofillOffers( WebDatabase* db) { DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::vector<std::unique_ptr<AutofillOfferData>> offers; - AutofillTable::FromWebDatabase(db)->GetCreditCardOffers(&offers); + AutofillTable::FromWebDatabase(db)->GetAutofillOffers(&offers); return std::make_unique< WDResult<std::vector<std::unique_ptr<AutofillOfferData>>>>( AUTOFILL_OFFER_DATA, std::move(offers));
diff --git a/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h b/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h index 58cee22..7d404fc 100644 --- a/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h +++ b/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h
@@ -199,7 +199,7 @@ std::unique_ptr<WDTypedResult> GetCreditCardCloudTokenData(WebDatabase* db); // Returns Credit Card Offers Data from the database. - std::unique_ptr<WDTypedResult> GetCreditCardOffers(WebDatabase* db); + std::unique_ptr<WDTypedResult> GetAutofillOffers(WebDatabase* db); WebDatabase::State ClearAllServerData(WebDatabase* db); WebDatabase::State ClearAllLocalData(WebDatabase* db);
diff --git a/components/autofill/core/browser/webdata/autofill_webdata_service.cc b/components/autofill/core/browser/webdata/autofill_webdata_service.cc index fd53c37..522e871 100644 --- a/components/autofill/core/browser/webdata/autofill_webdata_service.cc +++ b/components/autofill/core/browser/webdata/autofill_webdata_service.cc
@@ -280,11 +280,11 @@ consumer); } -WebDataServiceBase::Handle AutofillWebDataService::GetCreditCardOffers( +WebDataServiceBase::Handle AutofillWebDataService::GetAutofillOffers( WebDataServiceConsumer* consumer) { return wdbs_->ScheduleDBTaskWithResult( FROM_HERE, - base::BindOnce(&AutofillWebDataBackendImpl::GetCreditCardOffers, + base::BindOnce(&AutofillWebDataBackendImpl::GetAutofillOffers, autofill_backend_), consumer); }
diff --git a/components/autofill/core/browser/webdata/autofill_webdata_service.h b/components/autofill/core/browser/webdata/autofill_webdata_service.h index d2badf9..d0c5eb7f 100644 --- a/components/autofill/core/browser/webdata/autofill_webdata_service.h +++ b/components/autofill/core/browser/webdata/autofill_webdata_service.h
@@ -159,11 +159,11 @@ WebDataServiceBase::Handle GetCreditCardCloudTokenData( WebDataServiceConsumer* consumer); - // Initiates the request for credit card offer data. The method + // Initiates the request for autofill offer data. The method // OnWebDataServiceRequestDone of |consumer| gets called when the request is // finished, with the offer data included in the argument |result|. The // consumer owns the data. - WebDataServiceBase::Handle GetCreditCardOffers( + WebDataServiceBase::Handle GetAutofillOffers( WebDataServiceConsumer* consumer); void ClearAllServerData();
diff --git a/components/back_forward_cache/back_forward_cache_disable.cc b/components/back_forward_cache/back_forward_cache_disable.cc index 5546dac..1100ab4e 100644 --- a/components/back_forward_cache/back_forward_cache_disable.cc +++ b/components/back_forward_cache/back_forward_cache_disable.cc
@@ -33,6 +33,8 @@ return "ModalDialog"; case DisabledReasonId::kExtensions: return "Extensions"; + case DisabledReasonId::kExtensionMessaging: + return "ExtensionMessaging"; default: return "Unknown (default)"; }
diff --git a/components/back_forward_cache/back_forward_cache_disable.h b/components/back_forward_cache/back_forward_cache_disable.h index fb6520f..4f81cef1 100644 --- a/components/back_forward_cache/back_forward_cache_disable.h +++ b/components/back_forward_cache/back_forward_cache_disable.h
@@ -30,6 +30,7 @@ // the page. kModalDialog = 11, kExtensions = 12, + kExtensionMessaging = 13, // New reasons should be accompanied by a comment as to why BackForwardCache // cannot be used in this case and a link to a bug to fix that if it is // fixable.
diff --git a/components/browser_ui/strings/android/browser_ui_strings.grd b/components/browser_ui/strings/android/browser_ui_strings.grd index 1237ab1b..b3db4a4 100644 --- a/components/browser_ui/strings/android/browser_ui_strings.grd +++ b/components/browser_ui/strings/android/browser_ui_strings.grd
@@ -518,9 +518,6 @@ <message name="IDS_PAGE_INFO_SITE_SETTINGS_BUTTON" desc="Text in the button that opens a website's Site Settings from the Page Info dialog."> Site settings </message> - <message name="IDS_PAGE_INFO_FAST_SITE_SUMMARY" desc="A short summary phrase in the Page Info bubble (which shows when you click the lock icon) that indicates that pages on the current website should load quickly."> - Site is fast - </message> <message name="IDS_PAGE_INFO_COOKIES_CLEAR" desc="Text on the button to clear cookies for a site."> Clear cookies </message> @@ -541,9 +538,6 @@ =1 {1 cookie in use} other {# cookies in use}} </message> - <message name="IDS_PAGE_INFO_FAST_SITE_MESSAGE" desc="A short paragraph that explains what is meant by labeling the current website as fast."> - This site opens and responds quickly for most people - </message> <message name="IDS_PAGE_INFO_ANDROID_LOCATION_BLOCKED" desc="The label used in the Page Info dialog to indicate that location has been been disabled for the device in Android settings"> Turned off for this device </message>
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_PAGE_INFO_FAST_SITE_MESSAGE.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_PAGE_INFO_FAST_SITE_MESSAGE.png.sha1 deleted file mode 100644 index 7bcd7884..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_PAGE_INFO_FAST_SITE_MESSAGE.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -beb4e1ece71346f8fc006b16a1ad5ce880167cfb \ No newline at end of file
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_PAGE_INFO_FAST_SITE_SUMMARY.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_PAGE_INFO_FAST_SITE_SUMMARY.png.sha1 deleted file mode 100644 index 7bcd7884..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_PAGE_INFO_FAST_SITE_SUMMARY.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -beb4e1ece71346f8fc006b16a1ad5ce880167cfb \ No newline at end of file
diff --git a/components/exo/BUILD.gn b/components/exo/BUILD.gn index 42e3199f52..c6235bf 100644 --- a/components/exo/BUILD.gn +++ b/components/exo/BUILD.gn
@@ -133,6 +133,7 @@ "//chromeos/crosapi/cpp", "//chromeos/ui/base", "//chromeos/ui/frame", + "//components/full_restore", "//components/fullscreen_control", "//components/strings", "//ui/base",
diff --git a/components/exo/DEPS b/components/exo/DEPS index 279923cb..43bccd77 100644 --- a/components/exo/DEPS +++ b/components/exo/DEPS
@@ -5,6 +5,7 @@ "+chromeos/ui/base", "+chromeos/ui/frame", "+components/fullscreen_control", + "+components/full_restore", "+components/strings", "+components/viz/common", "+components/viz/host",
diff --git a/components/exo/shell_surface_base.cc b/components/exo/shell_surface_base.cc index 880e81ea..d03926e 100644 --- a/components/exo/shell_surface_base.cc +++ b/components/exo/shell_surface_base.cc
@@ -24,6 +24,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/traced_value.h" +#include "build/chromeos_buildflags.h" #include "cc/trees/layer_tree_frame_sink.h" #include "chromeos/crosapi/cpp/crosapi_constants.h" #include "chromeos/ui/base//window_properties.h" @@ -33,6 +34,8 @@ #include "components/exo/shell_surface_util.h" #include "components/exo/surface.h" #include "components/exo/wm_helper.h" +#include "components/full_restore/full_restore_info.h" +#include "components/full_restore/full_restore_utils.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" @@ -1049,11 +1052,16 @@ params.show_state = show_state; // Make shell surface a transient child if |parent_| has been set and // container_ isn't specified. - if (ash::desks_util::IsDeskContainerId(container_) && parent_) { - params.parent = parent_; + aura::Window* root_window = + WMHelper::GetInstance()->GetRootWindowForNewWindows(); + if (ash::desks_util::IsDeskContainerId(container_)) { + DCHECK_EQ(ash::desks_util::GetActiveDeskContainerId(), container_); + if (parent_) + params.parent = parent_; + else + params.context = root_window; } else { - params.parent = ash::Shell::GetContainer( - WMHelper::GetInstance()->GetRootWindowForNewWindows(), container_); + params.parent = ash::Shell::GetContainer(root_window, container_); } params.bounds = gfx::Rect(origin_, gfx::Size()); @@ -1083,6 +1091,12 @@ ? views::Widget::InitParams::Activatable::kYes : views::Widget::InitParams::Activatable::kNo; +#if BUILDFLAG(IS_CHROMEOS_ASH) + full_restore::ModifyWidgetParams(params.init_properties_container.GetProperty( + full_restore::kRestoreWindowIdKey), + ¶ms); +#endif + OverrideInitParams(¶ms); // Note: NativeWidget owns this widget.
diff --git a/components/history/core/browser/BUILD.gn b/components/history/core/browser/BUILD.gn index eb4c5fe..b7e715a 100644 --- a/components/history/core/browser/BUILD.gn +++ b/components/history/core/browser/BUILD.gn
@@ -180,6 +180,7 @@ "//components/test/data/history/history.41.sql", "//components/test/data/history/history.42.sql", "//components/test/data/history/history.43.sql", + "//components/test/data/history/history.44.sql", "//components/test/data/history/thumbnail_wild/Favicons.corrupt_meta.disable", "//components/test/data/history/thumbnail_wild/Favicons.v2.init.sql", "//components/test/data/history/thumbnail_wild/Favicons.v3.init.sql",
diff --git a/components/history/core/browser/cluster_visit_database.cc b/components/history/core/browser/cluster_visit_database.cc index 60915bc..bcc2f3e2 100644 --- a/components/history/core/browser/cluster_visit_database.cc +++ b/components/history/core/browser/cluster_visit_database.cc
@@ -86,12 +86,11 @@ // Convenience to construct a `ClusterVisitRow`. Assumes the visit values are // bound starting at index 0. ClusterVisitRow StatementToVisitRow(const sql::Statement& statement) { - return {statement.ColumnInt64(0), statement.ColumnInt64(1), - statement.ColumnInt64(2), + return {statement.ColumnInt64(0), ConstructContextSignalsWithFlags( - statement.ColumnInt64(3), - base::TimeDelta::FromMicroseconds(statement.ColumnInt64(4)), - statement.ColumnInt(5))}; + statement.ColumnInt64(1), + base::TimeDelta::FromMicroseconds(statement.ColumnInt64(2)), + statement.ColumnInt(3))}; } // Like `StatementToVisitRow()` but for multiple rows. @@ -107,31 +106,24 @@ } // namespace -// Columns, in order, excluding `cluster_visit_id`. -#define HISTORY_CLUSTER_VISIT_ROW_FIELDS_WITHOUT_ID \ - " url_id, visit_id, cluster_visit_context_signal_bitmask, " \ - "duration_since_last_visit, page_end_reason " - -// Columns, in order, including `cluster_visit_id`. -#define HISTORY_CLUSTER_VISIT_ROW_FIELDS \ - " cluster_visit_id," HISTORY_CLUSTER_VISIT_ROW_FIELDS_WITHOUT_ID +// Columns, in order. +#define HISTORY_CLUSTER_VISIT_ROW_FIELDS \ + " visit_id, context_annotation_flags, duration_since_last_visit, " \ + "page_end_reason " ClusterVisitDatabase::ClusterVisitDatabase() = default; ClusterVisitDatabase::~ClusterVisitDatabase() = default; bool ClusterVisitDatabase::InitClusterVisitTable() { - if (!GetDB().DoesTableExist("cluster_visits")) { + if (!GetDB().DoesTableExist("context_annotations")) { // See `ClusterVisitRow` and `ClusterVisitContextSignals` for details about // these fields. - if (!GetDB().Execute( - "CREATE TABLE cluster_visits(" - "cluster_visit_id INTEGER PRIMARY KEY," - "url_id INTEGER NOT NULL," - "visit_id INTEGER NOT NULL," - "cluster_visit_context_signal_bitmask INTEGER NOT NULL," - "duration_since_last_visit INTEGER NOT NULL," - "page_end_reason INTEGER NOT NULL)")) { + if (!GetDB().Execute("CREATE TABLE context_annotations(" + "visit_id INTEGER PRIMARY KEY," + "context_annotation_flags INTEGER DEFAULT 0 NOT NULL," + "duration_since_last_visit INTEGER," + "page_end_reason INTEGER)")) { return false; } } @@ -140,35 +132,34 @@ } bool ClusterVisitDatabase::DropClusterVisitTable() { - return GetDB().Execute("DROP TABLE cluster_visits"); + return GetDB().Execute("DROP TABLE context_annotations"); } void ClusterVisitDatabase::AddClusterVisit(const ClusterVisitRow& row) { sql::Statement statement(GetDB().GetCachedStatement( SQL_FROM_HERE, - "INSERT INTO cluster_visits (" HISTORY_CLUSTER_VISIT_ROW_FIELDS_WITHOUT_ID - ") VALUES (?, ?, ?, ?, ?)")); - statement.BindInt64(0, row.url_id); - statement.BindInt64(1, row.visit_id); - statement.BindInt64(2, ContextSignalsToFlags(row.context_signals)); + "INSERT INTO context_annotations (" HISTORY_CLUSTER_VISIT_ROW_FIELDS + ") VALUES (?, ?, ?, ?)")); + statement.BindInt64(0, row.visit_id); + statement.BindInt64(1, ContextSignalsToFlags(row.context_signals)); statement.BindInt64( - 3, row.context_signals.duration_since_last_visit.InMicroseconds()); - statement.BindInt(4, row.context_signals.page_end_reason); + 2, row.context_signals.duration_since_last_visit.InMicroseconds()); + statement.BindInt(3, row.context_signals.page_end_reason); if (!statement.Run()) { DVLOG(0) << "Failed to execute cluster visit insert statement: " - << "url_id = " << row.url_id << ", visit_id = " << row.visit_id; + << "visit_id = " << row.visit_id; } } -void ClusterVisitDatabase::DeleteClusterVisit(int64_t cluster_visit_id) { +void ClusterVisitDatabase::DeleteClusterVisit(VisitID visit_id) { sql::Statement statement(GetDB().GetCachedStatement( - SQL_FROM_HERE, "DELETE FROM cluster_visits WHERE cluster_visit_id = ?")); - statement.BindInt64(0, cluster_visit_id); + SQL_FROM_HERE, "DELETE FROM context_annotations WHERE visit_id = ?")); + statement.BindInt64(0, visit_id); if (!statement.Run()) { DVLOG(0) << "Failed to execute cluster visit delete statement: " - << "cluster_visit_id = " << cluster_visit_id; + << "visit_id = " << visit_id; } } @@ -176,7 +167,7 @@ int max_results) { sql::Statement statement(GetDB().GetCachedStatement( SQL_FROM_HERE, "SELECT" HISTORY_CLUSTER_VISIT_ROW_FIELDS - "FROM cluster_visits " + "FROM context_annotations " "JOIN visits ON visit_id = visits.id " "ORDER BY visits.visit_time DESC " "LIMIT ?")); @@ -184,4 +175,11 @@ return StatementToVisitRowVector(statement); } +bool ClusterVisitDatabase::MigrateReplaceClusterVisitsTable() { + // We don't need to actually copy values from the previous table; it's only + // rolled out behind a flag. + return !GetDB().DoesTableExist("cluster_visits") || + GetDB().Execute("DROP TABLE cluster_visits"); +} + } // namespace history
diff --git a/components/history/core/browser/cluster_visit_database.h b/components/history/core/browser/cluster_visit_database.h index 9386263..d0d6539 100644 --- a/components/history/core/browser/cluster_visit_database.h +++ b/components/history/core/browser/cluster_visit_database.h
@@ -20,6 +20,7 @@ // databases, as this joins with the visit table and could be thought of as // inheriting from VisitDatabase. However, this inheritance is not explicit as // things would get too complicated and have multiple inheritance. +// TODO(manukh) Merge with VisitAnnotationsDatabase. class ClusterVisitDatabase { public: // Must call InitClusterVisitTable() before using to make sure the database is @@ -36,7 +37,7 @@ void AddClusterVisit(const ClusterVisitRow& row); // Delete a `ClusterVisitRow` from the table. - void DeleteClusterVisit(int64_t cluster_visit_id); + void DeleteClusterVisit(VisitID visit_id); // Get the `max_results` most recent `ClusterVisitRow`s. std::vector<ClusterVisitRow> GetClusterVisits(int max_results); @@ -48,6 +49,12 @@ // Called by the derived classes on initialization to make sure the tables // and indices are properly set up. Must be called before anything else. bool InitClusterVisitTable(); + + // Replaces `cluster_visits` with `context_annotations`. Besides the name + // change, the new table drops 2 columns: cluster_visit_id (obsolete) and + // url_id (redundant); and renames 1 column: + // cluster_visit_context_signal_bitmask to context_annotation_flags. + bool MigrateReplaceClusterVisitsTable(); }; } // namespace history
diff --git a/components/history/core/browser/cluster_visit_database_unittest.cc b/components/history/core/browser/cluster_visit_database_unittest.cc index d9368529..f3f75ea0d5 100644 --- a/components/history/core/browser/cluster_visit_database_unittest.cc +++ b/components/history/core/browser/cluster_visit_database_unittest.cc
@@ -33,8 +33,9 @@ } ~ClusterVisitDatabaseTest() override { db_.Close(); } - void AddVisitWithVisitTime(base::Time visit_time) { + void AddVisitWithDetails(URLID url_id, base::Time visit_time) { VisitRow visit_row; + visit_row.url_id = url_id; visit_row.visit_time = visit_time; AddVisit(&visit_row, VisitSource::SOURCE_BROWSED); } @@ -47,42 +48,27 @@ }; TEST_F(ClusterVisitDatabaseTest, AddDeleteAndGet) { - AddVisitWithVisitTime(IntToTime(20)); - AddVisitWithVisitTime(IntToTime(30)); - AddVisitWithVisitTime(IntToTime(10)); + AddVisitWithDetails(1, IntToTime(20)); + AddVisitWithDetails(1, IntToTime(30)); + AddVisitWithDetails(2, IntToTime(10)); - AddClusterVisit({0, 1, 1, {true}}); // Ordered 2rd - AddClusterVisit({0, 2, 2, {false}}); // Ordered 1st - AddClusterVisit({0, 1, 1, {true}}); // Ordered 3nd - AddClusterVisit({0, 2, 3, {false}}); // Ordered 4th + AddClusterVisit({1, {true}}); // Ordered 2nd + AddClusterVisit({2, {false}}); // Ordered 1st + AddClusterVisit({3, {false}}); // Ordered 3rd std::vector<ClusterVisitRow> rows = GetClusterVisits(10); - ASSERT_EQ(rows.size(), 4u); - EXPECT_EQ(rows[0].cluster_visit_id, 2); - EXPECT_EQ(rows[0].url_id, 2); + ASSERT_EQ(rows.size(), 3u); EXPECT_EQ(rows[0].visit_id, 2); EXPECT_FALSE(rows[0].context_signals.omnibox_url_copied); - EXPECT_EQ(rows[1].cluster_visit_id, 1); - EXPECT_EQ(rows[1].url_id, 1); EXPECT_EQ(rows[1].visit_id, 1); EXPECT_TRUE(rows[1].context_signals.omnibox_url_copied); - EXPECT_EQ(rows[2].cluster_visit_id, 3); - EXPECT_EQ(rows[2].url_id, 1); - EXPECT_EQ(rows[2].visit_id, 1); - EXPECT_TRUE(rows[2].context_signals.omnibox_url_copied); - EXPECT_EQ(rows[3].cluster_visit_id, 4); - EXPECT_EQ(rows[3].url_id, 2); - EXPECT_EQ(rows[3].visit_id, 3); - EXPECT_FALSE(rows[3].context_signals.omnibox_url_copied); + EXPECT_EQ(rows[2].visit_id, 3); + EXPECT_FALSE(rows[2].context_signals.omnibox_url_copied); rows = GetClusterVisits(2); ASSERT_EQ(rows.size(), 2u); - EXPECT_EQ(rows[0].cluster_visit_id, 2); - EXPECT_EQ(rows[0].url_id, 2); EXPECT_EQ(rows[0].visit_id, 2); EXPECT_FALSE(rows[0].context_signals.omnibox_url_copied); - EXPECT_EQ(rows[1].cluster_visit_id, 1); - EXPECT_EQ(rows[1].url_id, 1); EXPECT_EQ(rows[1].visit_id, 1); EXPECT_TRUE(rows[1].context_signals.omnibox_url_copied); @@ -90,20 +76,7 @@ DeleteClusterVisit(3); rows = GetClusterVisits(10); - ASSERT_EQ(rows.size(), 2u); - EXPECT_EQ(rows[0].cluster_visit_id, 2); - EXPECT_EQ(rows[0].url_id, 2); - EXPECT_EQ(rows[0].visit_id, 2); - EXPECT_FALSE(rows[0].context_signals.omnibox_url_copied); - EXPECT_EQ(rows[1].cluster_visit_id, 4); - EXPECT_EQ(rows[1].url_id, 2); - EXPECT_EQ(rows[1].visit_id, 3); - EXPECT_FALSE(rows[1].context_signals.omnibox_url_copied); - - rows = GetClusterVisits(1); ASSERT_EQ(rows.size(), 1u); - EXPECT_EQ(rows[0].cluster_visit_id, 2); - EXPECT_EQ(rows[0].url_id, 2); EXPECT_EQ(rows[0].visit_id, 2); EXPECT_FALSE(rows[0].context_signals.omnibox_url_copied); }
diff --git a/components/history/core/browser/history_backend.cc b/components/history/core/browser/history_backend.cc index ef030a2..7f38d309 100644 --- a/components/history/core/browser/history_backend.cc +++ b/components/history/core/browser/history_backend.cc
@@ -1421,13 +1421,10 @@ void HistoryBackend::AddClusterVisit(const ClusterVisitRow& row) { TRACE_EVENT0("browser", "HistoryBackend::AddClusterVisit"); - DCHECK(row.url_id && row.visit_id); - URLRow url_row; + DCHECK(row.visit_id); VisitRow visit_row; - if (!db_ || !db_->GetURLRow(row.url_id, &url_row) || - !db_->GetRowForVisit(row.visit_id, &visit_row)) { + if (!db_ || !db_->GetRowForVisit(row.visit_id, &visit_row)) return; - } db_->AddClusterVisit(row); ScheduleCommit(); } @@ -1441,11 +1438,11 @@ for (const auto& row : db_->GetClusterVisits(max_results)) { URLRow url_row; VisitRow visit_row; - if (db_->GetURLRow(row.url_id, &url_row) && - db_->GetRowForVisit(row.visit_id, &visit_row)) { + if (db_->GetRowForVisit(row.visit_id, &visit_row) && + db_->GetURLRow(visit_row.url_id, &url_row)) { cluster_visits.push_back({url_row, visit_row, row.context_signals}); } else { - db_->DeleteClusterVisit(row.cluster_visit_id); + db_->DeleteClusterVisit(row.visit_id); deleted_any_visits = true; } }
diff --git a/components/history/core/browser/history_backend_db_unittest.cc b/components/history/core/browser/history_backend_db_unittest.cc index 222eb26..ef14c66 100644 --- a/components/history/core/browser/history_backend_db_unittest.cc +++ b/components/history/core/browser/history_backend_db_unittest.cc
@@ -1894,6 +1894,66 @@ } } +TEST_F(HistoryBackendDBTest, MigrateReplaceClusterVisitsTable) { + ASSERT_NO_FATAL_FAILURE(CreateDBVersion(44)); + + sql::Database db; + ASSERT_TRUE(db.Open(history_dir_.Append(kHistoryFilename))); + + const char kInsertVisitStatement[] = + "INSERT INTO visits " + "(id, url, visit_time) VALUES (?, ?, ?)"; + + const char kInsertAnnotationsStatement[] = + "INSERT INTO cluster_visits " + "(cluster_visit_id, url_id, visit_id, " + "cluster_visit_context_signal_bitmask, duration_since_last_visit, " + "page_end_reason) " + "VALUES (?, ?, ?, ?, ?, ?)"; + + // Add a row to `visits` table. + { + sql::Statement s(db.GetUniqueStatement(kInsertVisitStatement)); + s.BindInt64(0, 1); + s.BindInt64(1, 1); + s.BindTime(2, base::Time::Now()); + ASSERT_TRUE(s.Run()); + } + + // Add a row to the `cluster_visits` table. + { + sql::Statement s(db.GetUniqueStatement(kInsertAnnotationsStatement)); + s.BindInt64(0, 1); + s.BindInt64(1, 1); + s.BindInt64(2, 1); + s.BindInt64(3, 0); + s.BindInt64(4, 0); + s.BindInt(5, 0); + ASSERT_TRUE(s.Run()); + } + + // Re-open the db, triggering migration. + CreateBackendAndDatabase(); + + // The version should have been updated. + ASSERT_GE(HistoryDatabase::GetCurrentVersion(), 45); + + // Confirm the old `cluster_visits` table no longer exists. + ASSERT_FALSE(db.DoesTableExist("cluster_visits")); + + // Confirm the new `context_annotations` exists. + ASSERT_TRUE(db.DoesTableExist("context_annotations")); + + // Check `context_annotations` is empty. + { + sql::Statement s( + db.GetUniqueStatement("SELECT COUNT(*) FROM content_annotations")); + EXPECT_TRUE(s.Step()); + EXPECT_EQ(s.ColumnInt64(0), 0u); + EXPECT_FALSE(s.Step()); + } +} + // Tests that the migration code correctly replaces the lower_term column in the // keyword search terms table which normalized_term which contains the // normalized search term during migration to version 42.
diff --git a/components/history/core/browser/history_backend_unittest.cc b/components/history/core/browser/history_backend_unittest.cc index d2628d6..bc7c5b6 100644 --- a/components/history/core/browser/history_backend_unittest.cc +++ b/components/history/core/browser/history_backend_unittest.cc
@@ -3188,32 +3188,26 @@ (std::pair<URLID, VisitID>{2, 2})); EXPECT_EQ(add_url_and_visit("http://1.com/"), (std::pair<URLID, VisitID>{1, 3})); - backend_->AddClusterVisit({0, 1, 1, {true}}); - backend_->AddClusterVisit({0, 1, 3, {false}}); - backend_->AddClusterVisit({0, 2, 2, {true}}); + backend_->AddClusterVisit({1, {true}}); + backend_->AddClusterVisit({3, {false}}); + backend_->AddClusterVisit({2, {true}}); EXPECT_EQ(backend_->db_->GetClusterVisits(10).size(), 3u); - // Cluster visits should have URL & visit IDs - EXPECT_DCHECK_DEATH(backend_->AddClusterVisit({0, 0, 4, {true}})); - EXPECT_DCHECK_DEATH(backend_->AddClusterVisit({0, 3, 0, {true}})); + // Cluster visits should have a visit IDs. + EXPECT_DCHECK_DEATH(backend_->AddClusterVisit({0, {true}})); EXPECT_EQ(backend_->db_->GetClusterVisits(10).size(), 3u); - // Cluster visits without an associated URL or visit should not be added. - backend_->AddClusterVisit({0, 3, 1, {true}}); - backend_->AddClusterVisit({0, 1, 4, {true}}); + // Cluster visits without an associated visit should not be added. + backend_->AddClusterVisit({4, {true}}); EXPECT_EQ(add_url_and_visit("http://3.com/"), (std::pair<URLID, VisitID>{3, 4})); EXPECT_EQ(backend_->db_->GetClusterVisits(10).size(), 3u); - // Cluster visits associated with a removed URL or visit should not be added. + // Cluster visits associated with a removed visit should not be added. EXPECT_EQ(add_url_and_visit("http://4.com/"), (std::pair<URLID, VisitID>{4, 5})); - EXPECT_EQ(add_url_and_visit("http://5.com/"), - (std::pair<URLID, VisitID>{5, 6})); - delete_url(4); - delete_visit(6); - backend_->AddClusterVisit({0, 4, 1, {true}}); - backend_->AddClusterVisit({0, 1, 6, {true}}); + delete_visit(5); + backend_->AddClusterVisit({5, {true}}); EXPECT_EQ(backend_->db_->GetClusterVisits(10).size(), 3u); // Verify only the correct cluster visits are retrieved ordered recent visits
diff --git a/components/history/core/browser/history_database.cc b/components/history/core/browser/history_database.cc index f45d66a..eb63d00 100644 --- a/components/history/core/browser/history_database.cc +++ b/components/history/core/browser/history_database.cc
@@ -37,7 +37,7 @@ // Current version number. We write databases at the "current" version number, // but any previous version that can read the "compatible" one can make do with // our database without *too* many bad effects. -const int kCurrentVersionNumber = 44; +const int kCurrentVersionNumber = 45; const int kCompatibleVersionNumber = 16; const char kEarlyExpirationThresholdKey[] = "early_expiration_threshold"; @@ -115,9 +115,8 @@ // Prime the cache. db_.Preload(); - // Create the tables and indices. - // NOTE: If you add something here, also add it to - // RecreateAllButStarAndURLTables. + // Create the tables and indices. If you add something here, also add it to + // `RecreateAllTablesButURL()`. if (!meta_table_.Init(&db_, GetCurrentVersion(), kCompatibleVersionNumber)) return LogInitFailure(InitStep::META_TABLE_INIT); if (!CreateURLTable(false) || !InitVisitTable() || @@ -647,6 +646,12 @@ meta_table_.SetVersionNumber(cur_version); } + if (cur_version == 44) { + MigrateReplaceClusterVisitsTable(); + cur_version++; + meta_table_.SetVersionNumber(cur_version); + } + // ========================= ^^ new migration code goes here ^^ // ADDING NEW MIGRATION CODE // =========================
diff --git a/components/history/core/browser/history_database.h b/components/history/core/browser/history_database.h index 4dd4a57..c5106ee 100644 --- a/components/history/core/browser/history_database.h +++ b/components/history/core/browser/history_database.h
@@ -189,7 +189,7 @@ // Makes sure the version is up to date, updating if necessary. If the // database is too old to migrate, the user will be notified. Returns - // sql::INIT_OK iff the DB is up to date and ready for use. + // sql::INIT_OK iff the DB is up to date and ready for use. // // This assumes it is called from the init function inside a transaction. It // may commit the transaction and start a new one if migration requires it.
diff --git a/components/history/core/browser/history_types.cc b/components/history/core/browser/history_types.cc index dbdaf14..9122aab 100644 --- a/components/history/core/browser/history_types.cc +++ b/components/history/core/browser/history_types.cc
@@ -15,7 +15,7 @@ // VisitRow -------------------------------------------------------------------- -VisitRow::VisitRow() {} +VisitRow::VisitRow() = default; VisitRow::VisitRow(URLID arg_url_id, base::Time arg_visit_time, @@ -31,14 +31,13 @@ segment_id(arg_segment_id), incremented_omnibox_typed_score(arg_incremented_omnibox_typed_score) {} -VisitRow::~VisitRow() { -} +VisitRow::~VisitRow() = default; // QueryResults ---------------------------------------------------------------- -QueryResults::QueryResults() {} +QueryResults::QueryResults() = default; -QueryResults::~QueryResults() {} +QueryResults::~QueryResults() = default; QueryResults::QueryResults(QueryResults&& other) noexcept { Swap(&other); @@ -102,7 +101,7 @@ // exclusive, while ours is inclusive, hence the +1). results_.erase(results_.begin() + begin, results_.begin() + end + 1); - // Delete the indicies referencing the deleted entries. + // Delete the indices referencing the deleted entries. for (const auto& url : urls_modified) { auto found = url_to_results_.find(url); if (found == url_to_results_.end()) { @@ -114,7 +113,7 @@ for (int match = 0; match < static_cast<int>(found->second->size()); match++) { if (found->second[match] >= begin && found->second[match] <= end) { - // Remove this referece from the list. + // Remove this reference from the list. found->second->erase(found->second->begin() + match); match--; } @@ -145,18 +144,18 @@ } void QueryResults::AdjustResultMap(size_t begin, size_t end, ptrdiff_t delta) { - for (auto i = url_to_results_.begin(); i != url_to_results_.end(); ++i) { - for (size_t match = 0; match < i->second->size(); match++) { - size_t match_index = i->second[match]; + for (auto& url_to_result : url_to_results_) { + for (size_t match = 0; match < url_to_result.second->size(); match++) { + size_t match_index = url_to_result.second[match]; if (match_index >= begin && match_index <= end) - i->second[match] += delta; + url_to_result.second[match] += delta; } } } // QueryOptions ---------------------------------------------------------------- -QueryOptions::QueryOptions() {} +QueryOptions::QueryOptions() = default; void QueryOptions::SetRecentDayRange(int days_ago) { end_time = base::Time::Now(); @@ -192,7 +191,7 @@ // MostVisitedURL -------------------------------------------------------------- -MostVisitedURL::MostVisitedURL() {} +MostVisitedURL::MostVisitedURL() = default; MostVisitedURL::MostVisitedURL(const GURL& url, const std::u16string& title) : url(url), title(title) {} @@ -207,7 +206,7 @@ // FilteredURL ----------------------------------------------------------------- -FilteredURL::FilteredURL() {} +FilteredURL::FilteredURL() = default; FilteredURL::FilteredURL(const PageUsageData& page_data) : url(page_data.GetURL()), @@ -217,7 +216,7 @@ FilteredURL::FilteredURL(FilteredURL&& other) noexcept = default; -FilteredURL::~FilteredURL() {} +FilteredURL::~FilteredURL() = default; // FilteredURL::ExtendedInfo --------------------------------------------------- @@ -225,11 +224,11 @@ // TopSitesDelta -------------------------------------------------------------- -TopSitesDelta::TopSitesDelta() {} +TopSitesDelta::TopSitesDelta() = default; TopSitesDelta::TopSitesDelta(const TopSitesDelta& other) = default; -TopSitesDelta::~TopSitesDelta() {} +TopSitesDelta::~TopSitesDelta() = default; // HistoryAddPageArgs --------------------------------------------------------- @@ -277,24 +276,22 @@ HistoryAddPageArgs::HistoryAddPageArgs(const HistoryAddPageArgs& other) = default; -HistoryAddPageArgs::~HistoryAddPageArgs() {} +HistoryAddPageArgs::~HistoryAddPageArgs() = default; // DomainMetricSet ------------------------------------------------------------ -DomainMetricSet::DomainMetricSet() {} +DomainMetricSet::DomainMetricSet() = default; DomainMetricSet::DomainMetricSet(const DomainMetricSet&) = default; -DomainMetricSet::~DomainMetricSet() {} +DomainMetricSet::~DomainMetricSet() = default; DomainMetricSet& DomainMetricSet::operator=(const DomainMetricSet&) = default; // ExpireHistoryArgs ---------------------------------------------------------- -ExpireHistoryArgs::ExpireHistoryArgs() { -} +ExpireHistoryArgs::ExpireHistoryArgs() = default; ExpireHistoryArgs::ExpireHistoryArgs(const ExpireHistoryArgs& other) = default; -ExpireHistoryArgs::~ExpireHistoryArgs() { -} +ExpireHistoryArgs::~ExpireHistoryArgs() = default; void ExpireHistoryArgs::SetTimeRangeForOneDay(base::Time time) { begin_time = time.LocalMidnight();
diff --git a/components/history/core/browser/history_types.h b/components/history/core/browser/history_types.h index fc27e68..bf7b370 100644 --- a/components/history/core/browser/history_types.h +++ b/components/history/core/browser/history_types.h
@@ -317,7 +317,7 @@ // FilteredURL ----------------------------------------------------------------- -// Holds the per-URL information of the filterd url query. +// Holds the per-URL information of the filtered url query. struct FilteredURL { struct ExtendedInfo { ExtendedInfo(); @@ -662,6 +662,8 @@ kAndroidDb, }; +// Clusters -------------------------------------------------------------------- + // Context signals about a page visit collected during the page lifetime. // This struct encapsulates data that's shared between UKM and the on-device // storage for `HistoryCluster` metadata, recorded to both when the page @@ -724,20 +726,11 @@ struct ClusterVisitRow { ClusterVisitRow() = default; explicit ClusterVisitRow(const ClusterVisit& cluster_visit) - : ClusterVisitRow(0, - cluster_visit.url_row.id(), - cluster_visit.visit_row.visit_id, + : ClusterVisitRow(cluster_visit.visit_row.visit_id, cluster_visit.context_signals) {} - ClusterVisitRow(const int64_t cluster_visit_id, - const URLID url_id, - const VisitID visit_id, + ClusterVisitRow(const VisitID visit_id, const ClusterVisitContextSignals& context_signals) - : cluster_visit_id(cluster_visit_id), - url_id(url_id), - visit_id(visit_id), - context_signals(context_signals) {} - int64_t cluster_visit_id; - URLID url_id; + : visit_id(visit_id), context_signals(context_signals) {} VisitID visit_id; ClusterVisitContextSignals context_signals; };
diff --git a/components/history/core/browser/visit_annotations_database.cc b/components/history/core/browser/visit_annotations_database.cc index 333a1d0..e8b835e 100644 --- a/components/history/core/browser/visit_annotations_database.cc +++ b/components/history/core/browser/visit_annotations_database.cc
@@ -12,6 +12,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" +#include "components/history/core/browser/url_row.h" #include "sql/statement.h" namespace history {
diff --git a/components/history/core/browser/visit_annotations_database.h b/components/history/core/browser/visit_annotations_database.h index 83aef205..6bf557c 100644 --- a/components/history/core/browser/visit_annotations_database.h +++ b/components/history/core/browser/visit_annotations_database.h
@@ -13,6 +13,8 @@ namespace history { +struct VisitContentAnnotations; + // Holds annotations made for a user's visits. class VisitAnnotationsDatabase { public:
diff --git a/components/media_message_center/BUILD.gn b/components/media_message_center/BUILD.gn index 7becd24b..3302c66d 100644 --- a/components/media_message_center/BUILD.gn +++ b/components/media_message_center/BUILD.gn
@@ -4,6 +4,8 @@ component("media_message_center") { sources = [ + "media_artwork_view.cc", + "media_artwork_view.h", "media_controls_progress_view.cc", "media_controls_progress_view.h", "media_notification_background.h",
diff --git a/components/media_message_center/media_artwork_view.cc b/components/media_message_center/media_artwork_view.cc new file mode 100644 index 0000000..e2b12a65 --- /dev/null +++ b/components/media_message_center/media_artwork_view.cc
@@ -0,0 +1,110 @@ +// Copyright 2021 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/media_message_center/media_artwork_view.h" + +#include "ui/gfx/canvas.h" +#include "ui/gfx/skia_util.h" + +namespace media_message_center { + +namespace { + +// Get target bounds of the image fitting into |canvas_size|. +// If |image_size| is greater than |expect_size| in any dimension, +// we shrink it down to fit, keep the size otherwise. +gfx::Rect GetTargetBound(const gfx::Size image_size, + const gfx::Size expect_size, + const gfx::Size canvas_size) { + gfx::Size target_size = image_size; + if (image_size.width() > expect_size.width() || + image_size.height() > expect_size.height()) { + const float scale = std::min( + expect_size.width() / static_cast<float>(image_size.width()), + expect_size.height() / static_cast<float>(image_size.height())); + target_size = gfx::ScaleToFlooredSize(image_size, scale); + } + + int offset_x = (canvas_size.width() - target_size.width()) / 2; + int offset_y = (canvas_size.height() - target_size.height()) / 2; + return gfx::Rect(offset_x, offset_y, target_size.width(), + target_size.height()); +} + +} // anonymous namespace + +MediaArtworkView::MediaArtworkView(float corner_radius, + const gfx::Size& artwork_size, + const gfx::Size& favicon_size) + : corner_radius_(corner_radius), + artwork_size_(artwork_size), + favicon_size_(favicon_size) {} + +void MediaArtworkView::SetVignetteColor(const SkColor& vignette_color) { + if (vignette_color_ == vignette_color) + return; + vignette_color_ = vignette_color; + OnPropertyChanged(&vignette_color_, views::kPropertyEffectsPaint); +} + +SkColor MediaArtworkView::GetVignetteColor() const { + return vignette_color_; +} + +void MediaArtworkView::SetBackgroundColor(const SkColor& background_color) { + background_color_ = background_color; +} + +void MediaArtworkView::SetImage(const gfx::ImageSkia& image) { + image_ = image; +} + +void MediaArtworkView::SetFavicon(const gfx::ImageSkia& favicon) { + favicon_ = favicon; +} + +void MediaArtworkView::OnPaint(gfx::Canvas* canvas) { + views::View::OnPaint(canvas); + + { + // Paint background. + cc::PaintFlags paint_flags; + paint_flags.setStyle(cc::PaintFlags::kFill_Style); + paint_flags.setAntiAlias(true); + paint_flags.setColor(background_color_); + canvas->DrawRect(gfx::Rect(artwork_size_), paint_flags); + } + + // Draw image if we have artwork; fallback to favicon if we don't. + if (!image_.isNull()) { + gfx::Rect target = + GetTargetBound(image_.size(), artwork_size_, artwork_size_); + canvas->DrawImageInt(image_, 0, 0, image_.width(), image_.height(), + target.x(), target.y(), target.width(), + target.height(), false); + } else if (!favicon_.isNull()) { + gfx::Rect target = + GetTargetBound(favicon_.size(), favicon_size_, artwork_size_); + canvas->DrawImageInt(favicon_, 0, 0, favicon_.width(), favicon_.height(), + target.x(), target.y(), target.width(), + target.height(), false); + } + + { + auto path = SkPath().addRoundRect(RectToSkRect(GetLocalBounds()), + corner_radius_, corner_radius_); + path.toggleInverseFillType(); + cc::PaintFlags paint_flags; + paint_flags.setStyle(cc::PaintFlags::kFill_Style); + paint_flags.setAntiAlias(true); + paint_flags.setColor(vignette_color_); + canvas->DrawPath(path, paint_flags); + } +} + +BEGIN_METADATA(MediaArtworkView, views::View) +ADD_PROPERTY_METADATA(SkColor, VignetteColor) +END_METADATA + +} // namespace media_message_center
diff --git a/components/media_message_center/media_artwork_view.h b/components/media_message_center/media_artwork_view.h new file mode 100644 index 0000000..1833c0e --- /dev/null +++ b/components/media_message_center/media_artwork_view.h
@@ -0,0 +1,49 @@ +// Copyright 2021 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_MEDIA_MESSAGE_CENTER_MEDIA_ARTWORK_VIEW_H_ +#define COMPONENTS_MEDIA_MESSAGE_CENTER_MEDIA_ARTWORK_VIEW_H_ + +#include "ui/base/metadata/metadata_header_macros.h" +#include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/gfx/color_palette.h" +#include "ui/views/view.h" + +namespace media_message_center { + +// An artwork view with a rounded rectangle vignette +class MediaArtworkView : public views::View { + public: + METADATA_HEADER(MediaArtworkView); + MediaArtworkView(float corner_radius, + const gfx::Size& artwork_size, + const gfx::Size& favicon_size); + ~MediaArtworkView() override = default; + + void SetVignetteColor(const SkColor& vignette_color); + SkColor GetVignetteColor() const; + + void SetBackgroundColor(const SkColor& background_color); + + void SetImage(const gfx::ImageSkia& image); + void SetFavicon(const gfx::ImageSkia& favicon); + + // views::View + void OnPaint(gfx::Canvas* canvas) override; + + private: + SkColor vignette_color_ = gfx::kPlaceholderColor; + SkColor background_color_ = gfx::kPlaceholderColor; + + gfx::ImageSkia image_; + gfx::ImageSkia favicon_; + + const float corner_radius_; + const gfx::Size artwork_size_; + const gfx::Size favicon_size_; +}; + +} // namespace media_message_center + +#endif // COMPONENTS_MEDIA_MESSAGE_CENTER_MEDIA_ARTWORK_VIEW_H_
diff --git a/components/media_message_center/media_notification_view_modern_impl.cc b/components/media_message_center/media_notification_view_modern_impl.cc index fb4e71c..8ac3f8e 100644 --- a/components/media_message_center/media_notification_view_modern_impl.cc +++ b/components/media_message_center/media_notification_view_modern_impl.cc
@@ -7,6 +7,7 @@ #include "base/containers/contains.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" +#include "components/media_message_center/media_artwork_view.h" #include "components/media_message_center/media_controls_progress_view.h" #include "components/media_message_center/media_notification_background_impl.h" #include "components/media_message_center/media_notification_constants.h" @@ -71,45 +72,7 @@ constexpr int kMediaButtonIconSize = 14; constexpr int kPlayPauseIconSize = 20; constexpr int kMediaButtonBorderThickness = 1; - -// An image view with a rounded rectangle vignette -class MediaArtworkView : public views::ImageView { - public: - METADATA_HEADER(MediaArtworkView); - explicit MediaArtworkView(float corner_radius) - : corner_radius_(corner_radius) {} - - void SetVignetteColor(const SkColor& vignette_color) { - if (vignette_color_ == vignette_color) - return; - vignette_color_ = vignette_color; - OnPropertyChanged(&vignette_color_, views::kPropertyEffectsPaint); - } - SkColor GetVignetteColor() const { return vignette_color_; } - - // ImageView - void OnPaint(gfx::Canvas* canvas) override; - - private: - SkColor vignette_color_ = gfx::kPlaceholderColor; - float corner_radius_; -}; - -BEGIN_METADATA(MediaArtworkView, views::ImageView) -ADD_PROPERTY_METADATA(SkColor, VignetteColor) -END_METADATA - -void MediaArtworkView::OnPaint(gfx::Canvas* canvas) { - views::ImageView::OnPaint(canvas); - auto path = SkPath().addRoundRect(RectToSkRect(GetLocalBounds()), - corner_radius_, corner_radius_); - path.toggleInverseFillType(); - cc::PaintFlags paint_flags; - paint_flags.setStyle(cc::PaintFlags::kFill_Style); - paint_flags.setAntiAlias(true); - paint_flags.setColor(vignette_color_); - canvas->DrawPath(path, paint_flags); -} +constexpr gfx::Size kFaviconSize = {20, 20}; void RecordMetadataHistogram( MediaNotificationViewModernImpl::Metadata metadata) { @@ -372,10 +335,6 @@ auto artwork_container = std::make_unique<views::View>(); artwork_container->SetPreferredSize(kArtworkSize); - // The artwork container will become visible once artwork has been set in - // UpdateWithMediaArtwork - artwork_container->SetVisible(false); - auto* artwork_container_layout = artwork_container->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(), 0)); @@ -385,8 +344,8 @@ views::BoxLayout::CrossAxisAlignment::kCenter); { - auto artwork = - std::make_unique<MediaArtworkView>(kArtworkVignetteCornerRadius); + auto artwork = std::make_unique<MediaArtworkView>( + kArtworkVignetteCornerRadius, kArtworkSize, kFaviconSize); artwork_ = artwork_container->AddChildView(std::move(artwork)); } @@ -578,14 +537,8 @@ GetMediaNotificationBackground()->UpdateArtwork(image); UMA_HISTOGRAM_BOOLEAN(kArtworkHistogramName, !image.isNull()); - - if (!image.isNull()) - artwork_container_->SetVisible(true); - artwork_->SetImage(image); artwork_->SetPreferredSize(kArtworkSize); - artwork_->SetVignetteColor( - GetMediaNotificationBackground()->GetBackgroundColor(*this)); UpdateForegroundColor(); @@ -600,6 +553,8 @@ const gfx::ImageSkia& icon) { GetMediaNotificationBackground()->UpdateFavicon(icon); + artwork_->SetFavicon(icon); + artwork_->SetPreferredSize(kArtworkSize); UpdateForegroundColor(); SchedulePaint(); } @@ -656,6 +611,9 @@ const SkColor disabled_icon_color = SkColorSetA(foreground, gfx::kDisabledControlAlpha); + artwork_->SetBackgroundColor(disabled_icon_color); + artwork_->SetVignetteColor(background); + progress_->SetForegroundColor(foreground); progress_->SetBackgroundColor(disabled_icon_color); progress_->SetTextColor(foreground);
diff --git a/components/media_message_center/media_notification_view_modern_impl.h b/components/media_message_center/media_notification_view_modern_impl.h index 126e89a..ebef6a9 100644 --- a/components/media_message_center/media_notification_view_modern_impl.h +++ b/components/media_message_center/media_notification_view_modern_impl.h
@@ -24,10 +24,10 @@ namespace media_message_center { namespace { -class MediaArtworkView; class MediaButton; } // anonymous namespace +class MediaArtworkView; class MediaControlsProgressView; class MediaNotificationBackground; class MediaNotificationContainer;
diff --git a/components/metrics/metrics_log.cc b/components/metrics/metrics_log.cc index 5dbfd90..384f849 100644 --- a/components/metrics/metrics_log.cc +++ b/components/metrics/metrics_log.cc
@@ -10,6 +10,7 @@ #include <string> #include "base/build_time.h" +#include "base/command_line.h" #include "base/cpu.h" #include "base/logging.h" #include "base/metrics/histogram_base.h" @@ -32,6 +33,7 @@ #include "components/metrics/metrics_service_client.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" +#include "components/variations/hashing.h" #include "third_party/metrics_proto/histogram_event.pb.h" #include "third_party/metrics_proto/system_profile.pb.h" #include "third_party/metrics_proto/user_action_event.pb.h" @@ -189,6 +191,14 @@ std::string brand_code; if (client->GetBrand(&brand_code)) system_profile->set_brand_code(brand_code); + + // Records 32-bit hashes of the command line keys. + const auto command_line_switches = + base::CommandLine::ForCurrentProcess()->GetSwitches(); + for (const auto& command_line_switch : command_line_switches) { + system_profile->add_command_line_key_hash( + variations::HashName(command_line_switch.first)); + } } // static
diff --git a/components/metrics/metrics_log.h b/components/metrics/metrics_log.h index e0b9f46..4043e92 100644 --- a/components/metrics/metrics_log.h +++ b/components/metrics/metrics_log.h
@@ -113,11 +113,11 @@ // always incrementing for use in measuring time durations. static int64_t GetCurrentTime(); - // Record core profile settings into the SystemProfileProto. + // Records core profile settings into the SystemProfileProto. static void RecordCoreSystemProfile(MetricsServiceClient* client, SystemProfileProto* system_profile); - // Record core profile settings into the SystemProfileProto without a client. + // Records core profile settings into the SystemProfileProto without a client. static void RecordCoreSystemProfile( const std::string& version, metrics::SystemProfileProto::Channel channel,
diff --git a/components/metrics/metrics_log_unittest.cc b/components/metrics/metrics_log_unittest.cc index 9edff69..0393b81 100644 --- a/components/metrics/metrics_log_unittest.cc +++ b/components/metrics/metrics_log_unittest.cc
@@ -148,6 +148,14 @@ client.set_version_string("bogus version"); const std::string kClientId = "totally bogus client ID"; TestingPrefServiceSimple prefs; + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + // Clears existing command line flags and sets mock flags: + // "--mock-flag-1 --mock-flag-2=unused_value" + // Hashes of these flags should be populated on the system_profile field. + command_line->InitFromArgv(0, nullptr); + command_line->AppendSwitch("mock-flag-1"); + command_line->AppendSwitchASCII("mock-flag-2", "unused_value"); + MetricsLog log(kClientId, 137, MetricsLog::ONGOING_LOG, &client); log.CloseLog(); @@ -171,6 +179,9 @@ system_profile->set_channel(client.GetChannel()); system_profile->set_application_locale(client.GetApplicationLocale()); system_profile->set_brand_code(TestMetricsServiceClient::kBrandForTesting); + // Hashes of "mock-flag-1" and "mock-flag-2" from SetUpCommandLine. + system_profile->add_command_line_key_hash(2578836236); + system_profile->add_command_line_key_hash(2867288449); #if defined(ADDRESS_SANITIZER) || DCHECK_IS_ON() system_profile->set_is_instrumented_build(true);
diff --git a/components/optimization_guide/core/optimization_guide_features.cc b/components/optimization_guide/core/optimization_guide_features.cc index ead75ac..86ec68e 100644 --- a/components/optimization_guide/core/optimization_guide_features.cc +++ b/components/optimization_guide/core/optimization_guide_features.cc
@@ -22,15 +22,9 @@ namespace features { // Enables the syncing of the Optimization Hints component, which provides -// hints for what Previews can be applied on a page load. -const base::Feature kOptimizationHints { - "OptimizationHints", -#if defined(OS_ANDROID) - base::FEATURE_ENABLED_BY_DEFAULT -#else // !defined(OS_ANDROID) - base::FEATURE_DISABLED_BY_DEFAULT -#endif // defined(OS_ANDROID) -}; +// hints for what optimizations can be applied on a page load. +const base::Feature kOptimizationHints{"OptimizationHints", + base::FEATURE_ENABLED_BY_DEFAULT}; // Feature flag that contains a feature param that specifies the field trials // that are allowed to be sent up to the Optimization Guide Server. @@ -38,14 +32,8 @@ "OptimizationHintsFieldTrials", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables fetching from a remote Optimization Guide Service. -const base::Feature kRemoteOptimizationGuideFetching { - "OptimizationHintsFetching", -#if defined(OS_ANDROID) - base::FEATURE_ENABLED_BY_DEFAULT -#else // !defined(OS_ANDROID) - base::FEATURE_DISABLED_BY_DEFAULT -#endif // defined(OS_ANDROID) -}; +const base::Feature kRemoteOptimizationGuideFetching{ + "OptimizationHintsFetching", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kRemoteOptimizationGuideFetchingAnonymousDataConsent{ "OptimizationHintsFetchingAnonymousDataConsent",
diff --git a/components/page_info/android/java/res/layout/page_info.xml b/components/page_info/android/java/res/layout/page_info.xml index 6a89c70..e61d6d4f 100644 --- a/components/page_info/android/java/res/layout/page_info.xml +++ b/components/page_info/android/java/res/layout/page_info.xml
@@ -50,26 +50,6 @@ android:textAppearance="@style/TextAppearance.TextMedium.Primary" android:visibility="gone" /> - <TextView - android:id="@+id/page_info_performance_summary" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:lineSpacingExtra="3dp" - android:paddingTop="16dp" - android:textAppearance="@style/TextAppearance.TextLarge.Primary" - android:text="@string/page_info_fast_site_summary" - android:visibility="gone" /> - - <TextView - android:id="@+id/page_info_performance_message" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:lineSpacingExtra="3dp" - android:paddingTop="8dp" - android:textAppearance="@style/TextAppearance.TextMedium.Primary" - android:text="@string/page_info_fast_site_message" - android:visibility="gone" /> - <View android:id="@+id/page_info_preview_separator" android:layout_marginTop="16dp"
diff --git a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoController.java b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoController.java index 7e168871..b2a12832a 100644 --- a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoController.java +++ b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoController.java
@@ -308,8 +308,6 @@ setupForgetSiteButton(view2.getForgetSiteButton()); } } else { - mView.showPerformanceInfo(mDelegate.shouldShowPerformanceBadge(mFullUrl)); - CookieControlsView.CookieControlsParams cookieControlsParams = new CookieControlsView.CookieControlsParams(); cookieControlsParams.onCheckedChangedCallback = (Boolean blockCookies) -> {
diff --git a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoControllerDelegate.java b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoControllerDelegate.java index f890b72..deee01b 100644 --- a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoControllerDelegate.java +++ b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoControllerDelegate.java
@@ -21,7 +21,6 @@ import org.chromium.components.omnibox.AutocompleteSchemeClassifier; import org.chromium.components.page_info.PageInfoView.PageInfoViewParams; import org.chromium.ui.modaldialog.ModalDialogManager; -import org.chromium.url.GURL; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -157,13 +156,6 @@ } /** - * Returns whether or not the performance badge should be shown for |url|. - */ - public boolean shouldShowPerformanceBadge(GURL url) { - return false; - } - - /** * Whether Site settings are available. */ public boolean isSiteSettingsAvailable() {
diff --git a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoView.java b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoView.java index b2aba14..5a1f66c 100644 --- a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoView.java +++ b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoView.java
@@ -186,8 +186,6 @@ // Components specific to this PageInfoView private TextView mConnectionSummary; private TextView mConnectionMessage; - private TextView mPerformanceSummary; - private TextView mPerformanceMessage; private TextView mHttpsImageCompressionMessage; private View mCookieControlsSeparator; private CookieControlsView mCookieControlsView; @@ -205,7 +203,6 @@ protected void init(PageInfoViewParams params) { initUrlTitle(params); initConnection(params); - initPerformance(params); initHttpsImageCompression(params); initPermissions(params); initCookies(params); @@ -234,13 +231,6 @@ initializePageInfoViewChild(mConnectionMessage, params.connectionMessageShown, null); } - protected void initPerformance(PageInfoViewParams params) { - mPerformanceSummary = findViewById(R.id.page_info_performance_summary); - mPerformanceMessage = findViewById(R.id.page_info_performance_message); - initializePageInfoViewChild(mPerformanceSummary, false, null); - initializePageInfoViewChild(mPerformanceMessage, false, null); - } - protected void initHttpsImageCompression(PageInfoViewParams params) { mHttpsImageCompressionMessage = findViewById(R.id.page_info_lite_mode_https_image_compression_message); @@ -304,16 +294,6 @@ } } - public void showPerformanceInfo(boolean show) { - if (show) { - mPerformanceSummary.setVisibility(View.VISIBLE); - mPerformanceMessage.setVisibility(View.VISIBLE); - } else { - mPerformanceSummary.setVisibility(View.GONE); - mPerformanceMessage.setVisibility(View.GONE); - } - } - public void showHttpsImageCompressionInfo(boolean show) { if (show) { mHttpsImageCompressionMessage.setVisibility(View.VISIBLE); @@ -359,8 +339,6 @@ animatableViews.add(mUrlTitle); animatableViews.add(mConnectionSummary); animatableViews.add(mConnectionMessage); - animatableViews.add(mPerformanceSummary); - animatableViews.add(mPerformanceMessage); animatableViews.add(mHttpsImageCompressionMessage); animatableViews.add(mInstantAppButton); animatableViews.add(mCookieControlsSeparator);
diff --git a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoViewV2.java b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoViewV2.java index 82702b3..452d9673 100644 --- a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoViewV2.java +++ b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoViewV2.java
@@ -50,9 +50,6 @@ } @Override - protected void initPerformance(PageInfoView.PageInfoViewParams params) {} - - @Override protected void initPermissions(PageInfoView.PageInfoViewParams params) { mPermissionsRow = findViewById(R.id.page_info_permissions_row); }
diff --git a/components/policy/core/common/policy_test_utils.cc b/components/policy/core/common/policy_test_utils.cc index ea5b2c49..dc67e9e09 100644 --- a/components/policy/core/common/policy_test_utils.cc +++ b/components/policy/core/common/policy_test_utils.cc
@@ -59,77 +59,56 @@ case base::Value::Type::NONE: return kCFNull; - case base::Value::Type::BOOLEAN: { - bool bool_value; - if (value.GetAsBoolean(&bool_value)) - return bool_value ? kCFBooleanTrue : kCFBooleanFalse; - break; - } + case base::Value::Type::BOOLEAN: + return value.GetBool() ? kCFBooleanTrue : kCFBooleanFalse; case base::Value::Type::INTEGER: { - int int_value; - if (value.GetAsInteger(&int_value)) { - return CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, - &int_value); - } - break; + const int int_value = value.GetInt(); + return CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &int_value); } case base::Value::Type::DOUBLE: { - double double_value; - if (value.GetAsDouble(&double_value)) { - return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, - &double_value); - } - break; + const double double_value = value.GetDouble(); + return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, + &double_value); } case base::Value::Type::STRING: { - std::string string_value; - if (value.GetAsString(&string_value)) - return base::SysUTF8ToCFStringRef(string_value).release(); - break; + const std::string& string_value = value.GetString(); + return base::SysUTF8ToCFStringRef(string_value).release(); } case base::Value::Type::DICTIONARY: { - const base::DictionaryValue* dict_value; - if (value.GetAsDictionary(&dict_value)) { - // |dict| is owned by the caller. - CFMutableDictionaryRef dict = CFDictionaryCreateMutable( - kCFAllocatorDefault, dict_value->size(), - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - for (base::DictionaryValue::Iterator iterator(*dict_value); - !iterator.IsAtEnd(); iterator.Advance()) { - // CFDictionaryAddValue() retains both |key| and |value|, so make sure - // the references are balanced. - base::ScopedCFTypeRef<CFStringRef> key( - base::SysUTF8ToCFStringRef(iterator.key())); - base::ScopedCFTypeRef<CFPropertyListRef> cf_value( - ValueToProperty(iterator.value())); - if (cf_value) - CFDictionaryAddValue(dict, key, cf_value); - } - return dict; + // |dict| is owned by the caller. + CFMutableDictionaryRef dict = CFDictionaryCreateMutable( + kCFAllocatorDefault, value.DictSize(), &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + for (const auto& key_value_pair : value.DictItems()) { + // CFDictionaryAddValue() retains both |key| and |value|, so make sure + // the references are balanced. + base::ScopedCFTypeRef<CFStringRef> key( + base::SysUTF8ToCFStringRef(key_value_pair.first)); + base::ScopedCFTypeRef<CFPropertyListRef> cf_value( + ValueToProperty(key_value_pair.second)); + if (cf_value) + CFDictionaryAddValue(dict, key, cf_value); } - break; + return dict; } case base::Value::Type::LIST: { - const base::ListValue* list; - if (value.GetAsList(&list)) { - CFMutableArrayRef array = - CFArrayCreateMutable(NULL, list->GetSize(), &kCFTypeArrayCallBacks); - for (const auto& entry : *list) { - // CFArrayAppendValue() retains |cf_value|, so make sure the reference - // created by ValueToProperty() is released. - base::ScopedCFTypeRef<CFPropertyListRef> cf_value( - ValueToProperty(entry)); - if (cf_value) - CFArrayAppendValue(array, cf_value); - } - return array; + base::Value::ConstListView list_view = value.GetList(); + CFMutableArrayRef array = + CFArrayCreateMutable(NULL, list_view.size(), &kCFTypeArrayCallBacks); + for (const base::Value& entry : list_view) { + // CFArrayAppendValue() retains |cf_value|, so make sure the reference + // created by ValueToProperty() is released. + base::ScopedCFTypeRef<CFPropertyListRef> cf_value( + ValueToProperty(entry)); + if (cf_value) + CFArrayAppendValue(array, cf_value); } - break; + return array; } case base::Value::Type::BINARY:
diff --git a/components/power_scheduler/power_scheduler.cc b/components/power_scheduler/power_scheduler.cc index f9c366b..4ef10ef 100644 --- a/components/power_scheduler/power_scheduler.cc +++ b/components/power_scheduler/power_scheduler.cc
@@ -19,6 +19,24 @@ namespace { +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +// Keep in sync with base::CpuAffinityMode and CpuAffinityMode in enums.xml. +enum class CpuAffinityModeForUma { + kDefault = 0, + kLittleCoresOnly = 1, + kMaxValue = kLittleCoresOnly, +}; + +CpuAffinityModeForUma GetCpuAffinityModeForUma(base::CpuAffinityMode affinity) { + switch (affinity) { + case base::CpuAffinityMode::kDefault: + return CpuAffinityModeForUma::kDefault; + case base::CpuAffinityMode::kLittleCoresOnly: + return CpuAffinityModeForUma::kLittleCoresOnly; + } +} + perfetto::StaticString TraceEventNameForAffinityMode( base::CpuAffinityMode affinity) { switch (affinity) { @@ -42,6 +60,11 @@ base::UmaHistogramBoolean( "Power.CpuAffinityExperiments.ProcessAffinityUpdateSuccess", success); + if (success) { + base::UmaHistogramEnumeration( + "Power.CpuAffinityExperiments.ProcessAffinityMode", + GetCpuAffinityModeForUma(affinity)); + } } bool CpuAffinityApplicable() {
diff --git a/components/reporting/storage/storage_queue.cc b/components/reporting/storage/storage_queue.cc index c0a6c37..093261c 100644 --- a/components/reporting/storage/storage_queue.cc +++ b/components/reporting/storage/storage_queue.cc
@@ -144,7 +144,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(storage_queue_sequence_checker_); // Stop upload timer. - upload_timer_.Stop(); + upload_timer_.AbandonAndStop(); // Make sure no pending writes is present. DCHECK(write_contexts_queue_.empty()); @@ -664,6 +664,9 @@ base::Unretained(this)), storage_queue->sequenced_task_runner_), async_start_upload_cb_(storage_queue->async_start_upload_cb_), + must_invoke_upload_( + EncryptionModuleInterface::is_enabled() && + storage_queue->encryption_module_->need_encryption_key()), storage_queue_weakptr_factory_{storage_queue.get()} { DCHECK(storage_queue.get()); DCHECK(async_start_upload_cb_); @@ -682,26 +685,16 @@ Response(Status(error::UNAVAILABLE, "StorageQueue shut down")); return; } - base::ThreadPool::PostTask( - FROM_HERE, {base::TaskPriority::BEST_EFFORT}, - base::BindOnce( - [](ReadContext* self) { - self->async_start_upload_cb_.Run( - base::BindOnce(&ReadContext::ScheduleOnUploaderInstantiated, - base::Unretained(self))); - }, - base::Unretained(this))); + if (!must_invoke_upload_) { + PrepareDataFiles(); + return; + } + + InstantiateUploader( + base::BindOnce(&ReadContext::PrepareDataFiles, base::Unretained(this))); } - void ScheduleOnUploaderInstantiated( - StatusOr<std::unique_ptr<UploaderInterface>> uploader_result) { - Schedule(base::BindOnce(&ReadContext::OnUploaderInstantiated, - base::Unretained(this), - std::move(uploader_result))); - } - - void OnUploaderInstantiated( - StatusOr<std::unique_ptr<UploaderInterface>> uploader_result) { + void PrepareDataFiles() { DCHECK_CALLED_ON_VALID_SEQUENCE(read_sequence_checker_); base::WeakPtr<StorageQueue> storage_queue = storage_queue_weakptr_factory_.GetWeakPtr(); @@ -709,16 +702,6 @@ Response(Status(error::UNAVAILABLE, "StorageQueue shut down")); return; } - if (!uploader_result.ok()) { - Response(Status(error::FAILED_PRECONDITION, - base::StrCat({"Failed to provide the Uploader, status=", - uploader_result.status().ToString()}))); - return; - } - DCHECK(!uploader_) - << "Uploader instantiated more than once for single upload"; - uploader_ = std::move(uploader_result.ValueOrDie()); - // Fill in initial sequencing information to track progress: // use minimum of first_sequencing_id_ and first_unconfirmed_sequencing_id_ // if the latter has been recorded. @@ -760,6 +743,25 @@ // Register with storage_queue, to make sure selected files are not removed. ++(storage_queue->active_read_operations_); + if (uploader_) { + // Uploader already created. + BeginUploading(); + return; + } + + InstantiateUploader( + base::BindOnce(&ReadContext::BeginUploading, base::Unretained(this))); + } + + void BeginUploading() { + DCHECK_CALLED_ON_VALID_SEQUENCE(read_sequence_checker_); + base::WeakPtr<StorageQueue> storage_queue = + storage_queue_weakptr_factory_.GetWeakPtr(); + if (!storage_queue) { + Response(Status(error::UNAVAILABLE, "StorageQueue shut down")); + return; + } + // The first <seq.file> pair is the current file now, and we are at its // start or ahead of it. current_file_ = files_.begin(); @@ -1038,12 +1040,50 @@ // Resume at ScheduleNextRecord. } + void InstantiateUploader(base::OnceCallback<void()> continuation) { + base::ThreadPool::PostTask( + FROM_HERE, {base::TaskPriority::BEST_EFFORT}, + base::BindOnce( + [](base::OnceCallback<void()> continuation, ReadContext* self) { + self->async_start_upload_cb_.Run(base::BindOnce( + &ReadContext::ScheduleOnUploaderInstantiated, + base::Unretained(self), std::move(continuation))); + }, + std::move(continuation), base::Unretained(this))); + } + + void ScheduleOnUploaderInstantiated( + base::OnceCallback<void()> continuation, + StatusOr<std::unique_ptr<UploaderInterface>> uploader_result) { + Schedule(base::BindOnce(&ReadContext::OnUploaderInstantiated, + base::Unretained(this), std::move(continuation), + std::move(uploader_result))); + } + + void OnUploaderInstantiated( + base::OnceCallback<void()> continuation, + StatusOr<std::unique_ptr<UploaderInterface>> uploader_result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(read_sequence_checker_); + if (!uploader_result.ok()) { + Response(Status(error::FAILED_PRECONDITION, + base::StrCat({"Failed to provide the Uploader, status=", + uploader_result.status().ToString()}))); + return; + } + DCHECK(!uploader_) + << "Uploader instantiated more than once for single upload"; + uploader_ = std::move(uploader_result.ValueOrDie()); + + std::move(continuation).Run(); + } + // Files that will be read (in order of sequencing ids). std::map<int64_t, scoped_refptr<SingleFile>> files_; SequencingInformation sequencing_info_; uint32_t current_pos_; std::map<int64_t, scoped_refptr<SingleFile>>::iterator current_file_; const AsyncStartUploaderCb async_start_upload_cb_; + const bool must_invoke_upload_; std::unique_ptr<UploaderInterface> uploader_; base::WeakPtrFactory<StorageQueue> storage_queue_weakptr_factory_;
diff --git a/components/reporting/storage/storage_unittest.cc b/components/reporting/storage/storage_unittest.cc index f57e292..bae80a9 100644 --- a/components/reporting/storage/storage_unittest.cc +++ b/components/reporting/storage/storage_unittest.cc
@@ -365,22 +365,16 @@ // Helper class for setting up mock client expectations for key delivery. class SetKeyDelivery { public: - explicit SetKeyDelivery(MockUploadClient* client, - test::TestCallbackWaiter* waiter) - : client_(client), waiter_(waiter) {} + explicit SetKeyDelivery(MockUploadClient* client) : client_(client) {} ~SetKeyDelivery() { EXPECT_CALL(*client_, UploadRecord(_, _, _)).Times(0); EXPECT_CALL(*client_, UploadRecordFailure(_, _, _)).Times(0); - test::TestCallbackWaiter* const waiter = - waiter_; // let pointer outlive SetUp - EXPECT_CALL(*client_, UploadComplete(Eq(Status::StatusOK()))) - .WillOnce(Invoke([waiter] { waiter->Signal(); })); + EXPECT_CALL(*client_, UploadComplete(Eq(Status::StatusOK()))).Times(1); } private: MockUploadClient* const client_; - test::TestCallbackWaiter* const waiter_; }; private: @@ -496,6 +490,12 @@ protected: void SetUp() override { ASSERT_TRUE(location_.CreateUniqueTempDir()); + // Disallow uploads unless other expectation is set (any later EXPECT_CALL + // will take precedence over this one). + EXPECT_CALL(set_mock_uploader_expectations_, Call(_, _, NotNull())) + .WillRepeatedly(WithoutArgs(Invoke([]() { + return Status(error::UNAVAILABLE, "Upload unavailable at this time"); + }))); // Encryption is disabled by default. ASSERT_FALSE(EncryptionModuleInterface::is_enabled()); if (is_encryption_enabled()) { @@ -526,18 +526,15 @@ StatusOr<scoped_refptr<Storage>> CreateTestStorage( const StorageOptions& options, scoped_refptr<EncryptionModuleInterface> encryption_module) { - test::TestCallbackWaiter waiter; if (expect_to_need_key_) { // Set uploader expectations for any queue; expect no records and need // key. Make sure no uploads happen, and key is requested. - waiter.Attach(); EXPECT_CALL(set_mock_uploader_expectations_, Call(_, /*need_encryption_key=*/Eq(true), NotNull())) - .WillOnce(WithArg<2>( - Invoke([&waiter](MockUploadClient* mock_upload_client) { - MockUploadClient::SetKeyDelivery client(mock_upload_client, - &waiter); - }))) + .WillOnce(WithArg<2>(Invoke([](MockUploadClient* mock_upload_client) { + MockUploadClient::SetKeyDelivery client(mock_upload_client); + return Status::StatusOK(); + }))) .RetiresOnSaturation(); } // Initialize Storage with no key. @@ -547,7 +544,8 @@ base::Unretained(this)), encryption_module, e.cb()); ASSIGN_OR_RETURN(auto storage, e.result()); - waiter.Wait(); + // Let asynchronous activity finish. + task_environment_.RunUntilIdle(); if (expect_to_need_key_) { // Provision the storage with a key. // Key delivery must have been requested above. @@ -571,7 +569,7 @@ } void ResetTestStorage() { - // Let everything ongoing to finish. + // Let asynchronous activity finish. task_environment_.RunUntilIdle(); storage_.reset(); // StorageQueue is destructed on a thread, @@ -617,8 +615,12 @@ UploaderInterface::UploaderInterfaceResultCb start_uploader_cb) { auto uploader = std::make_unique<MockUploadClient>( &last_record_digest_map_, sequenced_task_runner_, decryptor_); - set_mock_uploader_expectations_.Call(priority, need_encryption_key, - uploader.get()); + const auto status = set_mock_uploader_expectations_.Call( + priority, need_encryption_key, uploader.get()); + if (!status.ok()) { + std::move(start_uploader_cb).Run(status); + return; + } std::move(start_uploader_cb).Run(std::move(uploader)); } @@ -729,8 +731,8 @@ scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_{ base::ThreadPool::CreateSequencedTaskRunner(base::TaskTraits())}; - ::testing::MockFunction< - void(Priority, bool /*need_encryption_key*/, MockUploadClient*)> + ::testing::NiceMock<::testing::MockFunction< + Status(Priority, bool /*need_encryption_key*/, MockUploadClient*)>> set_mock_uploader_expectations_; }; @@ -740,7 +742,6 @@ TEST_P(StorageTest, WriteIntoNewStorageAndReopen) { CreateTestStorageOrDie(BuildTestStorageOptions()); - EXPECT_CALL(set_mock_uploader_expectations_, Call(_, _, NotNull())).Times(0); WriteStringOrDie(FAST_BATCH, kData[0]); WriteStringOrDie(FAST_BATCH, kData[1]); WriteStringOrDie(FAST_BATCH, kData[2]); @@ -750,10 +751,8 @@ CreateTestStorageOrDie(BuildTestStorageOptions()); } -// TODO(crbug.com/1196570): Fix flakiness. -TEST_P(StorageTest, DISABLED_WriteIntoNewStorageReopenAndWriteMore) { +TEST_P(StorageTest, WriteIntoNewStorageReopenAndWriteMore) { CreateTestStorageOrDie(BuildTestStorageOptions()); - EXPECT_CALL(set_mock_uploader_expectations_, Call(_, _, NotNull())).Times(0); WriteStringOrDie(FAST_BATCH, kData[0]); WriteStringOrDie(FAST_BATCH, kData[1]); WriteStringOrDie(FAST_BATCH, kData[2]); @@ -783,6 +782,7 @@ .Required(0, kData[0]) .Required(1, kData[1]) .Required(2, kData[2]); + return Status::StatusOK(); }))); // Trigger upload. @@ -810,6 +810,7 @@ .WillRepeatedly(WithArgs<0, 2>( Invoke([](Priority priority, MockUploadClient* mock_upload_client) { MockUploadClient::SetEmpty client(mock_upload_client); + return Status::StatusOK(); }))); EXPECT_CALL( set_mock_uploader_expectations_, @@ -820,6 +821,7 @@ .Required(0, kData[0]) .Required(1, kData[1]) .Required(2, kData[2]); + return Status::StatusOK(); }))); // Trigger upload with no key update. @@ -849,7 +851,9 @@ .Required(3, kMoreData[0]) .Required(4, kMoreData[1]) .Required(5, kMoreData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Trigger upload with key update after a long wait. EXPECT_OK(storage_->Flush(MANUAL_BATCH)); @@ -882,7 +886,9 @@ .Required(3, kMoreData[0]) .Required(4, kMoreData[1]) .Required(5, kMoreData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Trigger upload. task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); @@ -905,14 +911,15 @@ .Required(0, kData[0]) .Required(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Trigger upload. EXPECT_OK(storage_->Flush(MANUAL_BATCH)); } -// TODO(crbug.com/1196852): Fix flakiness. -TEST_P(StorageTest, DISABLED_WriteIntoNewStorageReopenWriteMoreAndFlush) { +TEST_P(StorageTest, WriteIntoNewStorageReopenWriteMoreAndFlush) { CreateTestStorageOrDie(BuildTestStorageOptions()); WriteStringOrDie(MANUAL_BATCH, kData[0]); WriteStringOrDie(MANUAL_BATCH, kData[1]); @@ -939,7 +946,9 @@ .Required(3, kMoreData[0]) .Required(4, kMoreData[1]) .Required(5, kMoreData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Trigger upload. EXPECT_OK(storage_->Flush(MANUAL_BATCH)); @@ -964,7 +973,9 @@ .Required(0, kData[0]) .Required(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Forward time to trigger upload task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); @@ -983,7 +994,9 @@ MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Forward time to trigger upload task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); } @@ -1000,7 +1013,9 @@ [&waiter](Priority priority, MockUploadClient* mock_upload_client) { MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Forward time to trigger upload task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); } @@ -1023,7 +1038,9 @@ .Required(3, kMoreData[0]) .Required(4, kMoreData[1]) .Required(5, kMoreData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); } @@ -1041,7 +1058,9 @@ .Required(3, kMoreData[0]) .Required(4, kMoreData[1]) .Required(5, kMoreData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); } } @@ -1061,7 +1080,9 @@ [&waiter](Priority priority, MockUploadClient* mock_upload_client) { MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(0, kData[0]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[0]); // Immediately uploads and verifies. } @@ -1076,7 +1097,9 @@ MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(0, kData[0]) .Required(1, kData[1]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[1]); // Immediately uploads and verifies. } @@ -1092,7 +1115,9 @@ .Required(0, kData[0]) .Required(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[2]); // Immediately uploads and verifies. } @@ -1114,7 +1139,9 @@ [&waiter](Priority priority, MockUploadClient* mock_upload_client) { MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(0, kData[0]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[0]); } @@ -1128,7 +1155,9 @@ MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(0, kData[0]) .Required(1, kData[1]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[1]); } @@ -1143,7 +1172,9 @@ .Required(0, kData[0]) .Required(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[2]); } @@ -1164,7 +1195,9 @@ MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(2, kData[2]) .Required(3, kMoreData[0]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kMoreData[0]); } @@ -1179,7 +1212,9 @@ .Required(2, kData[2]) .Required(3, kMoreData[0]) .Required(4, kMoreData[1]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kMoreData[1]); } @@ -1195,7 +1230,9 @@ .Required(3, kMoreData[0]) .Required(4, kMoreData[1]) .Required(5, kMoreData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kMoreData[2]); } } @@ -1212,7 +1249,9 @@ [&waiter](Priority priority, MockUploadClient* mock_upload_client) { MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(0, kData[0]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[0]); } @@ -1228,7 +1267,9 @@ MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(0, kData[0]) .Required(1, kData[1]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[1]); } @@ -1243,6 +1284,7 @@ .WillRepeatedly(WithArgs<0, 2>( Invoke([](Priority priority, MockUploadClient* mock_upload_client) { MockUploadClient::SetEmpty client(mock_upload_client); + return Status::StatusOK(); }))); EXPECT_CALL( set_mock_uploader_expectations_, @@ -1252,7 +1294,9 @@ MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Required(0, kMoreData[0]) .Required(1, kMoreData[1]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(20)); } @@ -1273,7 +1317,9 @@ MockUploadClient::SetUp(priority, mock_upload_client, &waiter) .Possible(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); WriteStringOrDie(IMMEDIATE, kData[2]); } WriteStringOrDie(SLOW_BATCH, kMoreData[2]); @@ -1287,6 +1333,7 @@ .WillRepeatedly(WithArgs<0, 2>( Invoke([](Priority priority, MockUploadClient* mock_upload_client) { MockUploadClient::SetEmpty client(mock_upload_client); + return Status::StatusOK(); }))); EXPECT_CALL( set_mock_uploader_expectations_, @@ -1296,7 +1343,9 @@ MockUploadClient::SetUp(SLOW_BATCH, mock_upload_client, &waiter) .Required(1, kMoreData[1]) .Required(2, kMoreData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(20)); } } @@ -1316,7 +1365,9 @@ .WillOnce(WithArg<1>( Invoke([](base::OnceCallback<void(StatusOr<EncryptedRecord>)> cb) { std::move(cb).Run(Status(error::UNKNOWN, "Failing for tests")); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); const Status result = WriteString(FAST_BATCH, "TEST_MESSAGE"); EXPECT_FALSE(result.ok()); EXPECT_EQ(result.error_code(), error::UNKNOWN); @@ -1341,7 +1392,9 @@ .Required(0, kData[0]) .Required(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Forward time to trigger upload task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); } @@ -1358,7 +1411,9 @@ [&waiter](Priority priority, MockUploadClient* mock_upload_client) { MockUploadClient::SetUp(FAST_BATCH, mock_upload_client, &waiter) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Forward time to trigger upload task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); } @@ -1384,7 +1439,9 @@ .PossibleGap(0, 2) .Possible(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Forward time to trigger upload task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); } @@ -1407,7 +1464,9 @@ .PossibleGap(1, 1) .Possible(1, kData[1]) .Required(2, kData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Forward time to trigger upload task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); } @@ -1444,20 +1503,19 @@ // This time key delivery is to succeed. // Set uploader expectations for any queue; expect no records and need // key. Make sure no uploads happen, and key is requested. - { - test::TestCallbackAutoWaiter waiter; - EXPECT_CALL(set_mock_uploader_expectations_, - Call(_, /*need_encryption_key=*/Eq(true), NotNull())) - .WillOnce( - WithArg<2>(Invoke([&waiter](MockUploadClient* mock_upload_client) { - MockUploadClient::SetKeyDelivery client(mock_upload_client, - &waiter); - }))) - .RetiresOnSaturation(); + EXPECT_CALL(set_mock_uploader_expectations_, + Call(_, /*need_encryption_key=*/Eq(true), NotNull())) + .WillOnce(WithArg<2>(Invoke([](MockUploadClient* mock_upload_client) { + MockUploadClient::SetKeyDelivery client(mock_upload_client); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); - // Forward time to trigger upload - task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); - } + // Forward time to trigger upload + task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); + + // Let asynchronous activity finish. + task_environment_.RunUntilIdle(); // Provision the storage with a key. // Key delivery must have been requested above. @@ -1480,6 +1538,7 @@ .Required(0, kData[0]) .Required(1, kData[1]) .Required(2, kData[2]); + return Status::StatusOK(); }))) .RetiresOnSaturation(); @@ -1510,7 +1569,9 @@ .Required(3, kMoreData[0]) .Required(4, kMoreData[1]) .Required(5, kMoreData[2]); - }))); + return Status::StatusOK(); + }))) + .RetiresOnSaturation(); // Trigger upload. task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1));
diff --git a/components/safe_browsing/content/browser/BUILD.gn b/components/safe_browsing/content/browser/BUILD.gn index ff9bc92..1eb4af6 100644 --- a/components/safe_browsing/content/browser/BUILD.gn +++ b/components/safe_browsing/content/browser/BUILD.gn
@@ -64,11 +64,15 @@ ] } -source_set("client_side_model_loader_unittest") { +source_set("unit_tests") { testonly = true - sources = [ "client_side_model_loader_unittest.cc" ] + sources = [ + "client_side_model_loader_unittest.cc", + "client_side_phishing_model_unittest.cc", + ] deps = [ + ":client_side_detection", ":client_side_model_loader", "//base:base", "//base/test:test_support",
diff --git a/components/safe_browsing/content/browser/client_side_detection_host.cc b/components/safe_browsing/content/browser/client_side_detection_host.cc index f4acd85a..2e213ab 100644 --- a/components/safe_browsing/content/browser/client_side_detection_host.cc +++ b/components/safe_browsing/content/browser/client_side_detection_host.cc
@@ -433,9 +433,9 @@ base::UmaHistogramEnumeration("SBClientPhishing.PhishingDetectorResult", result); if (result == mojom::PhishingDetectorResult::CLASSIFIER_NOT_READY) { - base::UmaHistogramEnumeration( - "SBClientPhishing.ClassifierNotReadyReason", - ClientSidePhishingModel::GetInstance()->GetLastModelStatus()); + base::UmaHistogramBoolean( + "SBClientPhishing.BrowserReadyOnClassifierNotReady", + ClientSidePhishingModel::GetInstance()->IsEnabled()); } if (result != mojom::PhishingDetectorResult::SUCCESS) return;
diff --git a/components/safe_browsing/content/browser/client_side_detection_service.cc b/components/safe_browsing/content/browser/client_side_detection_service.cc index 0e13fc1..4df9372 100644 --- a/components/safe_browsing/content/browser/client_side_detection_service.cc +++ b/components/safe_browsing/content/browser/client_side_detection_service.cc
@@ -209,8 +209,6 @@ } // Fill in metadata about which model we used. - request->set_model_filename( - ClientSidePhishingModel::GetInstance()->GetModelName()); *request->mutable_population() = delegate_->GetUserPopulation(); std::string request_data;
diff --git a/components/safe_browsing/content/browser/client_side_phishing_model.cc b/components/safe_browsing/content/browser/client_side_phishing_model.cc index ffd0830a..e368c50c 100644 --- a/components/safe_browsing/content/browser/client_side_phishing_model.cc +++ b/components/safe_browsing/content/browser/client_side_phishing_model.cc
@@ -5,12 +5,15 @@ #include "components/safe_browsing/content/browser/client_side_phishing_model.h" #include "base/memory/singleton.h" +#include "base/metrics/histogram_functions.h" +#include "base/task/post_task.h" +#include "components/safe_browsing/core/proto/client_model.pb.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace safe_browsing { -const int ClientSidePhishingModel::kInitialClientModelFetchDelayMs = 10000; - using base::AutoLock; struct ClientSidePhishingModelSingletonTrait @@ -41,60 +44,46 @@ return callbacks_.Add(std::move(callback)); } -void ClientSidePhishingModel::Start( - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) { - AutoLock lock(lock_); - model_loader_ = std::make_unique<ModelLoader>( - base::BindRepeating(&ClientSidePhishingModel::ModelUpdatedCallback, - base::Unretained(this)), - url_loader_factory, - /*extended_reporting=*/false); - - // Refresh the models when the service is enabled. This can happen when - // either of the preferences are toggled, or early during startup if - // safe browsing is already enabled. In a lot of cases the model will be - // in the cache so it won't actually be fetched from the network. - // We delay the first model fetches to avoid slowing down browser startup. - model_loader_->ScheduleFetch(kInitialClientModelFetchDelayMs); -} - -void ClientSidePhishingModel::Stop() { - AutoLock lock(lock_); - if (model_loader_) { - model_loader_->CancelFetcher(); - } - model_loader_ = nullptr; -} - bool ClientSidePhishingModel::IsEnabled() const { - return model_loader_.get(); + return !model_str_.empty(); } std::string ClientSidePhishingModel::GetModelStr() const { - if (!overridden_model_str_.empty()) - return overridden_model_str_; - return model_loader_ ? model_loader_->model_str() : ""; + return model_str_; } -std::string ClientSidePhishingModel::GetModelName() const { - return model_loader_ ? model_loader_->name() : ""; +void ClientSidePhishingModel::PopulateFromDynamicUpdate( + const std::string& model_str) { + AutoLock lock(lock_); + + ClientSideModel model_proto; + bool can_parse = model_proto.ParseFromString(model_str); + base::UmaHistogramBoolean("SBClientPhishing.ModelDynamicUpdateSuccess", + can_parse); + + if (can_parse) { + // At time of writing, versions go up to 25. We set a max version of 100 to + // give some room. + const int kMaxVersion = 100; + base::UmaHistogramExactLinear("SBClientPhishing.ModelDynamicUpdateVersion", + model_proto.version(), kMaxVersion + 1); + model_str_ = model_str; + // Unretained is safe because this is a singleton. + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ClientSidePhishingModel::NotifyCallbacksOnUI, + base::Unretained(this))); + } } -ModelLoader::ClientModelStatus ClientSidePhishingModel::GetLastModelStatus() - const { - return model_loader_ ? model_loader_->last_client_model_status() - : ModelLoader::MODEL_NEVER_FETCHED; +void ClientSidePhishingModel::NotifyCallbacksOnUI() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + callbacks_.Notify(); } void ClientSidePhishingModel::SetModelStrForTesting( const std::string& model_str) { AutoLock lock(lock_); - overridden_model_str_ = model_str; -} - -void ClientSidePhishingModel::ModelUpdatedCallback() { - AutoLock lock(lock_); - callbacks_.Notify(); + model_str_ = model_str; } } // namespace safe_browsing
diff --git a/components/safe_browsing/content/browser/client_side_phishing_model.h b/components/safe_browsing/content/browser/client_side_phishing_model.h index 03b56d1..2177613 100644 --- a/components/safe_browsing/content/browser/client_side_phishing_model.h +++ b/components/safe_browsing/content/browser/client_side_phishing_model.h
@@ -12,10 +12,6 @@ #include "base/synchronization/lock.h" #include "components/safe_browsing/content/browser/client_side_model_loader.h" -namespace network { -class SharedURLLoaderFactory; -} - namespace safe_browsing { struct ClientSidePhishingModelSingletonTrait; @@ -33,28 +29,20 @@ static ClientSidePhishingModel* GetInstance(); // Singleton - // Register a callback to be notified whenever the model changes. + // Register a callback to be notified whenever the model changes. All + // notifications will occur on the UI thread. base::CallbackListSubscription RegisterCallback( base::RepeatingCallback<void()> callback); - // Start loading the model with the given |url_loader_factory| - void Start(scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); - - // Cancel any pending model fetches. - void Stop(); - - // Returns whether we are currently actively fetching the model. + // Returns whether we currently have a model. bool IsEnabled() const; // Returns the model string, as a serialized protobuf. std::string GetModelStr() const; - // Returns the model name. - std::string GetModelName() const; - - // Returns the status of the most recent model fetch, or MODEL_NEVER_FETCHED - // if we have done no fetches. - ModelLoader::ClientModelStatus GetLastModelStatus() const; + // Updates the internal model string, when one is received from a component + // update. + void PopulateFromDynamicUpdate(const std::string& model_str); // Overrides the model string for use in tests. void SetModelStrForTesting(const std::string& model_str); @@ -64,18 +52,14 @@ ClientSidePhishingModel(); - // Callback when a new model proto has been fetched by |model_loader_| - void ModelUpdatedCallback(); + void NotifyCallbacksOnUI(); // The list of callbacks to notify when a new model is ready. Protected by - // lock_. + // lock_. Will always be notified on the UI thread. base::RepeatingCallbackList<void()> callbacks_; - // Fetches the ClientSideModel over the network. Protected by lock_. - std::unique_ptr<ModelLoader> model_loader_; - - // Fake model string used in testing. Protected by lock_. - std::string overridden_model_str_; + // Model string. Protected by lock_. + std::string model_str_; mutable base::Lock lock_;
diff --git a/components/safe_browsing/content/browser/client_side_phishing_model_unittest.cc b/components/safe_browsing/content/browser/client_side_phishing_model_unittest.cc new file mode 100644 index 0000000..28fc800 --- /dev/null +++ b/components/safe_browsing/content/browser/client_side_phishing_model_unittest.cc
@@ -0,0 +1,48 @@ +// Copyright 2020 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/safe_browsing/content/browser/client_side_phishing_model.h" + +#include "base/logging.h" +#include "base/run_loop.h" +#include "components/safe_browsing/core/proto/client_model.pb.h" +#include "content/public/test/browser_task_environment.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace safe_browsing { + +TEST(ClientSidePhishingModelTest, NotifiesOnUpdate) { + content::BrowserTaskEnvironment task_environment; + base::RunLoop run_loop; + bool called = false; + base::CallbackListSubscription subscription = + ClientSidePhishingModel::GetInstance()->RegisterCallback( + base::BindRepeating( + [](base::RepeatingClosure quit_closure, bool* called) { + *called = true; + std::move(quit_closure).Run(); + }, + run_loop.QuitClosure(), &called)); + + ClientSideModel model; + model.set_max_words_per_term(0); // Required field + ClientSidePhishingModel::GetInstance()->PopulateFromDynamicUpdate( + model.SerializeAsString()); + + run_loop.Run(); + + EXPECT_TRUE(called); + EXPECT_EQ(model.SerializeAsString(), + ClientSidePhishingModel::GetInstance()->GetModelStr()); +} + +TEST(ClientSidePhishingModelTest, RejectsInvalidProto) { + // Empty the model, just in case a previous test had successfully set it. + ClientSidePhishingModel::GetInstance()->SetModelStrForTesting(""); + ClientSidePhishingModel::GetInstance()->PopulateFromDynamicUpdate( + "bad proto"); + EXPECT_FALSE(ClientSidePhishingModel::GetInstance()->IsEnabled()); +} + +} // namespace safe_browsing
diff --git a/components/safe_browsing/core/features.cc b/components/safe_browsing/core/features.cc index 841456e..eb3338c2 100644 --- a/components/safe_browsing/core/features.cc +++ b/components/safe_browsing/core/features.cc
@@ -39,6 +39,9 @@ extern const base::Feature kClientSideDetectionModelVersion{ "ClientSideDetectionModel", base::FEATURE_ENABLED_BY_DEFAULT}; +extern const base::Feature kClientSideDetectionModelTag{ + "ClientSideDetectionTag", base::FEATURE_DISABLED_BY_DEFAULT}; + const base::Feature kClientSideDetectionReferrerChain{ "ClientSideDetectionReferrerChain", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/safe_browsing/core/features.h b/components/safe_browsing/core/features.h index 0552c9b..65f3925 100644 --- a/components/safe_browsing/core/features.h +++ b/components/safe_browsing/core/features.h
@@ -40,6 +40,9 @@ // Desktop. extern const base::Feature kClientSideDetectionModelVersion; +// Determines the tag to pass to Omaha to get a client side detection model. +extern const base::Feature kClientSideDetectionModelTag; + // Enables client side detection referrer chain. extern const base::Feature kClientSideDetectionReferrerChain;
diff --git a/components/test/data/history/history.44.sql b/components/test/data/history/history.44.sql new file mode 100644 index 0000000..4f710ff --- /dev/null +++ b/components/test/data/history/history.44.sql
@@ -0,0 +1,31 @@ +PRAGMA foreign_keys=OFF; +BEGIN TRANSACTION; +CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR); +INSERT INTO meta VALUES('mmap_status','-1'); +INSERT INTO meta VALUES('version','44'); +INSERT INTO meta VALUES('last_compatible_version','16'); +CREATE TABLE urls(id INTEGER PRIMARY KEY AUTOINCREMENT,url LONGVARCHAR,title LONGVARCHAR,visit_count INTEGER DEFAULT 0 NOT NULL,typed_count INTEGER DEFAULT 0 NOT NULL,last_visit_time INTEGER NOT NULL,hidden INTEGER DEFAULT 0 NOT NULL); +CREATE TABLE visits(id INTEGER PRIMARY KEY,url INTEGER NOT NULL,visit_time INTEGER NOT NULL,from_visit INTEGER,transition INTEGER DEFAULT 0 NOT NULL,segment_id INTEGER,visit_duration INTEGER DEFAULT 0 NOT NULL,incremented_omnibox_typed_score BOOLEAN DEFAULT FALSE NOT NULL,publicly_routable BOOLEAN DEFAULT FALSE NOT NULL); +CREATE TABLE visit_source(id INTEGER PRIMARY KEY,source INTEGER NOT NULL); +CREATE TABLE keyword_search_terms (keyword_id INTEGER NOT NULL,url_id INTEGER NOT NULL,term LONGVARCHAR NOT NULL,normalized_term LONGVARCHAR NOT NULL); +CREATE TABLE downloads (id INTEGER PRIMARY KEY,guid VARCHAR NOT NULL,current_path LONGVARCHAR NOT NULL,target_path LONGVARCHAR NOT NULL,start_time INTEGER NOT NULL,received_bytes INTEGER NOT NULL,total_bytes INTEGER NOT NULL,state INTEGER NOT NULL,danger_type INTEGER NOT NULL,interrupt_reason INTEGER NOT NULL,hash BLOB NOT NULL,end_time INTEGER NOT NULL,opened INTEGER NOT NULL,last_access_time INTEGER NOT NULL,transient INTEGER NOT NULL,referrer VARCHAR NOT NULL,site_url VARCHAR NOT NULL,tab_url VARCHAR NOT NULL,tab_referrer_url VARCHAR NOT NULL,http_method VARCHAR NOT NULL,by_ext_id VARCHAR NOT NULL,by_ext_name VARCHAR NOT NULL,etag VARCHAR NOT NULL,last_modified VARCHAR NOT NULL,mime_type VARCHAR(255) NOT NULL,original_mime_type VARCHAR(255) NOT NULL); +CREATE TABLE downloads_url_chains (id INTEGER NOT NULL,chain_index INTEGER NOT NULL,url LONGVARCHAR NOT NULL, PRIMARY KEY (id, chain_index) ); +CREATE TABLE downloads_slices (download_id INTEGER NOT NULL,offset INTEGER NOT NULL,received_bytes INTEGER NOT NULL,finished INTEGER NOT NULL DEFAULT 0,PRIMARY KEY (download_id, offset) ); +CREATE TABLE segments (id INTEGER PRIMARY KEY,name VARCHAR,url_id INTEGER NON NULL); +CREATE TABLE segment_usage (id INTEGER PRIMARY KEY,segment_id INTEGER NOT NULL,time_slot INTEGER NOT NULL,visit_count INTEGER DEFAULT 0 NOT NULL); +CREATE TABLE typed_url_sync_metadata (storage_key INTEGER PRIMARY KEY NOT NULL,value BLOB); +CREATE TABLE content_annotations (visit_id INTEGER PRIMARY KEY,floc_protected_score DECIMAL(3, 2),categories VARCHAR,page_topics_model_version INTEGER); +CREATE TABLE cluster_visits(cluster_visit_id INTEGER PRIMARY KEY, url_id INTEGER NOT NULL, visit_id INTEGER NOT NULL, cluster_visit_context_signal_bitmask INTEGER NOT NULL, duration_since_last_visit INTEGER NOT NULL, page_end_reason INTEGER NOT NULL); +DELETE FROM sqlite_sequence; +CREATE INDEX visits_url_index ON visits (url); +CREATE INDEX visits_from_index ON visits (from_visit); +CREATE INDEX visits_time_index ON visits (visit_time); +CREATE INDEX segments_name ON segments(name); +CREATE INDEX segments_url_id ON segments(url_id); +CREATE INDEX segment_usage_time_slot_segment_id ON segment_usage(time_slot, segment_id); +CREATE INDEX segments_usage_seg_id ON segment_usage(segment_id); +CREATE INDEX urls_url_index ON urls (url); +CREATE INDEX keyword_search_terms_index1 ON keyword_search_terms (keyword_id, normalized_term); +CREATE INDEX keyword_search_terms_index2 ON keyword_search_terms (url_id); +CREATE INDEX keyword_search_terms_index3 ON keyword_search_terms (term); +COMMIT;
diff --git a/components/viz/host/host_gpu_memory_buffer_manager.cc b/components/viz/host/host_gpu_memory_buffer_manager.cc index 5a1dbb8..b5a7350c 100644 --- a/components/viz/host/host_gpu_memory_buffer_manager.cc +++ b/components/viz/host/host_gpu_memory_buffer_manager.cc
@@ -197,8 +197,12 @@ std::make_pair(buffer_handle.id, buffer_info)); } - task_runner_->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), std::move(buffer_handle))); + if (call_sync) { + std::move(callback).Run(std::move(buffer_handle)); + } else { + task_runner_->PostTask(FROM_HERE, base::BindOnce(std::move(callback), + std::move(buffer_handle))); + } } bool HostGpuMemoryBufferManager::IsNativeGpuMemoryBufferConfiguration( @@ -226,10 +230,7 @@ base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); DCHECK(runs_on_ui_thread_ || !task_runner_->BelongsToCurrentThread()); - - bool call_sync = runs_on_ui_thread_ && - task_runner_->BelongsToCurrentThread() && - CreateBufferUsesGpuService(format, usage); + bool call_sync = runs_on_ui_thread_ && task_runner_->BelongsToCurrentThread(); // A refcounted wrapper around a bool so that if the thread waiting on a // PostTask to the main thread is quit due to shutdown and the task runs @@ -255,7 +256,7 @@ &HostGpuMemoryBufferManager::AllocateGpuMemoryBuffer, base::Unretained(this), id, client_id_, size, format, usage, surface_handle, std::move(reply_callback), call_sync); - if (runs_on_ui_thread_ && task_runner_->BelongsToCurrentThread()) { + if (call_sync) { std::move(allocate_callback).Run(); } else { task_runner_->PostTask(FROM_HERE, std::move(allocate_callback));
diff --git a/components/viz/service/display/surface_aggregator.cc b/components/viz/service/display/surface_aggregator.cc index ae7c246..2577cbe5 100644 --- a/components/viz/service/display/surface_aggregator.cc +++ b/components/viz/service/display/surface_aggregator.cc
@@ -782,9 +782,11 @@ const base::Optional<gfx::Rect>& clip_rect, AggregatedRenderPass* dest_pass, const MaskFilterInfoExt& mask_filter_info) { - // The primary surface is unavailable and there is no fallback - // surface specified so create a SolidColorDrawQuad with the default - // background color. + TRACE_EVENT1("viz", "SurfaceAggregator::EmitDefaultBackgroundColorQuad", + "surface_range", surface_quad->surface_range.ToString()); + + // No matching surface was found so create a SolidColorDrawQuad with the + // SurfaceDrawQuad default background color. SkColor background_color = surface_quad->default_background_color; auto* shared_quad_state = CopySharedQuadState(surface_quad->shared_quad_state, target_transform,
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index bad677b..6a64bd980 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -627,6 +627,17 @@ "code_cache/generated_code_cache_context.h", "compositor/surface_utils.cc", "compositor/surface_utils.h", + "compute_pressure/compute_pressure_host.cc", + "compute_pressure/compute_pressure_host.h", + "compute_pressure/compute_pressure_manager.cc", + "compute_pressure/compute_pressure_manager.h", + "compute_pressure/compute_pressure_quantizer.cc", + "compute_pressure/compute_pressure_quantizer.h", + "compute_pressure/compute_pressure_sample.h", + "compute_pressure/compute_pressure_sampler.cc", + "compute_pressure/compute_pressure_sampler.h", + "compute_pressure/cpu_probe.cc", + "compute_pressure/cpu_probe.h", "contacts/contacts_manager_impl.cc", "contacts/contacts_manager_impl.h", "contacts/contacts_provider.h",
diff --git a/content/browser/accessibility/captioning_controller.cc b/content/browser/accessibility/captioning_controller.cc index 19fe0176..11390e7 100644 --- a/content/browser/accessibility/captioning_controller.cc +++ b/content/browser/accessibility/captioning_controller.cc
@@ -6,7 +6,6 @@ #include "base/android/jni_string.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" #include "content/public/android/content_jni_headers/CaptioningController_jni.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h"
diff --git a/content/browser/android/ime_adapter_android.cc b/content/browser/android/ime_adapter_android.cc index dfd03b0..61f0e04 100644 --- a/content/browser/android/ime_adapter_android.cc +++ b/content/browser/android/ime_adapter_android.cc
@@ -19,7 +19,6 @@ #include "content/browser/renderer_host/render_view_host_delegate.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_android.h" -#include "content/common/frame_messages.h" #include "content/public/android/content_jni_headers/ImeAdapterImpl_jni.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/native_web_keyboard_event.h"
diff --git a/content/browser/browser_interface_binders.cc b/content/browser/browser_interface_binders.cc index 1659946..d7c8300 100644 --- a/content/browser/browser_interface_binders.cc +++ b/content/browser/browser_interface_binders.cc
@@ -102,6 +102,7 @@ #include "third_party/blink/public/mojom/buckets/bucket_manager_host.mojom.h" #include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom.h" #include "third_party/blink/public/mojom/choosers/color_chooser.mojom.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" #include "third_party/blink/public/mojom/content_index/content_index.mojom.h" #include "third_party/blink/public/mojom/cookie_store/cookie_store.mojom.h" #include "third_party/blink/public/mojom/credentialmanager/credential_manager.mojom.h" @@ -558,6 +559,9 @@ map->Add<blink::mojom::CacheStorage>(base::BindRepeating( &RenderFrameHostImpl::BindCacheStorage, base::Unretained(host))); + map->Add<blink::mojom::ComputePressureHost>(base::BindRepeating( + &RenderFrameHostImpl::BindComputePressureHost, base::Unretained(host))); + map->Add<blink::mojom::ContactsManager>(base::BindRepeating( &RenderFrameHostImpl::GetContactsManager, base::Unretained(host)));
diff --git a/content/browser/compute_pressure/DIR_METADATA b/content/browser/compute_pressure/DIR_METADATA new file mode 100644 index 0000000..2a4156e --- /dev/null +++ b/content/browser/compute_pressure/DIR_METADATA
@@ -0,0 +1,4 @@ +monorail { + component: "Blink>PerformanceAPIs>ComputePressure" +} +team_email: "storage-dev@chromium.org"
diff --git a/content/browser/compute_pressure/OWNERS b/content/browser/compute_pressure/OWNERS new file mode 100644 index 0000000..79830e6 --- /dev/null +++ b/content/browser/compute_pressure/OWNERS
@@ -0,0 +1,7 @@ +# Primary +oyiptong@chromium.org + +# Secondary +jsbell@chromium.org +mek@chromium.org +pwnall@chromium.org
diff --git a/content/browser/compute_pressure/README.md b/content/browser/compute_pressure/README.md new file mode 100644 index 0000000..50fa263 --- /dev/null +++ b/content/browser/compute_pressure/README.md
@@ -0,0 +1,45 @@ +# Compute Pressure API + +This directory contains the browser-side implementation of the +[Compute Pressure API](https://github.com/oyiptong/compute-pressure/). + +## Code map + +The system is made up of the following components. + +`blink::mojom::ComputePressureHost`, defined in Blink, is the interface between +the renderer and the browser sides of the API implementation. + +`content::ComputePressureManager` is the top-level class for the browser-side +implementation. Each instance handles the Compute Pressure API needs for a user +profile. The class is responsible for coordinating between the objects that +serve mojo requests from renderers, and the objects that collect compute +pressure information from the underlying operating system. + +`content::ComputePressureHost` serves all the mojo connections from renderers +related to an origin. Each instance is owned by a `ComputePressureManager`, +which is responsible for creating and destorying instances as needed to meet +renderer requests. + +`content::ComputePressureSampler` drives measuring the device's compute pressure +state. The class is responsible for invoking platform-specific measurement code +at regular intervals, and for straddling between sequences to meet the +platform-specific code's requirements. + +`content::CpuProbe` is an abstract base class that interfaces between +`ComputePressureSampler` and platform-specific code that retrieves the compute +pressure state from the operating system. This interface is also a dependency +injection point for tests. + +`content::ComputePressureSample` represents the device's compute pressure state. +This information is collected by `CpuProbe` and bubbled up by +`ComputePressureSampler` to `ComputePressureManager`, which broadcats the +information to the `ComputePressureHost` instances that it owns. + +`content::ComputePressureQuantizer` implements the quantization logic that +converts a high-entropy `ComputePressureSample` into a low-entropy +`blink::mojom::ComputePressureState`, which minimizes the amount of information +exposed to a Web page that uses the Compute Pressure API. Each +`ComputePressureHost` uses a `ComputePressureQuantizer` instance, which stores +the origin's quantization schema and produces quantized data suitable for Web +pages served from that origin.
diff --git a/content/browser/compute_pressure/compute_pressure_host.cc b/content/browser/compute_pressure/compute_pressure_host.cc new file mode 100644 index 0000000..dcaedab --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_host.cc
@@ -0,0 +1,200 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/compute_pressure_host.h" + +#include <utility> + +#include "base/sequence_checker.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/browser/compute_pressure/compute_pressure_sampler.h" +#include "content/public/browser/global_routing_id.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/web_contents.h" +#include "services/network/public/cpp/is_potentially_trustworthy.h" +#include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom-shared.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" +#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h" + +namespace content { + +constexpr base::TimeDelta ComputePressureHost::kDefaultVisibleObserverRateLimit; + +ComputePressureHost::ComputePressureHost( + url::Origin origin, + bool is_supported, + base::TimeDelta visible_observer_rate_limit, + base::RepeatingCallback<void(ComputePressureHost*)> did_connection_change) + : origin_(std::move(origin)), + is_supported_(is_supported), + visible_observer_rate_limit_(visible_observer_rate_limit), + did_connections_change_callback_(std::move(did_connection_change)) { + DCHECK(network::IsOriginPotentiallyTrustworthy(origin_)); + + // base::Unretained use is safe because mojo guarantees the callback will not + // be called after `receivers_` is deallocated, and `receivers_` is owned by + // ComputePressureHost. + receivers_.set_disconnect_handler(base::BindRepeating( + &ComputePressureHost::OnReceiverDisconnected, base::Unretained(this))); + + // base::Unretained use is safe because mojo guarantees the callback will not + // be called after `observers_` is deallocated, and `observers_` is owned by + // ComputePressureHost. + observers_.set_disconnect_handler( + base::BindRepeating(&ComputePressureHost::OnObserverRemoteDisconnected, + base::Unretained(this))); +} + +ComputePressureHost::~ComputePressureHost() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +} + +void ComputePressureHost::BindReceiver( + GlobalFrameRoutingId frame_id, + mojo::PendingReceiver<blink::mojom::ComputePressureHost> receiver) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(frame_id); + + receivers_.Add(this, std::move(receiver), frame_id); + did_connections_change_callback_.Run(this); +} + +void ComputePressureHost::AddObserver( + mojo::PendingRemote<blink::mojom::ComputePressureObserver> observer, + blink::mojom::ComputePressureQuantizationPtr quantization, + AddObserverCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (!ComputePressureQuantizer::IsValid(*quantization)) { + mojo::ReportBadMessage("Invalid quantization"); + std::move(callback).Run( + blink::mojom::ComputePressureStatus::kSecurityError); + return; + } + + GlobalFrameRoutingId frame_id = receivers_.current_context(); + RenderFrameHost* rfh = content::RenderFrameHost::FromID(frame_id); + if (!rfh || !rfh->IsCurrent()) { + std::move(callback).Run( + blink::mojom::ComputePressureStatus::kSecurityError); + return; + } + + // The API is only available in frames served from the same origin as the + // top-level frame. + // + // This same-origin frame requirement is stricter than the usual same-site + // requirement for first-party iframes. + // + // The same-origin frame requirement is aligned with the requirement that all + // active observers belonging to the same origin must use the same + // quantization scheme, which limits information exposure. Web pages must not + // be able to bypass the quantization scheme limitations via iframes and + // postMessage(), so any frames that can communicate via postMessage() must + // either be constrained to the same quantization scheme, or be blocked from + // using the API. + if (rfh->GetLastCommittedOrigin() != origin_) { + std::move(callback).Run( + blink::mojom::ComputePressureStatus::kSecurityError); + return; + } + + if (observers_.empty() || !quantizer_.IsSame(*quantization)) { + ResetObserverState(); + quantizer_.Assign(std::move(quantization)); + } + + if (!is_supported_) { + std::move(callback).Run(blink::mojom::ComputePressureStatus::kNotSupported); + return; + } + + mojo::RemoteSetElementId observer_id = observers_.Add(std::move(observer)); + + bool success = observer_contexts_.emplace(observer_id, frame_id).second; + DCHECK(success) << "Observers set contains duplicate RemoteSetElementId " + << observer_id; + + std::move(callback).Run(blink::mojom::ComputePressureStatus::kOk); + did_connections_change_callback_.Run(this); +} + +void ComputePressureHost::UpdateObservers(ComputePressureSample sample, + base::Time sample_time) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + blink::mojom::ComputePressureState quantized_state = + quantizer_.Quantize(sample); + + // TODO(oyiptong): Rate-limit observers in non-visible frames instead of + // cutting off their updates completely. + if (sample_time - last_report_time_ < visible_observer_rate_limit_) { + return; + } + + for (auto it = observers_.begin(); it != observers_.end(); ++it) { + mojo::RemoteSetElementId observer_id = it.id(); + + DCHECK(observer_contexts_.count(observer_id)) + << "AddObserver() failed to register an observer in the map " + << observer_id; + GlobalFrameRoutingId frame_id = observer_contexts_[observer_id]; + + RenderFrameHost* rfh = content::RenderFrameHost::FromID(frame_id); + if (!rfh || !rfh->IsCurrent()) { + // TODO(oyiptong): Is it safe to disconnect observers in this state? + continue; + } + + if (rfh->GetVisibilityState() != + blink::mojom::PageVisibilityState::kVisible) { + // TODO(oyiptong): Rate-limit observers in non-visible frames instead of + // cutting off their updates completely. + continue; + } + + // `last_report_time_` is updated inside the loop so it remains unchanged if + // no observer receives an Update() call. This logic will change when we + // implement sending (less frequent) updates to observers in non-visible + // frames. + last_report_time_ = sample_time; + + (*it)->OnUpdate(quantized_state.Clone()); + } +} + +void ComputePressureHost::OnReceiverDisconnected() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + did_connections_change_callback_.Run(this); +} + +void ComputePressureHost::OnObserverRemoteDisconnected( + mojo::RemoteSetElementId observer_id) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + DCHECK(observer_contexts_.count(observer_id)) + << "AddObserver() failed to register an observer in the map " + << observer_id; + observer_contexts_.erase(observer_id); + + did_connections_change_callback_.Run(this); +} + +void ComputePressureHost::ResetObserverState() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + observers_.Clear(); + observer_contexts_.clear(); + + // Makes sure that rate-limiting can't be bypassed by changing the + // quantization scheme often. + last_report_time_ = base::Time::Now(); + + // Setting to an invalid value, so any state is considered an update. + last_report_sample_ = {.cpu_utilization = -1, .cpu_speed = -1}; +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_host.h b/content/browser/compute_pressure/compute_pressure_host.h new file mode 100644 index 0000000..b8397c7 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_host.h
@@ -0,0 +1,145 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_HOST_H_ +#define CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_HOST_H_ + +#include "base/callback.h" +#include "base/sequence_checker.h" +#include "base/thread_annotations.h" +#include "base/time/time.h" +#include "content/browser/compute_pressure/compute_pressure_quantizer.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/common/content_export.h" +#include "content/public/browser/global_routing_id.h" +#include "mojo/public/cpp/bindings/receiver_set.h" +#include "mojo/public/cpp/bindings/remote_set.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" +#include "url/origin.h" + +namespace content { + +// Serves all the Compute Pressure API mojo requests for an origin. +// +// ComputePressureManager owns an instance of this class for each origin that +// has at least one active mojo connection associated with the Compute Pressure +// API. Instances are dynamically created and destroyed to meet incoming +// requests from renderers. +// +// This class is not thread-safe, so each instance must be used on one sequence. +class CONTENT_EXPORT ComputePressureHost + : public blink::mojom::ComputePressureHost { + public: + static constexpr base::TimeDelta kDefaultVisibleObserverRateLimit = + base::TimeDelta::FromSeconds(1); + + // `did_connection_change` is called on changes to the mojo connections + // handled by this host are changed. The callback will not be Run() after + // the ComputePressureHost instance goes out of scope. + // + // If `is_supported` is false, UpdateObservers() will never get called. + // Observer requests will be bounced. + // + // `visible_observer_rate_limit` is exposed to avoid idling in tests. + // Production code should pass + // ComputePressureHost::kDefaultVisibleObserverRateLimit. + explicit ComputePressureHost( + url::Origin origin, + bool is_supported, + base::TimeDelta visible_observer_rate_limit, + base::RepeatingCallback<void(ComputePressureHost*)> + did_connections_change); + + ~ComputePressureHost() override; + + const url::Origin& origin() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return origin_; + } + bool has_receivers() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return !receivers_.empty(); + } + bool has_observers() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return !observers_.empty(); + } + + void BindReceiver( + GlobalFrameRoutingId frame_id, + mojo::PendingReceiver<blink::mojom::ComputePressureHost> receiver); + + // blink.mojom.ComputePressureManager implementation. + void AddObserver( + mojo::PendingRemote<blink::mojom::ComputePressureObserver> observer, + blink::mojom::ComputePressureQuantizationPtr quantization, + AddObserverCallback callback) override; + + // Called periodically by the ComputePressureManager that owns this host. + void UpdateObservers(ComputePressureSample sample, base::Time sample_time); + + private: + void OnReceiverDisconnected(); + + void OnObserverRemoteDisconnected(mojo::RemoteSetElementId observer_id); + + // Resets the state used to dispatch updates to observers. + // + // Called when the quantizing scheme changes. The caller is responsible for + // invoking `did_connection_change_callback_`. + void ResetObserverState(); + + SEQUENCE_CHECKER(sequence_checker_); + + // The origin whose connections are handled by this host. + const url::Origin origin_; + + // If false, the platform does not support compute pressure reports. + const bool is_supported_; + + // The minimum delay between two Update() calls for observers belonging to + // visibile frames. + const base::TimeDelta visible_observer_rate_limit_; + + // Keeps track of the frame associated with each receiver. + mojo::ReceiverSet<blink::mojom::ComputePressureHost, GlobalFrameRoutingId> + receivers_ GUARDED_BY_CONTEXT(sequence_checker_); + + // Called to inform the owner when the set of receivers or remotes changes. + // + // The owner may destroy this ComputePressureHost while the callback is + // running. + base::RepeatingCallback<void(ComputePressureHost*)> + did_connections_change_callback_ GUARDED_BY_CONTEXT(sequence_checker_); + + // Active observers that belong to this origin. + mojo::RemoteSet<blink::mojom::ComputePressureObserver> observers_ + GUARDED_BY_CONTEXT(sequence_checker_); + + // Keeps track of the frame associated with each observer. + // + // Used to determine the rate-limiting appropriate for each observer. + std::map<mojo::RemoteSetElementId, GlobalFrameRoutingId> observer_contexts_ + GUARDED_BY_CONTEXT(sequence_checker_); + + // Implements the quantizing scheme used for all the origin's observers. + ComputePressureQuantizer quantizer_; + + // The (quantized) sample that was last reported to this origin's observers. + // + // Stored to avoid sending updates when the underlying compute pressure state + // changes, but quantization produces the same values that were reported in + // the last update. + ComputePressureSample last_report_sample_ + GUARDED_BY_CONTEXT(sequence_checker_); + + // The last time the origin's observers received an update. + // + // Stored to implement rate-limiting. + base::Time last_report_time_ GUARDED_BY_CONTEXT(sequence_checker_); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_QUANTIZER_H_
diff --git a/content/browser/compute_pressure/compute_pressure_host_unittest.cc b/content/browser/compute_pressure/compute_pressure_host_unittest.cc new file mode 100644 index 0000000..77bbae0 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_host_unittest.cc
@@ -0,0 +1,371 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/compute_pressure_host.h" + +#include <memory> +#include <utility> + +#include "base/bind.h" +#include "base/time/time.h" +#include "content/browser/compute_pressure/compute_pressure_test_support.h" +#include "content/test/test_render_view_host.h" +#include "mojo/public/cpp/test_support/test_utils.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" + +namespace content { + +class ComputePressureHostTest : public RenderViewHostImplTestHarness { + public: + ComputePressureHostTest() = default; + + void SetUp() override { + RenderViewHostImplTestHarness::SetUp(); + NavigateAndCommit(kTestUrl); + + // base::Unretained use is safe here because the callback will only be + // called while the ComputePressureHost is alive, and this instance owns the + // ComputePressureHost. + SetHostImpl(std::make_unique<ComputePressureHost>( + kTestOrigin, /*is_supported=*/true, base::TimeDelta::FromSeconds(1), + base::BindRepeating(&ComputePressureHostTest::DidHostConnectionsChange, + base::Unretained(this)))); + } + + void SetHostImpl(std::unique_ptr<ComputePressureHost> new_host) { + host_impl_ = std::move(new_host); + int process_id = main_rfh()->GetProcess()->GetID(); + int routing_id = main_rfh()->GetRoutingID(); + main_frame_id_ = GlobalFrameRoutingId(process_id, routing_id); + + host_.reset(); + host_impl_->BindReceiver(main_frame_id_, + host_.BindNewPipeAndPassReceiver()); + host_sync_ = std::make_unique<ComputePressureHostSync>(host_.get()); + } + + void DidHostConnectionsChange(ComputePressureHost* host) { + DCHECK_EQ(host_impl_.get(), host); + } + + protected: + const GURL kTestUrl{"https://example.com/compute_pressure.html"}; + const url::Origin kTestOrigin = + url::Origin::Create(GURL("https://example.com")); + const url::Origin kThirdPartyOrigin = + url::Origin::Create(GURL("https://other.com")); + + // Quantization scheme used in most tests. + const blink::mojom::ComputePressureQuantization kQuantization = { + {0.2, 0.5, 0.8}, + {0.5}}; + + GlobalFrameRoutingId main_frame_id_; + // This member is a std::unique_ptr instead of a plain ComputePressureHost + // so it can be replaced inside tests. + std::unique_ptr<ComputePressureHost> host_impl_; + mojo::Remote<blink::mojom::ComputePressureHost> host_; + std::unique_ptr<ComputePressureHostSync> host_sync_; +}; + +TEST_F(ComputePressureHostTest, OneObserver) { + FakeComputePressureObserver observer; + ASSERT_EQ(host_sync_->AddObserver(kQuantization, + observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + base::Time now = base::Time::Now(); + + host_impl_->UpdateObservers({.cpu_utilization = 0.42, .cpu_speed = 0.84}, + now + base::TimeDelta::FromSeconds(1)); + observer.WaitForUpdate(); + ASSERT_THAT(observer.updates(), testing::SizeIs(testing::Eq(1u))); + EXPECT_EQ(observer.updates()[0], + blink::mojom::ComputePressureState(0.35, 0.75)); +} + +TEST_F(ComputePressureHostTest, OneObserver_UpdateRateLimiting) { + FakeComputePressureObserver observer; + ASSERT_EQ(host_sync_->AddObserver(kQuantization, + observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + base::Time after_add = base::Time::Now(); + + host_impl_->UpdateObservers( + {.cpu_utilization = 0.42, .cpu_speed = 0.84}, + after_add + base::TimeDelta::FromMilliseconds(1000)); + observer.WaitForUpdate(); + observer.updates().clear(); + + // The first update should be blocked due to rate-limiting. + host_impl_->UpdateObservers( + {.cpu_utilization = 1.0, .cpu_speed = 1.0}, + after_add + base::TimeDelta::FromMilliseconds(1500)); + host_impl_->UpdateObservers( + {.cpu_utilization = 0.0, .cpu_speed = 0.0}, + after_add + base::TimeDelta::FromMilliseconds(2100)); + observer.WaitForUpdate(); + + ASSERT_THAT(observer.updates(), testing::SizeIs(testing::Eq(1u))); + EXPECT_EQ(observer.updates()[0], + blink::mojom::ComputePressureState(0.1, 0.25)); +} + +TEST_F(ComputePressureHostTest, OneObserver_AddRateLimiting) { + base::Time before_add = base::Time::Now(); + + FakeComputePressureObserver observer; + ASSERT_EQ(host_sync_->AddObserver(kQuantization, + observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + base::Time after_add = base::Time::Now(); + + ASSERT_LE(after_add - before_add, base::TimeDelta::FromMilliseconds(500)) + << "test timings assume that AddObserver completes in at most 500ms"; + + // The first update should be blocked due to rate-limiting. + host_impl_->UpdateObservers( + {.cpu_utilization = 0.42, .cpu_speed = 0.84}, + before_add + base::TimeDelta::FromMilliseconds(700)); + host_impl_->UpdateObservers( + {.cpu_utilization = 0.0, .cpu_speed = 0.0}, + before_add + base::TimeDelta::FromMilliseconds(1600)); + observer.WaitForUpdate(); + + ASSERT_THAT(observer.updates(), testing::SizeIs(testing::Eq(1u))); + EXPECT_EQ(observer.updates()[0], + blink::mojom::ComputePressureState(0.1, 0.25)); +} + +TEST_F(ComputePressureHostTest, ThreeObservers) { + FakeComputePressureObserver observer1; + ASSERT_EQ(host_sync_->AddObserver(kQuantization, + observer1.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + FakeComputePressureObserver observer2; + ASSERT_EQ(host_sync_->AddObserver(kQuantization, + observer2.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + FakeComputePressureObserver observer3; + ASSERT_EQ(host_sync_->AddObserver(kQuantization, + observer3.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + base::Time now = base::Time::Now(); + + host_impl_->UpdateObservers({.cpu_utilization = 0.42, .cpu_speed = 0.84}, + now + base::TimeDelta::FromSeconds(1)); + FakeComputePressureObserver::WaitForUpdates( + {&observer1, &observer2, &observer3}); + + EXPECT_THAT(observer1.updates(), testing::SizeIs(testing::Eq(1u))); + EXPECT_THAT( + observer1.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.35, 0.75))); + EXPECT_THAT(observer2.updates(), testing::SizeIs(testing::Eq(1u))); + EXPECT_THAT( + observer2.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.35, 0.75))); + EXPECT_THAT(observer3.updates(), testing::SizeIs(testing::Eq(1u))); + EXPECT_THAT( + observer3.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.35, 0.75))); +} + +TEST_F(ComputePressureHostTest, AddObserver_NewQuantization) { + // 0.42, 0.84 would quantize as 0.4, 0.6 + blink::mojom::ComputePressureQuantization quantization1 = {{0.8}, {0.2}}; + FakeComputePressureObserver observer1; + ASSERT_EQ(host_sync_->AddObserver(quantization1, + observer1.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + // 0.42, 0.84 would quantize as 0.6, 0.4 + blink::mojom::ComputePressureQuantization quantization2 = {{0.2}, {0.8}}; + FakeComputePressureObserver observer2; + ASSERT_EQ(host_sync_->AddObserver(quantization2, + observer2.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + // 0.42, 0.84 will quantize as 0.25, 0.75 + blink::mojom::ComputePressureQuantization quantization3 = {{0.5}, {0.5}}; + FakeComputePressureObserver observer3; + ASSERT_EQ(host_sync_->AddObserver(quantization3, + observer3.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + base::Time now = base::Time::Now(); + + host_impl_->UpdateObservers({.cpu_utilization = 0.42, .cpu_speed = 0.84}, + now + base::TimeDelta::FromMilliseconds(1000)); + observer3.WaitForUpdate(); + host_impl_->UpdateObservers({.cpu_utilization = 0.84, .cpu_speed = 0.42}, + now + base::TimeDelta::FromMilliseconds(2000)); + observer3.WaitForUpdate(); + + EXPECT_THAT(observer3.updates(), testing::SizeIs(testing::Eq(2u))); + EXPECT_THAT( + observer3.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.25, 0.75))); + EXPECT_THAT( + observer3.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.75, 0.25))); + + EXPECT_THAT(observer1.updates(), testing::SizeIs(testing::Eq(0u))); + EXPECT_THAT(observer2.updates(), testing::SizeIs(testing::Eq(0u))); +} + +TEST_F(ComputePressureHostTest, AddObserver_ThirdPartyFrame) { + ComputePressureHost host_3p_impl( + kThirdPartyOrigin, /*is_supported=*/true, base::TimeDelta::FromSeconds(1), + /*did_connections_change*/ base::DoNothing()); + mojo::Remote<blink::mojom::ComputePressureHost> host_3p; + host_3p_impl.BindReceiver(main_frame_id_, + host_3p.BindNewPipeAndPassReceiver()); + auto host_3p_sync = std::make_unique<ComputePressureHostSync>(host_3p.get()); + FakeComputePressureObserver first_party_observer; + ASSERT_EQ(host_sync_->AddObserver( + kQuantization, first_party_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + FakeComputePressureObserver third_party_observer; + EXPECT_EQ(host_3p_sync->AddObserver( + kQuantization, third_party_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kSecurityError); + + base::Time now = base::Time::Now(); + + host_impl_->UpdateObservers({.cpu_utilization = 0.0, .cpu_speed = 0.0}, + now + base::TimeDelta::FromMilliseconds(1000)); + first_party_observer.WaitForUpdate(); + host_impl_->UpdateObservers({.cpu_utilization = 1.0, .cpu_speed = 1.0}, + now + base::TimeDelta::FromMilliseconds(2000)); + first_party_observer.WaitForUpdate(); + + EXPECT_THAT(first_party_observer.updates(), testing::SizeIs(testing::Eq(2u))); + EXPECT_THAT(first_party_observer.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.1, 0.25))); + EXPECT_THAT(first_party_observer.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.9, 0.75))); + + EXPECT_THAT(third_party_observer.updates(), testing::SizeIs(testing::Eq(0u))); +} + +TEST_F(ComputePressureHostTest, AddObserver_NoVisibility) { + test_rvh()->SimulateWasHidden(); + + FakeComputePressureObserver observer; + EXPECT_EQ(host_sync_->AddObserver(kQuantization, + observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + base::Time now = base::Time::Now(); + + // The first two updates should be blocked due to invisibility. + host_impl_->UpdateObservers({.cpu_utilization = 0.0, .cpu_speed = 0.0}, + now + base::TimeDelta::FromMilliseconds(1000)); + host_impl_->UpdateObservers({.cpu_utilization = 1.0, .cpu_speed = 1.0}, + now + base::TimeDelta::FromMilliseconds(2000)); + + test_rvh()->SimulateWasShown(); + + // The third update should be dispatched. It should not be rate-limited by the + // time proximity to the second update, because the second update is not + // dispatched. + host_impl_->UpdateObservers({.cpu_utilization = 1.0, .cpu_speed = 1.0}, + now + base::TimeDelta::FromMilliseconds(2100)); + observer.WaitForUpdate(); + + ASSERT_THAT(observer.updates(), testing::SizeIs(testing::Eq(1u))); + EXPECT_EQ(observer.updates()[0], + blink::mojom::ComputePressureState(0.9, 0.75)); +} + +TEST_F(ComputePressureHostTest, AddObserver_InvalidFrame) { + GlobalFrameRoutingId invalid_routing_id(main_rfh()->GetProcess()->GetID() + 1, + main_rfh()->GetRoutingID() + 1); + mojo::Remote<blink::mojom::ComputePressureHost> host_invalid; + host_impl_->BindReceiver(invalid_routing_id, + host_invalid.BindNewPipeAndPassReceiver()); + auto host_invalid_sync = + std::make_unique<ComputePressureHostSync>(host_invalid.get()); + FakeComputePressureObserver valid_observer; + ASSERT_EQ(host_sync_->AddObserver(kQuantization, + valid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + FakeComputePressureObserver invalid_observer; + EXPECT_EQ(host_invalid_sync->AddObserver( + kQuantization, invalid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kSecurityError); + + base::Time now = base::Time::Now(); + + host_impl_->UpdateObservers({.cpu_utilization = 0.0, .cpu_speed = 0.0}, + now + base::TimeDelta::FromMilliseconds(1000)); + valid_observer.WaitForUpdate(); + host_impl_->UpdateObservers({.cpu_utilization = 1.0, .cpu_speed = 1.0}, + now + base::TimeDelta::FromMilliseconds(2000)); + valid_observer.WaitForUpdate(); + + EXPECT_THAT(valid_observer.updates(), testing::SizeIs(testing::Eq(2u))); + EXPECT_THAT(valid_observer.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.1, 0.25))); + EXPECT_THAT(valid_observer.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.9, 0.75))); + + EXPECT_THAT(invalid_observer.updates(), testing::SizeIs(testing::Eq(0u))); +} + +TEST_F(ComputePressureHostTest, AddObserver_InvalidQuantization) { + FakeComputePressureObserver valid_observer; + ASSERT_EQ(host_sync_->AddObserver(kQuantization, + valid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + FakeComputePressureObserver invalid_observer; + blink::mojom::ComputePressureQuantization invalid_quantization( + std::vector<double>{-1.0}, std::vector<double>{0.5}); + + { + mojo::test::BadMessageObserver bad_message_observer; + EXPECT_EQ( + host_sync_->AddObserver(invalid_quantization, + invalid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kSecurityError); + EXPECT_EQ("Invalid quantization", bad_message_observer.WaitForBadMessage()); + } + + base::Time now = base::Time::Now(); + + host_impl_->UpdateObservers({.cpu_utilization = 0.0, .cpu_speed = 0.0}, + now + base::TimeDelta::FromMilliseconds(1000)); + valid_observer.WaitForUpdate(); + host_impl_->UpdateObservers({.cpu_utilization = 1.0, .cpu_speed = 1.0}, + now + base::TimeDelta::FromMilliseconds(2000)); + valid_observer.WaitForUpdate(); + + EXPECT_THAT(valid_observer.updates(), testing::SizeIs(testing::Eq(2u))); + EXPECT_THAT(valid_observer.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.1, 0.25))); + EXPECT_THAT(valid_observer.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.9, 0.75))); + + EXPECT_THAT(invalid_observer.updates(), testing::SizeIs(testing::Eq(0u))); +} + +TEST_F(ComputePressureHostTest, AddObserver_NotSupported) { + SetHostImpl(std::make_unique<ComputePressureHost>( + kTestOrigin, /*is_supported=*/false, base::TimeDelta::FromSeconds(1), + /*did_connections_change=*/base::DoNothing())); + + FakeComputePressureObserver observer; + EXPECT_EQ(host_sync_->AddObserver(kQuantization, + observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kNotSupported); +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_manager.cc b/content/browser/compute_pressure/compute_pressure_manager.cc new file mode 100644 index 0000000..f2729e7 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_manager.cc
@@ -0,0 +1,135 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/compute_pressure_manager.h" + +#include <tuple> +#include <utility> + +#include "base/bind.h" +#include "base/check_op.h" +#include "base/feature_list.h" +#include "base/sequence_checker.h" +#include "base/time/time.h" +#include "base/types/pass_key.h" +#include "content/browser/compute_pressure/compute_pressure_host.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/browser/compute_pressure/compute_pressure_sampler.h" +#include "content/browser/compute_pressure/cpu_probe.h" +#include "content/public/browser/global_routing_id.h" +#include "mojo/public/cpp/bindings/message.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "services/network/public/cpp/is_potentially_trustworthy.h" +#include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" + +namespace content { + +constexpr base::TimeDelta ComputePressureManager::kDefaultSamplingInterval; + +// static +std::unique_ptr<ComputePressureManager> ComputePressureManager::Create() { + return std::make_unique<ComputePressureManager>( + CpuProbe::Create(), ComputePressureManager::kDefaultSamplingInterval, + ComputePressureHost::kDefaultVisibleObserverRateLimit, + base::PassKey<ComputePressureManager>()); +} + +// static +std::unique_ptr<ComputePressureManager> +ComputePressureManager::CreateForTesting( + std::unique_ptr<CpuProbe> cpu_probe, + base::TimeDelta sampling_interval, + base::TimeDelta visible_observer_rate_limit) { + return std::make_unique<ComputePressureManager>( + std::move(cpu_probe), sampling_interval, visible_observer_rate_limit, + base::PassKey<ComputePressureManager>()); +} + +ComputePressureManager::ComputePressureManager( + std::unique_ptr<CpuProbe> cpu_probe, + base::TimeDelta sampling_interval, + base::TimeDelta visible_observer_rate_limit, + base::PassKey<ComputePressureManager>) + // base::Unretained usage is safe here because the callback is only run + // while `sampler_` is alive, and `sampler_` is owned by this instance. + : sampler_(std::move(cpu_probe), + sampling_interval, + base::BindRepeating(&ComputePressureManager::UpdateObservers, + base::Unretained(this))), + visible_observer_rate_limit_(visible_observer_rate_limit) {} + +ComputePressureManager::~ComputePressureManager() = default; + +void ComputePressureManager::BindReceiver( + url::Origin origin, + GlobalFrameRoutingId frame_id, + mojo::PendingReceiver<blink::mojom::ComputePressureHost> receiver) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(frame_id); + + if (!base::FeatureList::IsEnabled(blink::features::kComputePressure)) { + mojo::ReportBadMessage("Compute Pressure not enabled"); + return; + } + + if (!network::IsOriginPotentiallyTrustworthy(origin)) { + mojo::ReportBadMessage("Compute Pressure access from an insecure origin"); + return; + } + + auto it = hosts_by_origin_.lower_bound(origin); + if (it == hosts_by_origin_.end() || it->first != origin) { + // base::Unretained use is safe here because the callback will only be Run() + // while the ComputePressureHost instance is alive, and the + // ComputePressureHost instance is owned by this ComputePressureManager + // indirectly, via `hosts_by_origin_`. + it = hosts_by_origin_.emplace_hint( + it, std::piecewise_construct, std::forward_as_tuple(origin), + std::forward_as_tuple( + origin, sampler_.has_probe(), visible_observer_rate_limit_, + base::BindRepeating( + &ComputePressureManager::DidHostConnectionsChange, + base::Unretained(this)))); + } + + ComputePressureHost& host = it->second; + DCHECK_EQ(origin, host.origin()); + host.BindReceiver(frame_id, std::move(receiver)); +} + +void ComputePressureManager::UpdateObservers(ComputePressureSample sample) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + base::Time sample_time = base::Time::Now(); + for (auto& origin_and_host : hosts_by_origin_) + origin_and_host.second.UpdateObservers(sample, sample_time); +} + +void ComputePressureManager::DidHostConnectionsChange( + ComputePressureHost* host) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(host); + DCHECK(hosts_by_origin_.count(host->origin())); + DCHECK_EQ(&hosts_by_origin_.at(host->origin()), host); + + if (host->has_observers()) { + hosts_with_observers_.insert(host->origin()); + sampler_.EnsureStarted(); + } else { + hosts_with_observers_.erase(host->origin()); + if (hosts_with_observers_.empty()) { + // If there are no observers left, we can save CPU cycles (and therefore + // power) by stopping the sampler. + sampler_.Stop(); + } + + if (!host->has_receivers()) { + // `host` is no longer valid after the erase. + hosts_by_origin_.erase(host->origin()); + } + } +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_manager.h b/content/browser/compute_pressure/compute_pressure_manager.h new file mode 100644 index 0000000..bd9b6c6 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_manager.h
@@ -0,0 +1,103 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_MANAGER_H_ +#define CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_MANAGER_H_ + +#include <map> +#include <memory> +#include <set> + +#include "base/sequence_checker.h" +#include "base/thread_annotations.h" +#include "base/time/time.h" +#include "base/types/pass_key.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/browser/compute_pressure/compute_pressure_sampler.h" +#include "content/common/content_export.h" +#include "content/public/browser/global_routing_id.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom-forward.h" +#include "url/origin.h" + +namespace content { + +class CpuProbe; +class ComputePressureHost; + +// Drives the Compute Pressure API implementation for a user profile. +// +// Coordinates between the objects responsible for serving mojo requests from +// the renderer side of the API implementation, and the objects responsible for +// collecting compute pressure information from the underlying operating system. +// +// Each StoragePartitionImpl owns exactly one instance of this class. +// +// Instances are not thread-safe and should be used on the same sequence. +class CONTENT_EXPORT ComputePressureManager { + public: + // The sampling interval must be smaller or equal to the rate-limit for + // observer updates. + static constexpr base::TimeDelta kDefaultSamplingInterval = + base::TimeDelta::FromSeconds(1); + + // Factory method for production instances. + static std::unique_ptr<ComputePressureManager> Create(); + + // Factory method with dependency injection support for testing. + static std::unique_ptr<ComputePressureManager> CreateForTesting( + std::unique_ptr<CpuProbe> cpu_probe, + base::TimeDelta sampling_interval, + base::TimeDelta visible_observer_rate_limit); + + // The constructor is public for internal use of std::make_unique. + // + // Production code should call ComputePressureManager::Create(). Testing code + // should call ComputePressureManager::CreateForTesting(). + explicit ComputePressureManager(std::unique_ptr<CpuProbe> cpu_probe, + base::TimeDelta sampling_interval, + base::TimeDelta visible_observer_rate_limit, + base::PassKey<ComputePressureManager>); + ~ComputePressureManager(); + + ComputePressureManager(const ComputePressureManager&) = delete; + ComputePressureManager& operator=(const ComputePressureManager&) = delete; + + void BindReceiver( + url::Origin origin, + GlobalFrameRoutingId frame_id, + mojo::PendingReceiver<blink::mojom::ComputePressureHost> receiver); + + // Used by tests that pass in a FakeCpuProbe that they need to direct. + CpuProbe* cpu_probe_for_testing() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return sampler_.cpu_probe_for_testing(); + } + + private: + // Called periodically by ComputePressureSampler. + void UpdateObservers(ComputePressureSample sample); + + // Called by owned ComputePressureHosts to report frame / observer changes. + void DidHostConnectionsChange(ComputePressureHost* host); + + SEQUENCE_CHECKER(sequence_checker_); + + ComputePressureSampler sampler_ GUARDED_BY_CONTEXT(sequence_checker_); + + // Passed to ComputePressureHost. + const base::TimeDelta visible_observer_rate_limit_; + + // Keeps track of options for each observers' origin. Only one per origin + // allowed. + std::map<url::Origin, ComputePressureHost> hosts_by_origin_ + GUARDED_BY_CONTEXT(sequence_checker_); + + // Used to determine when it's safe to stop the ComputePressureSampler. + std::set<url::Origin> hosts_with_observers_; +}; + +} // namespace content + +#endif // CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_MANAGER_H_
diff --git a/content/browser/compute_pressure/compute_pressure_manager_unittest.cc b/content/browser/compute_pressure/compute_pressure_manager_unittest.cc new file mode 100644 index 0000000..529b199 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_manager_unittest.cc
@@ -0,0 +1,237 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/compute_pressure_manager.h" + +#include <memory> +#include <utility> + +#include "base/test/scoped_feature_list.h" +#include "content/browser/compute_pressure/compute_pressure_test_support.h" +#include "content/public/browser/global_routing_id.h" +#include "content/test/fake_mojo_message_dispatch_context.h" +#include "content/test/test_render_frame_host.h" +#include "content/test/test_web_contents.h" +#include "mojo/public/cpp/bindings/remote.h" +#include "mojo/public/cpp/test_support/test_utils.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" + +namespace content { + +class ComputePressureManagerTest : public RenderViewHostImplTestHarness { + public: + ComputePressureManagerTest() { + scoped_feature_list_.InitAndEnableFeature( + blink::features::kComputePressure); + } + + void SetUp() override { + RenderViewHostImplTestHarness::SetUp(); + NavigateAndCommit(kTestUrl); + + SetManager(ComputePressureManager::CreateForTesting( + std::make_unique<FakeCpuProbe>(), base::TimeDelta::FromMilliseconds(1), + base::TimeDelta::FromMilliseconds(1))); + } + + void TearDown() override { + // Get the CpuProbe freed. + manager_.reset(); + task_environment()->RunUntilIdle(); + + RenderViewHostImplTestHarness::TearDown(); + } + + void SetManager(std::unique_ptr<ComputePressureManager> new_manager) { + manager_ = std::move(new_manager); + int process_id = main_rfh()->GetProcess()->GetID(); + int routing_id = main_rfh()->GetRoutingID(); + main_frame_id_ = GlobalFrameRoutingId(process_id, routing_id); + + main_host_.reset(); + manager_->BindReceiver(kTestOrigin, main_frame_id_, + main_host_.BindNewPipeAndPassReceiver()); + main_host_sync_ = + std::make_unique<ComputePressureHostSync>(main_host_.get()); + } + + protected: + const GURL kTestUrl{"https://example.com/compute_pressure.html"}; + const url::Origin kTestOrigin = + url::Origin::Create(GURL("https://example.com")); + const url::Origin kInsecureOrigin = + url::Origin::Create(GURL("http://example.com")); + const url::Origin kThirdPartyOrigin = + url::Origin::Create(GURL("https://other.com")); + + // Quantization scheme used in most tests. + const blink::mojom::ComputePressureQuantization kQuantization = { + {0.2, 0.5, 0.8}, + {0.5}}; + + base::test::ScopedFeatureList scoped_feature_list_; + + GlobalFrameRoutingId main_frame_id_; + // This member is a std::unique_ptr instead of a plain ComputePressureManager + // so it can be replaced inside tests. + std::unique_ptr<ComputePressureManager> manager_; + mojo::Remote<blink::mojom::ComputePressureHost> main_host_; + std::unique_ptr<ComputePressureHostSync> main_host_sync_; +}; + +TEST_F(ComputePressureManagerTest, OneObserver) { + FakeComputePressureObserver observer; + ASSERT_EQ(main_host_sync_->AddObserver(kQuantization, + observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + observer.WaitForUpdate(); + EXPECT_THAT(observer.updates(), testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT( + observer.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.35, 0.75))); +} + +TEST_F(ComputePressureManagerTest, ThreeObservers) { + FakeComputePressureObserver observer1; + ASSERT_EQ(main_host_sync_->AddObserver(kQuantization, + observer1.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + FakeComputePressureObserver observer2; + ASSERT_EQ(main_host_sync_->AddObserver(kQuantization, + observer2.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + FakeComputePressureObserver observer3; + ASSERT_EQ(main_host_sync_->AddObserver(kQuantization, + observer3.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); + + FakeComputePressureObserver::WaitForUpdates( + {&observer1, &observer2, &observer3}); + + EXPECT_THAT(observer1.updates(), testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT( + observer1.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.35, 0.75))); + EXPECT_THAT(observer2.updates(), testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT( + observer2.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.35, 0.75))); + EXPECT_THAT(observer3.updates(), testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT( + observer3.updates(), + testing::Contains(blink::mojom::ComputePressureState(0.35, 0.75))); +} + +TEST_F(ComputePressureManagerTest, AddObserver_ThirdPartyFrame) { + mojo::Remote<blink::mojom::ComputePressureHost> third_party_host; + manager_->BindReceiver(kThirdPartyOrigin, main_frame_id_, + third_party_host.BindNewPipeAndPassReceiver()); + auto third_party_host_sync = + std::make_unique<ComputePressureHostSync>(third_party_host.get()); + + FakeComputePressureObserver third_party_observer; + EXPECT_EQ(third_party_host_sync->AddObserver( + kQuantization, third_party_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kSecurityError); + FakeComputePressureObserver first_party_observer; + EXPECT_EQ(main_host_sync_->AddObserver( + kQuantization, first_party_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); +} + +TEST_F(ComputePressureManagerTest, AddObserver_NoVisibility) { + test_rvh()->SimulateWasHidden(); + + FakeComputePressureObserver observer; + EXPECT_EQ(main_host_sync_->AddObserver(kQuantization, + observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); +} + +TEST_F(ComputePressureManagerTest, AddObserver_InvalidFrame) { + GlobalFrameRoutingId invalid_routing_id(main_rfh()->GetProcess()->GetID() + 1, + main_rfh()->GetRoutingID() + 1); + mojo::Remote<blink::mojom::ComputePressureHost> invalid_host; + manager_->BindReceiver(kTestOrigin, invalid_routing_id, + invalid_host.BindNewPipeAndPassReceiver()); + auto invalid_host_sync = + std::make_unique<ComputePressureHostSync>(invalid_host.get()); + FakeComputePressureObserver invalid_observer; + EXPECT_EQ(invalid_host_sync->AddObserver( + kQuantization, invalid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kSecurityError); + FakeComputePressureObserver valid_observer; + EXPECT_EQ(main_host_sync_->AddObserver( + kQuantization, valid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); +} + +TEST_F(ComputePressureManagerTest, AddObserver_InvalidQuantization) { + FakeComputePressureObserver invalid_observer; + blink::mojom::ComputePressureQuantization invalid_quantization( + std::vector<double>{-1.0}, std::vector<double>{0.5}); + + { + mojo::test::BadMessageObserver bad_message_observer; + EXPECT_EQ( + main_host_sync_->AddObserver( + invalid_quantization, invalid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kSecurityError); + EXPECT_EQ("Invalid quantization", bad_message_observer.WaitForBadMessage()); + } + + FakeComputePressureObserver valid_observer; + EXPECT_EQ(main_host_sync_->AddObserver( + kQuantization, valid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); +} + +TEST_F(ComputePressureManagerTest, AddObserver_InsecureOrigin) { + { + FakeMojoMessageDispatchContext fake_dispatch_context; + mojo::test::BadMessageObserver bad_message_observer; + mojo::Remote<blink::mojom::ComputePressureHost> insecure_host; + manager_->BindReceiver(kInsecureOrigin, main_frame_id_, + insecure_host.BindNewPipeAndPassReceiver()); + EXPECT_EQ("Compute Pressure access from an insecure origin", + bad_message_observer.WaitForBadMessage()); + } + + FakeComputePressureObserver valid_observer; + EXPECT_EQ(main_host_sync_->AddObserver( + kQuantization, valid_observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kOk); +} + +TEST_F(ComputePressureManagerTest, AddObserver_NoProbe) { + SetManager(ComputePressureManager::CreateForTesting( + /*cpu_probe=*/nullptr, base::TimeDelta::FromMilliseconds(1), + base::TimeDelta::FromMilliseconds(1))); + + FakeComputePressureObserver observer; + EXPECT_EQ(main_host_sync_->AddObserver(kQuantization, + observer.BindNewPipeAndPassRemote()), + blink::mojom::ComputePressureStatus::kNotSupported); +} + +TEST_F(ComputePressureManagerTest, AddObserver_NoFeature) { + scoped_feature_list_.Reset(); + scoped_feature_list_.InitAndDisableFeature(blink::features::kComputePressure); + + { + FakeMojoMessageDispatchContext fake_dispatch_context; + mojo::test::BadMessageObserver bad_message_observer; + mojo::Remote<blink::mojom::ComputePressureHost> insecure_host; + manager_->BindReceiver(kInsecureOrigin, main_frame_id_, + insecure_host.BindNewPipeAndPassReceiver()); + EXPECT_EQ("Compute Pressure not enabled", + bad_message_observer.WaitForBadMessage()); + } +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_quantizer.cc b/content/browser/compute_pressure/compute_pressure_quantizer.cc new file mode 100644 index 0000000..58b6142 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_quantizer.cc
@@ -0,0 +1,139 @@ +// Copyright 2021 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 <vector> + +#include "base/sequence_checker.h" +#include "content/browser/compute_pressure/compute_pressure_quantizer.h" + +namespace content { + +ComputePressureQuantizer::ComputePressureQuantizer() = default; + +ComputePressureQuantizer::~ComputePressureQuantizer() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +} + +// static +bool ComputePressureQuantizer::IsValid( + const blink::mojom::ComputePressureQuantization& quantization) { + if (quantization.cpu_utilization_thresholds.size() > + blink::mojom::kMaxComputePressureCpuUtilizationThresholds) { + return false; + } + if (!ValueQuantizer::IsValid(quantization.cpu_utilization_thresholds)) + return false; + + if (quantization.cpu_speed_thresholds.size() > + blink::mojom::kMaxComputePressureCpuSpeedThresholds) { + return false; + } + if (!ValueQuantizer::IsValid(quantization.cpu_speed_thresholds)) + return false; + + return true; +} + +bool ComputePressureQuantizer::IsSame( + const blink::mojom::ComputePressureQuantization& quantization) const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(ComputePressureQuantizer::IsValid(quantization)); + + if (!cpu_utilization_quantizer_.IsSame( + quantization.cpu_utilization_thresholds)) { + return false; + } + if (!cpu_speed_quantizer_.IsSame(quantization.cpu_speed_thresholds)) + return false; + + return true; +} + +blink::mojom::ComputePressureState ComputePressureQuantizer::Quantize( + ComputePressureSample sample) const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + blink::mojom::ComputePressureState state; + state.cpu_utilization = + cpu_utilization_quantizer_.Quantize(sample.cpu_utilization); + state.cpu_speed = cpu_speed_quantizer_.Quantize(sample.cpu_speed); + + return state; +} + +void ComputePressureQuantizer::Assign( + blink::mojom::ComputePressureQuantizationPtr quantization) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(ComputePressureQuantizer::IsValid(*quantization)); + + cpu_utilization_quantizer_.Assign( + std::move(quantization->cpu_utilization_thresholds)); + cpu_speed_quantizer_.Assign(std::move(quantization->cpu_speed_thresholds)); +} + +ComputePressureQuantizer::ValueQuantizer::ValueQuantizer() = default; + +ComputePressureQuantizer::ValueQuantizer::~ValueQuantizer() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +} + +// static +bool ComputePressureQuantizer::ValueQuantizer::IsValid( + const std::vector<double>& thresholds) { + double last_threshold = 0.0; + + for (double threshold : thresholds) { + if (threshold <= 0.0 || threshold >= 1.0) + return false; + + if (threshold <= last_threshold) + return false; + + last_threshold = threshold; + } + return true; +} + +bool ComputePressureQuantizer::ValueQuantizer::IsSame( + const std::vector<double>& thresholds) const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(ValueQuantizer::IsValid(thresholds)); + + if (thresholds_.size() != thresholds.size()) + return false; + + for (size_t i = 0; i < thresholds_.size(); ++i) { + if (std::abs(thresholds_[i] - thresholds[i]) >= 0.00001) + return false; + } + return true; +} + +double ComputePressureQuantizer::ValueQuantizer::Quantize(double value) const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + double lower_bound = 0.0; + double upper_bound = 1.0; + + for (double threshold : thresholds_) { + DCHECK_GT(threshold, lower_bound) << "thresholds_ is not sorted"; + if (value < threshold) { + upper_bound = threshold; + break; + } + lower_bound = threshold; + } + + return (lower_bound + upper_bound) / 2; +} + +void ComputePressureQuantizer::ValueQuantizer::Assign( + std::vector<double> thresholds) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(ValueQuantizer::IsValid(thresholds)); + + thresholds_ = std::move(thresholds); +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_quantizer.h b/content/browser/compute_pressure/compute_pressure_quantizer.h new file mode 100644 index 0000000..4c6071f --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_quantizer.h
@@ -0,0 +1,94 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_QUANTIZER_H_ +#define CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_QUANTIZER_H_ + +#include <vector> + +#include "base/callback_forward.h" +#include "base/sequence_checker.h" +#include "base/thread_annotations.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/common/content_export.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" + +namespace content { + +// Quantizes compute pressure data for an origin. +// +// See blink::mojom::ComputePressureQuantization for a descripion of the +// quantization scheme. The scheme converts a high-entropy ComputePressureSample +// into a low-entropy blink::mojom::ComputePressureState, which minimizes the +// amount of information exposed to a Web page that uses the Compute Pressure +// API. +// +// This class is not thread-safe, so each instance must be used on one sequence. +class CONTENT_EXPORT ComputePressureQuantizer { + public: + // Creates a quantizer with the single sub-interval [0, 1]. + // + // Until Assign() is called, all values will be quantized to the same value. + ComputePressureQuantizer(); + ~ComputePressureQuantizer(); + + ComputePressureQuantizer(const ComputePressureQuantizer&) = delete; + ComputePressureQuantizer& operator=(const ComputePressureQuantizer&) = delete; + + // True iff `quantization` is a valid compute pressure quantization scheme. + static bool IsValid( + const blink::mojom::ComputePressureQuantization& quantization); + + // True if this quantizer's scheme is the same as `quantization`. + // + // This is a bit more complicated than element-wise vector equality to allow + // for floating-point precision errors, such as 0.5 != 0.2 + 0.3. + // + // `quantization` must be valid. + bool IsSame( + const blink::mojom::ComputePressureQuantization& quantization) const; + + // Overwrites the quantization scheme used by this quantizer. + void Assign(blink::mojom::ComputePressureQuantizationPtr quantization); + + // Quantizes `sample` using the current quantization scheme. + blink::mojom::ComputePressureState Quantize( + ComputePressureSample sample) const; + + private: + // Quantizes a single value in compute pressure data. + class ValueQuantizer { + public: + ValueQuantizer(); + ~ValueQuantizer(); + + ValueQuantizer(const ValueQuantizer&) = delete; + ValueQuantizer& operator=(const ValueQuantizer&) = delete; + + static bool IsValid(const std::vector<double>& thresholds); + bool IsSame(const std::vector<double>& thresholds) const; + double Quantize(double value) const; + void Assign(std::vector<double> thresholds); + + private: + SEQUENCE_CHECKER(sequence_checker_); + + // The array of thresholds passes the IsValid() check. + // + // This means that the array is sorted and does not include 0.0 or 1.0. An + // empty array is a valid quantizing scheme that transforms every input to + // 0.5. + std::vector<double> thresholds_ GUARDED_BY_CONTEXT(sequence_checker_); + }; + + SEQUENCE_CHECKER(sequence_checker_); + + ValueQuantizer cpu_utilization_quantizer_ + GUARDED_BY_CONTEXT(sequence_checker_); + ValueQuantizer cpu_speed_quantizer_ GUARDED_BY_CONTEXT(sequence_checker_); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_QUANTIZER_H_
diff --git a/content/browser/compute_pressure/compute_pressure_quantizer_unittest.cc b/content/browser/compute_pressure/compute_pressure_quantizer_unittest.cc new file mode 100644 index 0000000..ddcae6f --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_quantizer_unittest.cc
@@ -0,0 +1,128 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/compute_pressure_quantizer.h" + +#include <utility> +#include <vector> + +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/browser/compute_pressure/compute_pressure_sampler.h" +#include "content/browser/compute_pressure/compute_pressure_test_support.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" + +namespace content { + +TEST(ComputePressureQuantizer, IsValid_Valid) { + std::vector<blink::mojom::ComputePressureQuantization> valid_cases = { + {{}, {}}, + {{0.5}, {0.5}}, + {{0.2, 0.5, 0.8}, {0.5}}, + }; + + for (const auto& quantization : valid_cases) { + EXPECT_TRUE(ComputePressureQuantizer::IsValid(quantization)); + } +} + +TEST(ComputePressureQuantizer, IsValid_Invalid) { + std::vector<blink::mojom::ComputePressureQuantization> invalid_cases = { + {{0.2, 0.3, 0.4, 0.5}, {0.5}}, // Too many utilization thresholds. + {{0.5}, {0.2, 0.5, 0.8}}, // Too many speed thresholds. + {{0.2, 0.8, 0.5}, {0.5}}, // Incorrectly sorted thresholds. + {{-1.0}, {0.5}}, // Threshold outside range. + {{0.0}, {0.5}}, + {{1.0}, {0.5}}, + {{2.0}, {0.5}}, + {{0.5}, {-1.0}}, + {{0.5}, {0.0}}, + {{0.5}, {1.0}}, + {{0.5}, {2.0}}, + }; + + for (const auto& quantization : invalid_cases) { + EXPECT_FALSE(ComputePressureQuantizer::IsValid(quantization)); + } +} + +TEST(ComputePressureQuantizer, IsSame_True) { + std::vector<std::pair<blink::mojom::ComputePressureQuantization, + blink::mojom::ComputePressureQuantization>> + true_cases = { + {{{0.1}, {0.2}}, {{0.1}, {0.2}}}, + {{{0.2, 0.5, 0.8}, {0.5}}, {{0.2, 0.5, 0.8}, {0.5}}}, + {{{0.3}, {0.2}}, {{0.1 + 0.1 + 0.1}, {0.1 + 0.1}}}, + }; + + for (const auto& quantizations : true_cases) { + ComputePressureQuantizer quantizer; + quantizer.Assign(quantizations.first.Clone()); + EXPECT_TRUE(quantizer.IsSame(quantizations.second)); + } +} + +TEST(ComputePressureQuantizer, IsSame_False) { + std::vector<std::pair<blink::mojom::ComputePressureQuantization, + blink::mojom::ComputePressureQuantization>> + false_cases = { + {{{0.1}, {0.2}}, {{0.2}, {0.2}}}, + {{{0.1}, {0.2}}, {{0.1}, {0.3}}}, + {{{0.1, 0.15}, {0.2}}, {{0.1}, {0.2}}}, + {{{0.1}, {}}, {{0.1}, {0.2}}}, + {{{0.1}, {0.2}}, {{0.1, 0.15}, {0.2}}}, + {{{0.1}, {0.2}}, {{0.1}, {}}}, + {{{0.1}, {0.2}}, {{0.101}, {0.2}}}, + {{{0.1}, {0.2}}, {{0.1}, {0.201}}}, + {{{0.2, 0.5, 0.8}, {0.5}}, {{0.2, 0.6, 0.8}, {0.5}}}, + {{{0.2, 0.5, 0.8}, {0.5}}, {{0.2, 0.5, 0.9}, {0.5}}}, + }; + + for (const auto& quantizations : false_cases) { + ComputePressureQuantizer quantizer; + quantizer.Assign(quantizations.first.Clone()); + EXPECT_FALSE(quantizer.IsSame(quantizations.second)); + } +} + +TEST(ComputePressureQuantizer, Quantize_Empty) { + ComputePressureQuantizer quantizer; + auto empty_quantization_ptr = + blink::mojom::ComputePressureQuantization::New(); + quantizer.Assign(std::move(empty_quantization_ptr)); + + EXPECT_EQ(blink::mojom::ComputePressureState(0.5, 0.5), + quantizer.Quantize({.cpu_utilization = 0.0, .cpu_speed = 0.0})); + EXPECT_EQ(blink::mojom::ComputePressureState(0.5, 0.5), + quantizer.Quantize({.cpu_utilization = 1.0, .cpu_speed = 1.0})); +} + +TEST(ComputePressureQuantizer, Quantize) { + ComputePressureQuantizer quantizer; + auto quantization_ptr = blink::mojom::ComputePressureQuantization::New( + std::vector<double>{0.2, 0.5, 0.8}, std::vector<double>{0.5}); + quantizer.Assign(std::move(quantization_ptr)); + + std::vector< + std::pair<ComputePressureSample, blink::mojom::ComputePressureState>> + test_cases = { + {{0.0, 0.0}, {0.1, 0.25}}, {{1.0, 0.0}, {0.9, 0.25}}, + {{0.0, 1.0}, {0.1, 0.75}}, {{1.0, 1.0}, {0.9, 0.75}}, + {{0.1, 0.1}, {0.1, 0.25}}, {{0.19, 0.19}, {0.1, 0.25}}, + {{0.21, 0.21}, {0.35, 0.25}}, {{0.49, 0.49}, {0.35, 0.25}}, + {{0.51, 0.51}, {0.65, 0.75}}, {{0.79, 0.79}, {0.65, 0.75}}, + {{0.81, 0.81}, {0.9, 0.75}}, {{0.99, 0.99}, {0.9, 0.75}}, + }; + + for (const auto& test_case : test_cases) { + ComputePressureSample input = test_case.first; + blink::mojom::ComputePressureState expected = test_case.second; + blink::mojom::ComputePressureState output = quantizer.Quantize(input); + + EXPECT_DOUBLE_EQ(expected.cpu_utilization, output.cpu_utilization) << input; + EXPECT_DOUBLE_EQ(expected.cpu_speed, output.cpu_speed) << input; + } +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_sample.h b/content/browser/compute_pressure/compute_pressure_sample.h new file mode 100644 index 0000000..b6aa6e0 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_sample.h
@@ -0,0 +1,29 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_SAMPLE_H_ +#define CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_SAMPLE_H_ + +#include "content/common/content_export.h" + +namespace content { + +// Represents availability of compute resources measured over a period of time. +struct CONTENT_EXPORT ComputePressureSample { + // Average utilization of all CPU cores. + // + // Values use a scale from 0.0 (no utilization) to 1.0 (100% utilization). + double cpu_utilization; + + // Average normalized clock speed over all CPU cores. + // + // The normalized clock speed for each CPU core uses a piecewise-linear scale + // from 0.0 (minimum clock speed) to 0.5 (base clock speed) to 1.0 (maximum + // clock-speed). + double cpu_speed; +}; + +} // namespace content + +#endif // CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_SAMPLE_H_
diff --git a/content/browser/compute_pressure/compute_pressure_sampler.cc b/content/browser/compute_pressure/compute_pressure_sampler.cc new file mode 100644 index 0000000..80eba82 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_sampler.cc
@@ -0,0 +1,118 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/compute_pressure_sampler.h" + +#include <utility> + +#include "base/bind.h" +#include "base/callback_forward.h" +#include "base/location.h" +#include "base/memory/scoped_refptr.h" +#include "base/sequence_checker.h" +#include "base/sequenced_task_runner.h" +#include "base/task/post_task.h" +#include "base/task/task_traits.h" +#include "base/task/thread_pool.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "base/time/time.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/browser/compute_pressure/cpu_probe.h" +#include "content/public/browser/browser_thread.h" + +namespace content { + +namespace { + +scoped_refptr<base::SequencedTaskRunner> CreateProbeTaskRunner() { + // While some samples can be collected without doing blocking operations, + // this isn't guaranteed on all operating systems. + return base::ThreadPool::CreateSequencedTaskRunner( + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); +} + +} // namespace + +ComputePressureSampler::ComputePressureSampler( + std::unique_ptr<CpuProbe> probe, + base::TimeDelta sampling_interval, + base::RepeatingCallback<void(ComputePressureSample)> sampling_callback) + : probe_task_runner_(CreateProbeTaskRunner()), + probe_(std::move(probe)), + sampling_interval_(sampling_interval), + sampling_callback_(std::move(sampling_callback)) { + DCHECK(sampling_callback_); +} + +ComputePressureSampler::~ComputePressureSampler() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + probe_task_runner_->DeleteSoon(FROM_HERE, std::move(probe_)); +} + +void ComputePressureSampler::EnsureStarted() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(has_probe()) << __func__ + << " should not be called if has_probe() returns false"; + + DCHECK(probe_); + if (timer_.IsRunning()) + return; + + DCHECK(!got_probe_baseline_) << "got_probe_baseline_ incorrectly reset"; + + // Schedule the first CpuProbe update right away. This update's result will + // not be reported, thanks to the accounting done by `got_probe_baseline_`. + UpdateProbe(); + + // base::Unretained usage is safe here because base::RepeatingTimer guarantees + // that its callback will not be called after it goes out of scope. + timer_.Start(FROM_HERE, sampling_interval_, + base::BindRepeating(&ComputePressureSampler::UpdateProbe, + base::Unretained(this))); +} + +void ComputePressureSampler::Stop() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + timer_.AbandonAndStop(); + got_probe_baseline_ = false; +} + +void ComputePressureSampler::UpdateProbe() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(has_probe()); + + // Raw CpuProbe pointer usage is safe here because the CpuProbe instance will + // be destroyed by queueing a task on `probe_task_runner_`. That task must get + // queued after this task. + probe_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce( + [](CpuProbe* probe) -> ComputePressureSample { + probe->Update(); + return probe->LastSample(); + }, + probe_.get()), + base::BindOnce(&ComputePressureSampler::DidUpdateProbe, + weak_factory_.GetWeakPtr())); +} + +void ComputePressureSampler::DidUpdateProbe(ComputePressureSample sample) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // Don't report the update result if Stop() was called. + if (!timer_.IsRunning()) + return; + + // Don't report the first update result. + if (!got_probe_baseline_) { + got_probe_baseline_ = true; + return; + } + + sampling_callback_.Run(sample); +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_sampler.h b/content/browser/compute_pressure/compute_pressure_sampler.h new file mode 100644 index 0000000..4ce7752 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_sampler.h
@@ -0,0 +1,108 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_SAMPLER_H_ +#define CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_SAMPLER_H_ + +#include <memory> + +#include "base/callback.h" +#include "base/callback_forward.h" +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner.h" +#include "base/thread_annotations.h" +#include "base/timer/timer.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/common/content_export.h" + +namespace content { + +class CpuProbe; + +// Drives the process that measures the compute pressure state. +// +// Responsible for invoking the platform-specific measurement code in a CpuProbe +// implementation at regular intervals, and for straddling between sequences to +// meet the CpuProbe requirements. +// +// Instances are not thread-safe. They must be used on the same sequence. +// +// Each instance is owned by a ComputePressureManager. +class CONTENT_EXPORT ComputePressureSampler { + public: + // The caller must ensure that `cpu_probe` outlives this instance. Production + // code should pass CpuProbe::Create(). + // + // `sampling_interval` is exposed to avoid idling in tests. Production code + // should pass `kDefaultSamplingInterval`. + // + // `sampling_callback` is called regularly every `sampling_interval` while the + // sampler is started. + explicit ComputePressureSampler( + std::unique_ptr<CpuProbe> cpu_probe, + base::TimeDelta sampling_interval, + base::RepeatingCallback<void(ComputePressureSample)> sampling_callback); + ~ComputePressureSampler(); + + bool has_probe() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return probe_ != nullptr; + } + + // Idempotent. Must only be called if has_probe() returns true. + // + // After this method is called, the sampling callback passsed to the + // constructor will be called regularly. + void EnsureStarted(); + + // Idempotent. + void Stop(); + + // Used by tests that pass in a FakeCpuProbe that they need to direct. + CpuProbe* cpu_probe_for_testing() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return probe_.get(); + } + + private: + // Called periodically while the sampler is running. + void UpdateProbe(); + // Called after the CpuProbe is updated. + void DidUpdateProbe(ComputePressureSample sample); + + SEQUENCE_CHECKER(sequence_checker_); + + // A sequence that can execute methods on the CpuProbe instance. + const scoped_refptr<base::SequencedTaskRunner> probe_task_runner_; + + // Methods on the underlying probe must be executed on `probe_task_runner_`. + // + // Constant between the sampler's construction and destruction. + std::unique_ptr<CpuProbe> probe_ GUARDED_BY_CONTEXT(sequence_checker_); + + // Drives repeated sampling. + base::RepeatingTimer timer_ GUARDED_BY_CONTEXT(sequence_checker_); + const base::TimeDelta sampling_interval_ + GUARDED_BY_CONTEXT(sequence_checker_); + + // Called with each sample reading. + base::RepeatingCallback<void(ComputePressureSample)> sampling_callback_ + GUARDED_BY_CONTEXT(sequence_checker_); + + // True if the CpuProbe state will be reported after the next update. + // + // The ComputePressureSample reported by many CpuProbe implementations relies + // on the differences observed between two Update() calls. For this reason, + // the ComputePressureSample reported after a first Update() call is not + // reported via `sampling_callback_`. + bool got_probe_baseline_ = false; + + base::WeakPtrFactory<ComputePressureSampler> weak_factory_ + GUARDED_BY_CONTEXT(sequence_checker_){this}; +}; + +} // namespace content + +#endif // CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_SAMPLER_H_
diff --git a/content/browser/compute_pressure/compute_pressure_sampler_unittest.cc b/content/browser/compute_pressure/compute_pressure_sampler_unittest.cc new file mode 100644 index 0000000..3fa0ea6 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_sampler_unittest.cc
@@ -0,0 +1,243 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/compute_pressure_sampler.h" + +#include <cstddef> +#include <memory> +#include <utility> + +#include "base/bind.h" +#include "base/check_op.h" +#include "base/run_loop.h" +#include "base/sequence_checker.h" +#include "base/test/bind.h" +#include "base/test/task_environment.h" +#include "base/thread_annotations.h" +#include "base/threading/platform_thread.h" +#include "base/threading/scoped_blocking_call.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/browser/compute_pressure/compute_pressure_test_support.h" +#include "content/browser/compute_pressure/cpu_probe.h" +#include "content/public/test/browser_task_environment.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" + +namespace content { + +class ComputePressureSamplerTest : public testing::Test { + public: + ComputePressureSamplerTest() + : sampler_(std::make_unique<ComputePressureSampler>( + std::make_unique<FakeCpuProbe>(), + base::TimeDelta::FromMilliseconds(1), + base::BindRepeating(&ComputePressureSamplerTest::SamplerCallback, + base::Unretained(this)))) {} + + void WaitForUpdate() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + base::RunLoop run_loop; + SetNextUpdateCallback(run_loop.QuitClosure()); + run_loop.Run(); + } + + // Only valid if `sampler_` uses a FakeCpuProbe. This is guaranteed if + // `sampler_` is not replaced during the test. + FakeCpuProbe& cpu_probe() { + auto* cpu_probe = + static_cast<FakeCpuProbe*>(sampler_->cpu_probe_for_testing()); + DCHECK(cpu_probe); + return *cpu_probe; + } + + void SamplerCallback(ComputePressureSample sample) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + samples_.push_back(sample); + if (update_callback_) { + std::move(update_callback_).Run(); + update_callback_.Reset(); + } + } + + protected: + SEQUENCE_CHECKER(sequence_checker_); + + base::test::TaskEnvironment task_environment_; + + // This member is a std::unique_ptr instead of a plain ComputePressureSampler + // so it can be replaced inside tests. + std::unique_ptr<ComputePressureSampler> sampler_; + + // The samples reported by the callback. + std::vector<ComputePressureSample> samples_ + GUARDED_BY_CONTEXT(sequence_checker_); + + private: + void SetNextUpdateCallback(base::OnceClosure callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!update_callback_) + << __func__ << " already called before update received"; + update_callback_ = std::move(callback); + } + + // Used to implement WaitForUpdate(). + base::OnceClosure update_callback_ GUARDED_BY_CONTEXT(sequence_checker_); +}; + +TEST_F(ComputePressureSamplerTest, EnsureStarted) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + sampler_->EnsureStarted(); + WaitForUpdate(); + + EXPECT_THAT(samples_, testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT(samples_, testing::Contains(ComputePressureSample( + {.cpu_utilization = 0.42, .cpu_speed = 0.84}))); +} + +namespace { + +// TestDouble for CpuProbe that produces a different value after every Update(). +class StreamingCpuProbe : public CpuProbe { + public: + explicit StreamingCpuProbe(std::vector<ComputePressureSample> samples) + : samples_(std::move(samples)) { + DETACH_FROM_SEQUENCE(sequence_checker_); + DCHECK_GT(samples_.size(), 0u); + } + ~StreamingCpuProbe() override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + } + + // CpuProbe implementation. + void Update() override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + base::ScopedBlockingCall scoped_blocking_call( + FROM_HERE, base::BlockingType::MAY_BLOCK); + + ++sample_index_; + DCHECK_LT(sample_index_, samples_.size()); + } + ComputePressureSample LastSample() override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return samples_.at(sample_index_); + } + + private: + SEQUENCE_CHECKER(sequence_checker_); + + std::vector<ComputePressureSample> samples_ + GUARDED_BY_CONTEXT(sequence_checker_); + size_t sample_index_ GUARDED_BY_CONTEXT(sequence_checker_) = 0; +}; + +} // namespace + +TEST_F(ComputePressureSamplerTest, EnsureStarted_SkipsFirstSample) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + std::vector<ComputePressureSample> samples = { + // Value right after construction. + {.cpu_utilization = 0.1, .cpu_speed = 0.2}, + // Value after first Update(), should be discarded. + {.cpu_utilization = 0.2, .cpu_speed = 0.4}, + // Value after second Update(), should be reported. + {.cpu_utilization = 0.3, .cpu_speed = 0.6}, + // A couple of extra values so the test doesn't crash on off-by-one + // errors. + {.cpu_utilization = 0.4, .cpu_speed = 0.8}, + {.cpu_utilization = 0.5, .cpu_speed = 1.0}, + }; + + sampler_ = std::make_unique<ComputePressureSampler>( + std::make_unique<StreamingCpuProbe>(samples), + base::TimeDelta::FromMilliseconds(1), + base::BindRepeating(&ComputePressureSamplerTest::SamplerCallback, + base::Unretained(this))); + sampler_->EnsureStarted(); + WaitForUpdate(); + + EXPECT_THAT(samples_, testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT(samples_, testing::Not(testing::Contains(ComputePressureSample( + {.cpu_utilization = 0.1, .cpu_speed = 0.2})))); + EXPECT_THAT(samples_, testing::Not(testing::Contains(ComputePressureSample( + {.cpu_utilization = 0.2, .cpu_speed = 0.4})))); + EXPECT_THAT(samples_, testing::Contains(ComputePressureSample( + {.cpu_utilization = 0.3, .cpu_speed = 0.6}))); +} + +TEST_F(ComputePressureSamplerTest, Stop_Delayed_EnsureStarted_Immediate) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + sampler_->EnsureStarted(); + WaitForUpdate(); + sampler_->Stop(); + + samples_.clear(); + cpu_probe().SetLastSample({.cpu_utilization = 0.25, .cpu_speed = 0.5}); + + sampler_->EnsureStarted(); + WaitForUpdate(); + EXPECT_THAT(samples_, testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT(samples_, testing::Contains(ComputePressureSample( + {.cpu_utilization = 0.25, .cpu_speed = 0.5}))); +} + +TEST_F(ComputePressureSamplerTest, Stop_Delayed_EnsureStarted_Delayed) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + sampler_->EnsureStarted(); + WaitForUpdate(); + sampler_->Stop(); + + samples_.clear(); + cpu_probe().SetLastSample({.cpu_utilization = 0.25, .cpu_speed = 0.5}); + // 10ms should be long enough to ensure that all the sampling tasks are done. + base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10)); + + sampler_->EnsureStarted(); + WaitForUpdate(); + EXPECT_THAT(samples_, testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT(samples_, testing::Contains(ComputePressureSample( + {.cpu_utilization = 0.25, .cpu_speed = 0.5}))); +} + +TEST_F(ComputePressureSamplerTest, Stop_Immediate_EnsureStarted_Immediate) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + sampler_->EnsureStarted(); + sampler_->Stop(); + + samples_.clear(); + cpu_probe().SetLastSample({.cpu_utilization = 0.25, .cpu_speed = 0.5}); + + sampler_->EnsureStarted(); + WaitForUpdate(); + EXPECT_THAT(samples_, testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT(samples_, testing::Contains(ComputePressureSample( + {.cpu_utilization = 0.25, .cpu_speed = 0.5}))); +} + +TEST_F(ComputePressureSamplerTest, Stop_Immediate_EnsureStarted_Delayed) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + sampler_->EnsureStarted(); + sampler_->Stop(); + + samples_.clear(); + cpu_probe().SetLastSample({.cpu_utilization = 0.25, .cpu_speed = 0.5}); + // 10ms should be long enough to ensure that all the sampling tasks are done. + base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10)); + + sampler_->EnsureStarted(); + WaitForUpdate(); + EXPECT_THAT(samples_, testing::SizeIs(testing::Ge(1u))); + EXPECT_THAT(samples_, testing::Contains(ComputePressureSample( + {.cpu_utilization = 0.25, .cpu_speed = 0.5}))); +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_test_support.cc b/content/browser/compute_pressure/compute_pressure_test_support.cc new file mode 100644 index 0000000..986228c --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_test_support.cc
@@ -0,0 +1,136 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/compute_pressure_test_support.h" + +#include <initializer_list> +#include <ostream> +#include <utility> + +#include "base/barrier_closure.h" +#include "base/location.h" +#include "base/sequence_checker.h" +#include "base/synchronization/lock.h" +#include "base/threading/scoped_blocking_call.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" + +namespace content { + +bool operator==(const ComputePressureSample& lhs, + const ComputePressureSample& rhs) noexcept { + return std::make_pair(lhs.cpu_utilization, lhs.cpu_speed) == + std::make_pair(rhs.cpu_utilization, rhs.cpu_speed); +} +std::ostream& operator<<(std::ostream& os, + const ComputePressureSample& sample) { + os << "[utilization: " << sample.cpu_utilization + << " speed: " << sample.cpu_speed << "]"; + return os; +} + +ComputePressureHostSync::ComputePressureHostSync( + blink::mojom::ComputePressureHost* host) + : host_(host) { + DCHECK(host); +} + +ComputePressureHostSync::~ComputePressureHostSync() = default; + +blink::mojom::ComputePressureStatus ComputePressureHostSync::AddObserver( + const blink::mojom::ComputePressureQuantization& quantization, + mojo::PendingRemote<blink::mojom::ComputePressureObserver> observer) { + blink::mojom::ComputePressureStatus result; + base::RunLoop run_loop; + host_->AddObserver(std::move(observer), quantization.Clone(), + base::BindLambdaForTesting( + [&](blink::mojom::ComputePressureStatus status) { + result = status; + run_loop.Quit(); + })); + run_loop.Run(); + return result; +} + +FakeComputePressureObserver::FakeComputePressureObserver() : receiver_(this) {} + +FakeComputePressureObserver::~FakeComputePressureObserver() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +} + +void FakeComputePressureObserver::OnUpdate( + blink::mojom::ComputePressureStatePtr state) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + updates_.push_back(*state); + if (update_callback_) { + std::move(update_callback_).Run(); + update_callback_.Reset(); + } +} + +void FakeComputePressureObserver::SetNextUpdateCallback( + base::OnceClosure callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!update_callback_) + << __func__ << " already called before update received"; + update_callback_ = std::move(callback); +} + +void FakeComputePressureObserver::WaitForUpdate() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + base::RunLoop run_loop; + SetNextUpdateCallback(run_loop.QuitClosure()); + run_loop.Run(); +} + +// static +void FakeComputePressureObserver::WaitForUpdates( + std::initializer_list<FakeComputePressureObserver*> observers) { + base::RunLoop run_loop; + base::RepeatingClosure update_barrier = + base::BarrierClosure(observers.size(), run_loop.QuitClosure()); + for (FakeComputePressureObserver* observer : observers) + observer->SetNextUpdateCallback(update_barrier); + run_loop.Run(); +} + +mojo::PendingRemote<blink::mojom::ComputePressureObserver> +FakeComputePressureObserver::BindNewPipeAndPassRemote() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return receiver_.BindNewPipeAndPassRemote(); +} + +constexpr ComputePressureSample FakeCpuProbe::kInitialSample; + +FakeCpuProbe::FakeCpuProbe() : last_sample_(kInitialSample) { + DETACH_FROM_SEQUENCE(sequence_checker_); +} + +FakeCpuProbe::~FakeCpuProbe() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +} + +void FakeCpuProbe::Update() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // In DCHECKed builds, the ScopedBlockingCall ensures that Update() is only + // called on sequences where I/O is allowed. + base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, + base::BlockingType::MAY_BLOCK); +} + +ComputePressureSample FakeCpuProbe::LastSample() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + base::AutoLock auto_lock(lock_); + return last_sample_; +} + +void FakeCpuProbe::SetLastSample(ComputePressureSample sample) { + base::AutoLock auto_lock(lock_); + last_sample_ = sample; +} + +} // namespace content
diff --git a/content/browser/compute_pressure/compute_pressure_test_support.h b/content/browser/compute_pressure/compute_pressure_test_support.h new file mode 100644 index 0000000..0ed57bf54 --- /dev/null +++ b/content/browser/compute_pressure/compute_pressure_test_support.h
@@ -0,0 +1,115 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_TEST_SUPPORT_H_ +#define CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_TEST_SUPPORT_H_ + +#include <initializer_list> +#include <ostream> +#include <utility> + +#include "base/sequence_checker.h" +#include "base/synchronization/lock.h" +#include "base/test/bind.h" +#include "base/thread_annotations.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/browser/compute_pressure/cpu_probe.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" + +namespace content { + +// googletest integration with ComputePressureSample. +bool operator==(const ComputePressureSample& lhs, + const ComputePressureSample& rhs) noexcept; + +std::ostream& operator<<(std::ostream& os, const ComputePressureSample& sample); + +// Synchronous proxy to a blink::mojom::ComputePressureManager. +class ComputePressureHostSync { + public: + // The caller must ensure that `manager` outlives the newly created instance. + explicit ComputePressureHostSync(blink::mojom::ComputePressureHost* host); + ~ComputePressureHostSync(); + + ComputePressureHostSync(const ComputePressureHostSync&) = delete; + ComputePressureHostSync& operator=(const ComputePressureHostSync&) = delete; + + blink::mojom::ComputePressureStatus AddObserver( + const blink::mojom::ComputePressureQuantization& quantization, + mojo::PendingRemote<blink::mojom::ComputePressureObserver> observer); + + private: + blink::mojom::ComputePressureHost* const host_; +}; + +// Test double for ComputePressureObserver that records all updates. +class FakeComputePressureObserver + : public blink::mojom::ComputePressureObserver { + public: + FakeComputePressureObserver(); + ~FakeComputePressureObserver() override; + + FakeComputePressureObserver(const FakeComputePressureObserver&) = delete; + FakeComputePressureObserver& operator=(const FakeComputePressureObserver&) = + delete; + + // blink::mojom::ComputePressureObserver implementation. + void OnUpdate(blink::mojom::ComputePressureStatePtr state) override; + + std::vector<blink::mojom::ComputePressureState>& updates() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return updates_; + } + + void SetNextUpdateCallback(base::OnceClosure callback); + void WaitForUpdate(); + static void WaitForUpdates( + std::initializer_list<FakeComputePressureObserver*> observers); + + mojo::PendingRemote<blink::mojom::ComputePressureObserver> + BindNewPipeAndPassRemote(); + + private: + SEQUENCE_CHECKER(sequence_checker_); + + std::vector<blink::mojom::ComputePressureState> updates_ + GUARDED_BY_CONTEXT(sequence_checker_); + + // Used to implement WaitForUpdate(). + base::OnceClosure update_callback_ GUARDED_BY_CONTEXT(sequence_checker_); + + mojo::Receiver<blink::mojom::ComputePressureObserver> receiver_ + GUARDED_BY_CONTEXT(sequence_checker_); +}; + +// Test double for CpuProbe that always returns a predetermined value. +class FakeCpuProbe : public CpuProbe { + public: + // Value returned by LastSample() if SetLastSample() is not called. + static constexpr ComputePressureSample kInitialSample = { + .cpu_utilization = 0.42, + .cpu_speed = 0.84}; + + FakeCpuProbe(); + ~FakeCpuProbe() override; + + // CpuProbe implementation. + void Update() override; + ComputePressureSample LastSample() override; + + // Can be called from any thread. + void SetLastSample(ComputePressureSample sample); + + private: + // Bound to the sequence for Update() and LastSample(). + SEQUENCE_CHECKER(sequence_checker_); + + base::Lock lock_; + ComputePressureSample last_sample_ GUARDED_BY_CONTEXT(lock_); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_COMPUTE_PRESSURE_COMPUTE_PRESSURE_TEST_SUPPORT_H_
diff --git a/content/browser/compute_pressure/cpu_probe.cc b/content/browser/compute_pressure/cpu_probe.cc new file mode 100644 index 0000000..4b4926f --- /dev/null +++ b/content/browser/compute_pressure/cpu_probe.cc
@@ -0,0 +1,57 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/compute_pressure/cpu_probe.h" + +#include <memory> + +#include "base/no_destructor.h" +#include "base/sequence_checker.h" +#include "base/threading/scoped_blocking_call.h" +#include "build/build_config.h" +#include "content/browser/compute_pressure/compute_pressure_sample.h" + +namespace content { + +constexpr ComputePressureSample CpuProbe::kUnsupportedValue; + +CpuProbe::CpuProbe() = default; +CpuProbe::~CpuProbe() = default; + +class NullCpuProbe : public CpuProbe { + public: + NullCpuProbe() { DETACH_FROM_SEQUENCE(sequence_checker_); } + ~NullCpuProbe() override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + } + + // CpuProbe implementation. + void Update() override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // Checks that + base::ScopedBlockingCall scoped_blocking_call( + FROM_HERE, base::BlockingType::MAY_BLOCK); + } + ComputePressureSample LastSample() override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return CpuProbe::kUnsupportedValue; + } + + private: + SEQUENCE_CHECKER(sequence_checker_); +}; + +// Default implementation for platforms that don't have one. + +// static +std::unique_ptr<CpuProbe> CpuProbe::Create() { +#if defined(OS_ANDROID) + return nullptr; +#else + return std::make_unique<NullCpuProbe>(); +#endif // defined(OS_ANDROID) +} + +} // namespace content
diff --git a/content/browser/compute_pressure/cpu_probe.h b/content/browser/compute_pressure/cpu_probe.h new file mode 100644 index 0000000..f8e1081 --- /dev/null +++ b/content/browser/compute_pressure/cpu_probe.h
@@ -0,0 +1,69 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_COMPUTE_PRESSURE_CPU_PROBE_H_ +#define CONTENT_BROWSER_COMPUTE_PRESSURE_CPU_PROBE_H_ + +#include <memory> + +#include "content/browser/compute_pressure/compute_pressure_sample.h" +#include "content/common/content_export.h" + +namespace content { + +// Interface for retrieving the compute pressure state from the underlying OS. +// +// Operating systems differ in how they summarize the info needed to derive the +// compute pressure state. For example, the Linux kernel exposes CPU utilization +// as a summary over the device's entire uptime, while the Windows WMI exposes +// CPU utilization over the last second. +// +// This interface abstracts over the differences with a unified model where the +// implementation is responsible for integrating over the time between two +// Update() calls. +// +// This interface has rather strict requirements. This is because operating +// systems differ in requirements for accessing compute pressure information, +// and this interface expresses the union of all requirements. +// +// Instances are not thread-safe. All methods except for the constructor must be +// created on the same sequence. The sequence must allow blocking I/O +// operations. +class CONTENT_EXPORT CpuProbe { + public: + // LastSample() return value when the implementation fails to get a result. + static constexpr ComputePressureSample kUnsupportedValue = { + .cpu_utilization = 0.0, + // CPUs without dynamic clocking are considered to run at base speed. + .cpu_speed = 0.5, + }; + + // Instantiates the CpuProbe subclass most suitable for the current platform. + // + // Returns nullptr if no suitable implementation exists. + static std::unique_ptr<CpuProbe> Create(); + + CpuProbe(const CpuProbe&) = delete; + CpuProbe& operator=(const CpuProbe&) = delete; + + virtual ~CpuProbe(); + + // Collects new CPU compute resource availability. + // + // The return value of LastSample() will reflect resource availability between + // the current state and the last Update() call. + virtual void Update() = 0; + + // CPU compute resource availability between the last two Update() calls. + virtual ComputePressureSample LastSample() = 0; + + protected: + // The constructor is intentionally only exposed to subclasses. Production + // code must use the Create() factory method. + CpuProbe(); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_COMPUTE_PRESSURE_CPU_PROBE_H_
diff --git a/content/browser/cross_site_transfer_browsertest.cc b/content/browser/cross_site_transfer_browsertest.cc index 8409b9e..def11d49 100644 --- a/content/browser/cross_site_transfer_browsertest.cc +++ b/content/browser/cross_site_transfer_browsertest.cc
@@ -15,7 +15,6 @@ #include "content/browser/renderer_host/frame_tree_node.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h"
diff --git a/content/browser/download/save_package.cc b/content/browser/download/save_package.cc index 0395a592..96d6764 100644 --- a/content/browser/download/save_package.cc +++ b/content/browser/download/save_package.cc
@@ -47,7 +47,6 @@ #include "content/browser/renderer_host/render_view_host_delegate.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h"
diff --git a/content/browser/find_request_manager.cc b/content/browser/find_request_manager.cc index e7078d1..81fdab3 100644 --- a/content/browser/find_request_manager.cc +++ b/content/browser/find_request_manager.cc
@@ -12,7 +12,6 @@ #include "content/browser/find_in_page_client.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" namespace content {
diff --git a/content/browser/media/key_system_support_impl.cc b/content/browser/media/key_system_support_impl.cc index 1e09146..4877aa4 100644 --- a/content/browser/media/key_system_support_impl.cc +++ b/content/browser/media/key_system_support_impl.cc
@@ -41,11 +41,6 @@ available); } -template <typename T> -std::vector<T> SetToVector(const base::flat_set<T>& s) { - return std::vector<T>(s.begin(), s.end()); -} - // Returns a CdmCapability with codecs specified on command line. Returns null // if kOverrideHardwareSecureCodecsForTesting was not specified or not valid // codecs specified. @@ -248,30 +243,15 @@ hw_secure_capability)); } - auto sw_secure_capability = GetSoftwareSecureCapability(key_system); + auto capability = media::mojom::KeySystemCapability::New(); + capability->sw_secure_capability = GetSoftwareSecureCapability(key_system); + capability->hw_secure_capability = hw_secure_capability; - if (!sw_secure_capability && !hw_secure_capability) { + if (!capability->sw_secure_capability && !capability->hw_secure_capability) { std::move(callback).Run(false, nullptr); return; } - auto capability = media::mojom::KeySystemCapability::New(); - - if (sw_secure_capability) { - capability->video_codecs = sw_secure_capability->video_codecs; - capability->encryption_schemes = - SetToVector(sw_secure_capability->encryption_schemes); - capability->session_types = - SetToVector(sw_secure_capability->session_types); - } - - if (hw_secure_capability) { - capability->hw_secure_video_codecs = hw_secure_capability->video_codecs; - capability->hw_secure_encryption_schemes = - SetToVector(hw_secure_capability->encryption_schemes); - // TODO(xhwang): Also populate supported session types here. - } - std::move(callback).Run(true, std::move(capability)); }
diff --git a/content/browser/media/key_system_support_impl_unittest.cc b/content/browser/media/key_system_support_impl_unittest.cc index 5aa910c..743d5a7 100644 --- a/content/browser/media/key_system_support_impl_unittest.cc +++ b/content/browser/media/key_system_support_impl_unittest.cc
@@ -50,26 +50,30 @@ return a == Container(b); } -#define EXPECT_STL_EQ(a, ...) \ - do { \ - EXPECT_TRUE(StlEquals(a, {__VA_ARGS__})); \ +#define EXPECT_STL_EQ(container, ...) \ + do { \ + EXPECT_THAT(container, ::testing::ElementsAre(__VA_ARGS__)); \ } while (false) #define EXPECT_VIDEO_CODECS(...) \ - EXPECT_STL_EQ(capability_->video_codecs, __VA_ARGS__) + EXPECT_STL_EQ(capability_->sw_secure_capability->video_codecs, __VA_ARGS__) -#define EXPECT_ENCRYPTION_SCHEMES(...) \ - EXPECT_STL_EQ(capability_->encryption_schemes, __VA_ARGS__) +#define EXPECT_ENCRYPTION_SCHEMES(...) \ + EXPECT_STL_EQ(capability_->sw_secure_capability->encryption_schemes, \ + __VA_ARGS__) #define EXPECT_SESSION_TYPES(...) \ - EXPECT_STL_EQ(capability_->session_types, __VA_ARGS__) + EXPECT_STL_EQ(capability_->sw_secure_capability->session_types, __VA_ARGS__) #define EXPECT_HW_SECURE_VIDEO_CODECS(...) \ - EXPECT_STL_EQ(capability_->hw_secure_video_codecs, __VA_ARGS__) + EXPECT_STL_EQ(capability_->hw_secure_capability->video_codecs, __VA_ARGS__) -#define EXPECT_HW_SECURE_ENCRYPTION_SCHEMES(...) \ - EXPECT_STL_EQ(capability_->hw_secure_encryption_schemes, __VA_ARGS__) +#define EXPECT_HW_SECURE_ENCRYPTION_SCHEMES(...) \ + EXPECT_STL_EQ(capability_->hw_secure_capability->encryption_schemes, \ + __VA_ARGS__) +#define EXPECT_HW_SECURE_SESSION_TYPES(...) \ + EXPECT_STL_EQ(capability_->hw_secure_capability->session_types, __VA_ARGS__) } // namespace class KeySystemSupportImplTest : public testing::Test { @@ -139,6 +143,8 @@ Register("KeySystem", TestCdmCapability()); EXPECT_TRUE(IsSupported("KeySystem")); + EXPECT_TRUE(capability_->sw_secure_capability); + EXPECT_FALSE(capability_->hw_secure_capability); EXPECT_VIDEO_CODECS(VideoCodec::kCodecVP8, VideoCodec::kCodecVP9); EXPECT_ENCRYPTION_SCHEMES(EncryptionScheme::kCenc, EncryptionScheme::kCbcs); EXPECT_SESSION_TYPES(CdmSessionType::kTemporary, @@ -158,11 +164,13 @@ Register("KeySystem", TestCdmCapability(), Robustness::kHardwareSecure); EXPECT_TRUE(IsSupported("KeySystem")); + EXPECT_FALSE(capability_->sw_secure_capability); + EXPECT_TRUE(capability_->hw_secure_capability); EXPECT_HW_SECURE_VIDEO_CODECS(VideoCodec::kCodecVP8, VideoCodec::kCodecVP9); EXPECT_HW_SECURE_ENCRYPTION_SCHEMES(EncryptionScheme::kCenc, EncryptionScheme::kCbcs); - // TODO(xhwang): Support hardware secure session types. - EXPECT_TRUE(capability_->session_types.empty()); + EXPECT_HW_SECURE_SESSION_TYPES(CdmSessionType::kTemporary, + CdmSessionType::kPersistentLicense); } TEST_F(KeySystemSupportImplTest, MultipleKeySystems) {
diff --git a/content/browser/media/key_system_support_win.cc b/content/browser/media/key_system_support_win.cc index 750226a..f39080b 100644 --- a/content/browser/media/key_system_support_win.cc +++ b/content/browser/media/key_system_support_win.cc
@@ -24,20 +24,19 @@ CdmCapabilityCB cdm_capability_cb, bool is_supported, media::mojom::KeySystemCapabilityPtr key_system_capability) { + // Key system must support at least 1 video codec, 1 encryption scheme, + // and 1 encryption scheme to be considered. Support for audio codecs is + // optional. if (!is_supported || !key_system_capability || - key_system_capability->hw_secure_video_codecs.empty() || - key_system_capability->hw_secure_encryption_schemes.empty()) { + !key_system_capability->hw_secure_capability || + key_system_capability->hw_secure_capability->video_codecs.empty() || + key_system_capability->hw_secure_capability->encryption_schemes.empty() || + key_system_capability->hw_secure_capability->session_types.empty()) { std::move(cdm_capability_cb).Run(base::nullopt); return; } - // TODO(xhwang/jrummell): Support hardware session types. Now only assume - // temporary session support. - std::move(cdm_capability_cb) - .Run(media::CdmCapability( - key_system_capability->hw_secure_video_codecs, - VectorToSet(key_system_capability->hw_secure_encryption_schemes), - {media::CdmSessionType::kTemporary})); + std::move(cdm_capability_cb).Run(key_system_capability->hw_secure_capability); } } // namespace
diff --git a/content/browser/media/session/pepper_playback_observer.cc b/content/browser/media/session/pepper_playback_observer.cc index f712f25..ee47ded9 100644 --- a/content/browser/media/session/pepper_playback_observer.cc +++ b/content/browser/media/session/pepper_playback_observer.cc
@@ -10,7 +10,6 @@ #include "base/metrics/histogram_macros.h" #include "content/browser/media/session/media_session_impl.h" #include "content/browser/media/session/pepper_player_delegate.h" -#include "content/common/frame_messages.h" #include "ipc/ipc_message_macros.h" #include "media/base/media_content_type.h" #include "media/base/media_switches.h"
diff --git a/content/browser/media/session/pepper_player_delegate.cc b/content/browser/media/session/pepper_player_delegate.cc index 61af2f53..8635055 100644 --- a/content/browser/media/session/pepper_player_delegate.cc +++ b/content/browser/media/session/pepper_player_delegate.cc
@@ -7,7 +7,6 @@ #include "base/command_line.h" #include "content/browser/media/session/pepper_playback_observer.h" #include "content/browser/renderer_host/render_frame_host_impl.h" -#include "content/common/frame_messages.h" #include "media/base/media_switches.h" #include "services/media_session/public/cpp/media_position.h"
diff --git a/content/browser/message_port_provider.cc b/content/browser/message_port_provider.cc index 00f6d69..036c679 100644 --- a/content/browser/message_port_provider.cc +++ b/content/browser/message_port_provider.cc
@@ -13,7 +13,6 @@ #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_thread.h" #include "third_party/blink/public/common/messaging/string_message_codec.h"
diff --git a/content/browser/navigation_browsertest.cc b/content/browser/navigation_browsertest.cc index cb8a1e32..02f4c44d 100644 --- a/content/browser/navigation_browsertest.cc +++ b/content/browser/navigation_browsertest.cc
@@ -29,7 +29,6 @@ #include "content/browser/renderer_host/navigation_request.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/content_navigation_policy.h" -#include "content/common/frame_messages.h" #include "content/common/frame_messages.mojom-forward.h" #include "content/common/navigation_client.mojom-forward.h" #include "content/common/navigation_client.mojom.h"
diff --git a/content/browser/renderer_host/cookie_browsertest.cc b/content/browser/renderer_host/cookie_browsertest.cc index 84cfc62d..74c9606 100644 --- a/content/browser/renderer_host/cookie_browsertest.cc +++ b/content/browser/renderer_host/cookie_browsertest.cc
@@ -16,7 +16,6 @@ #include "content/browser/bad_message.h" #include "content/browser/renderer_host/frame_tree.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/content/browser/renderer_host/cross_process_frame_connector.cc b/content/browser/renderer_host/cross_process_frame_connector.cc index b0e298ec..89ecb17 100644 --- a/content/browser/renderer_host/cross_process_frame_connector.cc +++ b/content/browser/renderer_host/cross_process_frame_connector.cc
@@ -19,7 +19,6 @@ #include "content/browser/renderer_host/render_widget_host_input_event_router.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/renderer_host/render_widget_host_view_child_frame.h" -#include "content/common/frame_messages.h" #include "content/public/common/use_zoom_for_dsf_policy.h" #include "gpu/ipc/common/gpu_messages.h" #include "third_party/blink/public/common/frame/frame_visual_properties.h"
diff --git a/content/browser/renderer_host/frame_tree_node.cc b/content/browser/renderer_host/frame_tree_node.cc index a7f21b3..292ee87 100644 --- a/content/browser/renderer_host/frame_tree_node.cc +++ b/content/browser/renderer_host/frame_tree_node.cc
@@ -23,7 +23,6 @@ #include "content/browser/renderer_host/navigator_delegate.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params.h" #include "content/common/navigation_params_utils.h" #include "content/public/browser/browser_thread.h"
diff --git a/content/browser/renderer_host/frame_tree_unittest.cc b/content/browser/renderer_host/frame_tree_unittest.cc index 7d18ce5..d6dad1b2 100644 --- a/content/browser/renderer_host/frame_tree_unittest.cc +++ b/content/browser/renderer_host/frame_tree_unittest.cc
@@ -15,7 +15,6 @@ #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/mock_render_process_host.h"
diff --git a/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc b/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc index 945a9d5..669ac1fc 100644 --- a/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc +++ b/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc
@@ -16,7 +16,6 @@ #include "content/browser/renderer_host/render_widget_host_view_child_frame.h" #include "content/browser/renderer_host/render_widget_host_view_event_handler.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h"
diff --git a/content/browser/renderer_host/ipc_utils.cc b/content/browser/renderer_host/ipc_utils.cc index 28d172a90..0d3db79 100644 --- a/content/browser/renderer_host/ipc_utils.cc +++ b/content/browser/renderer_host/ipc_utils.cc
@@ -11,7 +11,6 @@ #include "content/browser/blob_storage/chrome_blob_storage_context.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params_utils.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h"
diff --git a/content/browser/renderer_host/mixed_content_navigation_throttle.cc b/content/browser/renderer_host/mixed_content_navigation_throttle.cc index ed7a339..482d5c73a 100644 --- a/content/browser/renderer_host/mixed_content_navigation_throttle.cc +++ b/content/browser/renderer_host/mixed_content_navigation_throttle.cc
@@ -15,7 +15,6 @@ #include "content/browser/renderer_host/render_frame_host_delegate.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params.mojom.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/content_client.h"
diff --git a/content/browser/renderer_host/navigation_controller_impl.cc b/content/browser/renderer_host/navigation_controller_impl.cc index a1a67daa..814eebf 100644 --- a/content/browser/renderer_host/navigation_controller_impl.cc +++ b/content/browser/renderer_host/navigation_controller_impl.cc
@@ -70,7 +70,6 @@ #include "content/browser/web_package/subresource_web_bundle_navigation_info.h" #include "content/browser/web_package/web_bundle_navigation_info.h" #include "content/common/content_constants_internal.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params_utils.h" #include "content/common/trace_utils.h" #include "content/public/browser/browser_context.h"
diff --git a/content/browser/renderer_host/navigation_controller_impl_browsertest.cc b/content/browser/renderer_host/navigation_controller_impl_browsertest.cc index b112ff6..8d66903 100644 --- a/content/browser/renderer_host/navigation_controller_impl_browsertest.cc +++ b/content/browser/renderer_host/navigation_controller_impl_browsertest.cc
@@ -37,7 +37,6 @@ #include "content/browser/web_contents/web_contents_impl.h" #include "content/browser/web_contents/web_contents_view.h" #include "content/common/content_navigation_policy.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/content/browser/renderer_host/navigation_controller_impl_unittest.cc b/content/browser/renderer_host/navigation_controller_impl_unittest.cc index a5d6da5..f181d4f 100644 --- a/content/browser/renderer_host/navigation_controller_impl_unittest.cc +++ b/content/browser/renderer_host/navigation_controller_impl_unittest.cc
@@ -34,7 +34,6 @@ #include "content/browser/webui/web_ui_controller_factory_registry.h" #include "content/common/content_navigation_policy.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h"
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index e106918..d176366 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -76,7 +76,6 @@ #include "content/common/appcache_interfaces.h" #include "content/common/content_constants_internal.h" #include "content/common/debug_utils.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params.h" #include "content/common/navigation_params_mojom_traits.h" #include "content/common/navigation_params_utils.h"
diff --git a/content/browser/renderer_host/navigator.cc b/content/browser/renderer_host/navigator.cc index bc2d7c7f..e494a06 100644 --- a/content/browser/renderer_host/navigator.cc +++ b/content/browser/renderer_host/navigator.cc
@@ -31,7 +31,6 @@ #include "content/browser/web_package/web_bundle_handle_tracker.h" #include "content/browser/webui/web_ui_controller_factory_registry.h" #include "content/browser/webui/web_ui_impl.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params.h" #include "content/common/navigation_params_utils.h" #include "content/public/browser/browser_context.h"
diff --git a/content/browser/renderer_host/navigator_unittest.cc b/content/browser/renderer_host/navigator_unittest.cc index 3c7180d2..35cd4f90 100644 --- a/content/browser/renderer_host/navigator_unittest.cc +++ b/content/browser/renderer_host/navigator_unittest.cc
@@ -20,7 +20,6 @@ #include "content/browser/site_instance_impl.h" #include "content/common/content_navigation_policy.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/common/content_features.h"
diff --git a/content/browser/renderer_host/pepper/pepper_renderer_connection.cc b/content/browser/renderer_host/pepper/pepper_renderer_connection.cc index a9e0ec6..a619469 100644 --- a/content/browser/renderer_host/pepper/pepper_renderer_connection.cc +++ b/content/browser/renderer_host/pepper/pepper_renderer_connection.cc
@@ -20,7 +20,6 @@ #include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h" #include "content/browser/renderer_host/pepper/pepper_file_ref_host.h" #include "content/browser/renderer_host/pepper/pepper_file_system_browser_host.h" -#include "content/common/frame_messages.h" #include "content/common/pepper_renderer_instance_data.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h"
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index c1e98b143..3925d8f 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -54,6 +54,7 @@ #include "content/browser/bluetooth/web_bluetooth_service_impl.h" #include "content/browser/browser_main_loop.h" #include "content/browser/child_process_security_policy_impl.h" +#include "content/browser/compute_pressure/compute_pressure_manager.h" #include "content/browser/contacts/contacts_manager_impl.h" #include "content/browser/coop_coep_cross_origin_isolated_info.h" #include "content/browser/data_url_loader_factory.h" @@ -152,7 +153,6 @@ #include "content/common/content_constants_internal.h" #include "content/common/content_navigation_policy.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_client.mojom.h" #include "content/common/navigation_params.h" #include "content/common/navigation_params_mojom_traits.h" @@ -242,6 +242,7 @@ #include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom.h" #include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h" #include "third_party/blink/public/mojom/choosers/popup_menu.mojom.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h" #include "third_party/blink/public/mojom/frame/frame.mojom.h" #include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" @@ -8600,6 +8601,14 @@ std::move(receiver)); } +void RenderFrameHostImpl::BindComputePressureHost( + mojo::PendingReceiver<blink::mojom::ComputePressureHost> receiver) { + static_cast<StoragePartitionImpl*>(GetProcess()->GetStoragePartition()) + ->GetComputePressureManager() + ->BindReceiver(GetLastCommittedOrigin(), GetGlobalFrameRoutingId(), + std::move(receiver)); +} + void RenderFrameHostImpl::GetFileSystemAccessManager( mojo::PendingReceiver<blink::mojom::FileSystemAccessManager> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI);
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index 24dd5cd..1dee8acc 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -104,6 +104,7 @@ #include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h" #include "third_party/blink/public/mojom/choosers/popup_menu.mojom.h" #include "third_party/blink/public/mojom/commit_result/commit_result.mojom.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom-forward.h" #include "third_party/blink/public/mojom/contacts/contacts_manager.mojom.h" #include "third_party/blink/public/mojom/devtools/devtools_agent.mojom.h" #include "third_party/blink/public/mojom/devtools/inspector_issue.mojom.h" @@ -1472,6 +1473,9 @@ void GetFontAccessManager( mojo::PendingReceiver<blink::mojom::FontAccessManager> receiver); + void BindComputePressureHost( + mojo::PendingReceiver<blink::mojom::ComputePressureHost> receiver); + void GetFileSystemAccessManager( mojo::PendingReceiver<blink::mojom::FileSystemAccessManager> receiver);
diff --git a/content/browser/renderer_host/render_frame_host_impl_browsertest.cc b/content/browser/renderer_host/render_frame_host_impl_browsertest.cc index 0170166e..e768178 100644 --- a/content/browser/renderer_host/render_frame_host_impl_browsertest.cc +++ b/content/browser/renderer_host/render_frame_host_impl_browsertest.cc
@@ -34,7 +34,6 @@ #include "content/browser/sms/test/mock_sms_provider.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/content_navigation_policy.h" -#include "content/common/frame_messages.h" #include "content/public/browser/javascript_dialog_manager.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h"
diff --git a/content/browser/renderer_host/render_frame_host_manager.cc b/content/browser/renderer_host/render_frame_host_manager.cc index f2ccdb0..3bd26f7 100644 --- a/content/browser/renderer_host/render_frame_host_manager.cc +++ b/content/browser/renderer_host/render_frame_host_manager.cc
@@ -46,7 +46,6 @@ #include "content/browser/site_instance_impl.h" #include "content/browser/webui/web_ui_controller_factory_registry.h" #include "content/common/content_navigation_policy.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h"
diff --git a/content/browser/renderer_host/render_frame_host_manager_unittest.cc b/content/browser/renderer_host/render_frame_host_manager_unittest.cc index b87449b..35f0483a 100644 --- a/content/browser/renderer_host/render_frame_host_manager_unittest.cc +++ b/content/browser/renderer_host/render_frame_host_manager_unittest.cc
@@ -35,7 +35,6 @@ #include "content/browser/site_instance_impl.h" #include "content/browser/webui/web_ui_controller_factory_registry.h" #include "content/common/content_navigation_policy.h" -#include "content/common/frame_messages.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_iterator.h"
diff --git a/content/browser/renderer_host/render_frame_proxy_host.cc b/content/browser/renderer_host/render_frame_proxy_host.cc index f2549a0b..72e0067 100644 --- a/content/browser/renderer_host/render_frame_proxy_host.cc +++ b/content/browser/renderer_host/render_frame_proxy_host.cc
@@ -30,7 +30,6 @@ #include "content/browser/renderer_host/render_widget_host_view_child_frame.h" #include "content/browser/scoped_active_url.h" #include "content/browser/site_instance_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_client.h" #include "content/public/common/content_features.h"
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index d94dbfaf..6eee013d 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -135,7 +135,6 @@ #include "content/common/child_process_host_impl.h" #include "content/common/content_constants_internal.h" #include "content/common/content_switches_internal.h" -#include "content/common/frame_messages.h" #include "content/common/in_process_child_thread_params.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/browser/browser_context.h"
diff --git a/content/browser/renderer_host/render_process_host_unittest.cc b/content/browser/renderer_host/render_process_host_unittest.cc index f264f87e..817610a5 100644 --- a/content/browser/renderer_host/render_process_host_unittest.cc +++ b/content/browser/renderer_host/render_process_host_unittest.cc
@@ -15,7 +15,6 @@ #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "content/browser/child_process_security_policy_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/content_client.h"
diff --git a/content/browser/renderer_host/render_view_host_impl.cc b/content/browser/renderer_host/render_view_host_impl.cc index 756ad32..ba94f41 100644 --- a/content/browser/renderer_host/render_view_host_impl.cc +++ b/content/browser/renderer_host/render_view_host_impl.cc
@@ -54,7 +54,6 @@ #include "content/browser/scoped_active_url.h" #include "content/common/agent_scheduling_group.mojom.h" #include "content/common/content_switches_internal.h" -#include "content/common/frame_messages.h" #include "content/common/render_message_filter.mojom.h" #include "content/common/renderer.mojom.h" #include "content/public/browser/ax_event_notification_details.h"
diff --git a/content/browser/renderer_host/render_view_host_unittest.cc b/content/browser/renderer_host/render_view_host_unittest.cc index bd543680..4ccc3384 100644 --- a/content/browser/renderer_host/render_view_host_unittest.cc +++ b/content/browser/renderer_host/render_view_host_unittest.cc
@@ -13,7 +13,6 @@ #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_view_host_delegate_view.h" #include "content/browser/renderer_host/render_widget_helper.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/storage_partition.h"
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 7aaea096..252e799 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -83,7 +83,6 @@ #include "content/browser/storage_partition_impl.h" #include "content/common/content_constants_internal.h" #include "content/common/cursors/webcursor.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/device_service.h"
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index 1446338..114e0740 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -24,7 +24,6 @@ #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/renderer_host/render_widget_host_view_child_frame.h" -#include "content/common/frame_messages.h" #include "content/public/browser/render_widget_host_iterator.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "ui/base/layout.h"
diff --git a/content/browser/renderer_host/render_widget_host_view_android.cc b/content/browser/renderer_host/render_widget_host_view_android.cc index 6bf39d05..f22125c 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.cc +++ b/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -2100,6 +2100,16 @@ bool RenderWidgetHostViewAndroid::OnMouseEvent( const ui::MotionEventAndroid& event) { + // Ignore ACTION_HOVER_ENTER & ACTION_HOVER_EXIT because every mouse-down on + // Android follows a hover-exit and is followed by a hover-enter. + // https://crbug.com/715114 filed on distinguishing actual hover + // enter/exit from these bogus ones. + auto action = event.GetAction(); + if (action == ui::MotionEventAndroid::Action::HOVER_ENTER || + action == ui::MotionEventAndroid::Action::HOVER_EXIT) { + return false; + } + RecordToolTypeForActionDown(event); SendMouseEvent(event, event.GetActionButton()); return true;
diff --git a/content/browser/renderer_host/render_widget_host_view_browsertest.cc b/content/browser/renderer_host/render_widget_host_view_browsertest.cc index d2f49b20..d19360f 100644 --- a/content/browser/renderer_host/render_widget_host_view_browsertest.cc +++ b/content/browser/renderer_host/render_widget_host_view_browsertest.cc
@@ -21,7 +21,6 @@ #include "content/browser/renderer_host/dip_util.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" -#include "content/common/frame_messages.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h"
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc b/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc index 6a325900..a4e6212 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc
@@ -17,7 +17,6 @@ #include "content/browser/renderer_host/frame_tree_node.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h"
diff --git a/content/browser/screen_orientation/screen_orientation_provider_unittest.cc b/content/browser/screen_orientation/screen_orientation_provider_unittest.cc index 0d09f60d..7b8d968 100644 --- a/content/browser/screen_orientation/screen_orientation_provider_unittest.cc +++ b/content/browser/screen_orientation/screen_orientation_provider_unittest.cc
@@ -8,7 +8,6 @@ #include "base/callback_helpers.h" #include "base/optional.h" #include "base/run_loop.h" -#include "content/common/frame_messages.h" #include "content/public/browser/screen_orientation_delegate.h" #include "content/public/browser/web_contents_delegate.h" #include "content/test/test_render_view_host.h"
diff --git a/content/browser/security_exploit_browsertest.cc b/content/browser/security_exploit_browsertest.cc index 6a633fe..75b6bc2f 100644 --- a/content/browser/security_exploit_browsertest.cc +++ b/content/browser/security_exploit_browsertest.cc
@@ -28,7 +28,6 @@ #include "content/browser/web_contents/file_chooser_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/render_message_filter.mojom.h" #include "content/public/browser/blob_handle.h" #include "content/public/browser/browser_context.h"
diff --git a/content/browser/service_worker/service_worker_test_utils.cc b/content/browser/service_worker/service_worker_test_utils.cc index 30a4236c..f1b396f 100644 --- a/content/browser/service_worker/service_worker_test_utils.cc +++ b/content/browser/service_worker/service_worker_test_utils.cc
@@ -22,7 +22,6 @@ #include "content/browser/service_worker/service_worker_host.h" #include "content/browser/service_worker/service_worker_registration.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/frame_messages.mojom.h" #include "content/public/common/child_process_host.h" #include "content/public/test/policy_container_utils.h"
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 57253fe..41c70dc 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -78,7 +78,6 @@ #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/content_navigation_policy.h" #include "content/common/frame.mojom-test-utils.h" -#include "content/common/frame_messages.h" #include "content/common/input/actions_parser.h" #include "content/common/input/synthetic_pinch_gesture_params.h" #include "content/common/renderer.mojom.h"
diff --git a/content/browser/site_per_process_hit_test_browsertest.cc b/content/browser/site_per_process_hit_test_browsertest.cc index 4101d0265..9e88faa 100644 --- a/content/browser/site_per_process_hit_test_browsertest.cc +++ b/content/browser/site_per_process_hit_test_browsertest.cc
@@ -29,7 +29,6 @@ #include "content/browser/renderer_host/render_widget_host_input_event_router.h" #include "content/browser/renderer_host/render_widget_host_view_child_frame.h" #include "content/browser/site_per_process_browsertest.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/context_menu_params.h"
diff --git a/content/browser/site_per_process_unload_browsertest.cc b/content/browser/site_per_process_unload_browsertest.cc index 0febca6..48d67ef 100644 --- a/content/browser/site_per_process_unload_browsertest.cc +++ b/content/browser/site_per_process_unload_browsertest.cc
@@ -33,7 +33,6 @@ #include "content/browser/renderer_host/render_widget_host_view_child_frame.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/content_navigation_policy.h" -#include "content/common/frame_messages.h" #include "content/public/browser/navigation_handle.h" #include "content/public/common/url_constants.h" #include "content/public/test/back_forward_cache_util.h"
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index a6dbfdb..c764717 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -48,6 +48,7 @@ #include "content/browser/browsing_data/storage_partition_code_cache_data_remover.h" #include "content/browser/code_cache/generated_code_cache.h" #include "content/browser/code_cache/generated_code_cache_context.h" +#include "content/browser/compute_pressure/compute_pressure_manager.h" #include "content/browser/conversions/conversion_manager_impl.h" #include "content/browser/cookie_store/cookie_store_context.h" #include "content/browser/devtools/devtools_instrumentation.h" @@ -1328,6 +1329,7 @@ } font_access_manager_ = std::make_unique<FontAccessManagerImpl>(); + compute_pressure_manager_ = ComputePressureManager::Create(); } void StoragePartitionImpl::OnStorageServiceDisconnected() { @@ -1597,6 +1599,11 @@ return interest_group_manager_.get(); } +ComputePressureManager* StoragePartitionImpl::GetComputePressureManager() { + DCHECK(initialized_); + return compute_pressure_manager_.get(); +} + ContentIndexContextImpl* StoragePartitionImpl::GetContentIndexContext() { DCHECK(initialized_); return content_index_context_.get();
diff --git a/content/browser/storage_partition_impl.h b/content/browser/storage_partition_impl.h index 983ed52..7716a7c 100644 --- a/content/browser/storage_partition_impl.h +++ b/content/browser/storage_partition_impl.h
@@ -79,6 +79,7 @@ class BackgroundFetchContext; class BlobRegistryWrapper; class ConversionManagerImpl; +class ComputePressureManager; class CookieStoreContext; class FontAccessContext; class GeneratedCodeCacheContext; @@ -226,6 +227,7 @@ ConversionManagerImpl* GetConversionManager(); FontAccessManagerImpl* GetFontAccessManager(); InterestGroupManager* GetInterestGroupStorage(); + ComputePressureManager* GetComputePressureManager(); std::string GetPartitionDomain(); // blink::mojom::DomStorage interface. @@ -562,6 +564,10 @@ std::unique_ptr<FontAccessManagerImpl> font_access_manager_; std::unique_ptr<InterestGroupManager> interest_group_manager_; + // TODO(crbug.com/1205695): ComputePressureManager should live elsewher. The + // Compute Pressure API does not store data. + std::unique_ptr<ComputePressureManager> compute_pressure_manager_; + // ReceiverSet for DomStorage, using the // ChildProcessSecurityPolicyImpl::Handle as the binding context type. The // handle can subsequently be used during interface method calls to
diff --git a/content/browser/web_contents/web_contents_android.cc b/content/browser/web_contents/web_contents_android.cc index c02d4e27..264de52 100644 --- a/content/browser/web_contents/web_contents_android.cc +++ b/content/browser/web_contents/web_contents_android.cc
@@ -27,7 +27,6 @@ #include "content/browser/web_contents/web_contents_impl.h" #include "content/browser/web_contents/web_contents_view_android.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/public/android/content_jni_headers/WebContentsImpl_jni.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h"
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 6b2e8b1..24f086e 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -105,7 +105,6 @@ #include "content/browser/webui/web_ui_impl.h" #include "content/browser/xr/service/xr_runtime_manager_impl.h" #include "content/common/content_switches_internal.h" -#include "content/common/frame_messages.h" #include "content/common/render_message_filter.mojom.h" #include "content/public/browser/ax_event_notification_details.h" #include "content/public/browser/ax_inspect_factory.h"
diff --git a/content/browser/web_contents/web_contents_impl_browsertest.cc b/content/browser/web_contents/web_contents_impl_browsertest.cc index 31552d9..7e0fbd7 100644 --- a/content/browser/web_contents/web_contents_impl_browsertest.cc +++ b/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -40,7 +40,6 @@ #include "content/common/content_navigation_policy.h" #include "content/common/frame.mojom-test-utils.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/public/browser/back_forward_cache.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h"
diff --git a/content/browser/web_contents/web_contents_impl_unittest.cc b/content/browser/web_contents/web_contents_impl_unittest.cc index a49f57f..ec63eaa12 100644 --- a/content/browser/web_contents/web_contents_impl_unittest.cc +++ b/content/browser/web_contents/web_contents_impl_unittest.cc
@@ -31,7 +31,6 @@ #include "content/browser/webui/web_ui_controller_factory_registry.h" #include "content/common/content_navigation_policy.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/context_menu_params.h"
diff --git a/content/browser/webui/web_ui_impl.cc b/content/browser/webui/web_ui_impl.cc index fc6ab53..64b34f4 100644 --- a/content/browser/webui/web_ui_impl.cc +++ b/content/browser/webui/web_ui_impl.cc
@@ -27,7 +27,6 @@ #include "content/browser/web_contents/web_contents_view.h" #include "content/browser/webui/web_ui_controller_factory_registry.h" #include "content/browser/webui/web_ui_main_frame_observer.h" -#include "content/common/frame_messages.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h"
diff --git a/content/common/common_param_traits_macros.h b/content/common/common_param_traits_macros.h index 637f242..97c5f326 100644 --- a/content/common/common_param_traits_macros.h +++ b/content/common/common_param_traits_macros.h
@@ -10,7 +10,6 @@ #include "cc/trees/browser_controls_params.h" #include "content/common/content_export.h" -#include "content/common/frame_messages.h" #include "ipc/ipc_message_macros.h" #include "services/device/public/mojom/screen_orientation_lock_types.mojom-shared.h" #include "third_party/blink/public/common/widget/device_emulation_params.h"
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index d128a2ef1..3f2e9a61 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -10,85 +10,18 @@ #include <stddef.h> #include <stdint.h> -#include "base/optional.h" -#include "base/unguessable_token.h" -#include "build/build_config.h" -#include "cc/input/touch_action.h" -#include "components/viz/common/surfaces/surface_id.h" -#include "components/viz/common/surfaces/surface_info.h" #include "content/common/buildflags.h" #include "content/common/common_param_traits_macros.h" #include "content/common/content_export.h" -#include "content/common/content_param_traits.h" -#include "content/common/navigation_gesture.h" -#include "content/common/navigation_params.h" #include "content/public/common/common_param_traits.h" -#include "content/public/common/referrer.h" -#include "content/public/common/stop_find_action.h" -#include "content/public/common/three_d_api_types.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_message_macros.h" -#include "ipc/ipc_platform_file.h" -#include "mojo/public/cpp/system/message_pipe.h" -#include "ppapi/buildflags/buildflags.h" -#include "third_party/blink/public/common/context_menu_data/untrustworthy_context_menu_params.h" -#include "third_party/blink/public/common/frame/frame_policy.h" -#include "third_party/blink/public/common/frame/frame_visual_properties.h" -#include "third_party/blink/public/common/loader/previews_state.h" -#include "third_party/blink/public/common/messaging/message_port_channel.h" +#include "services/network/public/cpp/net_ipc_param_traits.h" #include "third_party/blink/public/common/navigation/impression.h" -#include "third_party/blink/public/common/navigation/navigation_policy.h" -#include "third_party/blink/public/common/page_state/page_state.h" -#include "third_party/blink/public/common/permissions_policy/permissions_policy.h" -#include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h" -#include "third_party/blink/public/mojom/devtools/console_message.mojom.h" -#include "third_party/blink/public/mojom/favicon/favicon_url.mojom.h" -#include "third_party/blink/public/mojom/frame/blocked_navigation_types.mojom.h" -#include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom.h" -#include "third_party/blink/public/mojom/frame/lifecycle.mojom.h" -#include "third_party/blink/public/mojom/frame/triggering_event_info.mojom-shared.h" -#include "third_party/blink/public/mojom/frame/user_activation_update_types.mojom.h" -#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" -#include "third_party/blink/public/mojom/manifest/display_mode.mojom.h" -#include "third_party/blink/public/mojom/permissions_policy/document_policy_feature.mojom.h" -#include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-shared.h" -#include "third_party/blink/public/mojom/permissions_policy/policy_disposition.mojom.h" -#include "third_party/blink/public/mojom/scroll/scrollbar_mode.mojom.h" -#include "third_party/blink/public/mojom/web_feature/web_feature.mojom.h" -#include "third_party/blink/public/web/web_frame_owner_properties.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/rect_f.h" -#include "ui/gfx/ipc/color/gfx_param_traits.h" -#include "ui/gfx/ipc/gfx_param_traits.h" -#include "url/gurl.h" -#include "url/origin.h" - -#if BUILDFLAG(ENABLE_PLUGINS) -#include "content/common/pepper_renderer_instance_data.h" -#endif #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT -IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::ScrollbarMode, - blink::mojom::ScrollbarMode::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(content::StopFindAction, - content::STOP_FIND_ACTION_LAST) -IPC_ENUM_TRAITS(network::mojom::WebSandboxFlags) // Bitmask. -IPC_ENUM_TRAITS_MAX_VALUE(ui::MenuSourceType, ui::MENU_SOURCE_TYPE_LAST) -IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::PermissionsPolicyFeature, - blink::mojom::PermissionsPolicyFeature::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::DocumentPolicyFeature, - blink::mojom::DocumentPolicyFeature::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::UserActivationUpdateType, - blink::mojom::UserActivationUpdateType::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::PolicyDisposition, - blink::mojom::PolicyDisposition::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::FrameVisibility, - blink::mojom::FrameVisibility::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::WebFeature, - blink::mojom::WebFeature::kMaxValue) - IPC_STRUCT_TRAITS_BEGIN(blink::Impression) IPC_STRUCT_TRAITS_MEMBER(conversion_destination) IPC_STRUCT_TRAITS_MEMBER(reporting_origin) @@ -96,36 +29,4 @@ IPC_STRUCT_TRAITS_MEMBER(expiry) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_TRAITS_BEGIN(blink::FramePolicy) - IPC_STRUCT_TRAITS_MEMBER(sandbox_flags) - IPC_STRUCT_TRAITS_MEMBER(container_policy) - IPC_STRUCT_TRAITS_MEMBER(required_document_policy) - IPC_STRUCT_TRAITS_MEMBER(disallow_document_access) -IPC_STRUCT_TRAITS_END() - -IPC_STRUCT_TRAITS_BEGIN(blink::ScreenInfo) - IPC_STRUCT_TRAITS_MEMBER(device_scale_factor) - IPC_STRUCT_TRAITS_MEMBER(display_color_spaces) - IPC_STRUCT_TRAITS_MEMBER(depth) - IPC_STRUCT_TRAITS_MEMBER(depth_per_component) - IPC_STRUCT_TRAITS_MEMBER(is_monochrome) - IPC_STRUCT_TRAITS_MEMBER(display_frequency) - IPC_STRUCT_TRAITS_MEMBER(rect) - IPC_STRUCT_TRAITS_MEMBER(available_rect) - IPC_STRUCT_TRAITS_MEMBER(orientation_type) - IPC_STRUCT_TRAITS_MEMBER(orientation_angle) -IPC_STRUCT_TRAITS_END() - -IPC_STRUCT_TRAITS_BEGIN(blink::ParsedPermissionsPolicyDeclaration) - IPC_STRUCT_TRAITS_MEMBER(feature) - IPC_STRUCT_TRAITS_MEMBER(allowed_origins) - IPC_STRUCT_TRAITS_MEMBER(matches_all_origins) - IPC_STRUCT_TRAITS_MEMBER(matches_opaque_src) -IPC_STRUCT_TRAITS_END() - -// Adding a new message? Stick to the sort order above: first platform -// independent FrameMsg, then ifdefs for platform specific FrameMsg, then -// platform independent FrameHostMsg, then ifdefs for platform specific -// FrameHostMsg. - #endif // CONTENT_COMMON_FRAME_MESSAGES_H_
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index caadac2d..9eff6e4b 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -55,7 +55,6 @@ #include "content/browser/web_contents/web_contents_impl.h" #include "content/browser/web_contents/web_contents_view.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/content/public/test/mock_render_process_host.cc b/content/public/test/mock_render_process_host.cc index aa53e88bb..6c90f61b 100644 --- a/content/public/test/mock_render_process_host.cc +++ b/content/public/test/mock_render_process_host.cc
@@ -22,7 +22,6 @@ #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/common/child_process_host_impl.h" -#include "content/common/frame_messages.h" #include "content/common/renderer.mojom.h" #include "content/public/browser/android/child_process_importance.h" #include "content/public/browser/browser_context.h"
diff --git a/content/public/test/mock_render_thread.cc b/content/public/test/mock_render_thread.cc index 917e087165..63186b8 100644 --- a/content/public/test/mock_render_thread.cc +++ b/content/public/test/mock_render_thread.cc
@@ -13,7 +13,6 @@ #include "build/build_config.h" #include "content/common/associated_interfaces.mojom.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/render_message_filter.mojom.h" #include "content/public/renderer/render_thread_observer.h" #include "content/renderer/render_thread_impl.h"
diff --git a/content/public/test/render_view_test.cc b/content/public/test/render_view_test.cc index a505e3a..5375878e 100644 --- a/content/public/test/render_view_test.cc +++ b/content/public/test/render_view_test.cc
@@ -18,7 +18,6 @@ #include "content/app/mojo/mojo_init.h" #include "content/common/agent_scheduling_group.mojom.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/renderer.mojom.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/native_web_keyboard_event.h"
diff --git a/content/renderer/accessibility/render_accessibility_impl_browsertest.cc b/content/renderer/accessibility/render_accessibility_impl_browsertest.cc index bcf29a96..833755e 100644 --- a/content/renderer/accessibility/render_accessibility_impl_browsertest.cc +++ b/content/renderer/accessibility/render_accessibility_impl_browsertest.cc
@@ -18,7 +18,6 @@ #include "base/test/task_environment.h" #include "base/time/time.h" #include "build/build_config.h" -#include "content/common/frame_messages.h" #include "content/common/render_accessibility.mojom-test-utils.h" #include "content/common/render_accessibility.mojom.h" #include "content/public/common/content_features.h"
diff --git a/content/renderer/dom_automation_controller.cc b/content/renderer/dom_automation_controller.cc index f0162ba4..418913bb 100644 --- a/content/renderer/dom_automation_controller.cc +++ b/content/renderer/dom_automation_controller.cc
@@ -6,7 +6,6 @@ #include "base/json/json_string_value_serializer.h" #include "base/strings/string_util.h" -#include "content/common/frame_messages.h" #include "content/renderer/render_view_impl.h" #include "content/renderer/v8_value_converter_impl.h" #include "gin/handle.h"
diff --git a/content/renderer/loader/web_worker_fetch_context_impl.cc b/content/renderer/loader/web_worker_fetch_context_impl.cc index b67bdeb..36a4ce9 100644 --- a/content/renderer/loader/web_worker_fetch_context_impl.cc +++ b/content/renderer/loader/web_worker_fetch_context_impl.cc
@@ -12,7 +12,6 @@ #include "base/task/thread_pool.h" #include "base/threading/sequenced_task_runner_handle.h" #include "content/child/child_thread_impl.h" -#include "content/common/frame_messages.h" #include "content/public/common/content_client.h" #include "content/public/common/origin_util.h" #include "content/public/renderer/content_renderer_client.h"
diff --git a/content/renderer/navigation_state.cc b/content/renderer/navigation_state.cc index 41ef6b4d5..14f7c65 100644 --- a/content/renderer/navigation_state.cc +++ b/content/renderer/navigation_state.cc
@@ -8,7 +8,6 @@ #include <utility> #include "base/memory/ptr_util.h" -#include "content/common/frame_messages.h" #include "content/renderer/internal_document_state_data.h" #include "third_party/blink/public/mojom/commit_result/commit_result.mojom.h"
diff --git a/content/renderer/pepper/host_dispatcher_wrapper.cc b/content/renderer/pepper/host_dispatcher_wrapper.cc index 2312e6a..bf877e5 100644 --- a/content/renderer/pepper/host_dispatcher_wrapper.cc +++ b/content/renderer/pepper/host_dispatcher_wrapper.cc
@@ -7,7 +7,6 @@ #include <memory> #include "build/build_config.h" -#include "content/common/frame_messages.h" #include "content/renderer/pepper/pepper_browser_connection.h" #include "content/renderer/pepper/pepper_hung_plugin_filter.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
diff --git a/content/renderer/pepper/pepper_browser_connection.cc b/content/renderer/pepper/pepper_browser_connection.cc index cc99fa9..47dd115 100644 --- a/content/renderer/pepper/pepper_browser_connection.cc +++ b/content/renderer/pepper/pepper_browser_connection.cc
@@ -7,7 +7,6 @@ #include <limits> #include "base/notreached.h" -#include "content/common/frame_messages.h" #include "content/public/common/content_features.h" #include "content/public/renderer/render_thread.h" #include "content/renderer/pepper/pepper_in_process_router.h"
diff --git a/content/renderer/pepper/pepper_hung_plugin_filter.cc b/content/renderer/pepper/pepper_hung_plugin_filter.cc index 26a33173..9cec206e 100644 --- a/content/renderer/pepper/pepper_hung_plugin_filter.cc +++ b/content/renderer/pepper/pepper_hung_plugin_filter.cc
@@ -6,7 +6,6 @@ #include "base/bind.h" #include "content/child/child_process.h" -#include "content/common/frame_messages.h" #include "content/renderer/render_thread_impl.h" namespace content {
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.cc b/content/renderer/pepper/pepper_plugin_instance_impl.cc index 1d06e82..b130a6a 100644 --- a/content/renderer/pepper/pepper_plugin_instance_impl.cc +++ b/content/renderer/pepper/pepper_plugin_instance_impl.cc
@@ -26,7 +26,6 @@ #include "build/chromeos_buildflags.h" #include "cc/layers/texture_layer.h" #include "content/common/content_constants_internal.h" -#include "content/common/frame_messages.h" #include "content/public/common/content_constants.h" #include "content/public/common/use_zoom_for_dsf_policy.h" #include "content/public/renderer/content_renderer_client.h"
diff --git a/content/renderer/pepper/plugin_module.cc b/content/renderer/pepper/plugin_module.cc index 175ce05c..d3de9462 100644 --- a/content/renderer/pepper/plugin_module.cc +++ b/content/renderer/pepper/plugin_module.cc
@@ -20,7 +20,6 @@ #include "base/time/time.h" #include "build/build_config.h" #include "components/nacl/common/buildflags.h" -#include "content/common/frame_messages.h" #include "content/public/common/content_features.h" #include "content/public/renderer/content_renderer_client.h" #include "content/renderer/pepper/host_dispatcher_wrapper.h"
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index d1f54fd..5050482 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -57,7 +57,6 @@ #include "content/common/associated_interfaces.mojom.h" #include "content/common/content_navigation_policy.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_client.mojom.h" #include "content/common/navigation_gesture.h" #include "content/common/navigation_params.h"
diff --git a/content/renderer/render_frame_impl_browsertest.cc b/content/renderer/render_frame_impl_browsertest.cc index 4535c72..a9eaa04 100644 --- a/content/renderer/render_frame_impl_browsertest.cc +++ b/content/renderer/render_frame_impl_browsertest.cc
@@ -20,7 +20,6 @@ #include "base/test/scoped_feature_list.h" #include "base/unguessable_token.h" #include "build/build_config.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params_mojom_traits.h" #include "content/common/renderer.mojom.h" #include "content/public/common/content_features.h"
diff --git a/content/renderer/render_frame_proxy.h b/content/renderer/render_frame_proxy.h index 47acde0..7067208 100644 --- a/content/renderer/render_frame_proxy.h +++ b/content/renderer/render_frame_proxy.h
@@ -9,7 +9,6 @@ #include "base/memory/ref_counted.h" #include "cc/paint/paint_canvas.h" #include "content/common/content_export.h" -#include "content/common/frame_messages.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_sender.h" #include "mojo/public/cpp/bindings/associated_receiver.h"
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 20bad6d2..2d3f4ec 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -65,7 +65,6 @@ #include "content/child/runtime_features.h" #include "content/common/buildflags.h" #include "content/common/content_constants_internal.h" -#include "content/common/frame_messages.h" #include "content/common/partition_alloc_support.h" #include "content/common/process_visibility_tracker.h" #include "content/public/common/content_constants.h"
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 38ca41c..df7e323 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -30,7 +30,6 @@ #include "build/build_config.h" #include "cc/input/browser_controls_state.h" #include "cc/trees/layer_tree_host.h" -#include "content/common/frame_messages.h" #include "content/common/renderer.mojom.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/native_web_keyboard_event.h"
diff --git a/content/renderer/render_view_browsertest_mac.mm b/content/renderer/render_view_browsertest_mac.mm index 07e6ba0b..6872bf8 100644 --- a/content/renderer/render_view_browsertest_mac.mm +++ b/content/renderer/render_view_browsertest_mac.mm
@@ -5,7 +5,6 @@ #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "content/common/frame_messages.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/test/render_view_test.h" #include "content/renderer/render_view_impl.h"
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 1db5cf1..a0bf7476 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -33,7 +33,6 @@ #include "content/child/child_process.h" #include "content/common/android/sync_compositor_statics.h" #include "content/common/content_constants_internal.h" -#include "content/common/frame_messages.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/gpu_stream_constants.h"
diff --git a/content/renderer/web_ui_extension.cc b/content/renderer/web_ui_extension.cc index 8f333b89a..cd842e9 100644 --- a/content/renderer/web_ui_extension.cc +++ b/content/renderer/web_ui_extension.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/values.h" -#include "content/common/frame_messages.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/url_constants.h" #include "content/public/renderer/chrome_object_extensions_utils.h"
diff --git a/content/renderer/web_ui_extension_data.cc b/content/renderer/web_ui_extension_data.cc index 5372e6a..2af70516 100644 --- a/content/renderer/web_ui_extension_data.cc +++ b/content/renderer/web_ui_extension_data.cc
@@ -4,7 +4,6 @@ #include "content/renderer/web_ui_extension_data.h" -#include "content/common/frame_messages.h" #include "content/public/renderer/render_frame.h" #include "mojo/public/cpp/bindings/self_owned_associated_receiver.h" #include "third_party/blink/public/common/browser_interface_broker_proxy.h"
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index b7743969..9465bee 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1878,6 +1878,12 @@ "../browser/child_process_security_policy_unittest.cc", "../browser/client_hints/client_hints_unittest.cc", "../browser/code_cache/generated_code_cache_unittest.cc", + "../browser/compute_pressure/compute_pressure_host_unittest.cc", + "../browser/compute_pressure/compute_pressure_manager_unittest.cc", + "../browser/compute_pressure/compute_pressure_quantizer_unittest.cc", + "../browser/compute_pressure/compute_pressure_sampler_unittest.cc", + "../browser/compute_pressure/compute_pressure_test_support.cc", + "../browser/compute_pressure/compute_pressure_test_support.h", "../browser/content_index/content_index_database_unittest.cc", "../browser/content_index/content_index_service_impl_unittest.cc", "../browser/conversions/conversion_host_unittest.cc",
diff --git a/content/test/content_browser_test_utils_internal.h b/content/test/content_browser_test_utils_internal.h index 34a211f..0fac28a4 100644 --- a/content/test/content_browser_test_utils_internal.h +++ b/content/test/content_browser_test_utils_internal.h
@@ -23,7 +23,6 @@ #include "build/build_config.h" #include "content/browser/bad_message.h" #include "content/browser/renderer_host/back_forward_cache_metrics.h" -#include "content/common/frame_messages.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/javascript_dialog_manager.h" #include "content/public/browser/navigation_type.h"
diff --git a/content/test/did_commit_navigation_interceptor.cc b/content/test/did_commit_navigation_interceptor.cc index 64d78ac..7b97a85 100644 --- a/content/test/did_commit_navigation_interceptor.cc +++ b/content/test/did_commit_navigation_interceptor.cc
@@ -6,7 +6,6 @@ #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/common/frame.mojom-test-utils.h" -#include "content/common/frame_messages.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h"
diff --git a/content/test/frame_host_interceptor.cc b/content/test/frame_host_interceptor.cc index 051215d..4122703 100644 --- a/content/test/frame_host_interceptor.cc +++ b/content/test/frame_host_interceptor.cc
@@ -9,7 +9,6 @@ #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/common/frame.mojom-test-utils.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "mojo/public/cpp/bindings/associated_receiver.h"
diff --git a/content/test/navigation_simulator_impl.cc b/content/test/navigation_simulator_impl.cc index 7da7d26..bdf7b70466 100644 --- a/content/test/navigation_simulator_impl.cc +++ b/content/test/navigation_simulator_impl.cc
@@ -17,7 +17,6 @@ #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/content_navigation_policy.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params.h" #include "content/common/navigation_params_utils.h" #include "content/public/browser/web_contents.h"
diff --git a/content/test/test_render_frame.cc b/content/test/test_render_frame.cc index 225a4a6..41ea72f 100644 --- a/content/test/test_render_frame.cc +++ b/content/test/test_render_frame.cc
@@ -14,7 +14,6 @@ #include "base/unguessable_token.h" #include "build/build_config.h" #include "content/common/frame.mojom.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_params.h" #include "content/common/navigation_params.mojom.h" #include "content/public/common/url_constants.h"
diff --git a/content/test/test_render_frame_host.h b/content/test/test_render_frame_host.h index ec04227..e4cafa2 100644 --- a/content/test/test_render_frame_host.h +++ b/content/test/test_render_frame_host.h
@@ -14,7 +14,6 @@ #include "base/macros.h" #include "base/optional.h" #include "content/browser/renderer_host/render_frame_host_impl.h" -#include "content/common/frame_messages.h" #include "content/common/navigation_client.mojom-forward.h" #include "content/common/navigation_params.mojom-forward.h" #include "content/public/browser/web_contents_observer.h"
diff --git a/content/test/test_render_view_host.cc b/content/test/test_render_view_host.cc index d661a274..b287255 100644 --- a/content/test/test_render_view_host.cc +++ b/content/test/test_render_view_host.cc
@@ -20,7 +20,6 @@ #include "content/browser/renderer_host/render_widget_host_input_event_router.h" #include "content/browser/site_instance_impl.h" #include "content/browser/storage_partition_impl.h" -#include "content/common/frame_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_controller.h"
diff --git a/content/test/test_web_contents.cc b/content/test/test_web_contents.cc index 0596088e..b3c8821 100644 --- a/content/test/test_web_contents.cc +++ b/content/test/test_web_contents.cc
@@ -20,7 +20,6 @@ #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/site_instance_impl.h" -#include "content/common/frame_messages.h" #include "content/common/render_message_filter.mojom.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_source.h"
diff --git a/content/test/web_contents_observer_consistency_checker.cc b/content/test/web_contents_observer_consistency_checker.cc index 85ee43f..80c908ff 100644 --- a/content/test/web_contents_observer_consistency_checker.cc +++ b/content/test/web_contents_observer_consistency_checker.cc
@@ -12,7 +12,6 @@ #include "content/browser/renderer_host/navigation_entry_impl.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/common/content_navigation_policy.h" -#include "content/common/frame_messages.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -366,7 +365,8 @@ void WebContentsObserverConsistencyChecker::DidStartLoading() { // TODO(clamy): add checks for the loading state in the rest of observer // methods. - CHECK(!is_loading_); + // TODO(crbug.com/1145572): Add back CHECK(!is_loading_). The CHECK was + // removed because of flaky failures during some browser_tests. CHECK(web_contents()->IsLoading()); is_loading_ = true; }
diff --git a/docs/speed/metrics_changelog/2021_05_fid.md b/docs/speed/metrics_changelog/2021_05_fid.md new file mode 100644 index 0000000..778c0de --- /dev/null +++ b/docs/speed/metrics_changelog/2021_05_fid.md
@@ -0,0 +1,19 @@ +# First Input Delay Changes in Chrome 91 + +### Disable double-tap-to-zoom on mobile viewports + +Double-tap-to-zoom (DTZ) is a gesture used to zoom into text. Previously, DTZ +was disabled when either zooming was disabled (min-zoom equal to max-zoom) or +when the content width fits the viewport width. After this change, we also +disable DTZ when the viewport meta tag specifies `width=device-width` or +`initial-scale>=1.0`, even when implicitly doing so, like for example in +`minimum-scale=1.5, maximum-scale=2`. + +Because DTZ negatively impacts FID and the amount of pages where DTZ is disabled +is increased, we expect some sites to see better FID scores. + +[Relevant bug](https://bugs.chromium.org/p/chromium/issues/detail?id=1108987) + +## When were users affected? + +Chrome 91 is currently scheduled to be released the week of July 20, 2021.
diff --git a/docs/speed/metrics_changelog/fid.md b/docs/speed/metrics_changelog/fid.md index 68b1a49..d81a7dc 100644 --- a/docs/speed/metrics_changelog/fid.md +++ b/docs/speed/metrics_changelog/fid.md
@@ -2,9 +2,11 @@ This is a list of changes to [First Input Delay](https://web.dev/fid). +* Chrome 91 + * Chrome change affecting metric: [Disable double-tap-to-zoom on mobile viewports](2021_05_fid.md) * Chrome 83 * Metric definition improvement: [First Input Delay includes inputs with delays < 1ms in Chrome User Experience Report](2020_05_fid.md) * Chrome 77 * Metric exposed via API: [First Input Delay](https://web.dev/fid/) available via [Event Timing API](https://github.com/tdresser/event-timing#first-input-timing) * Chrome 75 - * Metric definition improvement: [First Input Delay includes input events that had previously been filtered](2019_07_fid.md) \ No newline at end of file + * Metric definition improvement: [First Input Delay includes input events that had previously been filtered](2019_07_fid.md)
diff --git a/extensions/browser/BUILD.gn b/extensions/browser/BUILD.gn index 0249b59..a57032ed 100644 --- a/extensions/browser/BUILD.gn +++ b/extensions/browser/BUILD.gn
@@ -484,6 +484,7 @@ "//base", "//base:i18n", "//build:chromeos_buildflags", + "//components/back_forward_cache", "//components/cast_certificate", "//components/crx_file", "//components/crx_file:crx_creator",
diff --git a/extensions/browser/DEPS b/extensions/browser/DEPS index 08950430..b1403fad 100644 --- a/extensions/browser/DEPS +++ b/extensions/browser/DEPS
@@ -1,5 +1,6 @@ include_rules = [ "+chromeos", + "+components/back_forward_cache", "+components/guest_view", "+components/keyed_service", "+components/pref_registry",
diff --git a/extensions/browser/api/messaging/BUILD.gn b/extensions/browser/api/messaging/BUILD.gn index d189a24..a3bd77a1 100644 --- a/extensions/browser/api/messaging/BUILD.gn +++ b/extensions/browser/api/messaging/BUILD.gn
@@ -24,6 +24,7 @@ deps = [ ":native_messaging", "//base", + "//components/back_forward_cache", "//content/public/browser", "//content/public/common", "//extensions/browser/api",
diff --git a/extensions/browser/api/messaging/message_service.cc b/extensions/browser/api/messaging/message_service.cc index fd39c33..00da348 100644 --- a/extensions/browser/api/messaging/message_service.cc +++ b/extensions/browser/api/messaging/message_service.cc
@@ -18,6 +18,7 @@ #include "base/metrics/histogram_macros.h" #include "base/values.h" #include "build/build_config.h" +#include "components/back_forward_cache/back_forward_cache_disable.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" @@ -109,6 +110,14 @@ true); } +void DisableBackForwardCacheForMessaging(content::RenderFrameHost* host) { + if (!host) + return; + content::BackForwardCache::DisableForRenderFrameHost( + host, back_forward_cache::DisabledReason( + back_forward_cache::DisabledReasonId::kExtensionMessaging)); +} + } // namespace struct MessageService::MessageChannel { @@ -227,6 +236,9 @@ BrowserContext* context = source.browser_context(); DCHECK(ExtensionsBrowserClient::Get()->IsSameContext(context, context_)); + // Disable back forward cache. + DisableBackForwardCacheForMessaging(source_render_frame_host); + if (!opener_port) { DCHECK(source_endpoint.type == MessagingEndpoint::Type::kTab || source_endpoint.type == MessagingEndpoint::Type::kExtension); @@ -421,6 +433,10 @@ content::RenderFrameHost* source_rfh = source.is_for_render_frame() ? source.GetRenderFrameHost() : nullptr; + + // Disable back forward cache. + DisableBackForwardCacheForMessaging(source_rfh); + std::string error = kReceivingEndDoesntExistError; const PortId receiver_port_id = source_port_id.GetOppositePortId(); // NOTE: We're creating |receiver| with nullptr |source_rfh|, which seems to @@ -486,6 +502,9 @@ return; } + // Disable back forward cache. + DisableBackForwardCacheForMessaging(receiver_contents->GetMainFrame()); + const PortId receiver_port_id = source_port_id.GetOppositePortId(); std::unique_ptr<MessagePort> receiver = messaging_delegate_->CreateReceiverForTab(weak_factory_.GetWeakPtr(),
diff --git a/extensions/browser/event_listener_map.cc b/extensions/browser/event_listener_map.cc index f3beb4d..bf14420 100644 --- a/extensions/browser/event_listener_map.cc +++ b/extensions/browser/event_listener_map.cc
@@ -77,7 +77,7 @@ service_worker_version_id_ == other->service_worker_version_id_ && worker_thread_id_ == other->worker_thread_id_ && ((!!filter_.get()) == (!!other->filter_.get())) && - (!filter_.get() || filter_->Equals(other->filter_.get())); + (!filter_.get() || *filter_ == *other->filter_); } std::unique_ptr<EventListener> EventListener::Copy() const {
diff --git a/extensions/browser/event_router.cc b/extensions/browser/event_router.cc index e9e4ff9f..88e23f9 100644 --- a/extensions/browser/event_router.cc +++ b/extensions/browser/event_router.cc
@@ -528,7 +528,7 @@ for (size_t i = 0; i < filter_list->GetSize(); i++) { DictionaryValue* filter_value = nullptr; CHECK(filter_list->GetDictionary(i, &filter_value)); - if (filter_value->Equals(filter)) { + if (*filter_value == *filter) { filter_list->Remove(i, nullptr); break; }
diff --git a/extensions/browser/extension_prefs.cc b/extensions/browser/extension_prefs.cc index 2a72fbf..4ed728f 100644 --- a/extensions/browser/extension_prefs.cc +++ b/extensions/browser/extension_prefs.cc
@@ -1502,7 +1502,7 @@ const base::DictionaryValue* old_manifest = NULL; bool update_required = !extension_dict->GetDictionary(kPrefManifest, &old_manifest) || - !extension->manifest()->value()->Equals(old_manifest); + *extension->manifest()->value() != *old_manifest; if (update_required) { UpdateExtensionPref(extension->id(), kPrefManifest, extension->manifest()->value()->CreateDeepCopy());
diff --git a/extensions/browser/value_store/testing_value_store.cc b/extensions/browser/value_store/testing_value_store.cc index 06ba4f6..a42e56b9 100644 --- a/extensions/browser/value_store/testing_value_store.cc +++ b/extensions/browser/value_store/testing_value_store.cc
@@ -95,7 +95,7 @@ !it.IsAtEnd(); it.Advance()) { base::Value* old_value = NULL; if (!storage_.GetWithoutPathExpansion(it.key(), &old_value) || - !old_value->Equals(&it.value())) { + *old_value != it.value()) { changes.emplace_back(it.key(), old_value ? base::Optional<base::Value>(old_value->Clone())
diff --git a/extensions/common/api/web_view_internal.json b/extensions/common/api/web_view_internal.json index 960bfe28..bfbf21d 100644 --- a/extensions/common/api/web_view_internal.json +++ b/extensions/common/api/web_view_internal.json
@@ -11,7 +11,7 @@ }, "properties": { "MAX_CAPTURE_VISIBLE_REGION_CALLS_PER_SECOND": { - "value": 1, + "value": 2, "description": "The maximum number of times that $(ref:captureVisibleRegion) can be called per second. $(ref:captureVisibleRegion) is expensive and should not be called too often." } },
diff --git a/extensions/common/manifest.cc b/extensions/common/manifest.cc index 3e78fc7..1e0adc37 100644 --- a/extensions/common/manifest.cc +++ b/extensions/common/manifest.cc
@@ -384,7 +384,7 @@ } bool Manifest::EqualsForTesting(const Manifest& other) const { - return value_->Equals(other.value()) && location_ == other.location_ && + return *value_ == *other.value() && location_ == other.location_ && extension_id_ == other.extension_id_; }
diff --git a/extensions/common/permissions/manifest_permission.cc b/extensions/common/permissions/manifest_permission.cc index cf4458f..d88d6ac 100644 --- a/extensions/common/permissions/manifest_permission.cc +++ b/extensions/common/permissions/manifest_permission.cc
@@ -24,7 +24,7 @@ } bool ManifestPermission::Equal(const ManifestPermission* rhs) const { - return ToValue()->Equals(rhs->ToValue().get()); + return *ToValue() == *rhs->ToValue(); } void ManifestPermission::Write(base::Pickle* m) const {
diff --git a/extensions/common/value_counter.cc b/extensions/common/value_counter.cc index da0cc6f..f1fe285b 100644 --- a/extensions/common/value_counter.cc +++ b/extensions/common/value_counter.cc
@@ -33,7 +33,7 @@ bool ValueCounter::Add(const base::Value& value) { for (auto& entry : entries_) { - if (entry.value.Equals(&value)) { + if (entry.value == value) { ++entry.count; return false; } @@ -44,7 +44,7 @@ bool ValueCounter::Remove(const base::Value& value) { for (auto it = entries_.begin(); it != entries_.end(); ++it) { - if (it->value.Equals(&value)) { + if (it->value == value) { if (--it->count == 0) { std::swap(*it, entries_.back()); entries_.pop_back();
diff --git a/extensions/test/data/policy_violation/README.md b/extensions/test/data/policy_violation/README.md new file mode 100644 index 0000000..8dc50d7 --- /dev/null +++ b/extensions/test/data/policy_violation/README.md
@@ -0,0 +1,13 @@ +# Policy Violation Test Data +The files in this directory assist with manual testing policy-violating +extension behavior. + +- ext.crx: A small example extension. +- ext.pem: A private key corresponding to ext.crx. +- rsp.py: A python3 script that runs a server on port 8080 and serves a canned +response to POST queries indicating that ext.crx violates policy. + +ext.crx can be regenerated by unpacking it, modifying files, and then repacking +it using Chrome's "pack extension" function at chrome://extensions. As long as +ext.pem is reused, the extension ID will not change and rsp.py need not be +modified.
diff --git a/extensions/test/data/policy_violation/ext.crx b/extensions/test/data/policy_violation/ext.crx new file mode 100644 index 0000000..d7755d3 --- /dev/null +++ b/extensions/test/data/policy_violation/ext.crx Binary files differ
diff --git a/extensions/test/data/policy_violation/ext.pem b/extensions/test/data/policy_violation/ext.pem new file mode 100644 index 0000000..8e0c169 --- /dev/null +++ b/extensions/test/data/policy_violation/ext.pem
@@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDcd/dPiWQhHRpl +fMyjXACMO4TRizIpC74rn82+u2r6qPkLT83Lj0AgFiV0hxNPakAICIL9pAbNnbdf +m3WIGY1vzv+XeY4dFaDMW+kCnQFEk5x6okIS9oFJBUMDVGGfEalgHdWoHKpn38Lw +2xfuCzeCQrDMNS+s+mikzQqOqM3bQCBf5WIhtqXw4QgwThgLdApOt3oQggckEMxV +VZ4iBcLJ4wV7gpb5Nr1AQZZ+N1YvskJOiynRLzkBebeqaC6CBiGKFkR9Ipi9Uxob +fD03bhTr2T59OUUVgGCNvyp55Xfp3/PcJycx7kKXbYfTxw0Orfxpf8OrRLQuckQe +JdFdq6h7AgMBAAECggEAVmRILAmpi/RMkLJLukPmDw2PqVEDUeRBG/Ud+XyVmi22 +kYEvInI67ZfgC36WyYrYFo3HTr8Ez3PbFILllnR04PhbXa8LSkhcX1gwwY5mncm+ +CqwkeivQU53VOavKKTwRhBGM1LiO6e9cA2fHQ8dvdALQJuU8jmr9sH6MgYSSTjRj +WKQ2CKBMfNjJLmCFVTUl92h6VSxqy+td2u9Ow7OiDdXTcG4tO3hEuZykHxYPFNrj +ZWVMRJPIJX4uTbLQ2sb7/4wP+HbqitoBSwuo3QMimncE+8nX7irAM3BqKGXsTKj2 +/udGKwcF35x/YSN2434f5e7L0cWPE0bNrWOw89trmQKBgQD4uIZxeyimUnz0dmcP ++TOV+3wvtQTVoLmAhEOvyIr8Q9HO6zzjwCgyXGAEqPvf3J0h2jSsku7nrRlwow6p +kl7qHmbX+CWQ5uMTf+EJJm2jYkikQHT1r4XcjRdBLgjw3zjt5xbsljcOHJWRrby1 +yByUX3ZMP4gB0svfmoCGiWVBTwKBgQDi68TUtew4IOKi5ssc3kLvT3gUqSfiNeoS +8ZDK6+mMJMvUdh5tfz1fVtLjhvVIV0UDQ5NAFoGp6BXf+dnoU2OkfX+PZ2IZywxU +blwiRBmeIVku8FSWImpgxaqYyv0HFzM5HeGs7vrznmW7qEUYQWd5pJdM2ZDY0/NW +8fudobijFQKBgQCUUiYKgnFpTgOqHPm08t0qccBLCt4JL0GwPC/JIgSQDzmM9Ydo +Ie1WqvOvk74wb3Vc/K0wxKanjfh/zR0vTlQ/tUWLQTXVxXpg5H+kX0A+kJvVJ4MY +CEYBkjnt6q/2RIfEh2yKRcIrLiybpUnF9cHlUVBQhAptW/GsNIy0rjatzQKBgQCE +oWs1LHO5xrbQofa7k8kpmJhF8yylkf+TPO/1OvgRenxMXRGhzEnxzIyMghghRSjI +JJoPTlhRF56Zf652lS7bOKLzDWkQTFaTjsF5Ibabb0ByJ/Q4oDru/vmcPqCvoUbG +Lon2CuRQuhcaHNrtt2Ske6gXOd7obNGA0wTO+HQzlQKBgQC+EYnGvs+na66ggB7O +rgBzsMm+a3kCSrjSUjDkQx5LWsLi9ObTwHS9XkHgIbU58EtpuseHRRHScqiK0kDR +BbFtNVGHIUMgjKAeCeXCFzStZOkl7ocZP8wRZ+dumASaVXLJbn+h5lUG627BKXMG +1+gLF8gICX7FX1GXIrbf7euHmA== +-----END PRIVATE KEY-----
diff --git a/extensions/test/data/policy_violation/rsp.py b/extensions/test/data/policy_violation/rsp.py new file mode 100755 index 0000000..b951a7f --- /dev/null +++ b/extensions/test/data/policy_violation/rsp.py
@@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +# +# Copyright 2021 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 http.server + +RESPONSE_BODY = b""")]}' +{"response": + { + "server":"prod", + "protocol":"3.1", + "daystart":{"elapsed_seconds":45861,"elapsed_days":5205}, + "app":[ + { + "appid":"ebfcakiglfalfoplflllgbnmalfhaeio", + "cohort":"1::", + "status":"ok", + "cohortname":"", + "updatecheck":{"_esbAllowlist":"false","status":"noupdate"} + } + ] + } +} +""" + +class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.send_response(200) + self.end_headers() + self.wfile.write(RESPONSE_BODY) + +http.server.HTTPServer(('', 8080), Handler).serve_forever()
diff --git a/fuchsia/base/agent_impl_unittests.cc b/fuchsia/base/agent_impl_unittests.cc index 9033219..f919845 100644 --- a/fuchsia/base/agent_impl_unittests.cc +++ b/fuchsia/base/agent_impl_unittests.cc
@@ -25,7 +25,7 @@ class EmptyComponentState : public AgentImpl::ComponentStateBase { public: - EmptyComponentState(base::StringPiece component) + explicit EmptyComponentState(base::StringPiece component) : ComponentStateBase(component) {} }; @@ -47,7 +47,7 @@ class AccumulatorComponentState : public AgentImpl::ComponentStateBase { public: - AccumulatorComponentState(base::StringPiece component) + explicit AccumulatorComponentState(base::StringPiece component) : ComponentStateBase(component), service_binding_(outgoing_directory(), &service_) {} @@ -58,7 +58,7 @@ class KeepAliveComponentState : public AccumulatorComponentState { public: - KeepAliveComponentState(base::StringPiece component) + explicit KeepAliveComponentState(base::StringPiece component) : AccumulatorComponentState(component) { AddKeepAliveBinding(&service_binding_); }
diff --git a/fuchsia/engine/browser/content_directory_loader_factory.cc b/fuchsia/engine/browser/content_directory_loader_factory.cc index fcf964b..71c9b60b 100644 --- a/fuchsia/engine/browser/content_directory_loader_factory.cc +++ b/fuchsia/engine/browser/content_directory_loader_factory.cc
@@ -349,7 +349,7 @@ {base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})) {} -ContentDirectoryLoaderFactory::~ContentDirectoryLoaderFactory() {} +ContentDirectoryLoaderFactory::~ContentDirectoryLoaderFactory() = default; void ContentDirectoryLoaderFactory::CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader,
diff --git a/fuchsia/engine/browser/content_directory_loader_factory.h b/fuchsia/engine/browser/content_directory_loader_factory.h index 4d8a068..8fe135f 100644 --- a/fuchsia/engine/browser/content_directory_loader_factory.h +++ b/fuchsia/engine/browser/content_directory_loader_factory.h
@@ -36,15 +36,15 @@ // method). static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create(); + ContentDirectoryLoaderFactory(const ContentDirectoryLoaderFactory&) = delete; + ContentDirectoryLoaderFactory& operator=( + const ContentDirectoryLoaderFactory&) = delete; + private: explicit ContentDirectoryLoaderFactory( mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver); ~ContentDirectoryLoaderFactory() override; - ContentDirectoryLoaderFactory(const ContentDirectoryLoaderFactory&) = delete; - ContentDirectoryLoaderFactory& operator=( - const ContentDirectoryLoaderFactory&) = delete; - // network::mojom::URLLoaderFactory: void CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader,
diff --git a/fuchsia/engine/browser/frame_impl_browsertest.cc b/fuchsia/engine/browser/frame_impl_browsertest.cc index f9f7eb0..3f34f0d 100644 --- a/fuchsia/engine/browser/frame_impl_browsertest.cc +++ b/fuchsia/engine/browser/frame_impl_browsertest.cc
@@ -117,7 +117,7 @@ class FrameImplTest : public FrameImplTestBase { public: FrameImplTest() = default; - ~FrameImplTest() = default; + ~FrameImplTest() override = default; FrameImplTest(const FrameImplTest&) = delete; FrameImplTest& operator=(const FrameImplTest&) = delete; @@ -130,7 +130,7 @@ // TODO(crbug.com/1155378): Remove |navigation_listener_| and use the parent's // implementation of this method after updating all tests to use the // appropriate base. - fuchsia::web::FramePtr CreateFrame() { + fuchsia::web::FramePtr CreateFrame() override { return WebEngineBrowserTest::CreateFrame(&navigation_listener_); }
diff --git a/fuchsia/engine/browser/frame_layout_manager.cc b/fuchsia/engine/browser/frame_layout_manager.cc index c479829f..6f2c66f 100644 --- a/fuchsia/engine/browser/frame_layout_manager.cc +++ b/fuchsia/engine/browser/frame_layout_manager.cc
@@ -31,9 +31,8 @@ } // namespace -FrameLayoutManager::FrameLayoutManager() {} - -FrameLayoutManager::~FrameLayoutManager() {} +FrameLayoutManager::FrameLayoutManager() = default; +FrameLayoutManager::~FrameLayoutManager() = default; void FrameLayoutManager::ForceContentDimensions(gfx::Size size) { render_size_override_ = size;
diff --git a/fuchsia/engine/browser/virtual_keyboard_browsertest.cc b/fuchsia/engine/browser/virtual_keyboard_browsertest.cc index 2eff7d9a..397e7e9 100644 --- a/fuchsia/engine/browser/virtual_keyboard_browsertest.cc +++ b/fuchsia/engine/browser/virtual_keyboard_browsertest.cc
@@ -53,7 +53,7 @@ class MockVirtualKeyboardController : public virtualkeyboard::Controller { public: MockVirtualKeyboardController() : binding_(this) {} - ~MockVirtualKeyboardController() override {} + ~MockVirtualKeyboardController() override = default; MockVirtualKeyboardController(MockVirtualKeyboardController&) = delete; MockVirtualKeyboardController operator=(MockVirtualKeyboardController&) =
diff --git a/fuchsia/engine/browser/web_engine_devtools_controller.cc b/fuchsia/engine/browser/web_engine_devtools_controller.cc index 2bbbb895..a55ca49 100644 --- a/fuchsia/engine/browser/web_engine_devtools_controller.cc +++ b/fuchsia/engine/browser/web_engine_devtools_controller.cc
@@ -336,7 +336,7 @@ if (command_line.HasSwitch(switches::kRemoteDebuggingPort)) { // Set up DevTools to listen on all network routes on the command-line // provided port. - base::StringPiece command_line_port_value = + std::string command_line_port_value = command_line.GetSwitchValueASCII(switches::kRemoteDebuggingPort); int parsed_port = 0;
diff --git a/fuchsia/engine/context_provider_impl.cc b/fuchsia/engine/context_provider_impl.cc index 6d5ac6ea..75580d7 100644 --- a/fuchsia/engine/context_provider_impl.cc +++ b/fuchsia/engine/context_provider_impl.cc
@@ -132,9 +132,7 @@ DCHECK(launch_info->flat_namespace); DCHECK(!directories.empty()); - for (size_t i = 0; i < directories.size(); ++i) { - fuchsia::web::ContentDirectoryProvider& directory = directories[i]; - + for (auto& directory : directories) { if (!IsValidContentDirectoryName(directory.name())) { DLOG(ERROR) << "Invalid directory name: " << directory.name(); return false;
diff --git a/fuchsia/engine/context_provider_impl_unittest.cc b/fuchsia/engine/context_provider_impl_unittest.cc index 099be23a..e237a6b4 100644 --- a/fuchsia/engine/context_provider_impl_unittest.cc +++ b/fuchsia/engine/context_provider_impl_unittest.cc
@@ -111,9 +111,9 @@ using CreateComponentCallback = base::OnceCallback<void(const base::CommandLine&)>; - FakeSysLauncher(fuchsia::sys::Launcher* real_launcher) + explicit FakeSysLauncher(fuchsia::sys::Launcher* real_launcher) : real_launcher_(real_launcher) {} - ~FakeSysLauncher() final {} + ~FakeSysLauncher() final = default; void set_create_component_callback(CreateComponentCallback callback) { create_component_callback_ = std::move(callback);
diff --git a/fuchsia/engine/test_debug_listener.cc b/fuchsia/engine/test_debug_listener.cc index 4d64e64..a609916 100644 --- a/fuchsia/engine/test_debug_listener.cc +++ b/fuchsia/engine/test_debug_listener.cc
@@ -9,7 +9,7 @@ #include "base/test/bind.h" #include "testing/gtest/include/gtest/gtest.h" -TestDebugListener::TestDebugListener() {} +TestDebugListener::TestDebugListener() = default; TestDebugListener::~TestDebugListener() = default; void TestDebugListener::DestroyListener(TestPerContextListener* listener) {
diff --git a/fuchsia/engine/web_engine_integration_logging_test.cc b/fuchsia/engine/web_engine_integration_logging_test.cc index cf6d7cf..bfd0f07da 100644 --- a/fuchsia/engine/web_engine_integration_logging_test.cc +++ b/fuchsia/engine/web_engine_integration_logging_test.cc
@@ -43,8 +43,7 @@ class WebEngineIntegrationLoggingTest : public WebEngineIntegrationTestBase { protected: WebEngineIntegrationLoggingTest() - : WebEngineIntegrationTestBase(), - isolated_archivist_service_dir_( + : isolated_archivist_service_dir_( StartIsolatedArchivist(archivist_controller_.NewRequest())) { // Redirect the LogSink service to an isolated archivist instance. zx_status_t status = filtered_service_directory()
diff --git a/fuchsia/engine/web_engine_integration_test.cc b/fuchsia/engine/web_engine_integration_test.cc index 7457093b..e0189e7 100644 --- a/fuchsia/engine/web_engine_integration_test.cc +++ b/fuchsia/engine/web_engine_integration_test.cc
@@ -34,7 +34,7 @@ // Starts a WebEngine instance before running the test. class WebEngineIntegrationTest : public WebEngineIntegrationTestBase { protected: - WebEngineIntegrationTest() : WebEngineIntegrationTestBase() {} + WebEngineIntegrationTest() = default; void SetUp() override { WebEngineIntegrationTestBase::SetUp(); @@ -50,8 +50,7 @@ class WebEngineIntegrationMediaTest : public WebEngineIntegrationTest { protected: WebEngineIntegrationMediaTest() - : WebEngineIntegrationTest(), - fake_audio_consumer_service_(filtered_service_directory() + : fake_audio_consumer_service_(filtered_service_directory() .outgoing_directory() ->GetOrCreateDirectory("svc")) {} @@ -468,7 +467,7 @@ // starting it. class WebEngineIntegrationCameraTest : public WebEngineIntegrationTestBase { protected: - WebEngineIntegrationCameraTest() : WebEngineIntegrationTestBase() {} + WebEngineIntegrationCameraTest() = default; void RunCameraTest(bool grant_permission); };
diff --git a/fuchsia/runners/cast/cast_platform_bindings_ids.h b/fuchsia/runners/cast/cast_platform_bindings_ids.h index bfbac4cf..24c13b8b 100644 --- a/fuchsia/runners/cast/cast_platform_bindings_ids.h +++ b/fuchsia/runners/cast/cast_platform_bindings_ids.h
@@ -5,6 +5,8 @@ #ifndef FUCHSIA_RUNNERS_CAST_CAST_PLATFORM_BINDINGS_IDS_H_ #define FUCHSIA_RUNNERS_CAST_CAST_PLATFORM_BINDINGS_IDS_H_ +#include <cstdint> + // Managed the space of unique identifiers for injected scripts, to prevent ID // conflicts inside Cast Runner. enum class CastPlatformBindingsId : uint64_t {
diff --git a/gpu/ipc/client/shared_image_interface_proxy.cc b/gpu/ipc/client/shared_image_interface_proxy.cc index dd1585a..e976fc7 100644 --- a/gpu/ipc/client/shared_image_interface_proxy.cc +++ b/gpu/ipc/client/shared_image_interface_proxy.cc
@@ -171,7 +171,7 @@ GpuChannelMsg_CreateGMBSharedImage_Params params; params.mailbox = mailbox; params.handle = gpu_memory_buffer->CloneHandle(); - params.size = gpu_memory_buffer->GetSize(); + params.size = gpu_memory_buffer->GetSizeOfPlane(plane); params.format = gpu_memory_buffer->GetFormat(); params.plane = plane; params.color_space = color_space;
diff --git a/infra/config/generated/cr-buildbucket.cfg b/infra/config/generated/cr-buildbucket.cfg index 5c56abf..c308612 100644 --- a/infra/config/generated/cr-buildbucket.cfg +++ b/infra/config/generated/cr-buildbucket.cfg
@@ -7545,6 +7545,192 @@ } } builders { + name: "Linux Builder (core-32) (goma)" + swarming_host: "chromium-swarm.appspot.com" + swarming_tags: "vpython:native-python-wrapper" + dimensions: "builderless:1" + dimensions: "cores:32" + dimensions: "cpu:x86-64" + dimensions: "os:Ubuntu-16.04" + dimensions: "pool:luci.chromium.ci" + dimensions: "ssd:0" + exe { + cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" + cipd_version: "refs/heads/master" + cmd: "recipes" + } + properties: "{\"$build/goma\":{\"enable_ats\":true,\"jobs\":500,\"rpc_extra_params\":\"?prod\",\"server_host\":\"goma.chromium.org\",\"use_luci_auth\":true},\"$kitchen\":{\"devshell\":true,\"git_auth\":true},\"$recipe_engine/isolated\":{\"server\":\"https://isolateserver.appspot.com\"},\"builder_group\":\"chromium.fyi\",\"recipe\":\"chromium\"}" + execution_timeout_secs: 36000 + build_numbers: YES + service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" + experiments { + key: "chromium.resultdb.result_sink" + value: 100 + } + experiments { + key: "chromium.resultdb.result_sink.gtests_local" + value: 100 + } + experiments { + key: "chromium.resultdb.result_sink.junit_tests" + value: 100 + } + experiments { + key: "luci.buildbucket.use_bbagent" + value: 100 + } + experiments { + key: "luci.use_realms" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "luci-resultdb" + dataset: "chromium" + table: "ci_test_results" + test_results {} + } + bq_exports { + project: "luci-resultdb" + dataset: "chromium" + table: "gpu_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://(chrome/test:|content/test:fuchsia_)telemetry_gpu_integration_test/.+" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + } + builders { + name: "Linux Builder (core-32) (reclient)" + swarming_host: "chromium-swarm.appspot.com" + swarming_tags: "vpython:native-python-wrapper" + dimensions: "builderless:1" + dimensions: "cores:32" + dimensions: "cpu:x86-64" + dimensions: "os:Ubuntu-16.04" + dimensions: "pool:luci.chromium.ci" + dimensions: "ssd:0" + exe { + cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" + cipd_version: "refs/heads/master" + cmd: "recipes" + } + properties: "{\"$build/reclient\":{\"instance\":\"rbe-chromium-trusted\",\"jobs\":500,\"metrics_project\":\"chromium-reclient-metrics\"},\"$kitchen\":{\"devshell\":true,\"emulate_gce\":true,\"git_auth\":true},\"$recipe_engine/isolated\":{\"server\":\"https://isolateserver.appspot.com\"},\"builder_group\":\"chromium.fyi\",\"recipe\":\"chromium\"}" + execution_timeout_secs: 36000 + build_numbers: YES + service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" + experiments { + key: "chromium.resultdb.result_sink" + value: 100 + } + experiments { + key: "chromium.resultdb.result_sink.gtests_local" + value: 100 + } + experiments { + key: "chromium.resultdb.result_sink.junit_tests" + value: 100 + } + experiments { + key: "luci.buildbucket.use_bbagent" + value: 100 + } + experiments { + key: "luci.use_realms" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "luci-resultdb" + dataset: "chromium" + table: "ci_test_results" + test_results {} + } + bq_exports { + project: "luci-resultdb" + dataset: "chromium" + table: "gpu_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://(chrome/test:|content/test:fuchsia_)telemetry_gpu_integration_test/.+" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + } + builders { + name: "Linux Builder (core-32) (runsc) (reclient)" + swarming_host: "chromium-swarm.appspot.com" + swarming_tags: "vpython:native-python-wrapper" + dimensions: "builderless:1" + dimensions: "cores:32" + dimensions: "cpu:x86-64" + dimensions: "os:Ubuntu-16.04" + dimensions: "pool:luci.chromium.ci" + dimensions: "ssd:0" + exe { + cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" + cipd_version: "refs/heads/master" + cmd: "recipes" + } + properties: "{\"$build/reclient\":{\"instance\":\"rbe-chromium-gvisor-shadow\",\"jobs\":500,\"metrics_project\":\"chromium-reclient-metrics\"},\"$kitchen\":{\"devshell\":true,\"emulate_gce\":true,\"git_auth\":true},\"$recipe_engine/isolated\":{\"server\":\"https://isolateserver.appspot.com\"},\"builder_group\":\"chromium.fyi\",\"recipe\":\"chromium\"}" + execution_timeout_secs: 36000 + build_numbers: YES + service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" + experiments { + key: "chromium.resultdb.result_sink" + value: 100 + } + experiments { + key: "chromium.resultdb.result_sink.gtests_local" + value: 100 + } + experiments { + key: "chromium.resultdb.result_sink.junit_tests" + value: 100 + } + experiments { + key: "luci.buildbucket.use_bbagent" + value: 100 + } + experiments { + key: "luci.use_realms" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "luci-resultdb" + dataset: "chromium" + table: "ci_test_results" + test_results {} + } + bq_exports { + project: "luci-resultdb" + dataset: "chromium" + table: "gpu_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://(chrome/test:|content/test:fuchsia_)telemetry_gpu_integration_test/.+" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + } + builders { name: "Linux Builder (dbg)" swarming_host: "chromium-swarm.appspot.com" swarming_tags: "vpython:native-python-wrapper" @@ -25722,7 +25908,7 @@ dimensions: "builderless:1" dimensions: "cores:8" dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-16.04" + dimensions: "os:Ubuntu-18.04" dimensions: "pool:luci.chromium.ci" dimensions: "ssd:0" exe { @@ -26280,7 +26466,7 @@ dimensions: "builderless:1" dimensions: "cores:8" dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-16.04" + dimensions: "os:Ubuntu-18.04" dimensions: "pool:luci.chromium.ci" dimensions: "ssd:0" exe { @@ -26466,7 +26652,7 @@ dimensions: "builderless:1" dimensions: "cores:8" dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-16.04" + dimensions: "os:Ubuntu-18.04" dimensions: "pool:luci.chromium.ci" dimensions: "ssd:0" exe { @@ -46378,7 +46564,7 @@ dimensions: "builder:linux-chromeos-rel" dimensions: "cores:8" dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-16.04" + dimensions: "os:Ubuntu-18.04" dimensions: "pool:luci.chromium.try" exe { cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" @@ -47089,7 +47275,7 @@ dimensions: "builder:linux-lacros-rel" dimensions: "cores:16" dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-16.04" + dimensions: "os:Ubuntu-18.04" dimensions: "pool:luci.chromium.try" dimensions: "ssd:1" exe {
diff --git a/infra/config/generated/luci-milo.cfg b/infra/config/generated/luci-milo.cfg index a63b7481..04e19230 100644 --- a/infra/config/generated/luci-milo.cfg +++ b/infra/config/generated/luci-milo.cfg
@@ -5744,6 +5744,21 @@ category: "linux" } builders { + name: "buildbucket/luci.chromium.ci/Linux Builder (core-32) (goma)" + category: "linux" + short_name: "c32g" + } + builders { + name: "buildbucket/luci.chromium.ci/Linux Builder (core-32) (reclient)" + category: "linux" + short_name: "c32r" + } + builders { + name: "buildbucket/luci.chromium.ci/Linux Builder (core-32) (runsc) (reclient)" + category: "linux" + short_name: "c32rg" + } + builders { name: "buildbucket/luci.chromium.ci/Leak Detection Linux" category: "linux" short_name: "lk"
diff --git a/infra/config/generated/luci-scheduler.cfg b/infra/config/generated/luci-scheduler.cfg index 3839e67..4185651 100644 --- a/infra/config/generated/luci-scheduler.cfg +++ b/infra/config/generated/luci-scheduler.cfg
@@ -1606,6 +1606,39 @@ } } job { + id: "Linux Builder (core-32) (goma)" + realm: "ci" + schedule: "triggered" + acl_sets: "ci" + buildbucket { + server: "cr-buildbucket.appspot.com" + bucket: "luci.chromium.ci" + builder: "Linux Builder (core-32) (goma)" + } +} +job { + id: "Linux Builder (core-32) (reclient)" + realm: "ci" + schedule: "triggered" + acl_sets: "ci" + buildbucket { + server: "cr-buildbucket.appspot.com" + bucket: "luci.chromium.ci" + builder: "Linux Builder (core-32) (reclient)" + } +} +job { + id: "Linux Builder (core-32) (runsc) (reclient)" + realm: "ci" + schedule: "triggered" + acl_sets: "ci" + buildbucket { + server: "cr-buildbucket.appspot.com" + bucket: "luci.chromium.ci" + builder: "Linux Builder (core-32) (runsc) (reclient)" + } +} +job { id: "Linux Builder (dbg)" realm: "ci" acl_sets: "ci" @@ -6887,6 +6920,9 @@ triggers: "Libfuzzer Upload Windows ASan" triggers: "Linux ASan LSan Builder" triggers: "Linux Builder" + triggers: "Linux Builder (core-32) (goma)" + triggers: "Linux Builder (core-32) (reclient)" + triggers: "Linux Builder (core-32) (runsc) (reclient)" triggers: "Linux Builder (dbg)" triggers: "Linux Builder (dbg)(32)" triggers: "Linux Builder (deps-cache) (reclient)"
diff --git a/infra/config/subprojects/chromium/ci.star b/infra/config/subprojects/chromium/ci.star index ddcf2e7..ede15f1 100644 --- a/infra/config/subprojects/chromium/ci.star +++ b/infra/config/subprojects/chromium/ci.star
@@ -1827,6 +1827,7 @@ ), cq_mirrors_console_view = "mirrors", main_console_view = "main", + os = os.LINUX_BIONIC_REMOVE, ) ci.chromiumos_builder( @@ -1838,6 +1839,7 @@ ), cq_mirrors_console_view = "mirrors", main_console_view = "main", + os = os.LINUX_BIONIC_REMOVE, ) ci.chromiumos_builder( @@ -1851,6 +1853,7 @@ cq_mirrors_console_view = "mirrors", triggered_by = ["linux-lacros-builder-rel"], tree_closing = False, + os = os.LINUX_BIONIC_REMOVE, ) # For Chromebox for meetings(CfM) @@ -3508,6 +3511,51 @@ ) ci.fyi_builder( + name = "Linux Builder (core-32) (goma)", + console_view_entry = consoles.console_view_entry( + category = "linux", + short_name = "c32g", + ), + cores = 32, + goma_jobs = 500, + configure_kitchen = True, + os = os.LINUX_DEFAULT, + schedule = "triggered", +) + +ci.fyi_builder( + name = "Linux Builder (core-32) (reclient)", + console_view_entry = consoles.console_view_entry( + category = "linux", + short_name = "c32r", + ), + cores = 32, + goma_backend = None, + reclient_instance = "rbe-chromium-trusted", + reclient_jobs = 500, + configure_kitchen = True, + kitchen_emulate_gce = True, + os = os.LINUX_DEFAULT, + schedule = "triggered", +) + +ci.fyi_builder( + name = "Linux Builder (core-32) (runsc) (reclient)", + console_view_entry = consoles.console_view_entry( + category = "linux", + short_name = "c32rg", + ), + cores = 32, + goma_backend = None, + reclient_instance = "rbe-chromium-gvisor-shadow", + reclient_jobs = 500, + configure_kitchen = True, + kitchen_emulate_gce = True, + os = os.LINUX_DEFAULT, + schedule = "triggered", +) + +ci.fyi_builder( name = "Linux Builder (deps-cache) (reclient)", console_view_entry = consoles.console_view_entry( category = "linux",
diff --git a/infra/config/subprojects/chromium/try.star b/infra/config/subprojects/chromium/try.star index c6d43a5e..cc0531da 100644 --- a/infra/config/subprojects/chromium/try.star +++ b/infra/config/subprojects/chromium/try.star
@@ -852,6 +852,7 @@ main_list_view = "try", tryjob = try_.job(), use_clang_coverage = True, + os = os.LINUX_BIONIC_REMOVE, ) try_.chromium_chromiumos_builder( @@ -868,6 +869,7 @@ goma_jobs = goma.jobs.J300, main_list_view = "try", tryjob = try_.job(), + os = os.LINUX_BIONIC_REMOVE, ) try_.chromium_chromiumos_builder(
diff --git a/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.h b/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.h index 82e24c27..e1742999 100644 --- a/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.h +++ b/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.h
@@ -5,13 +5,15 @@ #ifndef IOS_CHROME_BROWSER_METRICS_IOS_CHROME_DEFAULT_BROWSER_METRICS_PROVIDER_H_ #define IOS_CHROME_BROWSER_METRICS_IOS_CHROME_DEFAULT_BROWSER_METRICS_PROVIDER_H_ +#include "components/metrics/metrics_log_uploader.h" #include "components/metrics/metrics_provider.h" // IOSChromeStabilityMetricsProvider records iOS default-browser related // metrics. class IOSChromeDefaultBrowserMetricsProvider : public metrics::MetricsProvider { public: - explicit IOSChromeDefaultBrowserMetricsProvider(); + explicit IOSChromeDefaultBrowserMetricsProvider( + metrics::MetricsLogUploader::MetricServiceType metrics_service_type); ~IOSChromeDefaultBrowserMetricsProvider() override; // metrics::MetricsProvider: @@ -20,6 +22,10 @@ private: DISALLOW_COPY_AND_ASSIGN(IOSChromeDefaultBrowserMetricsProvider); + + // The type of the metrics service for which to emit the user demographics + // status histogram (e.g., UMA). + const metrics::MetricsLogUploader::MetricServiceType metrics_service_type_; }; #endif // IOS_CHROME_BROWSER_METRICS_IOS_CHROME_DEFAULT_BROWSER_METRICS_PROVIDER_H_
diff --git a/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.mm b/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.mm index 22b02900..3352f44 100644 --- a/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.mm +++ b/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.mm
@@ -6,23 +6,38 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" +#include "components/metrics/metrics_log_uploader.h" +#include "components/ukm/ios/ukm_url_recorder.h" #import "ios/chrome/browser/ui/default_promo/default_browser_utils.h" +#include "services/metrics/public/cpp/ukm_builders.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif -IOSChromeDefaultBrowserMetricsProvider:: - IOSChromeDefaultBrowserMetricsProvider() {} +IOSChromeDefaultBrowserMetricsProvider::IOSChromeDefaultBrowserMetricsProvider( + metrics::MetricsLogUploader::MetricServiceType metrics_service_type) + : metrics_service_type_(metrics_service_type) {} IOSChromeDefaultBrowserMetricsProvider:: ~IOSChromeDefaultBrowserMetricsProvider() {} void IOSChromeDefaultBrowserMetricsProvider::ProvideCurrentSessionData( metrics::ChromeUserMetricsExtension* uma_proto) { - base::UmaHistogramBoolean("IOS.IsDefaultBrowser", - IsChromeLikelyDefaultBrowser()); - base::UmaHistogramBoolean( - "IOS.IsEligibleDefaultBrowserPromoUser", - IsLikelyInterestedDefaultBrowserUser(DefaultPromoTypeGeneral)); + bool is_default = IsChromeLikelyDefaultBrowser(); + + switch (metrics_service_type_) { + case metrics::MetricsLogUploader::MetricServiceType::UMA: + base::UmaHistogramBoolean("IOS.IsDefaultBrowser", is_default); + base::UmaHistogramBoolean( + "IOS.IsEligibleDefaultBrowserPromoUser", + IsLikelyInterestedDefaultBrowserUser(DefaultPromoTypeGeneral)); + return; + case metrics::MetricsLogUploader::MetricServiceType::UKM: + ukm::builders::IOS_IsDefaultBrowser(ukm::NoURLSourceId()) + .SetIsDefaultBrowser(is_default) + .Record(ukm::UkmRecorder::Get()); + return; + } + NOTREACHED(); }
diff --git a/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider_unittest.mm b/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider_unittest.mm index 5566e491..cd8e9629 100644 --- a/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider_unittest.mm +++ b/ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider_unittest.mm
@@ -5,6 +5,7 @@ #import "ios/chrome/browser/metrics/ios_chrome_default_browser_metrics_provider.h" #include "base/test/metrics/histogram_tester.h" +#include "components/metrics/metrics_log_uploader.h" #import "ios/chrome/browser/ui/default_promo/default_browser_utils.h" #include "testing/platform_test.h" @@ -23,7 +24,8 @@ TEST_F(IOSChromeDefaultBrowserMetricsProviderTest, ProvideCurrentSessionData) { [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLastHTTPURLOpenTime]; - IOSChromeDefaultBrowserMetricsProvider provider; + IOSChromeDefaultBrowserMetricsProvider provider( + metrics::MetricsLogUploader::MetricServiceType::UMA); provider.ProvideCurrentSessionData(nullptr /* uma_proto */); histogram_tester_.ExpectBucketCount("IOS.IsDefaultBrowser", false, 1); histogram_tester_.ExpectBucketCount("IOS.IsDefaultBrowser", true, 0);
diff --git a/ios/chrome/browser/metrics/ios_chrome_metrics_service_client.mm b/ios/chrome/browser/metrics/ios_chrome_metrics_service_client.mm index 35a07a8..a0c9561 100644 --- a/ios/chrome/browser/metrics/ios_chrome_metrics_service_client.mm +++ b/ios/chrome/browser/metrics/ios_chrome_metrics_service_client.mm
@@ -285,7 +285,8 @@ std::move(stability_metrics_provider)); metrics_service_->RegisterMetricsProvider( - std::make_unique<IOSChromeDefaultBrowserMetricsProvider>()); + std::make_unique<IOSChromeDefaultBrowserMetricsProvider>( + metrics::MetricsLogUploader::MetricServiceType::UMA)); // NOTE: metrics_state_manager_->IsMetricsReportingEnabled() returns false // during local testing. To test locally, modify @@ -337,6 +338,10 @@ ukm_service_->RegisterMetricsProvider( std::make_unique<variations::FieldTrialsProvider>(nullptr, kUKMFieldTrialSuffix)); + + metrics_service_->RegisterMetricsProvider( + std::make_unique<IOSChromeDefaultBrowserMetricsProvider>( + metrics::MetricsLogUploader::MetricServiceType::UKM)); } void IOSChromeMetricsServiceClient::CollectFinalHistograms() {
diff --git a/ios/chrome/browser/metrics/ios_chrome_metrics_service_client_unittest.mm b/ios/chrome/browser/metrics/ios_chrome_metrics_service_client_unittest.mm index 7788058..0ab0b68 100644 --- a/ios/chrome/browser/metrics/ios_chrome_metrics_service_client_unittest.mm +++ b/ios/chrome/browser/metrics/ios_chrome_metrics_service_client_unittest.mm
@@ -100,7 +100,7 @@ // This is the number of metrics providers that are registered inside // IOSChromeMetricsServiceClient::Initialize(). - expected_providers += 14; + expected_providers += 15; std::unique_ptr<IOSChromeMetricsServiceClient> chrome_metrics_service_client = IOSChromeMetricsServiceClient::Create(metrics_state_manager_.get());
diff --git a/ios/chrome/browser/ui/default_promo/tailored_promo_view_controller.mm b/ios/chrome/browser/ui/default_promo/tailored_promo_view_controller.mm index 0ee37b5..8f875b6b 100644 --- a/ios/chrome/browser/ui/default_promo/tailored_promo_view_controller.mm +++ b/ios/chrome/browser/ui/default_promo/tailored_promo_view_controller.mm
@@ -25,6 +25,7 @@ self.helpButtonAvailable = YES; self.primaryActionAvailable = YES; self.secondaryActionAvailable = YES; + self.imageHasFixedSize = YES; self.showDismissBarButton = NO; self.dismissBarButtonSystemItem = UIBarButtonSystemItemCancel; self.capitalizeTitle = NO;
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 index 93080739..6285771 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -cc99da2609bc1701ad400defb664b074df1edd1f \ No newline at end of file +ba2f750f898b6ed79ed4ecb839f16f0001e9a807 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 index 2a0679d..490dcc8 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -4e24a309f26c2ef99013ca1928c14575f253aaa8 \ No newline at end of file +bf0e4b81bfa593bc5dbcc4787baf7d0d61e3b76b \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 index 34289aa..49a0b651 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -45d4cc26d7a09b569e29f8fa60cdf677a50cf169 \ No newline at end of file +3490c9d3e7789fb60de05eab452aeba4fe25112e \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 index 9672f10..0f2c717b5 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -ef67e0103a5c3f2c0f1104aa65181cfdc84353da \ No newline at end of file +ce0b9ac57073f7779836b3972b586de6a2ad2863 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 index 9956539..93e921e 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -e2d0b2e4b41c3d64bebb7325e535075a87b57750 \ No newline at end of file +6bdc91143388e46ed412b107e0f76052e6270e4e \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 index fed6637a..cd8843f 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -bccfd385d7be4a825fd514b396d374a5d681e813 \ No newline at end of file +4d0b2ff2bc43edf0e4ba0e4bfdbaa00b993ef995 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 index 4fc38ab..dca3d61 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -419adfca73de7db4690181307e8553155a94ad41 \ No newline at end of file +7e82fa6fe85da49b245127cef40110f035ff68d6 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 index 3ef2e58..b8d09dc 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -03b3204010a7d95d413500591f9c39e05b16ee1d \ No newline at end of file +c6d2edb6c5280206d39935f515dc59510dc57e7f \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 index dfa3854..11cef89 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -99a84e09a49e63d49f9f2412d96b01ec5a51c946 \ No newline at end of file +f1dd6b281593161865a21301ee45063e2764622c \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 index a8a9736..476ccab 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -c2fe41d9583c39fdcc0078a36183b27c632bab86 \ No newline at end of file +a9a1b46c3da25dbdc8c314ad457806f3fd3f2906 \ No newline at end of file
diff --git a/media/mojo/mojom/BUILD.gn b/media/mojo/mojom/BUILD.gn index eacf42a..727d993 100644 --- a/media/mojo/mojom/BUILD.gn +++ b/media/mojo/mojom/BUILD.gn
@@ -536,6 +536,17 @@ "//ui/gfx/geometry/mojom", ] }, + { + types = [ + { + mojom = "media.mojom.CdmCapability" + cpp = "::media::CdmCapability" + }, + ] + traits_headers = [ "cdm_capability_mojom_traits.h" ] + traits_sources = [ "cdm_capability_mojom_traits.cc" ] + traits_public_deps = [ "//media" ] + }, ] cpp_typemaps += shared_typemaps
diff --git a/media/mojo/mojom/cdm_capability_mojom_traits.cc b/media/mojo/mojom/cdm_capability_mojom_traits.cc new file mode 100644 index 0000000..ac48d09 --- /dev/null +++ b/media/mojo/mojom/cdm_capability_mojom_traits.cc
@@ -0,0 +1,35 @@ +// Copyright 2021 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 "media/mojo/mojom/cdm_capability_mojom_traits.h" + +#include <utility> + +namespace mojo { + +// static +bool StructTraits<media::mojom::CdmCapabilityDataView, media::CdmCapability>:: + Read(media::mojom::CdmCapabilityDataView input, + media::CdmCapability* output) { + std::vector<media::VideoCodec> video_codecs; + if (!input.ReadVideoCodecs(&video_codecs)) + return false; + + std::vector<media::EncryptionScheme> encryption_schemes; + if (!input.ReadEncryptionSchemes(&encryption_schemes)) + return false; + + std::vector<media::CdmSessionType> session_types; + if (!input.ReadSessionTypes(&session_types)) + return false; + + // |encryption_schemes| and |session_types| are convert to a base::flat_map + // implicitly. + *output = media::CdmCapability(std::move(video_codecs), + std::move(encryption_schemes), + std::move(session_types)); + return true; +} + +} // namespace mojo
diff --git a/media/mojo/mojom/cdm_capability_mojom_traits.h b/media/mojo/mojom/cdm_capability_mojom_traits.h new file mode 100644 index 0000000..f060329 --- /dev/null +++ b/media/mojo/mojom/cdm_capability_mojom_traits.h
@@ -0,0 +1,44 @@ +// Copyright 2021 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 MEDIA_MOJO_MOJOM_CDM_CAPABILITY_MOJOM_TRAITS_H_ +#define MEDIA_MOJO_MOJOM_CDM_CAPABILITY_MOJOM_TRAITS_H_ + +#include <vector> + +#include "base/containers/flat_set.h" +#include "media/base/content_decryption_module.h" +#include "media/base/encryption_scheme.h" +#include "media/base/video_codecs.h" +#include "media/cdm/cdm_capability.h" +#include "media/mojo/mojom/key_system_support.mojom.h" + +namespace mojo { + +template <> +struct StructTraits<media::mojom::CdmCapabilityDataView, media::CdmCapability> { + static const std::vector<media::VideoCodec>& video_codecs( + const media::CdmCapability& input) { + return input.video_codecs; + } + + // List of encryption schemes supported by the CDM (e.g. cenc). + static const base::flat_set<media::EncryptionScheme>& encryption_schemes( + const media::CdmCapability& input) { + return input.encryption_schemes; + } + + // List of session types supported by the CDM. + static const base::flat_set<media::CdmSessionType>& session_types( + const media::CdmCapability& input) { + return input.session_types; + } + + static bool Read(media::mojom::CdmCapabilityDataView input, + media::CdmCapability* output); +}; + +} // namespace mojo + +#endif // MEDIA_MOJO_MOJOM_CDM_CAPABILITY_MOJOM_TRAITS_H_
diff --git a/media/mojo/mojom/key_system_support.mojom b/media/mojo/mojom/key_system_support.mojom index ce62672..b46dd12d 100644 --- a/media/mojo/mojom/key_system_support.mojom +++ b/media/mojo/mojom/key_system_support.mojom
@@ -10,20 +10,18 @@ // TODO(xhwang): Use "set" instead of "array" if supported by mojom. // TODO(crbug.com/796725) Find a way to include profiles and levels for // supported codecs. -struct KeySystemCapability { - // Software secure codecs and encryption schemes supported by the CDM. +struct CdmCapability { array<VideoCodec> video_codecs; array<EncryptionScheme> encryption_schemes; - - // Hardware secure codecs and encryption schemes supported by the CDM. - array<VideoCodec> hw_secure_video_codecs; - array<EncryptionScheme> hw_secure_encryption_schemes; - - // Session types supported in software secure mode if no - // |hw_secure_video_codecs| is supported, or in both modes otherwise. array<CdmSessionType> session_types; }; +struct KeySystemCapability { + CdmCapability? sw_secure_capability; + CdmCapability? hw_secure_capability; +}; + +// Used to query the browser to see if a specific key system is supported. interface KeySystemSupport { // Query to determine if the browser supports the |key_system|. If supported, // |key_system_capability| is non-null indicating supported capability.
diff --git a/mojo/public/cpp/bindings/array_traits_stl.h b/mojo/public/cpp/bindings/array_traits_stl.h index c72b2a1..68f44df 100644 --- a/mojo/public/cpp/bindings/array_traits_stl.h +++ b/mojo/public/cpp/bindings/array_traits_stl.h
@@ -11,6 +11,7 @@ #include <unordered_set> #include <vector> +#include "base/containers/flat_set.h" #include "mojo/public/cpp/bindings/array_traits.h" namespace mojo { @@ -112,6 +113,24 @@ } }; +// This ArrayTraits specialization is used only for serialization. +template <typename T> +struct ArrayTraits<base::flat_set<T>> { + using Element = T; + using ConstIterator = typename base::flat_set<T>::const_iterator; + + static bool IsNull(const base::flat_set<T>& input) { + // base::flat_set<> is always converted to non-null mojom array. + return false; + } + static size_t GetSize(const base::flat_set<T>& input) { return input.size(); } + static ConstIterator GetBegin(const base::flat_set<T>& input) { + return input.begin(); + } + static void AdvanceIterator(ConstIterator& iterator) { ++iterator; } + static const T& GetValue(ConstIterator& iterator) { return *iterator; } +}; + template <typename K, typename V> struct MapValuesArrayView { explicit MapValuesArrayView(const std::map<K, V>& map) : map(map) {}
diff --git a/net/BUILD.gn b/net/BUILD.gn index 15c13db..0adf237 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -32,8 +32,8 @@ enable_built_in_dns = !is_ios -# Unix sockets are not supported on iOS or NaCl. -enable_unix_sockets = is_posix && !is_ios && !is_nacl +# Unix sockets are not supported on iOS. +enable_unix_sockets = is_posix && !is_ios # x86/x64 cast_shell builds run on regular trybots and can use python runtime # and remote test server. ARM cast_shell builds don't have python runtime. @@ -117,18 +117,46 @@ "base/address_list.h", "base/auth.cc", "base/auth.h", + "base/backoff_entry.cc", + "base/backoff_entry.h", + "base/backoff_entry_serializer.cc", + "base/backoff_entry_serializer.h", + "base/cache_metrics.cc", + "base/cache_metrics.h", + "base/cache_type.h", + "base/chunked_upload_data_stream.cc", + "base/chunked_upload_data_stream.h", "base/completion_once_callback.h", "base/completion_repeating_callback.h", + "base/data_url.cc", + "base/data_url.h", "base/datagram_buffer.cc", "base/datagram_buffer.h", + "base/elements_upload_data_stream.cc", + "base/elements_upload_data_stream.h", "base/escape.cc", "base/escape.h", + "base/expiring_cache.h", "base/features.cc", "base/features.h", + "base/file_stream.cc", + "base/file_stream.h", + "base/file_stream_context.cc", + "base/file_stream_context.h", + "base/filename_util.cc", + "base/filename_util.h", + "base/filename_util_internal.cc", + "base/filename_util_internal.h", "base/hash_value.cc", "base/hash_value.h", + "base/hex_utils.cc", + "base/hex_utils.h", + "base/host_mapping_rules.cc", + "base/host_mapping_rules.h", "base/host_port_pair.cc", "base/host_port_pair.h", + "base/http_user_agent_settings.h", + "base/idempotency.h", "base/interval.h", "base/io_buffer.cc", "base/io_buffer.h", @@ -136,59 +164,135 @@ "base/ip_address.h", "base/ip_endpoint.cc", "base/ip_endpoint.h", + "base/isolation_info.cc", + "base/isolation_info.h", + "base/load_flags.h", + "base/load_flags_list.h", + "base/load_states.h", + "base/load_states_list.h", "base/load_timing_info.cc", "base/load_timing_info.h", + "base/logging_network_change_observer.cc", + "base/logging_network_change_observer.h", "base/lookup_string_in_fixed_set.cc", "base/lookup_string_in_fixed_set.h", + "base/mime_sniffer.cc", + "base/mime_sniffer.h", + "base/mime_util.cc", + "base/mime_util.h", "base/net_error_details.h", "base/net_error_list.h", "base/net_errors.cc", "base/net_errors.h", + "base/net_info_source_list.h", "base/net_module.cc", "base/net_module.h", "base/net_string_util.h", + "base/network_activity_monitor.cc", + "base/network_activity_monitor.h", + "base/network_change_notifier.cc", + "base/network_change_notifier.h", + "base/network_change_notifier_factory.h", + "base/network_delegate.cc", + "base/network_delegate.h", + "base/network_delegate_impl.cc", + "base/network_delegate_impl.h", "base/network_interfaces.cc", "base/network_interfaces.h", + "base/network_isolation_key.cc", + "base/network_isolation_key.h", "base/parse_number.cc", "base/parse_number.h", + "base/platform_mime_util.h", "base/port_util.cc", "base/port_util.h", + "base/prioritized_dispatcher.cc", + "base/prioritized_dispatcher.h", + "base/prioritized_task_runner.cc", + "base/prioritized_task_runner.h", + "base/priority_queue.h", "base/privacy_mode.cc", "base/privacy_mode.h", + "base/proxy_delegate.h", + "base/proxy_server.cc", + "base/proxy_server.h", "base/rand_callback.h", "base/registry_controlled_domains/registry_controlled_domain.cc", "base/registry_controlled_domains/registry_controlled_domain.h", + "base/request_priority.cc", + "base/request_priority.h", + "base/scheme_host_port_matcher.cc", + "base/scheme_host_port_matcher.h", + "base/scheme_host_port_matcher_result.h", + "base/scheme_host_port_matcher_rule.cc", + "base/scheme_host_port_matcher_rule.h", "base/schemeful_site.cc", "base/schemeful_site.h", "base/sockaddr_storage.cc", "base/sockaddr_storage.h", "base/sys_addrinfo.h", + "base/test_data_stream.cc", + "base/test_data_stream.h", "base/transport_info.cc", "base/transport_info.h", + "base/upload_bytes_element_reader.cc", + "base/upload_bytes_element_reader.h", + "base/upload_data_stream.cc", + "base/upload_data_stream.h", + "base/upload_element_reader.cc", + "base/upload_element_reader.h", + "base/upload_file_element_reader.cc", + "base/upload_file_element_reader.h", + "base/upload_progress.h", "base/url_util.cc", "base/url_util.h", "cert/asn1_util.cc", "cert/asn1_util.h", + "cert/caching_cert_verifier.cc", + "cert/caching_cert_verifier.h", "cert/cert_and_ct_verifier.cc", "cert/cert_and_ct_verifier.h", "cert/cert_database.cc", "cert/cert_database.h", + "cert/cert_net_fetcher.h", "cert/cert_status_flags.cc", "cert/cert_status_flags.h", "cert/cert_status_flags_list.h", "cert/cert_verifier.cc", "cert/cert_verifier.h", + "cert/cert_verify_proc.cc", + "cert/cert_verify_proc.h", + "cert/cert_verify_proc_builtin.cc", + "cert/cert_verify_proc_builtin.h", "cert/cert_verify_result.cc", "cert/cert_verify_result.h", "cert/client_cert_verifier.h", + "cert/coalescing_cert_verifier.cc", + "cert/coalescing_cert_verifier.h", "cert/crl_set.cc", "cert/crl_set.h", + "cert/ct_log_response_parser.cc", + "cert/ct_log_response_parser.h", + "cert/ct_log_verifier.cc", + "cert/ct_log_verifier.h", + "cert/ct_log_verifier_util.cc", + "cert/ct_log_verifier_util.h", + "cert/ct_objects_extractor.cc", + "cert/ct_objects_extractor.h", "cert/ct_policy_enforcer.cc", "cert/ct_policy_enforcer.h", "cert/ct_policy_status.h", + "cert/ct_sct_to_string.cc", + "cert/ct_sct_to_string.h", + "cert/ct_serialization.cc", + "cert/ct_serialization.h", + "cert/ct_signed_certificate_timestamp_log_param.cc", + "cert/ct_signed_certificate_timestamp_log_param.h", "cert/ct_verifier.h", "cert/do_nothing_ct_verifier.cc", "cert/do_nothing_ct_verifier.h", + "cert/ev_root_ca_metadata.cc", + "cert/ev_root_ca_metadata.h", "cert/internal/cert_error_id.cc", "cert/internal/cert_error_id.h", "cert/internal/cert_error_params.cc", @@ -230,6 +334,8 @@ "cert/internal/signature_algorithm.h", "cert/internal/simple_path_builder_delegate.cc", "cert/internal/simple_path_builder_delegate.h", + "cert/internal/system_trust_store.cc", + "cert/internal/system_trust_store.h", "cert/internal/trust_store.cc", "cert/internal/trust_store.h", "cert/internal/trust_store_collection.cc", @@ -242,11 +348,24 @@ "cert/internal/verify_name_match.h", "cert/internal/verify_signed_data.cc", "cert/internal/verify_signed_data.h", + "cert/known_roots.cc", + "cert/known_roots.h", + "cert/merkle_audit_proof.cc", + "cert/merkle_audit_proof.h", + "cert/merkle_consistency_proof.cc", + "cert/merkle_consistency_proof.h", + "cert/merkle_tree_leaf.cc", + "cert/merkle_tree_leaf.h", + "cert/multi_log_ct_verifier.cc", + "cert/multi_log_ct_verifier.h", + "cert/multi_threaded_cert_verifier.cc", + "cert/multi_threaded_cert_verifier.h", "cert/ocsp_revocation_status.h", "cert/ocsp_verify_result.cc", "cert/ocsp_verify_result.h", "cert/pem.cc", "cert/pem.h", + "cert/root_cert_list_generated.h", "cert/sct_auditing_delegate.h", "cert/sct_status_flags.cc", "cert/sct_status_flags.h", @@ -258,6 +377,8 @@ "cert/signed_tree_head.h", "cert/symantec_certs.cc", "cert/symantec_certs.h", + "cert/test_root_certs.cc", + "cert/test_root_certs.h", "cert/x509_cert_types.cc", "cert/x509_cert_types.h", "cert/x509_certificate.cc", @@ -266,6 +387,40 @@ "cert/x509_certificate_net_log_param.h", "cert/x509_util.cc", "cert/x509_util.h", + "cert_net/cert_net_fetcher_url_request.cc", + "cert_net/cert_net_fetcher_url_request.h", + "cookies/canonical_cookie.cc", + "cookies/canonical_cookie.h", + "cookies/cookie_access_delegate.cc", + "cookies/cookie_access_delegate.h", + "cookies/cookie_access_result.cc", + "cookies/cookie_access_result.h", + "cookies/cookie_change_dispatcher.cc", + "cookies/cookie_change_dispatcher.h", + "cookies/cookie_constants.cc", + "cookies/cookie_constants.h", + "cookies/cookie_deletion_info.cc", + "cookies/cookie_deletion_info.h", + "cookies/cookie_inclusion_status.cc", + "cookies/cookie_inclusion_status.h", + "cookies/cookie_monster.cc", + "cookies/cookie_monster.h", + "cookies/cookie_monster_change_dispatcher.cc", + "cookies/cookie_monster_change_dispatcher.h", + "cookies/cookie_monster_netlog_params.cc", + "cookies/cookie_monster_netlog_params.h", + "cookies/cookie_options.cc", + "cookies/cookie_options.h", + "cookies/cookie_store.cc", + "cookies/cookie_store.h", + "cookies/cookie_util.cc", + "cookies/cookie_util.h", + "cookies/parsed_cookie.cc", + "cookies/parsed_cookie.h", + "cookies/site_for_cookies.cc", + "cookies/site_for_cookies.h", + "cookies/static_cookie_policy.cc", + "cookies/static_cookie_policy.h", "der/encode_values.cc", "der/encode_values.h", "der/input.cc", @@ -276,35 +431,222 @@ "der/parser.h", "der/tag.cc", "der/tag.h", + "disk_cache/backend_cleanup_tracker.cc", + "disk_cache/backend_cleanup_tracker.h", + "disk_cache/blockfile/addr.cc", + "disk_cache/blockfile/addr.h", + "disk_cache/blockfile/backend_impl.cc", + "disk_cache/blockfile/backend_impl.h", + "disk_cache/blockfile/bitmap.cc", + "disk_cache/blockfile/bitmap.h", + "disk_cache/blockfile/block_files.cc", + "disk_cache/blockfile/block_files.h", + "disk_cache/blockfile/disk_format.cc", + "disk_cache/blockfile/disk_format.h", + "disk_cache/blockfile/disk_format_base.h", + "disk_cache/blockfile/entry_impl.cc", + "disk_cache/blockfile/entry_impl.h", + "disk_cache/blockfile/errors.h", + "disk_cache/blockfile/eviction.cc", + "disk_cache/blockfile/eviction.h", + "disk_cache/blockfile/experiments.h", + "disk_cache/blockfile/file.cc", + "disk_cache/blockfile/file.h", + "disk_cache/blockfile/file_block.h", + "disk_cache/blockfile/file_lock.cc", + "disk_cache/blockfile/file_lock.h", + "disk_cache/blockfile/histogram_macros.h", + "disk_cache/blockfile/in_flight_backend_io.cc", + "disk_cache/blockfile/in_flight_backend_io.h", + "disk_cache/blockfile/in_flight_io.cc", + "disk_cache/blockfile/in_flight_io.h", + "disk_cache/blockfile/mapped_file.cc", + "disk_cache/blockfile/mapped_file.h", + "disk_cache/blockfile/rankings.cc", + "disk_cache/blockfile/rankings.h", + "disk_cache/blockfile/sparse_control.cc", + "disk_cache/blockfile/sparse_control.h", + "disk_cache/blockfile/stats.cc", + "disk_cache/blockfile/stats.h", + "disk_cache/blockfile/storage_block-inl.h", + "disk_cache/blockfile/storage_block.h", + "disk_cache/blockfile/stress_support.h", + "disk_cache/cache_util.cc", + "disk_cache/cache_util.h", + "disk_cache/disk_cache.cc", + "disk_cache/disk_cache.h", + "disk_cache/memory/mem_backend_impl.cc", + "disk_cache/memory/mem_backend_impl.h", + "disk_cache/memory/mem_entry_impl.cc", + "disk_cache/memory/mem_entry_impl.h", + "disk_cache/net_log_parameters.cc", + "disk_cache/net_log_parameters.h", + "disk_cache/simple/post_doom_waiter.cc", + "disk_cache/simple/post_doom_waiter.h", + "disk_cache/simple/simple_backend_impl.cc", + "disk_cache/simple/simple_backend_impl.h", + "disk_cache/simple/simple_backend_version.h", + "disk_cache/simple/simple_entry_format.cc", + "disk_cache/simple/simple_entry_format.h", + "disk_cache/simple/simple_entry_format_history.h", + "disk_cache/simple/simple_entry_impl.cc", + "disk_cache/simple/simple_entry_impl.h", + "disk_cache/simple/simple_entry_operation.cc", + "disk_cache/simple/simple_entry_operation.h", + "disk_cache/simple/simple_file_tracker.cc", + "disk_cache/simple/simple_file_tracker.h", + "disk_cache/simple/simple_histogram_macros.h", + "disk_cache/simple/simple_index.cc", + "disk_cache/simple/simple_index.h", + "disk_cache/simple/simple_index_delegate.h", + "disk_cache/simple/simple_index_file.cc", + "disk_cache/simple/simple_index_file.h", + "disk_cache/simple/simple_net_log_parameters.cc", + "disk_cache/simple/simple_net_log_parameters.h", + "disk_cache/simple/simple_synchronous_entry.cc", + "disk_cache/simple/simple_synchronous_entry.h", + "disk_cache/simple/simple_util.cc", + "disk_cache/simple/simple_util.h", + "disk_cache/simple/simple_version_upgrade.cc", + "disk_cache/simple/simple_version_upgrade.h", + "filter/filter_source_stream.cc", + "filter/filter_source_stream.h", + "filter/gzip_header.cc", + "filter/gzip_header.h", + "filter/gzip_source_stream.cc", + "filter/gzip_source_stream.h", + "filter/source_stream.cc", + "filter/source_stream.h", + "http/alternative_service.cc", + "http/alternative_service.h", + "http/bidirectional_stream.cc", + "http/bidirectional_stream.h", + "http/bidirectional_stream_impl.cc", + "http/bidirectional_stream_impl.h", + "http/bidirectional_stream_request_info.cc", + "http/bidirectional_stream_request_info.h", + "http/broken_alternative_services.cc", + "http/broken_alternative_services.h", "http/hsts_info.h", + "http/http_auth.cc", + "http/http_auth.h", + "http/http_auth_cache.cc", + "http/http_auth_cache.h", "http/http_auth_challenge_tokenizer.cc", "http/http_auth_challenge_tokenizer.h", + "http/http_auth_controller.cc", + "http/http_auth_controller.h", + "http/http_auth_filter.cc", + "http/http_auth_filter.h", + "http/http_auth_handler.cc", + "http/http_auth_handler.h", + "http/http_auth_handler_basic.cc", + "http/http_auth_handler_basic.h", + "http/http_auth_handler_digest.cc", + "http/http_auth_handler_digest.h", + "http/http_auth_handler_factory.cc", + "http/http_auth_handler_factory.h", + "http/http_auth_handler_ntlm.cc", + "http/http_auth_handler_ntlm.h", + "http/http_auth_mechanism.h", + "http/http_auth_multi_round_parse.cc", + "http/http_auth_multi_round_parse.h", + "http/http_auth_preferences.cc", + "http/http_auth_preferences.h", "http/http_auth_scheme.cc", "http/http_auth_scheme.h", + "http/http_basic_state.cc", + "http/http_basic_state.h", + "http/http_basic_stream.cc", + "http/http_basic_stream.h", "http/http_byte_range.cc", "http/http_byte_range.h", + "http/http_cache.cc", + "http/http_cache.h", + "http/http_cache_lookup_manager.cc", + "http/http_cache_lookup_manager.h", + "http/http_cache_transaction.cc", + "http/http_cache_transaction.h", + "http/http_cache_writers.cc", + "http/http_cache_writers.h", + "http/http_chunked_decoder.cc", + "http/http_chunked_decoder.h", + "http/http_content_disposition.cc", + "http/http_content_disposition.h", "http/http_log_util.cc", "http/http_log_util.h", + "http/http_network_layer.cc", + "http/http_network_layer.h", + "http/http_network_session.cc", + "http/http_network_session.h", + "http/http_network_session_peer.cc", + "http/http_network_session_peer.h", + "http/http_network_transaction.cc", + "http/http_network_transaction.h", + "http/http_proxy_client_socket.cc", + "http/http_proxy_client_socket.h", + "http/http_proxy_connect_job.cc", + "http/http_proxy_connect_job.h", "http/http_raw_request_headers.cc", "http/http_raw_request_headers.h", "http/http_request_headers.cc", "http/http_request_headers.h", + "http/http_request_info.cc", + "http/http_request_info.h", + "http/http_response_body_drainer.cc", + "http/http_response_body_drainer.h", "http/http_response_headers.cc", "http/http_response_headers.h", "http/http_response_info.cc", "http/http_response_info.h", "http/http_security_headers.cc", "http/http_security_headers.h", + "http/http_server_properties.cc", + "http/http_server_properties.h", + "http/http_server_properties_manager.cc", + "http/http_server_properties_manager.h", + "http/http_status_code.cc", + "http/http_status_code.h", "http/http_status_code_list.h", + "http/http_stream.h", + "http/http_stream_factory.cc", + "http/http_stream_factory.h", + "http/http_stream_factory_job.cc", + "http/http_stream_factory_job.h", + "http/http_stream_factory_job_controller.cc", + "http/http_stream_factory_job_controller.h", + "http/http_stream_parser.cc", + "http/http_stream_parser.h", + "http/http_stream_request.cc", + "http/http_stream_request.h", + "http/http_transaction.h", + "http/http_transaction_factory.h", "http/http_util.cc", "http/http_util.h", "http/http_vary_data.cc", "http/http_vary_data.h", + "http/http_version.h", + "http/partial_data.cc", + "http/partial_data.h", + "http/proxy_client_socket.cc", + "http/proxy_client_socket.h", + "http/proxy_fallback.cc", + "http/proxy_fallback.h", "http/structured_headers.cc", "http/structured_headers.h", + "http/transport_security_persister.cc", + "http/transport_security_persister.h", "http/transport_security_state.h", "http/transport_security_state_source.cc", "http/transport_security_state_source.h", + "http/url_security_manager.cc", + "http/url_security_manager.h", + "http/webfonts_histogram.cc", + "http/webfonts_histogram.h", + "http2/platform/impl/http2_macros_impl.h", + "http2/platform/impl/http2_string_utils_impl.h", + "log/file_net_log_observer.cc", + "log/file_net_log_observer.h", "log/net_log.cc", "log/net_log.h", "log/net_log_capture_mode.cc", @@ -317,34 +659,315 @@ "log/net_log_source.h", "log/net_log_source_type.h", "log/net_log_source_type_list.h", + "log/net_log_util.cc", + "log/net_log_util.h", "log/net_log_values.cc", "log/net_log_values.h", "log/net_log_with_source.cc", "log/net_log_with_source.h", + "log/trace_net_log_observer.cc", + "log/trace_net_log_observer.h", + "nqe/cached_network_quality.cc", + "nqe/cached_network_quality.h", + "nqe/connectivity_monitor.cc", + "nqe/connectivity_monitor.h", + "nqe/effective_connection_type.cc", + "nqe/effective_connection_type.h", + "nqe/effective_connection_type_observer.h", + "nqe/event_creator.cc", + "nqe/event_creator.h", + "nqe/network_id.cc", + "nqe/network_id.h", + "nqe/network_qualities_prefs_manager.cc", + "nqe/network_qualities_prefs_manager.h", + "nqe/network_quality.cc", + "nqe/network_quality.h", + "nqe/network_quality_estimator.cc", + "nqe/network_quality_estimator.h", + "nqe/network_quality_estimator_params.cc", + "nqe/network_quality_estimator_params.h", + "nqe/network_quality_estimator_util.cc", + "nqe/network_quality_estimator_util.h", + "nqe/network_quality_observation.cc", + "nqe/network_quality_observation.h", + "nqe/network_quality_observation_source.h", + "nqe/network_quality_store.cc", + "nqe/network_quality_store.h", + "nqe/observation_buffer.cc", + "nqe/observation_buffer.h", + "nqe/peer_to_peer_connections_count_observer.h", + "nqe/pref_names.cc", + "nqe/pref_names.h", + "nqe/rtt_throughput_estimates_observer.h", + "nqe/socket_watcher.cc", + "nqe/socket_watcher.h", + "nqe/socket_watcher_factory.cc", + "nqe/socket_watcher_factory.h", + "nqe/throughput_analyzer.cc", + "nqe/throughput_analyzer.h", + "nqe/weighted_observation.h", + "proxy_resolution/configured_proxy_resolution_request.cc", + "proxy_resolution/configured_proxy_resolution_request.h", + "proxy_resolution/configured_proxy_resolution_service.cc", + "proxy_resolution/configured_proxy_resolution_service.h", + "proxy_resolution/dhcp_pac_file_fetcher.cc", + "proxy_resolution/dhcp_pac_file_fetcher.h", + "proxy_resolution/multi_threaded_proxy_resolver.cc", + "proxy_resolution/multi_threaded_proxy_resolver.h", + "proxy_resolution/network_delegate_error_observer.cc", + "proxy_resolution/network_delegate_error_observer.h", + "proxy_resolution/pac_file_data.cc", + "proxy_resolution/pac_file_data.h", + "proxy_resolution/pac_file_decider.cc", + "proxy_resolution/pac_file_decider.h", + "proxy_resolution/pac_file_fetcher.h", + "proxy_resolution/pac_file_fetcher_impl.cc", + "proxy_resolution/pac_file_fetcher_impl.h", + "proxy_resolution/polling_proxy_config_service.cc", + "proxy_resolution/polling_proxy_config_service.h", + "proxy_resolution/proxy_bypass_rules.cc", + "proxy_resolution/proxy_bypass_rules.h", + "proxy_resolution/proxy_config.cc", + "proxy_resolution/proxy_config.h", + "proxy_resolution/proxy_config_service.h", + "proxy_resolution/proxy_config_service_fixed.cc", + "proxy_resolution/proxy_config_service_fixed.h", + "proxy_resolution/proxy_config_with_annotation.cc", + "proxy_resolution/proxy_config_with_annotation.h", + "proxy_resolution/proxy_info.cc", + "proxy_resolution/proxy_info.h", + "proxy_resolution/proxy_list.cc", + "proxy_resolution/proxy_list.h", + "proxy_resolution/proxy_resolution_request.h", + "proxy_resolution/proxy_resolution_service.h", + "proxy_resolution/proxy_resolve_dns_operation.h", + "proxy_resolution/proxy_resolver.h", + "proxy_resolution/proxy_resolver_error_observer.h", + "proxy_resolution/proxy_resolver_factory.cc", + "proxy_resolution/proxy_resolver_factory.h", + "proxy_resolution/proxy_retry_info.h", + "quic/address_utils.h", + "quic/bidirectional_stream_quic_impl.cc", + "quic/bidirectional_stream_quic_impl.h", + "quic/crypto/proof_source_chromium.cc", + "quic/crypto/proof_source_chromium.h", + "quic/crypto/proof_verifier_chromium.cc", + "quic/crypto/proof_verifier_chromium.h", + "quic/dedicated_web_transport_http3_client.cc", + "quic/dedicated_web_transport_http3_client.h", + "quic/network_connection.cc", + "quic/network_connection.h", + "quic/platform/impl/quic_chromium_clock.cc", + "quic/platform/impl/quic_chromium_clock.h", + "quic/platform/impl/quic_client_stats_impl.h", + "quic/platform/impl/quic_containers_impl.h", + "quic/platform/impl/quic_error_code_wrappers_impl.h", + "quic/platform/impl/quic_file_utils_impl.h", + "quic/platform/impl/quic_flags_impl.cc", + "quic/platform/impl/quic_flags_impl.h", + "quic/platform/impl/quic_hostname_utils_impl.cc", + "quic/platform/impl/quic_hostname_utils_impl.h", + "quic/platform/impl/quic_iovec_impl.h", + "quic/platform/impl/quic_map_util_impl.h", + "quic/platform/impl/quic_mem_slice_impl.cc", + "quic/platform/impl/quic_mem_slice_impl.h", + "quic/platform/impl/quic_mem_slice_span_impl.cc", + "quic/platform/impl/quic_mem_slice_span_impl.h", + "quic/platform/impl/quic_mem_slice_storage_impl.cc", + "quic/platform/impl/quic_mem_slice_storage_impl.h", + "quic/platform/impl/quic_prefetch_impl.h", + "quic/platform/impl/quic_reference_counted_impl.h", + "quic/platform/impl/quic_server_stats_impl.h", + "quic/platform/impl/quic_sleep_impl.h", + "quic/platform/impl/quic_stack_trace_impl.h", + "quic/properties_based_quic_server_info.cc", + "quic/properties_based_quic_server_info.h", + "quic/quic_address_mismatch.cc", + "quic/quic_address_mismatch.h", + "quic/quic_chromium_alarm_factory.cc", + "quic/quic_chromium_alarm_factory.h", + "quic/quic_chromium_client_session.cc", + "quic/quic_chromium_client_session.h", + "quic/quic_chromium_client_stream.cc", + "quic/quic_chromium_client_stream.h", + "quic/quic_chromium_connection_helper.cc", + "quic/quic_chromium_connection_helper.h", + "quic/quic_chromium_packet_reader.cc", + "quic/quic_chromium_packet_reader.h", + "quic/quic_chromium_packet_writer.cc", + "quic/quic_chromium_packet_writer.h", + "quic/quic_client_session_cache.cc", + "quic/quic_client_session_cache.h", + "quic/quic_clock_skew_detector.cc", + "quic/quic_clock_skew_detector.h", + "quic/quic_connection_logger.cc", + "quic/quic_connection_logger.h", + "quic/quic_connectivity_monitor.cc", + "quic/quic_connectivity_monitor.h", + "quic/quic_connectivity_probing_manager.cc", + "quic/quic_connectivity_probing_manager.h", + "quic/quic_context.cc", + "quic/quic_context.h", + "quic/quic_crypto_client_config_handle.cc", + "quic/quic_crypto_client_config_handle.h", + "quic/quic_crypto_client_stream_factory.cc", + "quic/quic_crypto_client_stream_factory.h", + "quic/quic_event_logger.cc", + "quic/quic_event_logger.h", + "quic/quic_http3_logger.cc", + "quic/quic_http3_logger.h", + "quic/quic_http_stream.cc", + "quic/quic_http_stream.h", + "quic/quic_http_utils.cc", + "quic/quic_http_utils.h", + "quic/quic_proxy_client_socket.cc", + "quic/quic_proxy_client_socket.h", + "quic/quic_server_info.cc", + "quic/quic_server_info.h", + "quic/quic_session_key.cc", + "quic/quic_session_key.h", + "quic/quic_stream_factory.cc", + "quic/quic_stream_factory.h", + "quic/quic_transport_client.cc", + "quic/quic_transport_client.h", + "quic/quic_transport_error.cc", + "quic/quic_transport_error.h", + "quic/web_transport_client.cc", + "quic/web_transport_client.h", + "quiche/common/platform/impl/quiche_bug_tracker_impl.h", + "quiche/common/platform/impl/quiche_flag_utils_impl.h", + "quiche/common/platform/impl/quiche_flags_impl.cc", + "quiche/common/platform/impl/quiche_flags_impl.h", + "socket/client_socket_factory.cc", + "socket/client_socket_factory.h", "socket/client_socket_handle.cc", "socket/client_socket_handle.h", + "socket/client_socket_pool.cc", + "socket/client_socket_pool.h", + "socket/client_socket_pool_manager.cc", + "socket/client_socket_pool_manager.h", + "socket/client_socket_pool_manager_impl.cc", + "socket/client_socket_pool_manager_impl.h", "socket/connect_job.cc", "socket/connect_job.h", "socket/connection_attempts.h", + "socket/datagram_client_socket.h", + "socket/datagram_server_socket.h", + "socket/datagram_socket.h", + "socket/diff_serv_code_point.h", "socket/next_proto.cc", "socket/next_proto.h", + "socket/server_socket.cc", + "socket/server_socket.h", "socket/socket.cc", "socket/socket.h", "socket/socket_bio_adapter.cc", "socket/socket_bio_adapter.h", + "socket/socket_descriptor.cc", + "socket/socket_descriptor.h", + "socket/socket_net_log_params.cc", + "socket/socket_net_log_params.h", + "socket/socket_options.cc", + "socket/socket_options.h", "socket/socket_performance_watcher.h", "socket/socket_performance_watcher_factory.h", + "socket/socket_tag.cc", + "socket/socket_tag.h", + "socket/socks5_client_socket.cc", + "socket/socks5_client_socket.h", + "socket/socks_client_socket.cc", + "socket/socks_client_socket.h", + "socket/socks_connect_job.cc", + "socket/socks_connect_job.h", "socket/ssl_client_socket.cc", "socket/ssl_client_socket.h", "socket/ssl_client_socket_impl.cc", "socket/ssl_client_socket_impl.h", + "socket/ssl_connect_job.cc", + "socket/ssl_connect_job.h", + "socket/ssl_server_socket.h", + "socket/ssl_server_socket_impl.cc", + "socket/ssl_server_socket_impl.h", "socket/ssl_socket.h", "socket/stream_socket.cc", "socket/stream_socket.h", + "socket/tcp_client_socket.cc", + "socket/tcp_client_socket.h", + "socket/tcp_server_socket.cc", + "socket/tcp_server_socket.h", + "socket/tcp_socket.h", + "socket/transport_client_socket.cc", + "socket/transport_client_socket.h", + "socket/transport_client_socket_pool.cc", + "socket/transport_client_socket_pool.h", + "socket/transport_connect_job.cc", + "socket/transport_connect_job.h", + "socket/udp_client_socket.cc", + "socket/udp_client_socket.h", + "socket/udp_net_log_parameters.cc", + "socket/udp_net_log_parameters.h", + "socket/udp_server_socket.cc", + "socket/udp_server_socket.h", + "socket/udp_socket.h", + "socket/udp_socket_global_limits.cc", + "socket/udp_socket_global_limits.h", + "socket/websocket_endpoint_lock_manager.cc", + "socket/websocket_endpoint_lock_manager.h", + "socket/websocket_transport_client_socket_pool.cc", + "socket/websocket_transport_client_socket_pool.h", + "socket/websocket_transport_connect_job.cc", + "socket/websocket_transport_connect_job.h", + "socket/websocket_transport_connect_sub_job.cc", + "socket/websocket_transport_connect_sub_job.h", + "spdy/alps_decoder.cc", + "spdy/alps_decoder.h", + "spdy/bidirectional_stream_spdy_impl.cc", + "spdy/bidirectional_stream_spdy_impl.h", + "spdy/buffered_spdy_framer.cc", + "spdy/buffered_spdy_framer.h", + "spdy/header_coalescer.cc", + "spdy/header_coalescer.h", + "spdy/http2_priority_dependencies.cc", + "spdy/http2_priority_dependencies.h", + "spdy/http2_push_promise_index.cc", + "spdy/http2_push_promise_index.h", + "spdy/multiplexed_http_stream.cc", + "spdy/multiplexed_http_stream.h", + "spdy/multiplexed_session.cc", + "spdy/multiplexed_session.h", + "spdy/platform/impl/spdy_containers_impl.h", + "spdy/platform/impl/spdy_string_utils_impl.cc", + "spdy/platform/impl/spdy_string_utils_impl.h", + "spdy/server_push_delegate.h", + "spdy/spdy_buffer.cc", + "spdy/spdy_buffer.h", + "spdy/spdy_buffer_producer.cc", + "spdy/spdy_buffer_producer.h", + "spdy/spdy_http_stream.cc", + "spdy/spdy_http_stream.h", + "spdy/spdy_http_utils.cc", + "spdy/spdy_http_utils.h", + "spdy/spdy_log_util.cc", + "spdy/spdy_log_util.h", + "spdy/spdy_proxy_client_socket.cc", + "spdy/spdy_proxy_client_socket.h", + "spdy/spdy_read_queue.cc", + "spdy/spdy_read_queue.h", + "spdy/spdy_session.cc", + "spdy/spdy_session.h", + "spdy/spdy_session_key.cc", + "spdy/spdy_session_key.h", + "spdy/spdy_session_pool.cc", + "spdy/spdy_session_pool.h", + "spdy/spdy_stream.cc", + "spdy/spdy_stream.h", + "spdy/spdy_write_queue.cc", + "spdy/spdy_write_queue.h", "ssl/cert_compression.cc", "ssl/cert_compression.h", "ssl/client_cert_identity.cc", "ssl/client_cert_identity.h", + "ssl/client_cert_store.h", "ssl/openssl_ssl_util.cc", "ssl/openssl_ssl_util.h", "ssl/ssl_cert_request_info.cc", @@ -360,19 +983,85 @@ "ssl/ssl_config.h", "ssl/ssl_config_service.cc", "ssl/ssl_config_service.h", + "ssl/ssl_config_service_defaults.cc", + "ssl/ssl_config_service_defaults.h", "ssl/ssl_connection_status_flags.h", "ssl/ssl_handshake_details.h", "ssl/ssl_info.cc", "ssl/ssl_info.h", "ssl/ssl_key_logger.cc", "ssl/ssl_key_logger.h", + "ssl/ssl_key_logger_impl.cc", + "ssl/ssl_key_logger_impl.h", "ssl/ssl_legacy_crypto_fallback.h", + "ssl/ssl_platform_key_util.cc", + "ssl/ssl_platform_key_util.h", "ssl/ssl_private_key.cc", "ssl/ssl_private_key.h", "ssl/ssl_server_config.cc", "ssl/ssl_server_config.h", + "ssl/threaded_ssl_private_key.cc", + "ssl/threaded_ssl_private_key.h", "third_party/uri_template/uri_template.cc", "third_party/uri_template/uri_template.h", + "url_request/redirect_info.cc", + "url_request/redirect_info.h", + "url_request/redirect_util.cc", + "url_request/redirect_util.h", + "url_request/referrer_policy.h", + "url_request/report_sender.cc", + "url_request/report_sender.h", + "url_request/static_http_user_agent_settings.cc", + "url_request/static_http_user_agent_settings.h", + "url_request/url_fetcher.cc", + "url_request/url_fetcher.h", + "url_request/url_fetcher_core.cc", + "url_request/url_fetcher_core.h", + "url_request/url_fetcher_delegate.cc", + "url_request/url_fetcher_delegate.h", + "url_request/url_fetcher_factory.h", + "url_request/url_fetcher_impl.cc", + "url_request/url_fetcher_impl.h", + "url_request/url_fetcher_response_writer.cc", + "url_request/url_fetcher_response_writer.h", + "url_request/url_request.cc", + "url_request/url_request.h", + "url_request/url_request_context.cc", + "url_request/url_request_context.h", + "url_request/url_request_context_builder.cc", + "url_request/url_request_context_builder.h", + "url_request/url_request_context_getter.cc", + "url_request/url_request_context_getter.h", + "url_request/url_request_context_getter_observer.h", + "url_request/url_request_context_storage.cc", + "url_request/url_request_context_storage.h", + "url_request/url_request_error_job.cc", + "url_request/url_request_error_job.h", + "url_request/url_request_filter.cc", + "url_request/url_request_filter.h", + "url_request/url_request_http_job.cc", + "url_request/url_request_http_job.h", + "url_request/url_request_interceptor.cc", + "url_request/url_request_interceptor.h", + "url_request/url_request_job.cc", + "url_request/url_request_job.h", + "url_request/url_request_job_factory.cc", + "url_request/url_request_job_factory.h", + "url_request/url_request_netlog_params.cc", + "url_request/url_request_netlog_params.h", + "url_request/url_request_redirect_job.cc", + "url_request/url_request_redirect_job.h", + "url_request/url_request_test_job.cc", + "url_request/url_request_test_job.h", + "url_request/url_request_throttler_entry.cc", + "url_request/url_request_throttler_entry.h", + "url_request/url_request_throttler_entry_interface.h", + "url_request/url_request_throttler_manager.cc", + "url_request/url_request_throttler_manager.h", + "url_request/view_cache_helper.cc", + "url_request/view_cache_helper.h", + "url_request/websocket_handshake_userdata_key.cc", + "url_request/websocket_handshake_userdata_key.h", ] if (is_posix || is_fuchsia) { @@ -380,7 +1069,7 @@ } defines = [] - if (disable_brotli_filter || is_nacl) { + if (disable_brotli_filter) { defines += [ "NET_DISABLE_BROTLI" ] } @@ -413,1043 +1102,345 @@ "//net/third_party/quiche", ] - if (is_nacl) { - sources += [ "base/network_interfaces_nacl.cc" ] + if (enable_reporting) { + sources += [ + "network_error_logging/network_error_logging_service.cc", + "network_error_logging/network_error_logging_service.h", + "network_error_logging/persistent_reporting_and_nel_store.h", + "reporting/reporting_browsing_data_remover.cc", + "reporting/reporting_browsing_data_remover.h", + "reporting/reporting_cache.cc", + "reporting/reporting_cache.h", + "reporting/reporting_cache_impl.cc", + "reporting/reporting_cache_impl.h", + "reporting/reporting_cache_observer.cc", + "reporting/reporting_cache_observer.h", + "reporting/reporting_context.cc", + "reporting/reporting_context.h", + "reporting/reporting_delegate.cc", + "reporting/reporting_delegate.h", + "reporting/reporting_delivery_agent.cc", + "reporting/reporting_delivery_agent.h", + "reporting/reporting_endpoint.cc", + "reporting/reporting_endpoint.h", + "reporting/reporting_endpoint_manager.cc", + "reporting/reporting_endpoint_manager.h", + "reporting/reporting_garbage_collector.cc", + "reporting/reporting_garbage_collector.h", + "reporting/reporting_header_parser.cc", + "reporting/reporting_header_parser.h", + "reporting/reporting_network_change_observer.cc", + "reporting/reporting_network_change_observer.h", + "reporting/reporting_policy.cc", + "reporting/reporting_policy.h", + "reporting/reporting_report.cc", + "reporting/reporting_report.h", + "reporting/reporting_service.cc", + "reporting/reporting_service.h", + "reporting/reporting_uploader.cc", + "reporting/reporting_uploader.h", + ] } - if (!is_nacl) { + if (is_android) { sources += [ - "base/backoff_entry.cc", - "base/backoff_entry.h", - "base/backoff_entry_serializer.cc", - "base/backoff_entry_serializer.h", - "base/cache_metrics.cc", - "base/cache_metrics.h", - "base/cache_type.h", - "base/chunked_upload_data_stream.cc", - "base/chunked_upload_data_stream.h", - "base/data_url.cc", - "base/data_url.h", - "base/elements_upload_data_stream.cc", - "base/elements_upload_data_stream.h", - "base/expiring_cache.h", - "base/file_stream.cc", - "base/file_stream.h", - "base/file_stream_context.cc", - "base/file_stream_context.h", - "base/filename_util.cc", - "base/filename_util.h", - "base/filename_util_internal.cc", - "base/filename_util_internal.h", - "base/hex_utils.cc", - "base/hex_utils.h", - "base/host_mapping_rules.cc", - "base/host_mapping_rules.h", - "base/http_user_agent_settings.h", - "base/idempotency.h", - "base/isolation_info.cc", - "base/isolation_info.h", - "base/load_flags.h", - "base/load_flags_list.h", - "base/load_states.h", - "base/load_states_list.h", - "base/logging_network_change_observer.cc", - "base/logging_network_change_observer.h", - "base/mime_sniffer.cc", - "base/mime_sniffer.h", - "base/mime_util.cc", - "base/mime_util.h", - "base/net_info_source_list.h", - "base/network_activity_monitor.cc", - "base/network_activity_monitor.h", - "base/network_change_notifier.cc", - "base/network_change_notifier.h", - "base/network_change_notifier_factory.h", - "base/network_delegate.cc", - "base/network_delegate.h", - "base/network_delegate_impl.cc", - "base/network_delegate_impl.h", - "base/network_isolation_key.cc", - "base/network_isolation_key.h", - "base/platform_mime_util.h", - "base/prioritized_dispatcher.cc", - "base/prioritized_dispatcher.h", - "base/prioritized_task_runner.cc", - "base/prioritized_task_runner.h", - "base/priority_queue.h", - "base/proxy_delegate.h", - "base/proxy_server.cc", - "base/proxy_server.h", - "base/request_priority.cc", - "base/request_priority.h", - "base/scheme_host_port_matcher.cc", - "base/scheme_host_port_matcher.h", - "base/scheme_host_port_matcher_result.h", - "base/scheme_host_port_matcher_rule.cc", - "base/scheme_host_port_matcher_rule.h", - "base/test_data_stream.cc", - "base/test_data_stream.h", - "base/upload_bytes_element_reader.cc", - "base/upload_bytes_element_reader.h", - "base/upload_data_stream.cc", - "base/upload_data_stream.h", - "base/upload_element_reader.cc", - "base/upload_element_reader.h", - "base/upload_file_element_reader.cc", - "base/upload_file_element_reader.h", - "base/upload_progress.h", - "cert/caching_cert_verifier.cc", - "cert/caching_cert_verifier.h", - "cert/cert_net_fetcher.h", - "cert/cert_verify_proc.cc", - "cert/cert_verify_proc.h", - "cert/cert_verify_proc_builtin.cc", - "cert/cert_verify_proc_builtin.h", - "cert/coalescing_cert_verifier.cc", - "cert/coalescing_cert_verifier.h", - "cert/ct_log_response_parser.cc", - "cert/ct_log_response_parser.h", - "cert/ct_log_verifier.cc", - "cert/ct_log_verifier.h", - "cert/ct_log_verifier_util.cc", - "cert/ct_log_verifier_util.h", - "cert/ct_objects_extractor.cc", - "cert/ct_objects_extractor.h", - "cert/ct_sct_to_string.cc", - "cert/ct_sct_to_string.h", - "cert/ct_serialization.cc", - "cert/ct_serialization.h", - "cert/ct_signed_certificate_timestamp_log_param.cc", - "cert/ct_signed_certificate_timestamp_log_param.h", - "cert/ev_root_ca_metadata.cc", - "cert/ev_root_ca_metadata.h", - "cert/internal/system_trust_store.cc", - "cert/internal/system_trust_store.h", - "cert/known_roots.cc", - "cert/known_roots.h", - "cert/merkle_audit_proof.cc", - "cert/merkle_audit_proof.h", - "cert/merkle_consistency_proof.cc", - "cert/merkle_consistency_proof.h", - "cert/merkle_tree_leaf.cc", - "cert/merkle_tree_leaf.h", - "cert/multi_log_ct_verifier.cc", - "cert/multi_log_ct_verifier.h", - "cert/multi_threaded_cert_verifier.cc", - "cert/multi_threaded_cert_verifier.h", - "cert/root_cert_list_generated.h", - "cert/test_root_certs.cc", - "cert/test_root_certs.h", - "cert_net/cert_net_fetcher_url_request.cc", - "cert_net/cert_net_fetcher_url_request.h", - "cookies/canonical_cookie.cc", - "cookies/canonical_cookie.h", - "cookies/cookie_access_delegate.cc", - "cookies/cookie_access_delegate.h", - "cookies/cookie_access_result.cc", - "cookies/cookie_access_result.h", - "cookies/cookie_change_dispatcher.cc", - "cookies/cookie_change_dispatcher.h", - "cookies/cookie_constants.cc", - "cookies/cookie_constants.h", - "cookies/cookie_deletion_info.cc", - "cookies/cookie_deletion_info.h", - "cookies/cookie_inclusion_status.cc", - "cookies/cookie_inclusion_status.h", - "cookies/cookie_monster.cc", - "cookies/cookie_monster.h", - "cookies/cookie_monster_change_dispatcher.cc", - "cookies/cookie_monster_change_dispatcher.h", - "cookies/cookie_monster_netlog_params.cc", - "cookies/cookie_monster_netlog_params.h", - "cookies/cookie_options.cc", - "cookies/cookie_options.h", - "cookies/cookie_store.cc", - "cookies/cookie_store.h", - "cookies/cookie_util.cc", - "cookies/cookie_util.h", - "cookies/parsed_cookie.cc", - "cookies/parsed_cookie.h", - "cookies/site_for_cookies.cc", - "cookies/site_for_cookies.h", - "cookies/static_cookie_policy.cc", - "cookies/static_cookie_policy.h", - "disk_cache/backend_cleanup_tracker.cc", - "disk_cache/backend_cleanup_tracker.h", - "disk_cache/blockfile/addr.cc", - "disk_cache/blockfile/addr.h", - "disk_cache/blockfile/backend_impl.cc", - "disk_cache/blockfile/backend_impl.h", - "disk_cache/blockfile/bitmap.cc", - "disk_cache/blockfile/bitmap.h", - "disk_cache/blockfile/block_files.cc", - "disk_cache/blockfile/block_files.h", - "disk_cache/blockfile/disk_format.cc", - "disk_cache/blockfile/disk_format.h", - "disk_cache/blockfile/disk_format_base.h", - "disk_cache/blockfile/entry_impl.cc", - "disk_cache/blockfile/entry_impl.h", - "disk_cache/blockfile/errors.h", - "disk_cache/blockfile/eviction.cc", - "disk_cache/blockfile/eviction.h", - "disk_cache/blockfile/experiments.h", - "disk_cache/blockfile/file.cc", - "disk_cache/blockfile/file.h", - "disk_cache/blockfile/file_block.h", - "disk_cache/blockfile/file_lock.cc", - "disk_cache/blockfile/file_lock.h", - "disk_cache/blockfile/histogram_macros.h", - "disk_cache/blockfile/in_flight_backend_io.cc", - "disk_cache/blockfile/in_flight_backend_io.h", - "disk_cache/blockfile/in_flight_io.cc", - "disk_cache/blockfile/in_flight_io.h", - "disk_cache/blockfile/mapped_file.cc", - "disk_cache/blockfile/mapped_file.h", - "disk_cache/blockfile/rankings.cc", - "disk_cache/blockfile/rankings.h", - "disk_cache/blockfile/sparse_control.cc", - "disk_cache/blockfile/sparse_control.h", - "disk_cache/blockfile/stats.cc", - "disk_cache/blockfile/stats.h", - "disk_cache/blockfile/storage_block-inl.h", - "disk_cache/blockfile/storage_block.h", - "disk_cache/blockfile/stress_support.h", - "disk_cache/cache_util.cc", - "disk_cache/cache_util.h", - "disk_cache/disk_cache.cc", - "disk_cache/disk_cache.h", - "disk_cache/memory/mem_backend_impl.cc", - "disk_cache/memory/mem_backend_impl.h", - "disk_cache/memory/mem_entry_impl.cc", - "disk_cache/memory/mem_entry_impl.h", - "disk_cache/net_log_parameters.cc", - "disk_cache/net_log_parameters.h", - "disk_cache/simple/post_doom_waiter.cc", - "disk_cache/simple/post_doom_waiter.h", - "disk_cache/simple/simple_backend_impl.cc", - "disk_cache/simple/simple_backend_impl.h", - "disk_cache/simple/simple_backend_version.h", - "disk_cache/simple/simple_entry_format.cc", - "disk_cache/simple/simple_entry_format.h", - "disk_cache/simple/simple_entry_format_history.h", - "disk_cache/simple/simple_entry_impl.cc", - "disk_cache/simple/simple_entry_impl.h", - "disk_cache/simple/simple_entry_operation.cc", - "disk_cache/simple/simple_entry_operation.h", - "disk_cache/simple/simple_file_tracker.cc", - "disk_cache/simple/simple_file_tracker.h", - "disk_cache/simple/simple_histogram_macros.h", - "disk_cache/simple/simple_index.cc", - "disk_cache/simple/simple_index.h", - "disk_cache/simple/simple_index_delegate.h", - "disk_cache/simple/simple_index_file.cc", - "disk_cache/simple/simple_index_file.h", - "disk_cache/simple/simple_net_log_parameters.cc", - "disk_cache/simple/simple_net_log_parameters.h", - "disk_cache/simple/simple_synchronous_entry.cc", - "disk_cache/simple/simple_synchronous_entry.h", - "disk_cache/simple/simple_util.cc", - "disk_cache/simple/simple_util.h", - "disk_cache/simple/simple_version_upgrade.cc", - "disk_cache/simple/simple_version_upgrade.h", - "filter/filter_source_stream.cc", - "filter/filter_source_stream.h", - "filter/gzip_header.cc", - "filter/gzip_header.h", - "filter/gzip_source_stream.cc", - "filter/gzip_source_stream.h", - "filter/source_stream.cc", - "filter/source_stream.h", - "http/alternative_service.cc", - "http/alternative_service.h", - "http/bidirectional_stream.cc", - "http/bidirectional_stream.h", - "http/bidirectional_stream_impl.cc", - "http/bidirectional_stream_impl.h", - "http/bidirectional_stream_request_info.cc", - "http/bidirectional_stream_request_info.h", - "http/broken_alternative_services.cc", - "http/broken_alternative_services.h", - "http/http_auth.cc", - "http/http_auth.h", - "http/http_auth_cache.cc", - "http/http_auth_cache.h", - "http/http_auth_controller.cc", - "http/http_auth_controller.h", - "http/http_auth_filter.cc", - "http/http_auth_filter.h", - "http/http_auth_handler.cc", - "http/http_auth_handler.h", - "http/http_auth_handler_basic.cc", - "http/http_auth_handler_basic.h", - "http/http_auth_handler_digest.cc", - "http/http_auth_handler_digest.h", - "http/http_auth_handler_factory.cc", - "http/http_auth_handler_factory.h", - "http/http_auth_handler_ntlm.cc", - "http/http_auth_handler_ntlm.h", - "http/http_auth_mechanism.h", - "http/http_auth_multi_round_parse.cc", - "http/http_auth_multi_round_parse.h", - "http/http_auth_preferences.cc", - "http/http_auth_preferences.h", - "http/http_basic_state.cc", - "http/http_basic_state.h", - "http/http_basic_stream.cc", - "http/http_basic_stream.h", - "http/http_cache.cc", - "http/http_cache.h", - "http/http_cache_lookup_manager.cc", - "http/http_cache_lookup_manager.h", - "http/http_cache_transaction.cc", - "http/http_cache_transaction.h", - "http/http_cache_writers.cc", - "http/http_cache_writers.h", - "http/http_chunked_decoder.cc", - "http/http_chunked_decoder.h", - "http/http_content_disposition.cc", - "http/http_content_disposition.h", - "http/http_network_layer.cc", - "http/http_network_layer.h", - "http/http_network_session.cc", - "http/http_network_session.h", - "http/http_network_session_peer.cc", - "http/http_network_session_peer.h", - "http/http_network_transaction.cc", - "http/http_network_transaction.h", - "http/http_proxy_client_socket.cc", - "http/http_proxy_client_socket.h", - "http/http_proxy_connect_job.cc", - "http/http_proxy_connect_job.h", - "http/http_request_info.cc", - "http/http_request_info.h", - "http/http_response_body_drainer.cc", - "http/http_response_body_drainer.h", - "http/http_server_properties.cc", - "http/http_server_properties.h", - "http/http_server_properties_manager.cc", - "http/http_server_properties_manager.h", - "http/http_status_code.cc", - "http/http_status_code.h", - "http/http_stream.h", - "http/http_stream_factory.cc", - "http/http_stream_factory.h", - "http/http_stream_factory_job.cc", - "http/http_stream_factory_job.h", - "http/http_stream_factory_job_controller.cc", - "http/http_stream_factory_job_controller.h", - "http/http_stream_parser.cc", - "http/http_stream_parser.h", - "http/http_stream_request.cc", - "http/http_stream_request.h", - "http/http_transaction.h", - "http/http_transaction_factory.h", - "http/http_version.h", - "http/partial_data.cc", - "http/partial_data.h", - "http/proxy_client_socket.cc", - "http/proxy_client_socket.h", - "http/proxy_fallback.cc", - "http/proxy_fallback.h", - "http/transport_security_persister.cc", - "http/transport_security_persister.h", - "http/url_security_manager.cc", - "http/url_security_manager.h", - "http/webfonts_histogram.cc", - "http/webfonts_histogram.h", - "http2/platform/impl/http2_macros_impl.h", - "http2/platform/impl/http2_string_utils_impl.h", - "log/file_net_log_observer.cc", - "log/file_net_log_observer.h", - "log/net_log_util.cc", - "log/net_log_util.h", - "log/trace_net_log_observer.cc", - "log/trace_net_log_observer.h", - "nqe/cached_network_quality.cc", - "nqe/cached_network_quality.h", - "nqe/connectivity_monitor.cc", - "nqe/connectivity_monitor.h", - "nqe/effective_connection_type.cc", - "nqe/effective_connection_type.h", - "nqe/effective_connection_type_observer.h", - "nqe/event_creator.cc", - "nqe/event_creator.h", - "nqe/network_id.cc", - "nqe/network_id.h", - "nqe/network_qualities_prefs_manager.cc", - "nqe/network_qualities_prefs_manager.h", - "nqe/network_quality.cc", - "nqe/network_quality.h", - "nqe/network_quality_estimator.cc", - "nqe/network_quality_estimator.h", - "nqe/network_quality_estimator_params.cc", - "nqe/network_quality_estimator_params.h", - "nqe/network_quality_estimator_util.cc", - "nqe/network_quality_estimator_util.h", - "nqe/network_quality_observation.cc", - "nqe/network_quality_observation.h", - "nqe/network_quality_observation_source.h", - "nqe/network_quality_store.cc", - "nqe/network_quality_store.h", - "nqe/observation_buffer.cc", - "nqe/observation_buffer.h", - "nqe/peer_to_peer_connections_count_observer.h", - "nqe/pref_names.cc", - "nqe/pref_names.h", - "nqe/rtt_throughput_estimates_observer.h", - "nqe/socket_watcher.cc", - "nqe/socket_watcher.h", - "nqe/socket_watcher_factory.cc", - "nqe/socket_watcher_factory.h", - "nqe/throughput_analyzer.cc", - "nqe/throughput_analyzer.h", - "nqe/weighted_observation.h", - "proxy_resolution/configured_proxy_resolution_request.cc", - "proxy_resolution/configured_proxy_resolution_request.h", - "proxy_resolution/configured_proxy_resolution_service.cc", - "proxy_resolution/configured_proxy_resolution_service.h", - "proxy_resolution/dhcp_pac_file_fetcher.cc", - "proxy_resolution/dhcp_pac_file_fetcher.h", - "proxy_resolution/multi_threaded_proxy_resolver.cc", - "proxy_resolution/multi_threaded_proxy_resolver.h", - "proxy_resolution/network_delegate_error_observer.cc", - "proxy_resolution/network_delegate_error_observer.h", - "proxy_resolution/pac_file_data.cc", - "proxy_resolution/pac_file_data.h", - "proxy_resolution/pac_file_decider.cc", - "proxy_resolution/pac_file_decider.h", - "proxy_resolution/pac_file_fetcher.h", - "proxy_resolution/pac_file_fetcher_impl.cc", - "proxy_resolution/pac_file_fetcher_impl.h", - "proxy_resolution/polling_proxy_config_service.cc", - "proxy_resolution/polling_proxy_config_service.h", - "proxy_resolution/proxy_bypass_rules.cc", - "proxy_resolution/proxy_bypass_rules.h", - "proxy_resolution/proxy_config.cc", - "proxy_resolution/proxy_config.h", - "proxy_resolution/proxy_config_service.h", - "proxy_resolution/proxy_config_service_fixed.cc", - "proxy_resolution/proxy_config_service_fixed.h", - "proxy_resolution/proxy_config_with_annotation.cc", - "proxy_resolution/proxy_config_with_annotation.h", - "proxy_resolution/proxy_info.cc", - "proxy_resolution/proxy_info.h", - "proxy_resolution/proxy_list.cc", - "proxy_resolution/proxy_list.h", - "proxy_resolution/proxy_resolution_request.h", - "proxy_resolution/proxy_resolution_service.h", - "proxy_resolution/proxy_resolve_dns_operation.h", - "proxy_resolution/proxy_resolver.h", - "proxy_resolution/proxy_resolver_error_observer.h", - "proxy_resolution/proxy_resolver_factory.cc", - "proxy_resolution/proxy_resolver_factory.h", - "proxy_resolution/proxy_retry_info.h", - "quic/address_utils.h", - "quic/bidirectional_stream_quic_impl.cc", - "quic/bidirectional_stream_quic_impl.h", - "quic/crypto/proof_source_chromium.cc", - "quic/crypto/proof_source_chromium.h", - "quic/crypto/proof_verifier_chromium.cc", - "quic/crypto/proof_verifier_chromium.h", - "quic/dedicated_web_transport_http3_client.cc", - "quic/dedicated_web_transport_http3_client.h", - "quic/network_connection.cc", - "quic/network_connection.h", - "quic/platform/impl/quic_chromium_clock.cc", - "quic/platform/impl/quic_chromium_clock.h", - "quic/platform/impl/quic_client_stats_impl.h", - "quic/platform/impl/quic_containers_impl.h", - "quic/platform/impl/quic_error_code_wrappers_impl.h", - "quic/platform/impl/quic_file_utils_impl.h", - "quic/platform/impl/quic_flags_impl.cc", - "quic/platform/impl/quic_flags_impl.h", - "quic/platform/impl/quic_hostname_utils_impl.cc", - "quic/platform/impl/quic_hostname_utils_impl.h", - "quic/platform/impl/quic_iovec_impl.h", - "quic/platform/impl/quic_map_util_impl.h", - "quic/platform/impl/quic_mem_slice_impl.cc", - "quic/platform/impl/quic_mem_slice_impl.h", - "quic/platform/impl/quic_mem_slice_span_impl.cc", - "quic/platform/impl/quic_mem_slice_span_impl.h", - "quic/platform/impl/quic_mem_slice_storage_impl.cc", - "quic/platform/impl/quic_mem_slice_storage_impl.h", - "quic/platform/impl/quic_prefetch_impl.h", - "quic/platform/impl/quic_reference_counted_impl.h", - "quic/platform/impl/quic_server_stats_impl.h", - "quic/platform/impl/quic_sleep_impl.h", - "quic/platform/impl/quic_stack_trace_impl.h", - "quic/properties_based_quic_server_info.cc", - "quic/properties_based_quic_server_info.h", - "quic/quic_address_mismatch.cc", - "quic/quic_address_mismatch.h", - "quic/quic_chromium_alarm_factory.cc", - "quic/quic_chromium_alarm_factory.h", - "quic/quic_chromium_client_session.cc", - "quic/quic_chromium_client_session.h", - "quic/quic_chromium_client_stream.cc", - "quic/quic_chromium_client_stream.h", - "quic/quic_chromium_connection_helper.cc", - "quic/quic_chromium_connection_helper.h", - "quic/quic_chromium_packet_reader.cc", - "quic/quic_chromium_packet_reader.h", - "quic/quic_chromium_packet_writer.cc", - "quic/quic_chromium_packet_writer.h", - "quic/quic_client_session_cache.cc", - "quic/quic_client_session_cache.h", - "quic/quic_clock_skew_detector.cc", - "quic/quic_clock_skew_detector.h", - "quic/quic_connection_logger.cc", - "quic/quic_connection_logger.h", - "quic/quic_connectivity_monitor.cc", - "quic/quic_connectivity_monitor.h", - "quic/quic_connectivity_probing_manager.cc", - "quic/quic_connectivity_probing_manager.h", - "quic/quic_context.cc", - "quic/quic_context.h", - "quic/quic_crypto_client_config_handle.cc", - "quic/quic_crypto_client_config_handle.h", - "quic/quic_crypto_client_stream_factory.cc", - "quic/quic_crypto_client_stream_factory.h", - "quic/quic_event_logger.cc", - "quic/quic_event_logger.h", - "quic/quic_http3_logger.cc", - "quic/quic_http3_logger.h", - "quic/quic_http_stream.cc", - "quic/quic_http_stream.h", - "quic/quic_http_utils.cc", - "quic/quic_http_utils.h", - "quic/quic_proxy_client_socket.cc", - "quic/quic_proxy_client_socket.h", - "quic/quic_server_info.cc", - "quic/quic_server_info.h", - "quic/quic_session_key.cc", - "quic/quic_session_key.h", - "quic/quic_stream_factory.cc", - "quic/quic_stream_factory.h", - "quic/quic_transport_client.cc", - "quic/quic_transport_client.h", - "quic/quic_transport_error.cc", - "quic/quic_transport_error.h", - "quic/web_transport_client.cc", - "quic/web_transport_client.h", - "quiche/common/platform/impl/quiche_bug_tracker_impl.h", - "quiche/common/platform/impl/quiche_flag_utils_impl.h", - "quiche/common/platform/impl/quiche_flags_impl.cc", - "quiche/common/platform/impl/quiche_flags_impl.h", - "socket/client_socket_factory.cc", - "socket/client_socket_factory.h", - "socket/client_socket_pool.cc", - "socket/client_socket_pool.h", - "socket/client_socket_pool_manager.cc", - "socket/client_socket_pool_manager.h", - "socket/client_socket_pool_manager_impl.cc", - "socket/client_socket_pool_manager_impl.h", - "socket/datagram_client_socket.h", - "socket/datagram_server_socket.h", - "socket/datagram_socket.h", - "socket/diff_serv_code_point.h", - "socket/server_socket.cc", - "socket/server_socket.h", - "socket/socket_descriptor.cc", - "socket/socket_descriptor.h", - "socket/socket_net_log_params.cc", - "socket/socket_net_log_params.h", - "socket/socket_options.cc", - "socket/socket_options.h", - "socket/socket_tag.cc", - "socket/socket_tag.h", - "socket/socks5_client_socket.cc", - "socket/socks5_client_socket.h", - "socket/socks_client_socket.cc", - "socket/socks_client_socket.h", - "socket/socks_connect_job.cc", - "socket/socks_connect_job.h", - "socket/ssl_connect_job.cc", - "socket/ssl_connect_job.h", - "socket/ssl_server_socket.h", - "socket/ssl_server_socket_impl.cc", - "socket/ssl_server_socket_impl.h", - "socket/tcp_client_socket.cc", - "socket/tcp_client_socket.h", - "socket/tcp_server_socket.cc", - "socket/tcp_server_socket.h", - "socket/tcp_socket.h", - "socket/transport_client_socket.cc", - "socket/transport_client_socket.h", - "socket/transport_client_socket_pool.cc", - "socket/transport_client_socket_pool.h", - "socket/transport_connect_job.cc", - "socket/transport_connect_job.h", - "socket/udp_client_socket.cc", - "socket/udp_client_socket.h", - "socket/udp_net_log_parameters.cc", - "socket/udp_net_log_parameters.h", - "socket/udp_server_socket.cc", - "socket/udp_server_socket.h", - "socket/udp_socket.h", - "socket/udp_socket_global_limits.cc", - "socket/udp_socket_global_limits.h", - "socket/websocket_endpoint_lock_manager.cc", - "socket/websocket_endpoint_lock_manager.h", - "socket/websocket_transport_client_socket_pool.cc", - "socket/websocket_transport_client_socket_pool.h", - "socket/websocket_transport_connect_job.cc", - "socket/websocket_transport_connect_job.h", - "socket/websocket_transport_connect_sub_job.cc", - "socket/websocket_transport_connect_sub_job.h", - "spdy/alps_decoder.cc", - "spdy/alps_decoder.h", - "spdy/bidirectional_stream_spdy_impl.cc", - "spdy/bidirectional_stream_spdy_impl.h", - "spdy/buffered_spdy_framer.cc", - "spdy/buffered_spdy_framer.h", - "spdy/header_coalescer.cc", - "spdy/header_coalescer.h", - "spdy/http2_priority_dependencies.cc", - "spdy/http2_priority_dependencies.h", - "spdy/http2_push_promise_index.cc", - "spdy/http2_push_promise_index.h", - "spdy/multiplexed_http_stream.cc", - "spdy/multiplexed_http_stream.h", - "spdy/multiplexed_session.cc", - "spdy/multiplexed_session.h", - "spdy/platform/impl/spdy_containers_impl.h", - "spdy/platform/impl/spdy_string_utils_impl.cc", - "spdy/platform/impl/spdy_string_utils_impl.h", - "spdy/server_push_delegate.h", - "spdy/spdy_buffer.cc", - "spdy/spdy_buffer.h", - "spdy/spdy_buffer_producer.cc", - "spdy/spdy_buffer_producer.h", - "spdy/spdy_http_stream.cc", - "spdy/spdy_http_stream.h", - "spdy/spdy_http_utils.cc", - "spdy/spdy_http_utils.h", - "spdy/spdy_log_util.cc", - "spdy/spdy_log_util.h", - "spdy/spdy_proxy_client_socket.cc", - "spdy/spdy_proxy_client_socket.h", - "spdy/spdy_read_queue.cc", - "spdy/spdy_read_queue.h", - "spdy/spdy_session.cc", - "spdy/spdy_session.h", - "spdy/spdy_session_key.cc", - "spdy/spdy_session_key.h", - "spdy/spdy_session_pool.cc", - "spdy/spdy_session_pool.h", - "spdy/spdy_stream.cc", - "spdy/spdy_stream.h", - "spdy/spdy_write_queue.cc", - "spdy/spdy_write_queue.h", - "ssl/client_cert_store.h", - "ssl/ssl_config_service_defaults.cc", - "ssl/ssl_config_service_defaults.h", - "ssl/ssl_key_logger_impl.cc", - "ssl/ssl_key_logger_impl.h", - "ssl/ssl_platform_key_util.cc", - "ssl/ssl_platform_key_util.h", - "ssl/threaded_ssl_private_key.cc", - "ssl/threaded_ssl_private_key.h", - "url_request/redirect_info.cc", - "url_request/redirect_info.h", - "url_request/redirect_util.cc", - "url_request/redirect_util.h", - "url_request/referrer_policy.h", - "url_request/report_sender.cc", - "url_request/report_sender.h", - "url_request/static_http_user_agent_settings.cc", - "url_request/static_http_user_agent_settings.h", - "url_request/url_fetcher.cc", - "url_request/url_fetcher.h", - "url_request/url_fetcher_core.cc", - "url_request/url_fetcher_core.h", - "url_request/url_fetcher_delegate.cc", - "url_request/url_fetcher_delegate.h", - "url_request/url_fetcher_factory.h", - "url_request/url_fetcher_impl.cc", - "url_request/url_fetcher_impl.h", - "url_request/url_fetcher_response_writer.cc", - "url_request/url_fetcher_response_writer.h", - "url_request/url_request.cc", - "url_request/url_request.h", - "url_request/url_request_context.cc", - "url_request/url_request_context.h", - "url_request/url_request_context_builder.cc", - "url_request/url_request_context_builder.h", - "url_request/url_request_context_getter.cc", - "url_request/url_request_context_getter.h", - "url_request/url_request_context_getter_observer.h", - "url_request/url_request_context_storage.cc", - "url_request/url_request_context_storage.h", - "url_request/url_request_error_job.cc", - "url_request/url_request_error_job.h", - "url_request/url_request_filter.cc", - "url_request/url_request_filter.h", - "url_request/url_request_http_job.cc", - "url_request/url_request_http_job.h", - "url_request/url_request_interceptor.cc", - "url_request/url_request_interceptor.h", - "url_request/url_request_job.cc", - "url_request/url_request_job.h", - "url_request/url_request_job_factory.cc", - "url_request/url_request_job_factory.h", - "url_request/url_request_netlog_params.cc", - "url_request/url_request_netlog_params.h", - "url_request/url_request_redirect_job.cc", - "url_request/url_request_redirect_job.h", - "url_request/url_request_test_job.cc", - "url_request/url_request_test_job.h", - "url_request/url_request_throttler_entry.cc", - "url_request/url_request_throttler_entry.h", - "url_request/url_request_throttler_entry_interface.h", - "url_request/url_request_throttler_manager.cc", - "url_request/url_request_throttler_manager.h", - "url_request/view_cache_helper.cc", - "url_request/view_cache_helper.h", - "url_request/websocket_handshake_userdata_key.cc", - "url_request/websocket_handshake_userdata_key.h", + "android/android_http_util.cc", + "android/cellular_signal_strength.cc", + "android/cellular_signal_strength.h", + "android/cert_verify_result_android.cc", + "android/cert_verify_result_android.h", + "android/gurl_utils.cc", + "android/http_auth_negotiate_android.cc", + "android/http_auth_negotiate_android.h", + "android/keystore.cc", + "android/keystore.h", + "android/network_activation_request.cc", + "android/network_activation_request.h", + "android/network_change_notifier_android.cc", + "android/network_change_notifier_android.h", + "android/network_change_notifier_delegate_android.cc", + "android/network_change_notifier_delegate_android.h", + "android/network_change_notifier_factory_android.cc", + "android/network_change_notifier_factory_android.h", + "android/network_library.cc", + "android/network_library.h", + "android/traffic_stats.cc", + "android/traffic_stats.h", + "cert/cert_verify_proc_android.cc", + "cert/cert_verify_proc_android.h", + "cert/test_root_certs_android.cc", + "cert/x509_util_android.cc", + "proxy_resolution/proxy_config_service_android.cc", + "proxy_resolution/proxy_config_service_android.h", + "ssl/ssl_platform_key_android.cc", + "ssl/ssl_platform_key_android.h", ] + } - if (enable_reporting) { + if (is_chromeos_ash && use_nss_certs) { + sources += [ + "cert/nss_cert_database_chromeos.cc", + "cert/nss_cert_database_chromeos.h", + "cert/nss_profile_filter_chromeos.cc", + "cert/nss_profile_filter_chromeos.h", + ] + } + + if (is_ios) { + sources += [ + "cert/cert_verify_proc_ios.cc", + "cert/cert_verify_proc_ios.h", + "cert/x509_util_ios.cc", + "cert/x509_util_ios.h", + "disk_cache/blockfile/file_ios.cc", + "proxy_resolution/proxy_config_service_ios.cc", + "proxy_resolution/proxy_config_service_ios.h", + ] + } + + if (is_linux || is_chromeos_lacros) { + sources += [ + "base/network_change_notifier_linux.cc", + "base/network_change_notifier_linux.h", + "proxy_resolution/proxy_config_service_linux.cc", + "proxy_resolution/proxy_config_service_linux.h", + ] + } + + if (is_linux || is_chromeos || is_android) { + sources += [ + "base/address_tracker_linux.cc", + "base/address_tracker_linux.h", + "base/network_interfaces_linux.cc", + "base/network_interfaces_linux.h", + "base/platform_mime_util_linux.cc", + ] + } + + if (is_mac) { + sources += [ + "base/network_notification_thread_mac.cc", + "base/network_notification_thread_mac.h", + "cert/cert_database_mac.cc", + "cert/cert_verify_proc_mac.cc", + "cert/cert_verify_proc_mac.h", + "cert/internal/trust_store_mac.cc", + "cert/internal/trust_store_mac.h", + "cert/known_roots_mac.cc", + "cert/known_roots_mac.h", + "cert/test_keychain_search_list_mac.cc", + "cert/test_keychain_search_list_mac.h", + "cert/x509_util_mac.cc", + "cert/x509_util_mac.h", + "proxy_resolution/proxy_config_service_mac.cc", + "proxy_resolution/proxy_config_service_mac.h", + "ssl/client_cert_identity_mac.cc", + "ssl/client_cert_identity_mac.h", + "ssl/client_cert_store_mac.cc", + "ssl/client_cert_store_mac.h", + "ssl/ssl_platform_key_mac.cc", + "ssl/ssl_platform_key_mac.h", + ] + } + + if (is_apple) { + sources += [ + "base/mac/url_conversions.h", + "base/mac/url_conversions.mm", + "base/network_change_notifier_mac.h", + "base/network_change_notifier_mac.mm", + "base/network_config_watcher_mac.cc", + "base/network_config_watcher_mac.h", + "base/platform_mime_util_mac.mm", + "base/proxy_server_mac.cc", + "cert/test_root_certs_mac.cc", + "cert/x509_util_ios_and_mac.cc", + "cert/x509_util_ios_and_mac.h", + "proxy_resolution/proxy_resolver_mac.cc", + "proxy_resolution/proxy_resolver_mac.h", + ] + } + + if (is_win) { + sources += [ + "base/file_stream_context_win.cc", + "base/net_errors_win.cc", + "base/network_change_notifier_win.cc", + "base/network_change_notifier_win.h", + "base/network_interfaces_win.cc", + "base/network_interfaces_win.h", + "base/platform_mime_util_win.cc", + "base/winsock_init.cc", + "base/winsock_init.h", + "base/winsock_util.cc", + "base/winsock_util.h", + "cert/cert_verify_proc_win.cc", + "cert/cert_verify_proc_win.h", + "cert/known_roots_win.cc", + "cert/known_roots_win.h", + "cert/test_root_certs_win.cc", + "cert/x509_util_win.cc", + "cert/x509_util_win.h", + "disk_cache/blockfile/file_win.cc", + "disk_cache/blockfile/mapped_file_win.cc", + "disk_cache/cache_util_win.cc", + "disk_cache/simple/simple_index_file_win.cc", + "disk_cache/simple/simple_util_win.cc", + "http/http_auth_handler_ntlm_win.cc", + "http/http_auth_sspi_win.cc", + "http/http_auth_sspi_win.h", + "http/url_security_manager_win.cc", + "proxy_resolution/win/dhcp_pac_file_adapter_fetcher_win.cc", + "proxy_resolution/win/dhcp_pac_file_adapter_fetcher_win.h", + "proxy_resolution/win/dhcp_pac_file_fetcher_win.cc", + "proxy_resolution/win/dhcp_pac_file_fetcher_win.h", + "proxy_resolution/win/dhcpcsvc_init_win.cc", + "proxy_resolution/win/dhcpcsvc_init_win.h", + "proxy_resolution/win/proxy_config_service_win.cc", + "proxy_resolution/win/proxy_config_service_win.h", + "proxy_resolution/win/proxy_resolver_winhttp.cc", + "proxy_resolution/win/proxy_resolver_winhttp.h", + "proxy_resolution/win/windows_system_proxy_resolution_request.cc", + "proxy_resolution/win/windows_system_proxy_resolution_request.h", + "proxy_resolution/win/windows_system_proxy_resolution_service.cc", + "proxy_resolution/win/windows_system_proxy_resolution_service.h", + "proxy_resolution/win/windows_system_proxy_resolver.cc", + "proxy_resolution/win/windows_system_proxy_resolver.h", + "proxy_resolution/win/winhttp_api_wrapper.cc", + "proxy_resolution/win/winhttp_api_wrapper.h", + "proxy_resolution/win/winhttp_proxy_resolver_functions.cc", + "proxy_resolution/win/winhttp_proxy_resolver_functions.h", + "socket/tcp_socket_win.cc", + "socket/tcp_socket_win.h", + "socket/udp_socket_win.cc", + "socket/udp_socket_win.h", + "ssl/client_cert_store_win.cc", + "ssl/client_cert_store_win.h", + "ssl/ssl_platform_key_win.cc", + ] + } + + if (use_kerberos) { + sources += [ + "http/http_auth_handler_negotiate.cc", + "http/http_auth_handler_negotiate.h", + ] + } + + if (is_posix || is_fuchsia) { + sources += [ + "base/file_stream_context_posix.cc", + "base/network_interfaces_posix.cc", + "base/network_interfaces_posix.h", + "disk_cache/cache_util_posix.cc", + "disk_cache/simple/simple_index_file_posix.cc", + "disk_cache/simple/simple_util_posix.cc", + "http/url_security_manager_posix.cc", + "socket/socket_posix.cc", + "socket/socket_posix.h", + "socket/tcp_socket_posix.cc", + "socket/tcp_socket_posix.h", + "socket/udp_socket_posix.cc", + "socket/udp_socket_posix.h", + ] + if (!is_ios) { + sources += [ "disk_cache/blockfile/file_posix.cc" ] + } + if (posix_avoid_mmap) { + sources += [ "disk_cache/blockfile/mapped_file_avoid_mmap_posix.cc" ] + } else { + sources += [ "disk_cache/blockfile/mapped_file_posix.cc" ] + } + } + + if (is_android || is_chromeos_ash) { + sources += [ + "base/network_change_notifier_posix.cc", + "base/network_change_notifier_posix.h", + ] + } + + if (!is_win) { + sources += [ + "http/http_auth_handler_ntlm_portable.cc", + "http/http_auth_ntlm_mechanism.cc", + "http/http_auth_ntlm_mechanism.h", + "ntlm/ntlm.cc", + "ntlm/ntlm.h", + "ntlm/ntlm_buffer_reader.cc", + "ntlm/ntlm_buffer_reader.h", + "ntlm/ntlm_buffer_writer.cc", + "ntlm/ntlm_buffer_writer.h", + "ntlm/ntlm_client.cc", + "ntlm/ntlm_client.h", + "ntlm/ntlm_constants.cc", + "ntlm/ntlm_constants.h", + ] + } + + if (use_external_gssapi) { + sources += [ + "http/http_auth_gssapi_posix.cc", + "http/http_auth_gssapi_posix.h", + ] + } + + # Use getifaddrs() on POSIX platforms, except Linux. + if (is_posix && !is_linux && !is_chromeos) { + sources += [ + "base/network_interfaces_getifaddrs.cc", + "base/network_interfaces_getifaddrs.h", + ] + } + + if (use_nss_certs) { + sources += [ + "cert/internal/system_trust_store_nss.h", + "cert/internal/trust_store_nss.cc", + "cert/internal/trust_store_nss.h", + "cert/known_roots_nss.cc", + "cert/known_roots_nss.h", + "cert/nss_cert_database.cc", + "cert/nss_cert_database.h", + "cert/test_root_certs_builtin.cc", + "cert/x509_util_nss.cc", + "cert/x509_util_nss.h", + "third_party/mozilla_security_manager/nsNSSCertificateDB.cpp", + "third_party/mozilla_security_manager/nsNSSCertificateDB.h", + "third_party/mozilla_security_manager/nsPKCS12Blob.cpp", + "third_party/mozilla_security_manager/nsPKCS12Blob.h", + "third_party/nss/ssl/cmpcert.cc", + "third_party/nss/ssl/cmpcert.h", + ] + if (!is_chromecast) { sources += [ - "network_error_logging/network_error_logging_service.cc", - "network_error_logging/network_error_logging_service.h", - "network_error_logging/persistent_reporting_and_nel_store.h", - "reporting/reporting_browsing_data_remover.cc", - "reporting/reporting_browsing_data_remover.h", - "reporting/reporting_cache.cc", - "reporting/reporting_cache.h", - "reporting/reporting_cache_impl.cc", - "reporting/reporting_cache_impl.h", - "reporting/reporting_cache_observer.cc", - "reporting/reporting_cache_observer.h", - "reporting/reporting_context.cc", - "reporting/reporting_context.h", - "reporting/reporting_delegate.cc", - "reporting/reporting_delegate.h", - "reporting/reporting_delivery_agent.cc", - "reporting/reporting_delivery_agent.h", - "reporting/reporting_endpoint.cc", - "reporting/reporting_endpoint.h", - "reporting/reporting_endpoint_manager.cc", - "reporting/reporting_endpoint_manager.h", - "reporting/reporting_garbage_collector.cc", - "reporting/reporting_garbage_collector.h", - "reporting/reporting_header_parser.cc", - "reporting/reporting_header_parser.h", - "reporting/reporting_network_change_observer.cc", - "reporting/reporting_network_change_observer.h", - "reporting/reporting_policy.cc", - "reporting/reporting_policy.h", - "reporting/reporting_report.cc", - "reporting/reporting_report.h", - "reporting/reporting_service.cc", - "reporting/reporting_service.h", - "reporting/reporting_uploader.cc", - "reporting/reporting_uploader.h", + "ssl/client_cert_store_nss.cc", + "ssl/client_cert_store_nss.h", + "ssl/ssl_platform_key_nss.cc", + "ssl/ssl_platform_key_nss.h", ] } + } - if (is_android) { - sources += [ - "android/android_http_util.cc", - "android/cellular_signal_strength.cc", - "android/cellular_signal_strength.h", - "android/cert_verify_result_android.cc", - "android/cert_verify_result_android.h", - "android/gurl_utils.cc", - "android/http_auth_negotiate_android.cc", - "android/http_auth_negotiate_android.h", - "android/keystore.cc", - "android/keystore.h", - "android/network_activation_request.cc", - "android/network_activation_request.h", - "android/network_change_notifier_android.cc", - "android/network_change_notifier_android.h", - "android/network_change_notifier_delegate_android.cc", - "android/network_change_notifier_delegate_android.h", - "android/network_change_notifier_factory_android.cc", - "android/network_change_notifier_factory_android.h", - "android/network_library.cc", - "android/network_library.h", - "android/traffic_stats.cc", - "android/traffic_stats.h", - "cert/cert_verify_proc_android.cc", - "cert/cert_verify_proc_android.h", - "cert/test_root_certs_android.cc", - "cert/x509_util_android.cc", - "proxy_resolution/proxy_config_service_android.cc", - "proxy_resolution/proxy_config_service_android.h", - "ssl/ssl_platform_key_android.cc", - "ssl/ssl_platform_key_android.h", - ] - } + if (is_fuchsia) { + deps += [ "//third_party/fuchsia-sdk/sdk/pkg/async-loop-cpp" ] + public_deps += + [ "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.net.interfaces" ] + sources += [ + "base/network_change_notifier_fuchsia.cc", + "base/network_change_notifier_fuchsia.h", + "base/network_interfaces_fuchsia.cc", + "base/network_interfaces_fuchsia.h", + "base/platform_mime_util_fuchsia.cc", + "cert/test_root_certs_builtin.cc", + ] + } - if (is_chromeos_ash && use_nss_certs) { - sources += [ - "cert/nss_cert_database_chromeos.cc", - "cert/nss_cert_database_chromeos.h", - "cert/nss_profile_filter_chromeos.cc", - "cert/nss_profile_filter_chromeos.h", - ] - } - - if (is_ios) { - sources += [ - "cert/cert_verify_proc_ios.cc", - "cert/cert_verify_proc_ios.h", - "cert/x509_util_ios.cc", - "cert/x509_util_ios.h", - "disk_cache/blockfile/file_ios.cc", - "proxy_resolution/proxy_config_service_ios.cc", - "proxy_resolution/proxy_config_service_ios.h", - ] - } - - if (is_linux || is_chromeos_lacros) { - sources += [ - "base/network_change_notifier_linux.cc", - "base/network_change_notifier_linux.h", - "proxy_resolution/proxy_config_service_linux.cc", - "proxy_resolution/proxy_config_service_linux.h", - ] - } - - if (is_linux || is_chromeos || is_android) { - sources += [ - "base/address_tracker_linux.cc", - "base/address_tracker_linux.h", - "base/network_interfaces_linux.cc", - "base/network_interfaces_linux.h", - "base/platform_mime_util_linux.cc", - ] - } - - if (is_mac) { - sources += [ - "base/network_notification_thread_mac.cc", - "base/network_notification_thread_mac.h", - "cert/cert_database_mac.cc", - "cert/cert_verify_proc_mac.cc", - "cert/cert_verify_proc_mac.h", - "cert/internal/trust_store_mac.cc", - "cert/internal/trust_store_mac.h", - "cert/known_roots_mac.cc", - "cert/known_roots_mac.h", - "cert/test_keychain_search_list_mac.cc", - "cert/test_keychain_search_list_mac.h", - "cert/x509_util_mac.cc", - "cert/x509_util_mac.h", - "proxy_resolution/proxy_config_service_mac.cc", - "proxy_resolution/proxy_config_service_mac.h", - "ssl/client_cert_identity_mac.cc", - "ssl/client_cert_identity_mac.h", - "ssl/client_cert_store_mac.cc", - "ssl/client_cert_store_mac.h", - "ssl/ssl_platform_key_mac.cc", - "ssl/ssl_platform_key_mac.h", - ] - } - - if (is_apple) { - sources += [ - "base/mac/url_conversions.h", - "base/mac/url_conversions.mm", - "base/network_change_notifier_mac.h", - "base/network_change_notifier_mac.mm", - "base/network_config_watcher_mac.cc", - "base/network_config_watcher_mac.h", - "base/platform_mime_util_mac.mm", - "base/proxy_server_mac.cc", - "cert/test_root_certs_mac.cc", - "cert/x509_util_ios_and_mac.cc", - "cert/x509_util_ios_and_mac.h", - "proxy_resolution/proxy_resolver_mac.cc", - "proxy_resolution/proxy_resolver_mac.h", - ] - } - - if (is_win) { - sources += [ - "base/file_stream_context_win.cc", - "base/net_errors_win.cc", - "base/network_change_notifier_win.cc", - "base/network_change_notifier_win.h", - "base/network_interfaces_win.cc", - "base/network_interfaces_win.h", - "base/platform_mime_util_win.cc", - "base/winsock_init.cc", - "base/winsock_init.h", - "base/winsock_util.cc", - "base/winsock_util.h", - "cert/cert_verify_proc_win.cc", - "cert/cert_verify_proc_win.h", - "cert/known_roots_win.cc", - "cert/known_roots_win.h", - "cert/test_root_certs_win.cc", - "cert/x509_util_win.cc", - "cert/x509_util_win.h", - "disk_cache/blockfile/file_win.cc", - "disk_cache/blockfile/mapped_file_win.cc", - "disk_cache/cache_util_win.cc", - "disk_cache/simple/simple_index_file_win.cc", - "disk_cache/simple/simple_util_win.cc", - "http/http_auth_handler_ntlm_win.cc", - "http/http_auth_sspi_win.cc", - "http/http_auth_sspi_win.h", - "http/url_security_manager_win.cc", - "proxy_resolution/win/dhcp_pac_file_adapter_fetcher_win.cc", - "proxy_resolution/win/dhcp_pac_file_adapter_fetcher_win.h", - "proxy_resolution/win/dhcp_pac_file_fetcher_win.cc", - "proxy_resolution/win/dhcp_pac_file_fetcher_win.h", - "proxy_resolution/win/dhcpcsvc_init_win.cc", - "proxy_resolution/win/dhcpcsvc_init_win.h", - "proxy_resolution/win/proxy_config_service_win.cc", - "proxy_resolution/win/proxy_config_service_win.h", - "proxy_resolution/win/proxy_resolver_winhttp.cc", - "proxy_resolution/win/proxy_resolver_winhttp.h", - "proxy_resolution/win/windows_system_proxy_resolution_request.cc", - "proxy_resolution/win/windows_system_proxy_resolution_request.h", - "proxy_resolution/win/windows_system_proxy_resolution_service.cc", - "proxy_resolution/win/windows_system_proxy_resolution_service.h", - "proxy_resolution/win/windows_system_proxy_resolver.cc", - "proxy_resolution/win/windows_system_proxy_resolver.h", - "proxy_resolution/win/winhttp_api_wrapper.cc", - "proxy_resolution/win/winhttp_api_wrapper.h", - "proxy_resolution/win/winhttp_proxy_resolver_functions.cc", - "proxy_resolution/win/winhttp_proxy_resolver_functions.h", - "socket/tcp_socket_win.cc", - "socket/tcp_socket_win.h", - "socket/udp_socket_win.cc", - "socket/udp_socket_win.h", - "ssl/client_cert_store_win.cc", - "ssl/client_cert_store_win.h", - "ssl/ssl_platform_key_win.cc", - ] - } - - if (use_kerberos) { - sources += [ - "http/http_auth_handler_negotiate.cc", - "http/http_auth_handler_negotiate.h", - ] - } - - if (is_posix || is_fuchsia) { - sources += [ - "base/file_stream_context_posix.cc", - "base/network_interfaces_posix.cc", - "base/network_interfaces_posix.h", - "disk_cache/cache_util_posix.cc", - "disk_cache/simple/simple_index_file_posix.cc", - "disk_cache/simple/simple_util_posix.cc", - "http/url_security_manager_posix.cc", - "socket/socket_posix.cc", - "socket/socket_posix.h", - "socket/tcp_socket_posix.cc", - "socket/tcp_socket_posix.h", - "socket/udp_socket_posix.cc", - "socket/udp_socket_posix.h", - ] - if (!is_ios) { - sources += [ "disk_cache/blockfile/file_posix.cc" ] - } - if (posix_avoid_mmap) { - sources += [ "disk_cache/blockfile/mapped_file_avoid_mmap_posix.cc" ] - } else { - sources += [ "disk_cache/blockfile/mapped_file_posix.cc" ] - } - } - - if (is_android || is_chromeos_ash) { - sources += [ - "base/network_change_notifier_posix.cc", - "base/network_change_notifier_posix.h", - ] - } - - if (!is_win) { - sources += [ - "http/http_auth_handler_ntlm_portable.cc", - "http/http_auth_ntlm_mechanism.cc", - "http/http_auth_ntlm_mechanism.h", - "ntlm/ntlm.cc", - "ntlm/ntlm.h", - "ntlm/ntlm_buffer_reader.cc", - "ntlm/ntlm_buffer_reader.h", - "ntlm/ntlm_buffer_writer.cc", - "ntlm/ntlm_buffer_writer.h", - "ntlm/ntlm_client.cc", - "ntlm/ntlm_client.h", - "ntlm/ntlm_constants.cc", - "ntlm/ntlm_constants.h", - ] - } - - if (use_external_gssapi) { - sources += [ - "http/http_auth_gssapi_posix.cc", - "http/http_auth_gssapi_posix.h", - ] - } - - # Use getifaddrs() on POSIX platforms, except Linux. - if (is_posix && !is_linux && !is_chromeos) { - sources += [ - "base/network_interfaces_getifaddrs.cc", - "base/network_interfaces_getifaddrs.h", - ] - } - - if (use_nss_certs) { - sources += [ - "cert/internal/system_trust_store_nss.h", - "cert/internal/trust_store_nss.cc", - "cert/internal/trust_store_nss.h", - "cert/known_roots_nss.cc", - "cert/known_roots_nss.h", - "cert/nss_cert_database.cc", - "cert/nss_cert_database.h", - "cert/test_root_certs_builtin.cc", - "cert/x509_util_nss.cc", - "cert/x509_util_nss.h", - "third_party/mozilla_security_manager/nsNSSCertificateDB.cpp", - "third_party/mozilla_security_manager/nsNSSCertificateDB.h", - "third_party/mozilla_security_manager/nsPKCS12Blob.cpp", - "third_party/mozilla_security_manager/nsPKCS12Blob.h", - "third_party/nss/ssl/cmpcert.cc", - "third_party/nss/ssl/cmpcert.h", - ] - if (!is_chromecast) { - sources += [ - "ssl/client_cert_store_nss.cc", - "ssl/client_cert_store_nss.h", - "ssl/ssl_platform_key_nss.cc", - "ssl/ssl_platform_key_nss.h", - ] - } - } - - if (is_fuchsia) { - deps += [ "//third_party/fuchsia-sdk/sdk/pkg/async-loop-cpp" ] - public_deps += - [ "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.net.interfaces" ] - sources += [ - "base/network_change_notifier_fuchsia.cc", - "base/network_change_notifier_fuchsia.h", - "base/network_interfaces_fuchsia.cc", - "base/network_interfaces_fuchsia.h", - "base/platform_mime_util_fuchsia.cc", - "cert/test_root_certs_builtin.cc", - ] - } - - if (trial_comparison_cert_verifier_supported) { - sources += [ - "cert/trial_comparison_cert_verifier.cc", - "cert/trial_comparison_cert_verifier.h", - ] - } + if (trial_comparison_cert_verifier_supported) { + sources += [ + "cert/trial_comparison_cert_verifier.cc", + "cert/trial_comparison_cert_verifier.h", + ] } if (enable_unix_sockets) { @@ -1500,131 +1491,129 @@ ldflags = [ "/DELAYLOAD:urlmon.dll" ] } - if (!is_nacl) { - if (!disable_file_support) { - sources += [ - "base/directory_lister.cc", - "base/directory_lister.h", - "base/directory_listing.cc", - "base/directory_listing.h", - ] - } + if (!disable_file_support) { + sources += [ + "base/directory_lister.cc", + "base/directory_lister.h", + "base/directory_listing.cc", + "base/directory_listing.h", + ] + } - if (!disable_ftp_support) { - sources += [ - "ftp/ftp_auth_cache.cc", - "ftp/ftp_auth_cache.h", - "ftp/ftp_ctrl_response_buffer.cc", - "ftp/ftp_ctrl_response_buffer.h", - "ftp/ftp_directory_listing_parser.cc", - "ftp/ftp_directory_listing_parser.h", - "ftp/ftp_directory_listing_parser_ls.cc", - "ftp/ftp_directory_listing_parser_ls.h", - "ftp/ftp_directory_listing_parser_vms.cc", - "ftp/ftp_directory_listing_parser_vms.h", - "ftp/ftp_directory_listing_parser_windows.cc", - "ftp/ftp_directory_listing_parser_windows.h", - "ftp/ftp_network_layer.cc", - "ftp/ftp_network_layer.h", - "ftp/ftp_network_session.cc", - "ftp/ftp_network_session.h", - "ftp/ftp_network_transaction.cc", - "ftp/ftp_network_transaction.h", - "ftp/ftp_request_info.h", - "ftp/ftp_response_info.cc", - "ftp/ftp_response_info.h", - "ftp/ftp_server_type.h", - "ftp/ftp_transaction.h", - "ftp/ftp_transaction_factory.h", - "ftp/ftp_util.cc", - "ftp/ftp_util.h", - "url_request/ftp_protocol_handler.cc", - "url_request/ftp_protocol_handler.h", - "url_request/url_request_ftp_job.cc", - "url_request/url_request_ftp_job.h", - ] - } + if (!disable_ftp_support) { + sources += [ + "ftp/ftp_auth_cache.cc", + "ftp/ftp_auth_cache.h", + "ftp/ftp_ctrl_response_buffer.cc", + "ftp/ftp_ctrl_response_buffer.h", + "ftp/ftp_directory_listing_parser.cc", + "ftp/ftp_directory_listing_parser.h", + "ftp/ftp_directory_listing_parser_ls.cc", + "ftp/ftp_directory_listing_parser_ls.h", + "ftp/ftp_directory_listing_parser_vms.cc", + "ftp/ftp_directory_listing_parser_vms.h", + "ftp/ftp_directory_listing_parser_windows.cc", + "ftp/ftp_directory_listing_parser_windows.h", + "ftp/ftp_network_layer.cc", + "ftp/ftp_network_layer.h", + "ftp/ftp_network_session.cc", + "ftp/ftp_network_session.h", + "ftp/ftp_network_transaction.cc", + "ftp/ftp_network_transaction.h", + "ftp/ftp_request_info.h", + "ftp/ftp_response_info.cc", + "ftp/ftp_response_info.h", + "ftp/ftp_server_type.h", + "ftp/ftp_transaction.h", + "ftp/ftp_transaction_factory.h", + "ftp/ftp_util.cc", + "ftp/ftp_util.h", + "url_request/ftp_protocol_handler.cc", + "url_request/ftp_protocol_handler.h", + "url_request/url_request_ftp_job.cc", + "url_request/url_request_ftp_job.h", + ] + } - if (enable_websockets) { - sources += [ - "websockets/websocket_basic_handshake_stream.cc", - "websockets/websocket_basic_handshake_stream.h", - "websockets/websocket_basic_stream.cc", - "websockets/websocket_basic_stream.h", - "websockets/websocket_basic_stream_adapters.cc", - "websockets/websocket_basic_stream_adapters.h", - "websockets/websocket_channel.cc", - "websockets/websocket_channel.h", - "websockets/websocket_deflate_parameters.cc", - "websockets/websocket_deflate_parameters.h", - "websockets/websocket_deflate_predictor.h", - "websockets/websocket_deflate_predictor_impl.cc", - "websockets/websocket_deflate_predictor_impl.h", - "websockets/websocket_deflate_stream.cc", - "websockets/websocket_deflate_stream.h", - "websockets/websocket_deflater.cc", - "websockets/websocket_deflater.h", - "websockets/websocket_errors.cc", - "websockets/websocket_errors.h", - "websockets/websocket_event_interface.h", - "websockets/websocket_extension.cc", - "websockets/websocket_extension.h", - "websockets/websocket_extension_parser.cc", - "websockets/websocket_extension_parser.h", - "websockets/websocket_frame.cc", - "websockets/websocket_frame.h", - "websockets/websocket_frame_parser.cc", - "websockets/websocket_frame_parser.h", - "websockets/websocket_handshake_challenge.cc", - "websockets/websocket_handshake_challenge.h", - "websockets/websocket_handshake_constants.cc", - "websockets/websocket_handshake_constants.h", - "websockets/websocket_handshake_request_info.cc", - "websockets/websocket_handshake_request_info.h", - "websockets/websocket_handshake_response_info.cc", - "websockets/websocket_handshake_response_info.h", - "websockets/websocket_handshake_stream_base.cc", - "websockets/websocket_handshake_stream_base.h", - "websockets/websocket_handshake_stream_create_helper.cc", - "websockets/websocket_handshake_stream_create_helper.h", - "websockets/websocket_http2_handshake_stream.cc", - "websockets/websocket_http2_handshake_stream.h", - "websockets/websocket_inflater.cc", - "websockets/websocket_inflater.h", - "websockets/websocket_stream.cc", - "websockets/websocket_stream.h", - ] - } + if (enable_websockets) { + sources += [ + "websockets/websocket_basic_handshake_stream.cc", + "websockets/websocket_basic_handshake_stream.h", + "websockets/websocket_basic_stream.cc", + "websockets/websocket_basic_stream.h", + "websockets/websocket_basic_stream_adapters.cc", + "websockets/websocket_basic_stream_adapters.h", + "websockets/websocket_channel.cc", + "websockets/websocket_channel.h", + "websockets/websocket_deflate_parameters.cc", + "websockets/websocket_deflate_parameters.h", + "websockets/websocket_deflate_predictor.h", + "websockets/websocket_deflate_predictor_impl.cc", + "websockets/websocket_deflate_predictor_impl.h", + "websockets/websocket_deflate_stream.cc", + "websockets/websocket_deflate_stream.h", + "websockets/websocket_deflater.cc", + "websockets/websocket_deflater.h", + "websockets/websocket_errors.cc", + "websockets/websocket_errors.h", + "websockets/websocket_event_interface.h", + "websockets/websocket_extension.cc", + "websockets/websocket_extension.h", + "websockets/websocket_extension_parser.cc", + "websockets/websocket_extension_parser.h", + "websockets/websocket_frame.cc", + "websockets/websocket_frame.h", + "websockets/websocket_frame_parser.cc", + "websockets/websocket_frame_parser.h", + "websockets/websocket_handshake_challenge.cc", + "websockets/websocket_handshake_challenge.h", + "websockets/websocket_handshake_constants.cc", + "websockets/websocket_handshake_constants.h", + "websockets/websocket_handshake_request_info.cc", + "websockets/websocket_handshake_request_info.h", + "websockets/websocket_handshake_response_info.cc", + "websockets/websocket_handshake_response_info.h", + "websockets/websocket_handshake_stream_base.cc", + "websockets/websocket_handshake_stream_base.h", + "websockets/websocket_handshake_stream_create_helper.cc", + "websockets/websocket_handshake_stream_create_helper.h", + "websockets/websocket_http2_handshake_stream.cc", + "websockets/websocket_http2_handshake_stream.h", + "websockets/websocket_inflater.cc", + "websockets/websocket_inflater.h", + "websockets/websocket_stream.cc", + "websockets/websocket_stream.h", + ] + } - # ICU support. - if (use_platform_icu_alternatives) { - if (is_android) { - # Use ICU alternative on Android. - sources += [ "base/net_string_util_icu_alternatives_android.cc" ] - } else if (is_ios) { - # Use ICU alternative on iOS. - sources += [ "base/net_string_util_icu_alternatives_ios.mm" ] - } else { - assert(false, - "ICU alternative is not implemented for platform: " + target_os) - } + # ICU support. + if (use_platform_icu_alternatives) { + if (is_android) { + # Use ICU alternative on Android. + sources += [ "base/net_string_util_icu_alternatives_android.cc" ] + } else if (is_ios) { + # Use ICU alternative on iOS. + sources += [ "base/net_string_util_icu_alternatives_ios.mm" ] } else { - # Use ICU. - sources += [ - "base/filename_util_icu.cc", - "base/net_string_util_icu.cc", - ] + assert(false, + "ICU alternative is not implemented for platform: " + target_os) } + } else { + # Use ICU. + sources += [ + "base/filename_util_icu.cc", + "base/net_string_util_icu.cc", + ] + } - # Brotli support. - if (!disable_brotli_filter) { - sources += [ - "filter/brotli_source_stream.cc", - "filter/brotli_source_stream.h", - ] - } else { - sources += [ "filter/brotli_source_stream_disabled.cc" ] - } + # Brotli support. + if (!disable_brotli_filter) { + sources += [ + "filter/brotli_source_stream.cc", + "filter/brotli_source_stream.h", + ] + } else { + sources += [ "filter/brotli_source_stream_disabled.cc" ] } if (!is_debug && !optimize_for_size) { @@ -1661,52 +1650,47 @@ ":net_resources", ":preload_decoder", "//base", + "//base/third_party/dynamic_annotations", "//base/util/type_safety:type_safety", "//net/base/registry_controlled_domains", "//third_party/protobuf:protobuf_lite", + "//third_party/zlib", "//url:buildflags", ] public_configs = net_configs - if (!is_nacl) { + if (use_gio) { + public_configs += [ "//build/linux:gio_config" ] + } + + if (is_android) { + public_deps += [ ":net_jni_headers" ] + } + + if (is_fuchsia) { public_deps += [ - "//base/third_party/dynamic_annotations", - "//third_party/zlib", + "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.hardware.network", + "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.net.interfaces", + "//third_party/fuchsia-sdk/sdk/pkg/sys_cpp", ] + } - if (use_gio) { - public_configs += [ "//build/linux:gio_config" ] - } - + if (use_platform_icu_alternatives) { if (is_android) { public_deps += [ ":net_jni_headers" ] } + } else { + public_deps += [ + "//base:i18n", + "//third_party/icu", + ] + } - if (is_fuchsia) { - public_deps += [ - "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.hardware.network", - "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.net.interfaces", - "//third_party/fuchsia-sdk/sdk/pkg/sys_cpp", - ] - } - - if (use_platform_icu_alternatives) { - if (is_android) { - public_deps += [ ":net_jni_headers" ] - } - } else { - public_deps += [ - "//base:i18n", - "//third_party/icu", - ] - } - - if (!disable_brotli_filter) { - public_deps += [ "//third_party/brotli:dec" ] - } else { - public_deps += [ "//third_party/brotli:headers" ] - } + if (!disable_brotli_filter) { + public_deps += [ "//third_party/brotli:dec" ] + } else { + public_deps += [ "//third_party/brotli:headers" ] } } @@ -1739,10 +1723,6 @@ "//third_party/boringssl", "//url", ] - - if (is_nacl) { - public_deps += [ "//native_client_sdk/src/libraries/nacl_io" ] - } } if (is_android) {
diff --git a/net/base/network_interfaces.cc b/net/base/network_interfaces.cc index 29df129a..03ae43f 100644 --- a/net/base/network_interfaces.cc +++ b/net/base/network_interfaces.cc
@@ -44,10 +44,6 @@ ScopedWifiOptions::~ScopedWifiOptions() = default; std::string GetHostName() { -#if defined(OS_NACL) - NOTIMPLEMENTED(); - return std::string(); -#else // defined(OS_NACL) #if defined(OS_WIN) EnsureWinsockInit(); #endif @@ -60,7 +56,6 @@ buffer[0] = '\0'; } return std::string(buffer); -#endif // !defined(OS_NACL) } } // namespace net
diff --git a/net/base/network_interfaces_nacl.cc b/net/base/network_interfaces_nacl.cc deleted file mode 100644 index b25ca24..0000000 --- a/net/base/network_interfaces_nacl.cc +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/base/network_interfaces.h" - -namespace net { - -bool GetNetworkList(NetworkInterfaceList* networks, int policy) { - NOTIMPLEMENTED(); - return false; -} - -std::string GetWifiSSID() { - NOTIMPLEMENTED(); - return std::string(); -} - -WifiPHYLayerProtocol GetWifiPHYLayerProtocol() { - return WIFI_PHY_LAYER_PROTOCOL_UNKNOWN; -} - -std::unique_ptr<ScopedWifiOptions> SetWifiOptions(int options) { - return nullptr; -} - -} // namespace net
diff --git a/net/cert/cert_verifier.cc b/net/cert/cert_verifier.cc index b516423c..adae9fae 100644 --- a/net/cert/cert_verifier.cc +++ b/net/cert/cert_verifier.cc
@@ -13,14 +13,9 @@ #include "net/cert/crl_set.h" #include "third_party/boringssl/src/include/openssl/pool.h" #include "third_party/boringssl/src/include/openssl/sha.h" - -#if defined(OS_NACL) -#include "base/notreached.h" -#else #include "net/cert/caching_cert_verifier.h" #include "net/cert/coalescing_cert_verifier.h" #include "net/cert/multi_threaded_cert_verifier.h" -#endif namespace net { @@ -82,10 +77,6 @@ // static std::unique_ptr<CertVerifier> CertVerifier::CreateDefaultWithoutCaching( scoped_refptr<CertNetFetcher> cert_net_fetcher) { -#if defined(OS_NACL) - NOTIMPLEMENTED(); - return nullptr; -#else scoped_refptr<CertVerifyProc> verify_proc; #if defined(OS_FUCHSIA) || defined(OS_LINUX) || defined(OS_CHROMEOS) verify_proc = @@ -104,7 +95,6 @@ #endif return std::make_unique<MultiThreadedCertVerifier>(std::move(verify_proc)); -#endif } // static
diff --git a/net/cert/cert_verify_proc_blocklist.inc b/net/cert/cert_verify_proc_blocklist.inc index 9218bf08..51999c8 100644 --- a/net/cert/cert_verify_proc_blocklist.inc +++ b/net/cert/cert_verify_proc_blocklist.inc
@@ -359,6 +359,10 @@ {0xb0, 0xfc, 0xce, 0x78, 0xc1, 0x66, 0x4e, 0x29, 0x35, 0x44, 0xc1, 0x43, 0xe3, 0xd2, 0x68, 0x9f, 0x72, 0x3f, 0x5b, 0x6e, 0x63, 0x17, 0x10, 0x7e, 0x16, 0x3d, 0x22, 0xba, 0x80, 0x69, 0x79, 0x4a}, + // 0230a604d99220e5612ee7862ab9f7a6e18e4f1ac4c9e27075788cc5220169ab.pem + {0xc5, 0x62, 0x17, 0xb7, 0xa8, 0x28, 0xc7, 0x34, 0x1c, 0x0a, 0xe7, + 0xa5, 0x90, 0xd8, 0x79, 0x0d, 0x4d, 0xef, 0x53, 0x66, 0x52, 0xe6, + 0x0a, 0xe5, 0xb8, 0xbd, 0xfa, 0x26, 0x97, 0x8f, 0xe0, 0x9c}, }; // Hashes of SubjectPublicKeyInfos known to be used for interception by a @@ -380,4 +384,8 @@ {0xb0, 0xfc, 0xce, 0x78, 0xc1, 0x66, 0x4e, 0x29, 0x35, 0x44, 0xc1, 0x43, 0xe3, 0xd2, 0x68, 0x9f, 0x72, 0x3f, 0x5b, 0x6e, 0x63, 0x17, 0x10, 0x7e, 0x16, 0x3d, 0x22, 0xba, 0x80, 0x69, 0x79, 0x4a}, + // 0230a604d99220e5612ee7862ab9f7a6e18e4f1ac4c9e27075788cc5220169ab.pem + {0xc5, 0x62, 0x17, 0xb7, 0xa8, 0x28, 0xc7, 0x34, 0x1c, 0x0a, 0xe7, 0xa5, + 0x90, 0xd8, 0x79, 0x0d, 0x4d, 0xef, 0x53, 0x66, 0x52, 0xe6, 0x0a, 0xe5, + 0xb8, 0xbd, 0xfa, 0x26, 0x97, 0x8f, 0xe0, 0x9c}, };
diff --git a/net/data/ssl/blocklist/0230a604d99220e5612ee7862ab9f7a6e18e4f1ac4c9e27075788cc5220169ab.pem b/net/data/ssl/blocklist/0230a604d99220e5612ee7862ab9f7a6e18e4f1ac4c9e27075788cc5220169ab.pem new file mode 100644 index 0000000..06da243 --- /dev/null +++ b/net/data/ssl/blocklist/0230a604d99220e5612ee7862ab9f7a6e18e4f1ac4c9e27075788cc5220169ab.pem
@@ -0,0 +1,120 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 2524629941048074238 (0x2309498e297c5ffe) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=KZ, ST=Nur-Sultan, L=Nur-Sultan, O=ISCA, CN=Information Security Certification Authority + Validity + Not Before: Apr 28 13:18:00 2021 GMT + Not After : Apr 28 13:18:00 2031 GMT + Subject: C=KZ, ST=Nur-Sultan, L=Nur-Sultan, O=ISCA, CN=Information Security Certification Authority + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (4096 bit) + Modulus: + 00:c9:ec:d8:99:2c:25:5c:63:8a:a2:e9:4d:9b:d0: + 36:77:34:8f:ed:84:60:31:47:63:b7:94:97:8e:e0: + 63:ea:a6:46:f4:9c:35:39:62:6a:4b:2e:6a:0c:ba: + 4e:5d:41:29:0b:a0:ab:d4:41:f9:7f:ea:09:30:f1: + 0b:48:e0:24:bc:db:3d:2b:77:c3:b7:d1:63:65:40: + 77:3d:f6:0a:83:2f:13:44:42:de:4a:92:22:8a:58: + 8c:16:7c:a1:41:60:af:f6:f7:c4:b3:3d:62:11:0a: + 86:37:15:64:8b:46:69:f5:5b:3d:28:e9:1c:94:6d: + c3:13:15:4d:7f:32:e9:ad:95:ea:c5:4e:75:b7:a2: + 6e:e7:12:a3:81:21:af:84:38:d6:2e:17:c4:ab:7c: + a6:c4:b7:7f:cd:73:e0:54:68:31:b7:2b:bd:a4:03: + 29:3d:fb:b1:f8:e1:b9:3f:94:1e:bf:8e:da:32:97: + 86:95:e5:10:f6:7e:e7:32:09:c1:b1:07:d9:d7:b6: + 83:20:42:d6:d2:41:90:72:cd:86:0a:48:20:4c:19: + 78:9a:fd:92:dc:3e:cf:84:4a:61:88:95:dc:ee:3c: + 66:dd:89:e7:a4:1c:16:a8:ff:43:72:83:ec:43:a1: + 4e:97:2a:fa:76:38:2f:f4:dc:89:ff:fa:f9:ec:f3: + bd:3a:f7:79:a9:1a:0a:9f:ef:10:ec:a6:42:5a:6d: + dd:79:3e:eb:0b:95:ab:12:52:f8:54:3d:0b:f2:d9: + a5:df:ae:35:a3:1a:09:5f:0e:b7:57:d8:63:6c:5e: + 98:98:1c:dc:9c:7a:79:95:e4:05:8c:a9:4a:cc:c4: + e5:9a:51:37:af:02:44:2e:9e:68:3c:13:6d:46:df: + 57:fa:08:a3:fc:ad:e5:41:b9:4b:65:07:20:3b:85: + 3c:6f:f8:ae:89:1d:d3:f3:73:5a:79:52:b6:86:ec: + 8a:21:cf:2b:ca:41:70:9f:96:f0:ae:4d:18:aa:e8: + 7f:b5:8a:5a:75:4e:c4:9c:14:01:4d:e5:ef:e3:4a: + 52:55:e6:53:36:3b:9d:5a:fe:5c:59:86:f9:f2:af: + b7:2b:6d:e8:7c:15:4e:82:5e:56:bf:df:36:d2:3f: + 9a:c3:fc:02:cb:f9:81:eb:28:78:92:27:49:a1:9a: + 05:f6:19:d7:79:7d:c7:0c:8d:79:74:46:b8:55:e0: + b3:36:a1:2b:9a:a1:37:d4:2d:a7:1a:46:5e:f0:97: + 9f:8f:3e:89:4b:38:00:4e:dd:27:f2:51:46:4e:d6: + 55:a2:b7:45:62:07:94:4d:d0:1b:4d:d7:18:b9:e7: + 60:ee:fa:94:68:9f:b1:86:e7:54:85:2b:7e:2f:ed: + 2e:78:8d + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: critical + CA:TRUE + X509v3 Subject Key Identifier: + 26:7E:99:7C:CD:7B:8E:88:AC:3D:A9:72:CB:D4:B5:62:5D:2B:0D:6A + X509v3 Key Usage: critical + Certificate Sign, CRL Sign + Signature Algorithm: sha256WithRSAEncryption + 80:d5:ef:93:7f:b6:bb:5f:7d:34:19:21:f3:70:90:d6:c0:f0: + 94:de:35:36:d9:f4:fe:6a:2f:f7:c4:64:02:b6:1f:27:fc:d3: + 6e:19:e7:cb:8c:18:b9:53:0d:e7:84:1b:a7:f0:4e:8f:7f:e4: + 15:61:a7:ad:7d:11:fa:5b:60:f7:c4:53:08:9f:01:43:65:43: + ce:ee:5a:30:cb:2e:c1:06:a8:e6:69:b8:06:fe:27:90:0e:a0: + 6a:da:da:a5:d6:80:c2:3f:e8:22:3b:5d:de:b4:c1:8a:89:bb: + 95:1b:db:77:b8:c6:f6:a8:38:dd:80:e0:2c:90:4c:e0:e2:20: + 8c:08:00:6f:4e:6e:87:89:a2:69:88:8c:23:ea:e0:2a:33:7d: + f8:c5:58:20:d9:68:8e:30:2b:f3:34:59:25:29:d4:f2:35:d6: + 56:fc:99:4f:61:16:d3:1d:2a:18:4f:33:fa:5a:9b:69:72:c2: + 82:51:a8:a5:69:c3:ca:47:40:6b:80:85:f0:a9:98:6a:4c:b5: + 86:83:10:47:6a:de:19:13:d4:ff:bb:42:25:7b:c4:34:f1:4d: + ae:71:e5:59:77:41:a8:28:3a:5c:e4:28:b1:4b:b2:4c:8b:50: + 6d:c2:2a:b5:88:19:ef:3a:ba:45:8a:d8:5c:bd:22:5b:50:39: + cf:57:c5:52:b7:cc:34:c2:39:3e:df:60:ff:fa:f0:5c:02:ac: + 08:36:43:ac:2f:61:f1:d1:b8:6e:f0:54:04:ae:b0:0d:b2:bd: + e8:ca:ab:d0:c8:f7:31:1e:24:41:82:7d:cc:67:de:96:be:85: + 64:c4:4d:72:65:10:15:b3:2b:4b:d8:a3:95:e7:3c:12:42:b1: + cc:b6:09:5b:12:dc:43:74:1c:e9:4b:03:7b:d1:98:3b:af:0e: + 7b:08:9f:45:85:b5:4a:d6:89:6d:c7:be:7d:9a:75:fc:5c:6d: + ea:22:0e:3e:8e:ff:1f:d1:14:ec:47:a7:aa:78:b4:d8:45:cb: + 89:0a:df:56:78:84:f3:78:f1:4a:d4:be:60:03:fb:6a:1c:c8: + 4e:aa:bc:84:ee:bd:4c:78:ac:2e:da:e1:16:aa:d5:0b:5a:89: + 26:3f:b7:54:a4:0a:a2:0a:bf:2b:b0:41:0b:fa:8b:4c:6e:f3: + 40:8a:e2:f2:8d:b6:2d:74:f6:d9:36:5e:42:68:eb:16:54:f2: + 5e:a4:28:93:ae:1e:88:6c:40:e4:15:64:b7:70:8e:cd:16:02: + 52:eb:d5:01:34:27:5d:81:ff:fb:40:cd:f4:90:06:68:98:57: + 24:a8:59:15:b9:16:2a:cc:9f:96:83:61:a2:e0:75:09:2d:06: + cf:71:66:a9:78:bb:c5:b1 +-----BEGIN CERTIFICATE----- +MIIFvjCCA6agAwIBAgIIIwlJjil8X/4wDQYJKoZIhvcNAQELBQAwfTELMAkGA1UE +BhMCS1oxEzARBgNVBAgTCk51ci1TdWx0YW4xEzARBgNVBAcTCk51ci1TdWx0YW4x +DTALBgNVBAoTBElTQ0ExNTAzBgNVBAMTLEluZm9ybWF0aW9uIFNlY3VyaXR5IENl +cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTIxMDQyODEzMTgwMFoXDTMxMDQyODEz +MTgwMFowfTELMAkGA1UEBhMCS1oxEzARBgNVBAgTCk51ci1TdWx0YW4xEzARBgNV +BAcTCk51ci1TdWx0YW4xDTALBgNVBAoTBElTQ0ExNTAzBgNVBAMTLEluZm9ybWF0 +aW9uIFNlY3VyaXR5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG +9w0BAQEFAAOCAg8AMIICCgKCAgEAyezYmSwlXGOKoulNm9A2dzSP7YRgMUdjt5SX +juBj6qZG9Jw1OWJqSy5qDLpOXUEpC6Cr1EH5f+oJMPELSOAkvNs9K3fDt9FjZUB3 +PfYKgy8TRELeSpIiiliMFnyhQWCv9vfEsz1iEQqGNxVki0Zp9Vs9KOkclG3DExVN +fzLprZXqxU51t6Ju5xKjgSGvhDjWLhfEq3ymxLd/zXPgVGgxtyu9pAMpPfux+OG5 +P5Qev47aMpeGleUQ9n7nMgnBsQfZ17aDIELW0kGQcs2GCkggTBl4mv2S3D7PhEph +iJXc7jxm3YnnpBwWqP9DcoPsQ6FOlyr6djgv9NyJ//r57PO9Ovd5qRoKn+8Q7KZC +Wm3deT7rC5WrElL4VD0L8tml3641oxoJXw63V9hjbF6YmBzcnHp5leQFjKlKzMTl +mlE3rwJELp5oPBNtRt9X+gij/K3lQblLZQcgO4U8b/iuiR3T83NaeVK2huyKIc8r +ykFwn5bwrk0Yquh/tYpadU7EnBQBTeXv40pSVeZTNjudWv5cWYb58q+3K23ofBVO +gl5Wv9820j+aw/wCy/mB6yh4kidJoZoF9hnXeX3HDI15dEa4VeCzNqErmqE31C2n +GkZe8Jefjz6JSzgATt0n8lFGTtZVordFYgeUTdAbTdcYuedg7vqUaJ+xhudUhSt+ +L+0ueI0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUJn6ZfM17 +joisPalyy9S1Yl0rDWowDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4IC +AQCA1e+Tf7a7X300GSHzcJDWwPCU3jU22fT+ai/3xGQCth8n/NNuGefLjBi5Uw3n +hBun8E6Pf+QVYaetfRH6W2D3xFMInwFDZUPO7lowyy7BBqjmabgG/ieQDqBq2tql +1oDCP+giO13etMGKibuVG9t3uMb2qDjdgOAskEzg4iCMCABvTm6HiaJpiIwj6uAq +M334xVgg2WiOMCvzNFklKdTyNdZW/JlPYRbTHSoYTzP6WptpcsKCUailacPKR0Br +gIXwqZhqTLWGgxBHat4ZE9T/u0Ile8Q08U2uceVZd0GoKDpc5CixS7JMi1Btwiq1 +iBnvOrpFithcvSJbUDnPV8VSt8w0wjk+32D/+vBcAqwINkOsL2Hx0bhu8FQErrAN +sr3oyqvQyPcxHiRBgn3MZ96WvoVkxE1yZRAVsytL2KOV5zwSQrHMtglbEtxDdBzp +SwN70Zg7rw57CJ9FhbVK1oltx759mnX8XG3qIg4+jv8f0RTsR6eqeLTYRcuJCt9W +eITzePFK1L5gA/tqHMhOqryE7r1MeKwu2uEWqtULWokmP7dUpAqiCr8rsEEL+otM +bvNAiuLyjbYtdPbZNl5CaOsWVPJepCiTrh6IbEDkFWS3cI7NFgJS69UBNCddgf/7 +QM30kAZomFckqFkVuRYqzJ+Wg2Gi4HUJLQbPcWapeLvFsQ== +-----END CERTIFICATE-----
diff --git a/net/data/ssl/blocklist/README.md b/net/data/ssl/blocklist/README.md index d8bc3e2..405688b1 100644 --- a/net/data/ssl/blocklist/README.md +++ b/net/data/ssl/blocklist/README.md
@@ -306,6 +306,7 @@ * [00309c736dd661da6f1eb24173aa849944c168a43a15bffd192eecfdb6f8dbd2.pem](00309c736dd661da6f1eb24173aa849944c168a43a15bffd192eecfdb6f8dbd2.pem) * [61c0fc2e38b5b6f9071b42cee54a9013d858b6697c68b460948551b3249576a1.pem](61c0fc2e38b5b6f9071b42cee54a9013d858b6697c68b460948551b3249576a1.pem) * [1df696f021ab1c3ace9a376b07ed7256a40214cd3396d7934087614924e2d7ef.pem](1df696f021ab1c3ace9a376b07ed7256a40214cd3396d7934087614924e2d7ef.pem) + * [0230a604d99220e5612ee7862ab9f7a6e18e4f1ac4c9e27075788cc5220169ab.pem](0230a604d99220e5612ee7862ab9f7a6e18e4f1ac4c9e27075788cc5220169ab.pem) ### revoked.badssl.com
diff --git a/net/dns/BUILD.gn b/net/dns/BUILD.gn index 72ec4c53..c398d8a 100644 --- a/net/dns/BUILD.gn +++ b/net/dns/BUILD.gn
@@ -26,126 +26,121 @@ public = [] sources = [ + "address_info.cc", + "address_info.h", + "address_sorter.h", + "context_host_resolver.cc", + "context_host_resolver.h", + "dns_alias_utility.cc", + "dns_alias_utility.h", + "dns_config.cc", + "dns_config_service.cc", + "dns_config_service.h", + "dns_hosts.cc", + "dns_hosts.h", + "dns_query.cc", + "dns_query.h", + "dns_reloader.cc", + "dns_reloader.h", + "dns_response.cc", + "dns_response_result_extractor.cc", + "dns_response_result_extractor.h", + "dns_server_iterator.cc", + "dns_server_iterator.h", + "dns_session.cc", + "dns_session.h", + "dns_socket_allocator.cc", + "dns_socket_allocator.h", + "dns_transaction.cc", + "dns_udp_tracker.cc", + "dns_udp_tracker.h", "dns_util.cc", "dns_util.h", + "host_cache.cc", + "host_resolver.cc", + "host_resolver_manager.cc", + "host_resolver_mdns_listener_impl.cc", + "host_resolver_mdns_listener_impl.h", + "host_resolver_mdns_task.cc", + "host_resolver_mdns_task.h", + "host_resolver_proc.cc", + "host_resolver_proc.h", + "https_record_rdata.cc", + "httpssvc_metrics.cc", + "httpssvc_metrics.h", + "mapped_host_resolver.cc", + "nsswitch_reader.cc", + "nsswitch_reader.h", + "record_parsed.cc", + "record_rdata.cc", + "resolve_context.cc", + "resolve_context.h", + "serial_worker.cc", + "serial_worker.h", + "system_dns_config_change_notifier.cc", + "system_dns_config_change_notifier.h", ] - if (!is_nacl) { + if (is_win) { sources += [ - "address_info.cc", - "address_info.h", - "address_sorter.h", - "context_host_resolver.cc", - "context_host_resolver.h", - "dns_alias_utility.cc", - "dns_alias_utility.h", - "dns_config.cc", - "dns_config_service.cc", - "dns_config_service.h", - "dns_hosts.cc", - "dns_hosts.h", - "dns_query.cc", - "dns_query.h", - "dns_reloader.cc", - "dns_reloader.h", - "dns_response.cc", - "dns_response_result_extractor.cc", - "dns_response_result_extractor.h", - "dns_server_iterator.cc", - "dns_server_iterator.h", - "dns_session.cc", - "dns_session.h", - "dns_socket_allocator.cc", - "dns_socket_allocator.h", - "dns_transaction.cc", - "dns_udp_tracker.cc", - "dns_udp_tracker.h", - "host_cache.cc", - "host_resolver.cc", - "host_resolver_manager.cc", - "host_resolver_mdns_listener_impl.cc", - "host_resolver_mdns_listener_impl.h", - "host_resolver_mdns_task.cc", - "host_resolver_mdns_task.h", - "host_resolver_proc.cc", - "host_resolver_proc.h", - "https_record_rdata.cc", - "httpssvc_metrics.cc", - "httpssvc_metrics.h", - "mapped_host_resolver.cc", - "nsswitch_reader.cc", - "nsswitch_reader.h", - "record_parsed.cc", - "record_rdata.cc", - "resolve_context.cc", - "resolve_context.h", - "serial_worker.cc", - "serial_worker.h", - "system_dns_config_change_notifier.cc", - "system_dns_config_change_notifier.h", + "address_sorter_win.cc", + "dns_config_service_win.cc", + "dns_config_service_win.h", ] + } - if (is_win) { + if (is_mac) { + sources += [ + "dns_config_watcher_mac.cc", + "dns_config_watcher_mac.h", + "notify_watcher_mac.cc", + "notify_watcher_mac.h", + ] + } + + if (is_fuchsia) { + sources += [ + "dns_config_service_fuchsia.cc", + "dns_config_service_fuchsia.h", + ] + } + + if (is_android) { + sources += [ + "dns_config_service_android.cc", + "dns_config_service_android.h", + ] + } else if (is_linux) { + sources += [ + "dns_config_service_linux.cc", + "dns_config_service_linux.h", + ] + } else if (is_posix) { + sources += [ + "dns_config_service_posix.cc", + "dns_config_service_posix.h", + ] + } + + if (enable_built_in_dns) { + sources += [ "dns_client.cc" ] + + if (is_posix || is_fuchsia) { sources += [ - "address_sorter_win.cc", - "dns_config_service_win.cc", - "dns_config_service_win.h", + "address_sorter_posix.cc", + "address_sorter_posix.h", ] } + } - if (is_mac) { - sources += [ - "dns_config_watcher_mac.cc", - "dns_config_watcher_mac.h", - "notify_watcher_mac.cc", - "notify_watcher_mac.h", - ] - } - - if (is_fuchsia) { - sources += [ - "dns_config_service_fuchsia.cc", - "dns_config_service_fuchsia.h", - ] - } - - if (is_android) { - sources += [ - "dns_config_service_android.cc", - "dns_config_service_android.h", - ] - } else if (is_linux) { - sources += [ - "dns_config_service_linux.cc", - "dns_config_service_linux.h", - ] - } else if (is_posix) { - sources += [ - "dns_config_service_posix.cc", - "dns_config_service_posix.h", - ] - } - - if (enable_built_in_dns) { - sources += [ "dns_client.cc" ] - - if (is_posix || is_fuchsia) { - sources += [ - "address_sorter_posix.cc", - "address_sorter_posix.h", - ] - } - } - - if (enable_mdns) { - sources += [ - "mdns_cache.cc", - "mdns_cache.h", - "mdns_client.cc", - "mdns_client_impl.cc", - "mdns_client_impl.h", - ] - } + if (enable_mdns) { + sources += [ + "mdns_cache.cc", + "mdns_cache.h", + "mdns_client.cc", + "mdns_client_impl.cc", + "mdns_client_impl.h", + ] } deps = [ "//net:net_deps" ] @@ -218,19 +213,15 @@ "//services/proxy_resolver/*", ] - sources = [] + sources = [ + "dns_config.h", + "host_cache.h", + "host_resolver.h", + "host_resolver_source.h", + "mapped_host_resolver.h", + ] public = [] - if (!is_nacl) { - sources += [ - "dns_config.h", - "host_cache.h", - "host_resolver.h", - "host_resolver_source.h", - "mapped_host_resolver.h", - ] - } - deps = [ "//net:net_deps", "//net/dns/public", @@ -271,13 +262,9 @@ "//services/network/*", ] - sources = [] + sources = [ "host_resolver_manager.h" ] public = [] - if (!is_nacl) { - sources += [ "host_resolver_manager.h" ] - } - deps = [ ":host_resolver", "//net:net_deps", @@ -322,20 +309,16 @@ "//services/network/*", ] - sources = [] + sources = [ + "dns_client.h", + "dns_response.h", + "dns_transaction.h", + "https_record_rdata.h", + "record_parsed.h", + "record_rdata.h", + ] public = [] - if (!is_nacl) { - sources += [ - "dns_client.h", - "dns_response.h", - "dns_transaction.h", - "https_record_rdata.h", - "record_parsed.h", - "record_rdata.h", - ] - } - deps = [ ":host_resolver", "//net:net_deps", @@ -387,7 +370,7 @@ public = [] sources = [] - if (!is_nacl && enable_mdns) { + if (enable_mdns) { sources += [ "mdns_client.h" ] }
diff --git a/net/dns/dns_util.cc b/net/dns/dns_util.cc index ae4e063..94735a7 100644 --- a/net/dns/dns_util.cc +++ b/net/dns/dns_util.cc
@@ -30,12 +30,10 @@ #if defined(OS_POSIX) #include <netinet/in.h> -#if !defined(OS_NACL) #include <net/if.h> #if !defined(OS_ANDROID) #include <ifaddrs.h> #endif // !defined(OS_ANDROID) -#endif // !defined(OS_NACL) #endif // defined(OS_POSIX) #if defined(OS_ANDROID) @@ -205,7 +203,6 @@ return url_string; } -#if !defined(OS_NACL) namespace { bool GetTimeDeltaForConnectionTypeFromFieldTrial( @@ -240,7 +237,6 @@ out = default_delta; return out; } -#endif // !defined(OS_NACL) AddressListDeltaType FindAddressListDeltaType(const AddressList& a, const AddressList& b) {
diff --git a/net/dns/dns_util.h b/net/dns/dns_util.h index 0513270..33114a9 100644 --- a/net/dns/dns_util.h +++ b/net/dns/dns_util.h
@@ -90,13 +90,11 @@ NET_EXPORT_PRIVATE std::string GetURLFromTemplateWithoutParameters( const std::string& server_template); -#if !defined(OS_NACL) NET_EXPORT_PRIVATE base::TimeDelta GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault( const char* field_trial_name, base::TimeDelta default_delta, NetworkChangeNotifier::ConnectionType connection_type); -#endif // !defined(OS_NACL) // How similar or different two AddressLists are (see values for details). // Used in histograms; do not modify existing values.
diff --git a/net/dns/host_resolver.h b/net/dns/host_resolver.h index 944fd64..f1b8af5 100644 --- a/net/dns/host_resolver.h +++ b/net/dns/host_resolver.h
@@ -24,7 +24,7 @@ #include "net/dns/public/dns_config_overrides.h" #include "net/dns/public/dns_query_type.h" #include "net/dns/public/resolve_error_info.h" -#include "net/dns/public/secure_dns_mode.h" +#include "net/dns/public/secure_dns_policy.h" namespace base { class Value; @@ -266,9 +266,8 @@ // as is typically the case for LLMNR or mDNS queries without any results. bool avoid_multicast_resolution = false; - // Set to override the resolver's default secure dns mode for this request. - // TODO(crbug.com/1200908): Replace with a SecureDnsPolicy. - base::Optional<SecureDnsMode> secure_dns_mode_override = base::nullopt; + // Controls the resolver's Secure DNS behavior for this request. + SecureDnsPolicy secure_dns_policy = SecureDnsPolicy::kAllow; }; // Handler for an ongoing MDNS listening operation. Created by
diff --git a/net/dns/host_resolver_manager.cc b/net/dns/host_resolver_manager.cc index e1eeb39..92559fc 100644 --- a/net/dns/host_resolver_manager.cc +++ b/net/dns/host_resolver_manager.cc
@@ -4,18 +4,18 @@ #include "net/dns/host_resolver_manager.h" #include "base/task/thread_pool.h" +#include "net/dns/public/secure_dns_mode.h" +#include "net/dns/public/secure_dns_policy.h" #if defined(OS_WIN) #include <Winsock2.h> #elif defined(OS_POSIX) || defined(OS_FUCHSIA) #include <netdb.h> #include <netinet/in.h> -#if !defined(OS_NACL) #include <net/if.h> #if !defined(OS_ANDROID) #include <ifaddrs.h> #endif // !defined(OS_ANDROID) -#endif // !defined(OS_NACL) #endif // defined(OS_WIN) #include <algorithm> @@ -241,9 +241,6 @@ return false; #elif defined(OS_ANDROID) return android::HaveOnlyLoopbackAddresses(); -#elif defined(OS_NACL) - NOTIMPLEMENTED(); - return false; #elif defined(OS_POSIX) || defined(OS_FUCHSIA) struct ifaddrs* interface_addr = NULL; int rv = getifaddrs(&interface_addr); @@ -2774,8 +2771,7 @@ HostCache::Entry results = ResolveLocally( request->request_host().host(), request->network_isolation_key(), request->parameters().dns_query_type, request->parameters().source, - request->host_resolver_flags(), - request->parameters().secure_dns_mode_override, + request->host_resolver_flags(), request->parameters().secure_dns_policy, request->parameters().cache_usage, request->source_net_log(), request->host_cache(), request->resolve_context(), &effective_query_type, &effective_host_resolver_flags, &effective_secure_dns_mode, &tasks, @@ -2808,7 +2804,7 @@ DnsQueryType dns_query_type, HostResolverSource source, HostResolverFlags flags, - base::Optional<SecureDnsMode> secure_dns_mode_override, + SecureDnsPolicy secure_dns_policy, ResolveHostParameters::CacheUsage cache_usage, const NetLogWithSource& source_net_log, HostCache* cache, @@ -2828,10 +2824,10 @@ } GetEffectiveParametersForRequest( - hostname, dns_query_type, source, flags, secure_dns_mode_override, - cache_usage, ip_address_ptr, source_net_log, resolve_context, - out_effective_query_type, out_effective_host_resolver_flags, - out_effective_secure_dns_mode, out_tasks); + hostname, dns_query_type, source, flags, secure_dns_policy, cache_usage, + ip_address_ptr, source_net_log, resolve_context, out_effective_query_type, + out_effective_host_resolver_flags, out_effective_secure_dns_mode, + out_tasks); if (!ip_address.IsValid()) { // Check that the caller supplied a valid hostname to resolve. For @@ -3126,15 +3122,20 @@ } SecureDnsMode HostResolverManager::GetEffectiveSecureDnsMode( - const std::string& hostname, - base::Optional<SecureDnsMode> secure_dns_mode_override) { + SecureDnsPolicy secure_dns_policy) { + // Use switch() instead of if() to ensure that all policies are handled. + switch (secure_dns_policy) { + case SecureDnsPolicy::kDisable: + return SecureDnsMode::kOff; + case SecureDnsPolicy::kAllow: + break; + } + const DnsConfig* config = dns_client_ ? dns_client_->GetEffectiveConfig() : nullptr; SecureDnsMode secure_dns_mode = SecureDnsMode::kOff; - if (secure_dns_mode_override) { - secure_dns_mode = secure_dns_mode_override.value(); - } else if (config) { + if (config) { secure_dns_mode = config->secure_dns_mode; } return secure_dns_mode; @@ -3226,14 +3227,13 @@ DnsQueryType dns_query_type, HostResolverSource source, HostResolverFlags flags, - base::Optional<SecureDnsMode> secure_dns_mode_override, + SecureDnsPolicy secure_dns_policy, ResolveHostParameters::CacheUsage cache_usage, ResolveContext* resolve_context, SecureDnsMode* out_effective_secure_dns_mode, std::deque<TaskType>* out_tasks) { DCHECK(out_tasks->empty()); - *out_effective_secure_dns_mode = - GetEffectiveSecureDnsMode(hostname, secure_dns_mode_override); + *out_effective_secure_dns_mode = GetEffectiveSecureDnsMode(secure_dns_policy); // A cache lookup should generally be performed first. For jobs involving a // DnsTask, this task may be replaced. @@ -3316,7 +3316,7 @@ DnsQueryType dns_query_type, HostResolverSource source, HostResolverFlags flags, - base::Optional<SecureDnsMode> secure_dns_mode_override, + SecureDnsPolicy secure_dns_policy, ResolveHostParameters::CacheUsage cache_usage, const IPAddress* ip_address, const NetLogWithSource& net_log, @@ -3348,9 +3348,8 @@ } CreateTaskSequence(hostname, *out_effective_type, source, - *out_effective_flags, secure_dns_mode_override, - cache_usage, resolve_context, - out_effective_secure_dns_mode, out_tasks); + *out_effective_flags, secure_dns_policy, cache_usage, + resolve_context, out_effective_secure_dns_mode, out_tasks); } bool HostResolverManager::IsIPv6Reachable(const NetLogWithSource& net_log) {
diff --git a/net/dns/host_resolver_manager.h b/net/dns/host_resolver_manager.h index 4236235..9b0ab6f7 100644 --- a/net/dns/host_resolver_manager.h +++ b/net/dns/host_resolver_manager.h
@@ -32,6 +32,7 @@ #include "net/dns/public/dns_config_overrides.h" #include "net/dns/public/dns_query_type.h" #include "net/dns/public/secure_dns_mode.h" +#include "net/dns/public/secure_dns_policy.h" #include "net/dns/resolve_context.h" #include "net/dns/system_dns_config_change_notifier.h" #include "url/gurl.h" @@ -289,7 +290,7 @@ DnsQueryType requested_address_family, HostResolverSource source, HostResolverFlags flags, - base::Optional<SecureDnsMode> secure_dns_mode_override, + SecureDnsPolicy secure_dns_policy, ResolveHostParameters::CacheUsage cache_usage, const NetLogWithSource& request_net_log, HostCache* cache, @@ -343,11 +344,8 @@ bool default_family_due_to_no_ipv6); // Returns the secure dns mode to use for a job, taking into account the - // global DnsConfig mode and any per-request override. Requests matching DoH - // server hostnames are downgraded to off mode to avoid infinite loops. - SecureDnsMode GetEffectiveSecureDnsMode( - const std::string& hostname, - base::Optional<SecureDnsMode> secure_dns_mode_override); + // global DnsConfig mode and any per-request policy. + SecureDnsMode GetEffectiveSecureDnsMode(SecureDnsPolicy secure_dns_policy); // Returns true if a catch-all DNS block has been set for unit tests. No // DnsTasks should be issued in this case. @@ -366,16 +364,15 @@ // Initialized the sequence of tasks to run to resolve a request. The sequence // may be adjusted later and not all tasks need to be run. - void CreateTaskSequence( - const std::string& hostname, - DnsQueryType dns_query_type, - HostResolverSource source, - HostResolverFlags flags, - base::Optional<SecureDnsMode> secure_dns_mode_override, - ResolveHostParameters::CacheUsage cache_usage, - ResolveContext* resolve_context, - SecureDnsMode* out_effective_secure_dns_mode, - std::deque<TaskType>* out_tasks); + void CreateTaskSequence(const std::string& hostname, + DnsQueryType dns_query_type, + HostResolverSource source, + HostResolverFlags flags, + SecureDnsPolicy secure_dns_policy, + ResolveHostParameters::CacheUsage cache_usage, + ResolveContext* resolve_context, + SecureDnsMode* out_effective_secure_dns_mode, + std::deque<TaskType>* out_tasks); // Determines "effective" request parameters using manager properties and IPv6 // reachability. @@ -384,7 +381,7 @@ DnsQueryType dns_query_type, HostResolverSource source, HostResolverFlags flags, - base::Optional<SecureDnsMode> secure_dns_mode_override, + SecureDnsPolicy secure_dns_policy, ResolveHostParameters::CacheUsage cache_usage, const IPAddress* ip_address, const NetLogWithSource& net_log,
diff --git a/net/dns/host_resolver_manager_unittest.cc b/net/dns/host_resolver_manager_unittest.cc index 7918bc3..f039167 100644 --- a/net/dns/host_resolver_manager_unittest.cc +++ b/net/dns/host_resolver_manager_unittest.cc
@@ -63,6 +63,8 @@ #include "net/dns/public/dns_over_https_server_config.h" #include "net/dns/public/dns_query_type.h" #include "net/dns/public/resolve_error_info.h" +#include "net/dns/public/secure_dns_mode.h" +#include "net/dns/public/secure_dns_policy.h" #include "net/dns/resolve_context.h" #include "net/dns/test_dns_config_service.h" #include "net/log/net_log_event_type.h" @@ -4080,6 +4082,35 @@ ChangeDnsConfig(config); } + void TriggerInsecureFailureCondition() { + proc_->AddRuleForAllFamilies(std::string(), + std::string()); // Default to failures. + + // Disable Secure DNS for these requests. + HostResolver::ResolveHostParameters parameters; + parameters.secure_dns_policy = SecureDnsPolicy::kDisable; + + std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; + for (unsigned i = 0; i < maximum_insecure_dns_task_failures(); ++i) { + // Use custom names to require separate Jobs. + std::string hostname = base::StringPrintf("nx_%u", i); + // Ensure fallback to ProcTask succeeds. + proc_->AddRuleForAllFamilies(hostname, "192.168.1.101"); + responses.emplace_back( + std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( + HostPortPair(hostname, 80), NetworkIsolationKey(), + NetLogWithSource(), parameters, resolve_context_.get(), + resolve_context_->host_cache()))); + } + + proc_->SignalMultiple(responses.size()); + + for (const auto& response : responses) + EXPECT_THAT(response->result_error(), IsOk()); + + ASSERT_FALSE(proc_->HasBlockedRequests()); + } + scoped_refptr<base::TestMockTimeTaskRunner> notifier_task_runner_; TestDnsConfigService* config_service_; std::unique_ptr<SystemDnsConfigChangeNotifier> notifier_; @@ -4471,12 +4502,13 @@ // All other hostnames will fail in proc_. ChangeDnsConfig(CreateValidDnsConfig()); + DnsConfigOverrides overrides; + overrides.secure_dns_mode = SecureDnsMode::kAutomatic; + resolver_->SetDnsConfigOverrides(overrides); - HostResolver::ResolveHostParameters secure_parameters; - secure_parameters.secure_dns_mode_override = SecureDnsMode::kAutomatic; ResolveHostResponseHelper response_secure(resolver_->CreateRequest( HostPortPair("automatic", 80), NetworkIsolationKey(), NetLogWithSource(), - secure_parameters, resolve_context_.get(), + /* optional_parameters=*/base::nullopt, resolve_context_.get(), resolve_context_->host_cache())); EXPECT_FALSE(response_secure.complete()); @@ -4808,34 +4840,13 @@ DisableInsecureDnsClientOnPersistentFailure) { ChangeDnsConfig(CreateValidDnsConfig()); - proc_->AddRuleForAllFamilies(std::string(), - std::string()); // Default to failures. - // Check that DnsTask works. ResolveHostResponseHelper initial_response(resolver_->CreateRequest( HostPortPair("ok_1", 80), NetworkIsolationKey(), NetLogWithSource(), base::nullopt, resolve_context_.get(), resolve_context_->host_cache())); EXPECT_THAT(initial_response.result_error(), IsOk()); - std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses; - for (unsigned i = 0; i < maximum_insecure_dns_task_failures(); ++i) { - // Use custom names to require separate Jobs. - std::string hostname = base::StringPrintf("nx_%u", i); - // Ensure fallback to ProcTask succeeds. - proc_->AddRuleForAllFamilies(hostname, "192.168.1.101"); - responses.emplace_back( - std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( - HostPortPair(hostname, 80), NetworkIsolationKey(), - NetLogWithSource(), base::nullopt, resolve_context_.get(), - resolve_context_->host_cache()))); - } - - proc_->SignalMultiple(responses.size()); - - for (size_t i = 0; i < responses.size(); ++i) - EXPECT_THAT(responses[i]->result_error(), IsOk()); - - ASSERT_FALSE(proc_->HasBlockedRequests()); + TriggerInsecureFailureCondition(); // Insecure DnsTasks should be disabled by now unless explicitly requested via // |source|. @@ -4851,15 +4862,6 @@ EXPECT_THAT(fail_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED)); EXPECT_THAT(dns_response.result_error(), IsOk()); - // Secure DnsTasks should not be affected. - HostResolver::ResolveHostParameters secure_parameters; - secure_parameters.secure_dns_mode_override = SecureDnsMode::kAutomatic; - ResolveHostResponseHelper secure_response(resolver_->CreateRequest( - HostPortPair("automatic", 80), NetworkIsolationKey(), NetLogWithSource(), - secure_parameters, resolve_context_.get(), - resolve_context_->host_cache())); - EXPECT_THAT(secure_response.result_error(), IsOk()); - // Check that it is re-enabled after DNS change. ChangeDnsConfig(CreateValidDnsConfig()); ResolveHostResponseHelper reenabled_response(resolver_->CreateRequest( @@ -4868,6 +4870,21 @@ EXPECT_THAT(reenabled_response.result_error(), IsOk()); } +TEST_F(HostResolverManagerDnsTest, SecureDnsWorksAfterInsecureFailure) { + DnsConfig config = CreateValidDnsConfig(); + config.secure_dns_mode = SecureDnsMode::kSecure; + ChangeDnsConfig(config); + + TriggerInsecureFailureCondition(); + + // Secure DnsTasks should not be affected. + ResolveHostResponseHelper secure_response(resolver_->CreateRequest( + HostPortPair("secure", 80), NetworkIsolationKey(), NetLogWithSource(), + /* optional_parameters=*/base::nullopt, resolve_context_.get(), + resolve_context_->host_cache())); + EXPECT_THAT(secure_response.result_error(), IsOk()); +} + TEST_F(HostResolverManagerDnsTest, DontDisableDnsClientOnSporadicFailure) { ChangeDnsConfig(CreateValidDnsConfig()); @@ -5018,30 +5035,30 @@ TEST_F(HostResolverManagerDnsTest, SeparateJobsBySecureDnsMode) { MockDnsClientRuleList rules; rules.emplace_back("a", dns_protocol::kTypeA, true /* secure */, - MockDnsClientRule::Result(MockDnsClientRule::FAIL), - true /* delay */); + MockDnsClientRule::Result(MockDnsClientRule::OK), + false /* delay */); rules.emplace_back("a", dns_protocol::kTypeAAAA, true /* secure */, - MockDnsClientRule::Result(MockDnsClientRule::FAIL), - true /* delay */); + MockDnsClientRule::Result(MockDnsClientRule::OK), + false /* delay */); rules.emplace_back("a", dns_protocol::kTypeA, false /* secure */, MockDnsClientRule::Result(MockDnsClientRule::OK), - false /* delay */); + true /* delay */); rules.emplace_back("a", dns_protocol::kTypeAAAA, false /* secure */, MockDnsClientRule::Result(MockDnsClientRule::OK), - false /* delay */); + true /* delay */); UseMockDnsClient(CreateValidDnsConfig(), std::move(rules)); DnsConfigOverrides overrides; overrides.secure_dns_mode = SecureDnsMode::kAutomatic; resolver_->SetDnsConfigOverrides(overrides); - // Create three requests. One with a SECURE mode override, one with no - // mode override, and one with an AUTOMATIC mode override (which is a no-op - // since the DnsConfig uses AUTOMATIC). - HostResolver::ResolveHostParameters parameters_secure_override; - parameters_secure_override.secure_dns_mode_override = SecureDnsMode::kSecure; - ResolveHostResponseHelper secure_response(resolver_->CreateRequest( + // Create three requests. One with a DISABLE policy parameter, one with no + // resolution parameters at all, and one with an ALLOW policy parameter + // (which is a no-op). + HostResolver::ResolveHostParameters parameters_disable_secure; + parameters_disable_secure.secure_dns_policy = SecureDnsPolicy::kDisable; + ResolveHostResponseHelper insecure_response(resolver_->CreateRequest( HostPortPair("a", 80), NetworkIsolationKey(), NetLogWithSource(), - parameters_secure_override, resolve_context_.get(), + parameters_disable_secure, resolve_context_.get(), resolve_context_->host_cache())); EXPECT_EQ(1u, resolver_->num_jobs_for_testing()); @@ -5050,27 +5067,27 @@ base::nullopt, resolve_context_.get(), resolve_context_->host_cache())); EXPECT_EQ(2u, resolver_->num_jobs_for_testing()); - HostResolver::ResolveHostParameters parameters_automatic_override; - parameters_automatic_override.secure_dns_mode_override = - SecureDnsMode::kAutomatic; + HostResolver::ResolveHostParameters parameters_allow_secure; + parameters_allow_secure.secure_dns_policy = SecureDnsPolicy::kAllow; ResolveHostResponseHelper automatic_response1(resolver_->CreateRequest( HostPortPair("a", 80), NetworkIsolationKey(), NetLogWithSource(), - parameters_automatic_override, resolve_context_.get(), + parameters_allow_secure, resolve_context_.get(), resolve_context_->host_cache())); // The AUTOMATIC mode requests should be joined into the same job. EXPECT_EQ(2u, resolver_->num_jobs_for_testing()); - // All requests should be blocked on the secure transactions. + // Automatic mode requests have completed. Insecure request is still blocked. base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(secure_response.complete()); - EXPECT_FALSE(automatic_response0.complete()); - EXPECT_FALSE(automatic_response1.complete()); - - // Complete secure transactions. - dns_client_->CompleteDelayedTransactions(); - EXPECT_THAT(secure_response.result_error(), IsError(ERR_NAME_NOT_RESOLVED)); + EXPECT_FALSE(insecure_response.complete()); + EXPECT_TRUE(automatic_response0.complete()); + EXPECT_TRUE(automatic_response1.complete()); EXPECT_THAT(automatic_response0.result_error(), IsOk()); EXPECT_THAT(automatic_response1.result_error(), IsOk()); + + // Complete insecure transaction. + dns_client_->CompleteDelayedTransactions(); + EXPECT_TRUE(insecure_response.complete()); + EXPECT_THAT(insecure_response.result_error(), IsOk()); } // Cancel a request with a single DNS transaction active. @@ -6333,7 +6350,14 @@ true /* ipv6_reachable */, true /* check_ipv6_on_wifi */); - ChangeDnsConfig(CreateValidDnsConfig()); + // Set the resolver in automatic-secure mode. + net::DnsConfig config = CreateValidDnsConfig(); + config.secure_dns_mode = SecureDnsMode::kAutomatic; + ChangeDnsConfig(config); + + // Start with request parameters that disable Secure DNS. + HostResolver::ResolveHostParameters parameters; + parameters.secure_dns_policy = SecureDnsPolicy::kDisable; // Queue up enough failures to disable insecure DnsTasks. These will all // fall back to ProcTasks, and succeed there. @@ -6344,7 +6368,7 @@ failure_responses.emplace_back( std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest( HostPortPair(host, 80), NetworkIsolationKey(), NetLogWithSource(), - base::nullopt, resolve_context_.get(), + parameters, resolve_context_.get(), resolve_context_->host_cache()))); EXPECT_FALSE(failure_responses[i]->complete()); } @@ -6354,22 +6378,21 @@ proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.2"); ResolveHostResponseHelper response0(resolver_->CreateRequest( HostPortPair("slow_ok1", 80), NetworkIsolationKey(), NetLogWithSource(), - base::nullopt, resolve_context_.get(), resolve_context_->host_cache())); + parameters, resolve_context_.get(), resolve_context_->host_cache())); EXPECT_FALSE(response0.complete()); proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.3"); ResolveHostResponseHelper response1(resolver_->CreateRequest( HostPortPair("slow_ok2", 80), NetworkIsolationKey(), NetLogWithSource(), - base::nullopt, resolve_context_.get(), resolve_context_->host_cache())); + parameters, resolve_context_.get(), resolve_context_->host_cache())); EXPECT_FALSE(response1.complete()); proc_->AddRuleForAllFamilies("slow_ok3", "192.168.0.4"); ResolveHostResponseHelper response2(resolver_->CreateRequest( HostPortPair("slow_ok3", 80), NetworkIsolationKey(), NetLogWithSource(), - base::nullopt, resolve_context_.get(), resolve_context_->host_cache())); + parameters, resolve_context_.get(), resolve_context_->host_cache())); EXPECT_FALSE(response2.complete()); // Requests specifying DNS source cannot fallback to ProcTask, so they // should be unaffected. - HostResolver::ResolveHostParameters parameters; parameters.source = HostResolverSource::DNS; ResolveHostResponseHelper response_dns(resolver_->CreateRequest( HostPortPair("4slow_ok", 80), NetworkIsolationKey(), NetLogWithSource(), @@ -6386,12 +6409,10 @@ EXPECT_FALSE(response_system.complete()); // Secure DnsTasks should not be affected. - HostResolver::ResolveHostParameters secure_parameters; - secure_parameters.secure_dns_mode_override = SecureDnsMode::kAutomatic; ResolveHostResponseHelper response_secure(resolver_->CreateRequest( HostPortPair("automatic", 80), NetworkIsolationKey(), - NetLogWithSource(), secure_parameters, resolve_context_.get(), - resolve_context_->host_cache())); + NetLogWithSource(), /* optional_parameters=*/base::nullopt, + resolve_context_.get(), resolve_context_->host_cache())); EXPECT_FALSE(response_secure.complete()); proc_->SignalMultiple(maximum_insecure_dns_task_failures() + 4);
diff --git a/net/dns/mock_host_resolver.cc b/net/dns/mock_host_resolver.cc index b3ae390..b1aa9c9 100644 --- a/net/dns/mock_host_resolver.cc +++ b/net/dns/mock_host_resolver.cc
@@ -34,6 +34,7 @@ #include "net/dns/dns_alias_utility.h" #include "net/dns/host_cache.h" #include "net/dns/public/resolve_error_info.h" +#include "net/dns/public/secure_dns_policy.h" #include "net/url_request/url_request_context.h" #if defined(OS_WIN) @@ -543,7 +544,7 @@ int cache_invalidation_num, bool require_matching_rule) : last_request_priority_(DEFAULT_PRIORITY), - last_secure_dns_mode_override_(base::nullopt), + last_secure_dns_policy_(SecureDnsPolicy::kAllow), synchronous_mode_(false), ondemand_mode_(false), initial_cache_invalidation_num_(cache_invalidation_num), @@ -572,8 +573,7 @@ last_request_priority_ = request->parameters().initial_priority; last_request_network_isolation_key_ = request->network_isolation_key(); - last_secure_dns_mode_override_ = - request->parameters().secure_dns_mode_override; + last_secure_dns_policy_ = request->parameters().secure_dns_policy; num_resolve_++; AddressList addresses; base::Optional<HostCache::EntryStaleness> stale_info;
diff --git a/net/dns/mock_host_resolver.h b/net/dns/mock_host_resolver.h index 17aa878..6ae937d 100644 --- a/net/dns/mock_host_resolver.h +++ b/net/dns/mock_host_resolver.h
@@ -26,7 +26,7 @@ #include "net/dns/host_resolver_proc.h" #include "net/dns/host_resolver_source.h" #include "net/dns/public/dns_query_type.h" -#include "net/dns/public/secure_dns_mode.h" +#include "net/dns/public/secure_dns_policy.h" namespace base { class TickClock; @@ -203,10 +203,10 @@ return last_request_network_isolation_key_; } - // Returns the SecureDnsMode override of the last call to Resolve() (or + // Returns the SecureDnsPolicy of the last call to Resolve() (or // base::nullopt if Resolve() hasn't been called yet). - const base::Optional<SecureDnsMode>& last_secure_dns_mode_override() const { - return last_secure_dns_mode_override_; + SecureDnsPolicy last_secure_dns_policy() const { + return last_secure_dns_policy_; } bool IsDohProbeRunning() const { return !!doh_probe_request_; } @@ -276,7 +276,7 @@ RequestPriority last_request_priority_; base::Optional<NetworkIsolationKey> last_request_network_isolation_key_; - base::Optional<SecureDnsMode> last_secure_dns_mode_override_; + SecureDnsPolicy last_secure_dns_policy_; bool synchronous_mode_; bool ondemand_mode_; std::map<HostResolverSource, scoped_refptr<RuleBasedHostResolverProc>>
diff --git a/net/http/http_proxy_connect_job_unittest.cc b/net/http/http_proxy_connect_job_unittest.cc index 35ddc18..03902c6b 100644 --- a/net/http/http_proxy_connect_job_unittest.cc +++ b/net/http/http_proxy_connect_job_unittest.cc
@@ -24,7 +24,6 @@ #include "net/base/network_isolation_key.h" #include "net/base/test_proxy_delegate.h" #include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/http/http_network_session.h" #include "net/nqe/network_quality_estimator_test_util.h" @@ -887,14 +886,8 @@ &test_delegate, DEFAULT_PRIORITY, secure_dns_policy); EXPECT_THAT(connect_job->Connect(), test::IsError(ERR_IO_PENDING)); - EXPECT_EQ(secure_dns_policy == SecureDnsPolicy::kDisable, - session_deps_.host_resolver->last_secure_dns_mode_override() - .has_value()); - if (secure_dns_policy == SecureDnsPolicy::kDisable) { - EXPECT_EQ( - net::SecureDnsMode::kOff, - session_deps_.host_resolver->last_secure_dns_mode_override().value()); - } + EXPECT_EQ(secure_dns_policy, + session_deps_.host_resolver->last_secure_dns_policy()); } }
diff --git a/net/http/http_stream_factory_unittest.cc b/net/http/http_stream_factory_unittest.cc index 4bcf449..3f51333b 100644 --- a/net/http/http_stream_factory_unittest.cc +++ b/net/http/http_stream_factory_unittest.cc
@@ -36,7 +36,6 @@ #include "net/cert/mock_cert_verifier.h" #include "net/cert/multi_log_ct_verifier.h" #include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/http/bidirectional_stream_impl.h" #include "net/http/bidirectional_stream_request_info.h" @@ -1180,8 +1179,8 @@ /* enable_alternative_services = */ true, NetLogWithSource())); waiter.WaitForStream(); - EXPECT_FALSE( - session_deps.host_resolver->last_secure_dns_mode_override().has_value()); + EXPECT_EQ(SecureDnsPolicy::kAllow, + session_deps.host_resolver->last_secure_dns_policy()); EXPECT_EQ(GetSocketPoolGroupCount(ssl_pool), 1); std::unique_ptr<HttpStreamRequest> request2( @@ -1191,8 +1190,8 @@ /* enable_alternative_services = */ true, NetLogWithSource())); waiter.WaitForStream(); - EXPECT_FALSE( - session_deps.host_resolver->last_secure_dns_mode_override().has_value()); + EXPECT_EQ(SecureDnsPolicy::kAllow, + session_deps.host_resolver->last_secure_dns_policy()); EXPECT_EQ(GetSocketPoolGroupCount(ssl_pool), 1); request_info.secure_dns_policy = SecureDnsPolicy::kDisable; @@ -1203,9 +1202,8 @@ /* enable_alternative_services = */ true, NetLogWithSource())); waiter.WaitForStream(); - EXPECT_EQ( - net::SecureDnsMode::kOff, - session_deps.host_resolver->last_secure_dns_mode_override().value()); + EXPECT_EQ(SecureDnsPolicy::kDisable, + session_deps.host_resolver->last_secure_dns_policy()); EXPECT_EQ(GetSocketPoolGroupCount(ssl_pool), 2); }
diff --git a/net/quic/platform/impl/quic_iovec_impl.h b/net/quic/platform/impl/quic_iovec_impl.h index dea9b78..eb7f6ab2 100644 --- a/net/quic/platform/impl/quic_iovec_impl.h +++ b/net/quic/platform/impl/quic_iovec_impl.h
@@ -9,7 +9,7 @@ #include "build/build_config.h" -#if defined(OS_WIN) || defined(OS_NACL) +#if defined(OS_WIN) /* Structure for scatter/gather I/O. */ struct iovec { void* iov_base; /* Pointer to data. */ @@ -17,6 +17,6 @@ }; #elif defined(OS_POSIX) || defined(OS_FUCHSIA) #include <sys/uio.h> -#endif // defined(OS_WIN) || defined(OS_NACL) +#endif // defined(OS_WIN) #endif // NET_QUIC_PLATFORM_IMPL_QUIC_IOVEC_IMPL_H_
diff --git a/net/quic/quic_stream_factory.cc b/net/quic/quic_stream_factory.cc index 5d39a6c..12fab73 100644 --- a/net/quic/quic_stream_factory.cc +++ b/net/quic/quic_stream_factory.cc
@@ -35,7 +35,6 @@ #include "net/cert/cert_verifier.h" #include "net/dns/dns_alias_utility.h" #include "net/dns/host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/log/net_log.h" #include "net/log/net_log_capture_mode.h" @@ -704,8 +703,7 @@ parameters.cache_usage = HostResolver::ResolveHostParameters::CacheUsage::STALE_ALLOWED; } - if (key_.session_key().secure_dns_policy() == SecureDnsPolicy::kDisable) - parameters.secure_dns_mode_override = SecureDnsMode::kOff; + parameters.secure_dns_policy = key_.session_key().secure_dns_policy(); resolve_host_request_ = host_resolver_->CreateRequest( key_.destination(), key_.session_key().network_isolation_key(), net_log_, parameters);
diff --git a/net/quic/quic_stream_factory_test.cc b/net/quic/quic_stream_factory_test.cc index 357fd5c..fb2af0a 100644 --- a/net/quic/quic_stream_factory_test.cc +++ b/net/quic/quic_stream_factory_test.cc
@@ -30,7 +30,6 @@ #include "net/dns/host_resolver_source.h" #include "net/dns/mock_host_resolver.h" #include "net/dns/public/dns_query_type.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" @@ -12966,9 +12965,8 @@ std::unique_ptr<HttpStream> stream = CreateStream(&request); EXPECT_TRUE(stream.get()); - ASSERT_TRUE(host_resolver_->last_secure_dns_mode_override().has_value()); - EXPECT_EQ(net::SecureDnsMode::kOff, - host_resolver_->last_secure_dns_mode_override().value()); + EXPECT_EQ(net::SecureDnsPolicy::kDisable, + host_resolver_->last_secure_dns_policy()); ASSERT_TRUE(host_resolver_->last_request_network_isolation_key().has_value()); EXPECT_EQ(kNetworkIsolationKey, host_resolver_->last_request_network_isolation_key().value());
diff --git a/net/socket/socks_client_socket.cc b/net/socket/socks_client_socket.cc index e146eb3..d1a1d4c 100644 --- a/net/socket/socks_client_socket.cc +++ b/net/socket/socks_client_socket.cc
@@ -13,7 +13,6 @@ #include "base/sys_byteorder.h" #include "net/base/io_buffer.h" #include "net/dns/public/dns_query_type.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/log/net_log.h" #include "net/log/net_log_event_type.h" @@ -311,8 +310,7 @@ HostResolver::ResolveHostParameters parameters; parameters.dns_query_type = DnsQueryType::A; parameters.initial_priority = priority_; - if (secure_dns_policy_ == SecureDnsPolicy::kDisable) - parameters.secure_dns_mode_override = SecureDnsMode::kOff; + parameters.secure_dns_policy = secure_dns_policy_; resolve_host_request_ = host_resolver_->CreateRequest( destination_, network_isolation_key_, net_log_, parameters);
diff --git a/net/socket/socks_client_socket_unittest.cc b/net/socket/socks_client_socket_unittest.cc index 65ec94d..13005ed 100644 --- a/net/socket/socks_client_socket_unittest.cc +++ b/net/socket/socks_client_socket_unittest.cc
@@ -16,7 +16,6 @@ #include "net/base/winsock_init.h" #include "net/dns/host_resolver.h" #include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/log/net_log_event_type.h" #include "net/log/test_net_log.h" @@ -463,12 +462,7 @@ &host_resolver, secure_dns_policy, TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_EQ(ERR_IO_PENDING, socket.Connect(callback_.callback())); - EXPECT_EQ(secure_dns_policy == SecureDnsPolicy::kDisable, - host_resolver.last_secure_dns_mode_override().has_value()); - if (secure_dns_policy == SecureDnsPolicy::kDisable) { - EXPECT_EQ(net::SecureDnsMode::kOff, - host_resolver.last_secure_dns_mode_override().value()); - } + EXPECT_EQ(secure_dns_policy, host_resolver.last_secure_dns_policy()); } }
diff --git a/net/socket/socks_connect_job_unittest.cc b/net/socket/socks_connect_job_unittest.cc index eb152c2..c5c87f51 100644 --- a/net/socket/socks_connect_job_unittest.cc +++ b/net/socket/socks_connect_job_unittest.cc
@@ -16,7 +16,6 @@ #include "net/base/net_errors.h" #include "net/base/network_isolation_key.h" #include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/log/net_log.h" #include "net/socket/client_socket_factory.h" @@ -398,12 +397,7 @@ CreateSOCKSParams(SOCKSVersion::V4, secure_dns_policy), &test_delegate, nullptr /* net_log */); ASSERT_THAT(socks_connect_job.Connect(), test::IsError(ERR_IO_PENDING)); - EXPECT_EQ(secure_dns_policy == SecureDnsPolicy::kDisable, - host_resolver_.last_secure_dns_mode_override().has_value()); - if (secure_dns_policy == SecureDnsPolicy::kDisable) { - EXPECT_EQ(net::SecureDnsMode::kOff, - host_resolver_.last_secure_dns_mode_override().value()); - } + EXPECT_EQ(secure_dns_policy, host_resolver_.last_secure_dns_policy()); } }
diff --git a/net/socket/ssl_connect_job_unittest.cc b/net/socket/ssl_connect_job_unittest.cc index 3d7cd05de..d18586d 100644 --- a/net/socket/ssl_connect_job_unittest.cc +++ b/net/socket/ssl_connect_job_unittest.cc
@@ -24,7 +24,6 @@ #include "net/cert/ct_policy_enforcer.h" #include "net/cert/mock_cert_verifier.h" #include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_network_session.h" @@ -442,12 +441,7 @@ &test_delegate, nullptr /* net_log */); EXPECT_THAT(ssl_connect_job->Connect(), test::IsError(ERR_IO_PENDING)); - EXPECT_EQ(secure_dns_policy == SecureDnsPolicy::kDisable, - host_resolver_.last_secure_dns_mode_override().has_value()); - if (secure_dns_policy == SecureDnsPolicy::kDisable) { - EXPECT_EQ(net::SecureDnsMode::kOff, - host_resolver_.last_secure_dns_mode_override().value()); - } + EXPECT_EQ(secure_dns_policy, host_resolver_.last_secure_dns_policy()); } }
diff --git a/net/socket/tcp_client_socket.h b/net/socket/tcp_client_socket.h index 3d4c4ed..65127705 100644 --- a/net/socket/tcp_client_socket.h +++ b/net/socket/tcp_client_socket.h
@@ -25,10 +25,9 @@ #include "net/socket/transport_client_socket.h" #include "net/traffic_annotation/network_traffic_annotation.h" -// PowerMonitor exists on Android, but doesn't get suspend mode signals. It -// doesn't exist in NaCl, so don't use it to watch for suspend events on those -// platforms. -#if !defined(OS_ANDROID) && !defined(OS_NACL) +// PowerMonitor doesn't get suspend mode signals on Android, so don't use it to +// watch for suspend events. +#if !defined(OS_ANDROID) // Define SOCKETS_OBSERVE_SUSPEND if sockets should watch for suspend events so // they can fail pending socket operations on suspend. Otherwise, connections // hang for varying lengths of time when leaving suspend mode before failing
diff --git a/net/socket/tcp_client_socket_unittest.cc b/net/socket/tcp_client_socket_unittest.cc index eb394487..06a4e94 100644 --- a/net/socket/tcp_client_socket_unittest.cc +++ b/net/socket/tcp_client_socket_unittest.cc
@@ -38,7 +38,7 @@ // This matches logic in tcp_client_socket.cc. Only used once, but defining it // in this file instead of just inlining the OS checks where its used makes it // more grep-able. -#if !defined(OS_ANDROID) && !defined(OS_NACL) +#if !defined(OS_ANDROID) #define TCP_CLIENT_SOCKET_OBSERVES_SUSPEND #endif
diff --git a/net/socket/transport_client_socket_pool_unittest.cc b/net/socket/transport_client_socket_pool_unittest.cc index c790ec16..68dbf42a 100644 --- a/net/socket/transport_client_socket_pool_unittest.cc +++ b/net/socket/transport_client_socket_pool_unittest.cc
@@ -31,7 +31,6 @@ #include "net/cert/ct_policy_enforcer.h" #include "net/cert/mock_cert_verifier.h" #include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/http/http_network_session.h" #include "net/http/http_proxy_connect_job.h" @@ -274,14 +273,8 @@ LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(secure_dns_policy == SecureDnsPolicy::kDisable, - session_deps_.host_resolver->last_secure_dns_mode_override() - .has_value()); - if (secure_dns_policy == SecureDnsPolicy::kDisable) { - EXPECT_EQ( - net::SecureDnsMode::kOff, - session_deps_.host_resolver->last_secure_dns_mode_override().value()); - } + EXPECT_EQ(secure_dns_policy, + session_deps_.host_resolver->last_secure_dns_policy()); } }
diff --git a/net/socket/transport_connect_job.cc b/net/socket/transport_connect_job.cc index 9ad3dae..555b0e7 100644 --- a/net/socket/transport_connect_job.cc +++ b/net/socket/transport_connect_job.cc
@@ -20,7 +20,6 @@ #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/trace_constants.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/log/net_log.h" #include "net/log/net_log_event_type.h" @@ -271,8 +270,7 @@ HostResolver::ResolveHostParameters parameters; parameters.initial_priority = priority(); - if (params_->secure_dns_policy() == SecureDnsPolicy::kDisable) - parameters.secure_dns_mode_override = SecureDnsMode::kOff; + parameters.secure_dns_policy = params_->secure_dns_policy(); request_ = host_resolver()->CreateRequest(params_->destination(), params_->network_isolation_key(), net_log(), parameters);
diff --git a/net/socket/transport_connect_job_unittest.cc b/net/socket/transport_connect_job_unittest.cc index f7e451f..313b44c928 100644 --- a/net/socket/transport_connect_job_unittest.cc +++ b/net/socket/transport_connect_job_unittest.cc
@@ -18,7 +18,6 @@ #include "net/base/net_errors.h" #include "net/base/test_completion_callback.h" #include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/log/test_net_log.h" #include "net/socket/connect_job_test_util.h" @@ -275,12 +274,7 @@ &test_delegate, nullptr /* net_log */); test_delegate.StartJobExpectingResult(&transport_connect_job, OK, false /* expect_sync_result */); - EXPECT_EQ(secure_dns_policy == SecureDnsPolicy::kDisable, - host_resolver_.last_secure_dns_mode_override().has_value()); - if (secure_dns_policy == SecureDnsPolicy::kDisable) { - EXPECT_EQ(net::SecureDnsMode::kOff, - host_resolver_.last_secure_dns_mode_override().value()); - } + EXPECT_EQ(secure_dns_policy, host_resolver_.last_secure_dns_policy()); } }
diff --git a/net/third_party/quiche/BUILD.gn b/net/third_party/quiche/BUILD.gn index 9eb63a3..00debb79 100644 --- a/net/third_party/quiche/BUILD.gn +++ b/net/third_party/quiche/BUILD.gn
@@ -29,618 +29,613 @@ source_set("quiche") { sources = [ + "overrides/quiche_platform_impl/quic_mutex_impl.cc", + "overrides/quiche_platform_impl/quic_mutex_impl.h", "overrides/quiche_platform_impl/quiche_export_impl.h", + "overrides/quiche_platform_impl/quiche_logging_impl.h", + "overrides/quiche_platform_impl/quiche_time_utils_impl.cc", + "overrides/quiche_platform_impl/quiche_time_utils_impl.h", + "src/common/platform/api/quiche_export.h", + "src/common/platform/api/quiche_flag_utils.h", + "src/common/platform/api/quiche_flags.h", + "src/common/platform/api/quiche_logging.h", + "src/common/platform/api/quiche_time_utils.h", + "src/common/quiche_circular_deque.h", + "src/common/quiche_data_reader.cc", + "src/common/quiche_data_reader.h", + "src/common/quiche_data_writer.cc", + "src/common/quiche_data_writer.h", + "src/common/quiche_endian.h", + "src/common/quiche_linked_hash_map.h", + "src/common/quiche_text_utils.cc", + "src/common/quiche_text_utils.h", + "src/http2/core/http2_priority_write_scheduler.h", + "src/http2/core/priority_write_scheduler.h", + "src/http2/core/write_scheduler.h", + "src/http2/decoder/decode_buffer.cc", + "src/http2/decoder/decode_buffer.h", + "src/http2/decoder/decode_http2_structures.cc", + "src/http2/decoder/decode_http2_structures.h", + "src/http2/decoder/decode_status.cc", + "src/http2/decoder/decode_status.h", + "src/http2/decoder/frame_decoder_state.cc", + "src/http2/decoder/frame_decoder_state.h", + "src/http2/decoder/http2_frame_decoder.cc", + "src/http2/decoder/http2_frame_decoder.h", + "src/http2/decoder/http2_frame_decoder_listener.cc", + "src/http2/decoder/http2_frame_decoder_listener.h", + "src/http2/decoder/http2_structure_decoder.cc", + "src/http2/decoder/http2_structure_decoder.h", + "src/http2/decoder/payload_decoders/altsvc_payload_decoder.cc", + "src/http2/decoder/payload_decoders/altsvc_payload_decoder.h", + "src/http2/decoder/payload_decoders/continuation_payload_decoder.cc", + "src/http2/decoder/payload_decoders/continuation_payload_decoder.h", + "src/http2/decoder/payload_decoders/data_payload_decoder.cc", + "src/http2/decoder/payload_decoders/data_payload_decoder.h", + "src/http2/decoder/payload_decoders/goaway_payload_decoder.cc", + "src/http2/decoder/payload_decoders/goaway_payload_decoder.h", + "src/http2/decoder/payload_decoders/headers_payload_decoder.cc", + "src/http2/decoder/payload_decoders/headers_payload_decoder.h", + "src/http2/decoder/payload_decoders/ping_payload_decoder.cc", + "src/http2/decoder/payload_decoders/ping_payload_decoder.h", + "src/http2/decoder/payload_decoders/priority_payload_decoder.cc", + "src/http2/decoder/payload_decoders/priority_payload_decoder.h", + "src/http2/decoder/payload_decoders/priority_update_payload_decoder.cc", + "src/http2/decoder/payload_decoders/priority_update_payload_decoder.h", + "src/http2/decoder/payload_decoders/push_promise_payload_decoder.cc", + "src/http2/decoder/payload_decoders/push_promise_payload_decoder.h", + "src/http2/decoder/payload_decoders/rst_stream_payload_decoder.cc", + "src/http2/decoder/payload_decoders/rst_stream_payload_decoder.h", + "src/http2/decoder/payload_decoders/settings_payload_decoder.cc", + "src/http2/decoder/payload_decoders/settings_payload_decoder.h", + "src/http2/decoder/payload_decoders/unknown_payload_decoder.cc", + "src/http2/decoder/payload_decoders/unknown_payload_decoder.h", + "src/http2/decoder/payload_decoders/window_update_payload_decoder.cc", + "src/http2/decoder/payload_decoders/window_update_payload_decoder.h", + "src/http2/hpack/decoder/hpack_block_decoder.cc", + "src/http2/hpack/decoder/hpack_block_decoder.h", + "src/http2/hpack/decoder/hpack_decoder.cc", + "src/http2/hpack/decoder/hpack_decoder.h", + "src/http2/hpack/decoder/hpack_decoder_listener.cc", + "src/http2/hpack/decoder/hpack_decoder_listener.h", + "src/http2/hpack/decoder/hpack_decoder_state.cc", + "src/http2/hpack/decoder/hpack_decoder_state.h", + "src/http2/hpack/decoder/hpack_decoder_string_buffer.cc", + "src/http2/hpack/decoder/hpack_decoder_string_buffer.h", + "src/http2/hpack/decoder/hpack_decoder_tables.cc", + "src/http2/hpack/decoder/hpack_decoder_tables.h", + "src/http2/hpack/decoder/hpack_decoding_error.cc", + "src/http2/hpack/decoder/hpack_decoding_error.h", + "src/http2/hpack/decoder/hpack_entry_decoder.cc", + "src/http2/hpack/decoder/hpack_entry_decoder.h", + "src/http2/hpack/decoder/hpack_entry_decoder_listener.cc", + "src/http2/hpack/decoder/hpack_entry_decoder_listener.h", + "src/http2/hpack/decoder/hpack_entry_type_decoder.cc", + "src/http2/hpack/decoder/hpack_entry_type_decoder.h", + "src/http2/hpack/decoder/hpack_string_decoder.cc", + "src/http2/hpack/decoder/hpack_string_decoder.h", + "src/http2/hpack/decoder/hpack_string_decoder_listener.cc", + "src/http2/hpack/decoder/hpack_string_decoder_listener.h", + "src/http2/hpack/decoder/hpack_whole_entry_buffer.cc", + "src/http2/hpack/decoder/hpack_whole_entry_buffer.h", + "src/http2/hpack/decoder/hpack_whole_entry_listener.cc", + "src/http2/hpack/decoder/hpack_whole_entry_listener.h", + "src/http2/hpack/hpack_static_table_entries.inc", + "src/http2/hpack/http2_hpack_constants.cc", + "src/http2/hpack/http2_hpack_constants.h", + "src/http2/hpack/huffman/hpack_huffman_decoder.cc", + "src/http2/hpack/huffman/hpack_huffman_decoder.h", + "src/http2/hpack/huffman/hpack_huffman_encoder.cc", + "src/http2/hpack/huffman/hpack_huffman_encoder.h", + "src/http2/hpack/huffman/huffman_spec_tables.cc", + "src/http2/hpack/huffman/huffman_spec_tables.h", + "src/http2/hpack/varint/hpack_varint_decoder.cc", + "src/http2/hpack/varint/hpack_varint_decoder.h", + "src/http2/hpack/varint/hpack_varint_encoder.cc", + "src/http2/hpack/varint/hpack_varint_encoder.h", + "src/http2/http2_constants.cc", + "src/http2/http2_constants.h", + "src/http2/http2_structures.cc", + "src/http2/http2_structures.h", + "src/http2/platform/api/http2_bug_tracker.h", + "src/http2/platform/api/http2_containers.h", + "src/http2/platform/api/http2_estimate_memory_usage.h", + "src/http2/platform/api/http2_flag_utils.h", + "src/http2/platform/api/http2_flags.h", + "src/http2/platform/api/http2_logging.h", + "src/http2/platform/api/http2_macros.h", + "src/http2/platform/api/http2_string_utils.h", + "src/quic/core/congestion_control/bandwidth_sampler.cc", + "src/quic/core/congestion_control/bandwidth_sampler.h", + "src/quic/core/congestion_control/bbr2_drain.cc", + "src/quic/core/congestion_control/bbr2_drain.h", + "src/quic/core/congestion_control/bbr2_misc.cc", + "src/quic/core/congestion_control/bbr2_misc.h", + "src/quic/core/congestion_control/bbr2_probe_bw.cc", + "src/quic/core/congestion_control/bbr2_probe_bw.h", + "src/quic/core/congestion_control/bbr2_probe_rtt.cc", + "src/quic/core/congestion_control/bbr2_probe_rtt.h", + "src/quic/core/congestion_control/bbr2_sender.cc", + "src/quic/core/congestion_control/bbr2_sender.h", + "src/quic/core/congestion_control/bbr2_startup.cc", + "src/quic/core/congestion_control/bbr2_startup.h", + "src/quic/core/congestion_control/bbr_sender.cc", + "src/quic/core/congestion_control/bbr_sender.h", + "src/quic/core/congestion_control/cubic_bytes.cc", + "src/quic/core/congestion_control/cubic_bytes.h", + "src/quic/core/congestion_control/general_loss_algorithm.cc", + "src/quic/core/congestion_control/general_loss_algorithm.h", + "src/quic/core/congestion_control/hybrid_slow_start.cc", + "src/quic/core/congestion_control/hybrid_slow_start.h", + "src/quic/core/congestion_control/loss_detection_interface.h", + "src/quic/core/congestion_control/pacing_sender.cc", + "src/quic/core/congestion_control/pacing_sender.h", + "src/quic/core/congestion_control/prr_sender.cc", + "src/quic/core/congestion_control/prr_sender.h", + "src/quic/core/congestion_control/rtt_stats.cc", + "src/quic/core/congestion_control/rtt_stats.h", + "src/quic/core/congestion_control/send_algorithm_interface.cc", + "src/quic/core/congestion_control/send_algorithm_interface.h", + "src/quic/core/congestion_control/tcp_cubic_sender_bytes.cc", + "src/quic/core/congestion_control/tcp_cubic_sender_bytes.h", + "src/quic/core/congestion_control/uber_loss_algorithm.cc", + "src/quic/core/congestion_control/uber_loss_algorithm.h", + "src/quic/core/congestion_control/windowed_filter.h", + "src/quic/core/crypto/aead_base_decrypter.cc", + "src/quic/core/crypto/aead_base_decrypter.h", + "src/quic/core/crypto/aead_base_encrypter.cc", + "src/quic/core/crypto/aead_base_encrypter.h", + "src/quic/core/crypto/aes_128_gcm_12_decrypter.cc", + "src/quic/core/crypto/aes_128_gcm_12_decrypter.h", + "src/quic/core/crypto/aes_128_gcm_12_encrypter.cc", + "src/quic/core/crypto/aes_128_gcm_12_encrypter.h", + "src/quic/core/crypto/aes_128_gcm_decrypter.cc", + "src/quic/core/crypto/aes_128_gcm_decrypter.h", + "src/quic/core/crypto/aes_128_gcm_encrypter.cc", + "src/quic/core/crypto/aes_128_gcm_encrypter.h", + "src/quic/core/crypto/aes_256_gcm_decrypter.cc", + "src/quic/core/crypto/aes_256_gcm_decrypter.h", + "src/quic/core/crypto/aes_256_gcm_encrypter.cc", + "src/quic/core/crypto/aes_256_gcm_encrypter.h", + "src/quic/core/crypto/aes_base_decrypter.cc", + "src/quic/core/crypto/aes_base_decrypter.h", + "src/quic/core/crypto/aes_base_encrypter.cc", + "src/quic/core/crypto/aes_base_encrypter.h", + "src/quic/core/crypto/boring_utils.h", + "src/quic/core/crypto/cert_compressor.cc", + "src/quic/core/crypto/cert_compressor.h", + "src/quic/core/crypto/certificate_view.cc", + "src/quic/core/crypto/certificate_view.h", + "src/quic/core/crypto/chacha20_poly1305_decrypter.cc", + "src/quic/core/crypto/chacha20_poly1305_decrypter.h", + "src/quic/core/crypto/chacha20_poly1305_encrypter.cc", + "src/quic/core/crypto/chacha20_poly1305_encrypter.h", + "src/quic/core/crypto/chacha20_poly1305_tls_decrypter.cc", + "src/quic/core/crypto/chacha20_poly1305_tls_decrypter.h", + "src/quic/core/crypto/chacha20_poly1305_tls_encrypter.cc", + "src/quic/core/crypto/chacha20_poly1305_tls_encrypter.h", + "src/quic/core/crypto/chacha_base_decrypter.cc", + "src/quic/core/crypto/chacha_base_decrypter.h", + "src/quic/core/crypto/chacha_base_encrypter.cc", + "src/quic/core/crypto/chacha_base_encrypter.h", + "src/quic/core/crypto/channel_id.cc", + "src/quic/core/crypto/channel_id.h", + "src/quic/core/crypto/common_cert_set.cc", + "src/quic/core/crypto/common_cert_set.h", + "src/quic/core/crypto/crypto_framer.cc", + "src/quic/core/crypto/crypto_framer.h", + "src/quic/core/crypto/crypto_handshake.cc", + "src/quic/core/crypto/crypto_handshake.h", + "src/quic/core/crypto/crypto_handshake_message.cc", + "src/quic/core/crypto/crypto_handshake_message.h", + "src/quic/core/crypto/crypto_message_parser.h", + "src/quic/core/crypto/crypto_protocol.h", + "src/quic/core/crypto/crypto_secret_boxer.cc", + "src/quic/core/crypto/crypto_secret_boxer.h", + "src/quic/core/crypto/crypto_utils.cc", + "src/quic/core/crypto/crypto_utils.h", + "src/quic/core/crypto/curve25519_key_exchange.cc", + "src/quic/core/crypto/curve25519_key_exchange.h", + "src/quic/core/crypto/key_exchange.cc", + "src/quic/core/crypto/key_exchange.h", + "src/quic/core/crypto/null_decrypter.cc", + "src/quic/core/crypto/null_decrypter.h", + "src/quic/core/crypto/null_encrypter.cc", + "src/quic/core/crypto/null_encrypter.h", + "src/quic/core/crypto/p256_key_exchange.cc", + "src/quic/core/crypto/p256_key_exchange.h", + "src/quic/core/crypto/proof_source.cc", + "src/quic/core/crypto/proof_source.h", + "src/quic/core/crypto/proof_verifier.h", + "src/quic/core/crypto/quic_compressed_certs_cache.cc", + "src/quic/core/crypto/quic_compressed_certs_cache.h", + "src/quic/core/crypto/quic_crypter.cc", + "src/quic/core/crypto/quic_crypter.h", + "src/quic/core/crypto/quic_crypto_client_config.cc", + "src/quic/core/crypto/quic_crypto_client_config.h", + "src/quic/core/crypto/quic_crypto_proof.cc", + "src/quic/core/crypto/quic_crypto_proof.h", + "src/quic/core/crypto/quic_crypto_server_config.cc", + "src/quic/core/crypto/quic_crypto_server_config.h", + "src/quic/core/crypto/quic_decrypter.cc", + "src/quic/core/crypto/quic_decrypter.h", + "src/quic/core/crypto/quic_encrypter.cc", + "src/quic/core/crypto/quic_encrypter.h", + "src/quic/core/crypto/quic_hkdf.cc", + "src/quic/core/crypto/quic_hkdf.h", + "src/quic/core/crypto/quic_random.cc", + "src/quic/core/crypto/quic_random.h", + "src/quic/core/crypto/server_proof_verifier.h", + "src/quic/core/crypto/tls_client_connection.cc", + "src/quic/core/crypto/tls_client_connection.h", + "src/quic/core/crypto/tls_connection.cc", + "src/quic/core/crypto/tls_connection.h", + "src/quic/core/crypto/tls_server_connection.cc", + "src/quic/core/crypto/tls_server_connection.h", + "src/quic/core/crypto/transport_parameters.cc", + "src/quic/core/crypto/transport_parameters.h", + "src/quic/core/frames/quic_ack_frame.cc", + "src/quic/core/frames/quic_ack_frame.h", + "src/quic/core/frames/quic_ack_frequency_frame.cc", + "src/quic/core/frames/quic_ack_frequency_frame.h", + "src/quic/core/frames/quic_blocked_frame.cc", + "src/quic/core/frames/quic_blocked_frame.h", + "src/quic/core/frames/quic_connection_close_frame.cc", + "src/quic/core/frames/quic_connection_close_frame.h", + "src/quic/core/frames/quic_crypto_frame.cc", + "src/quic/core/frames/quic_crypto_frame.h", + "src/quic/core/frames/quic_frame.cc", + "src/quic/core/frames/quic_frame.h", + "src/quic/core/frames/quic_goaway_frame.cc", + "src/quic/core/frames/quic_goaway_frame.h", + "src/quic/core/frames/quic_handshake_done_frame.cc", + "src/quic/core/frames/quic_handshake_done_frame.h", + "src/quic/core/frames/quic_inlined_frame.h", + "src/quic/core/frames/quic_max_streams_frame.cc", + "src/quic/core/frames/quic_max_streams_frame.h", + "src/quic/core/frames/quic_message_frame.cc", + "src/quic/core/frames/quic_message_frame.h", + "src/quic/core/frames/quic_mtu_discovery_frame.h", + "src/quic/core/frames/quic_new_connection_id_frame.cc", + "src/quic/core/frames/quic_new_connection_id_frame.h", + "src/quic/core/frames/quic_new_token_frame.cc", + "src/quic/core/frames/quic_new_token_frame.h", + "src/quic/core/frames/quic_padding_frame.cc", + "src/quic/core/frames/quic_padding_frame.h", + "src/quic/core/frames/quic_path_challenge_frame.cc", + "src/quic/core/frames/quic_path_challenge_frame.h", + "src/quic/core/frames/quic_path_response_frame.cc", + "src/quic/core/frames/quic_path_response_frame.h", + "src/quic/core/frames/quic_ping_frame.cc", + "src/quic/core/frames/quic_ping_frame.h", + "src/quic/core/frames/quic_retire_connection_id_frame.cc", + "src/quic/core/frames/quic_retire_connection_id_frame.h", + "src/quic/core/frames/quic_rst_stream_frame.cc", + "src/quic/core/frames/quic_rst_stream_frame.h", + "src/quic/core/frames/quic_stop_sending_frame.cc", + "src/quic/core/frames/quic_stop_sending_frame.h", + "src/quic/core/frames/quic_stop_waiting_frame.cc", + "src/quic/core/frames/quic_stop_waiting_frame.h", + "src/quic/core/frames/quic_stream_frame.cc", + "src/quic/core/frames/quic_stream_frame.h", + "src/quic/core/frames/quic_streams_blocked_frame.cc", + "src/quic/core/frames/quic_streams_blocked_frame.h", + "src/quic/core/frames/quic_window_update_frame.cc", + "src/quic/core/frames/quic_window_update_frame.h", + "src/quic/core/handshaker_delegate_interface.h", + "src/quic/core/http/http_constants.cc", + "src/quic/core/http/http_constants.h", + "src/quic/core/http/http_decoder.cc", + "src/quic/core/http/http_decoder.h", + "src/quic/core/http/http_encoder.cc", + "src/quic/core/http/http_encoder.h", + "src/quic/core/http/http_frames.h", + "src/quic/core/http/quic_client_promised_info.cc", + "src/quic/core/http/quic_client_promised_info.h", + "src/quic/core/http/quic_client_push_promise_index.cc", + "src/quic/core/http/quic_client_push_promise_index.h", + "src/quic/core/http/quic_header_list.cc", + "src/quic/core/http/quic_header_list.h", + "src/quic/core/http/quic_headers_stream.cc", + "src/quic/core/http/quic_headers_stream.h", + "src/quic/core/http/quic_receive_control_stream.cc", + "src/quic/core/http/quic_receive_control_stream.h", + "src/quic/core/http/quic_send_control_stream.cc", + "src/quic/core/http/quic_send_control_stream.h", + "src/quic/core/http/quic_server_initiated_spdy_stream.cc", + "src/quic/core/http/quic_server_initiated_spdy_stream.h", + "src/quic/core/http/quic_server_session_base.cc", + "src/quic/core/http/quic_server_session_base.h", + "src/quic/core/http/quic_spdy_client_session.cc", + "src/quic/core/http/quic_spdy_client_session.h", + "src/quic/core/http/quic_spdy_client_session_base.cc", + "src/quic/core/http/quic_spdy_client_session_base.h", + "src/quic/core/http/quic_spdy_client_stream.cc", + "src/quic/core/http/quic_spdy_client_stream.h", + "src/quic/core/http/quic_spdy_session.cc", + "src/quic/core/http/quic_spdy_session.h", + "src/quic/core/http/quic_spdy_stream.cc", + "src/quic/core/http/quic_spdy_stream.h", + "src/quic/core/http/quic_spdy_stream_body_manager.cc", + "src/quic/core/http/quic_spdy_stream_body_manager.h", + "src/quic/core/http/spdy_server_push_utils.cc", + "src/quic/core/http/spdy_server_push_utils.h", + "src/quic/core/http/spdy_utils.cc", + "src/quic/core/http/spdy_utils.h", + "src/quic/core/http/web_transport_http3.cc", + "src/quic/core/http/web_transport_http3.h", + "src/quic/core/legacy_quic_stream_id_manager.cc", + "src/quic/core/legacy_quic_stream_id_manager.h", + "src/quic/core/packet_number_indexed_queue.h", + "src/quic/core/proto/cached_network_parameters_proto.h", + "src/quic/core/proto/crypto_server_config_proto.h", + "src/quic/core/proto/source_address_token_proto.h", + "src/quic/core/qpack/qpack_blocking_manager.cc", + "src/quic/core/qpack/qpack_blocking_manager.h", + "src/quic/core/qpack/qpack_decoded_headers_accumulator.cc", + "src/quic/core/qpack/qpack_decoded_headers_accumulator.h", + "src/quic/core/qpack/qpack_decoder.cc", + "src/quic/core/qpack/qpack_decoder.h", + "src/quic/core/qpack/qpack_decoder_stream_receiver.cc", + "src/quic/core/qpack/qpack_decoder_stream_receiver.h", + "src/quic/core/qpack/qpack_decoder_stream_sender.cc", + "src/quic/core/qpack/qpack_decoder_stream_sender.h", + "src/quic/core/qpack/qpack_encoder.cc", + "src/quic/core/qpack/qpack_encoder.h", + "src/quic/core/qpack/qpack_encoder_stream_receiver.cc", + "src/quic/core/qpack/qpack_encoder_stream_receiver.h", + "src/quic/core/qpack/qpack_encoder_stream_sender.cc", + "src/quic/core/qpack/qpack_encoder_stream_sender.h", + "src/quic/core/qpack/qpack_header_table.cc", + "src/quic/core/qpack/qpack_header_table.h", + "src/quic/core/qpack/qpack_index_conversions.cc", + "src/quic/core/qpack/qpack_index_conversions.h", + "src/quic/core/qpack/qpack_instruction_decoder.cc", + "src/quic/core/qpack/qpack_instruction_decoder.h", + "src/quic/core/qpack/qpack_instruction_encoder.cc", + "src/quic/core/qpack/qpack_instruction_encoder.h", + "src/quic/core/qpack/qpack_instructions.cc", + "src/quic/core/qpack/qpack_instructions.h", + "src/quic/core/qpack/qpack_progressive_decoder.cc", + "src/quic/core/qpack/qpack_progressive_decoder.h", + "src/quic/core/qpack/qpack_receive_stream.cc", + "src/quic/core/qpack/qpack_receive_stream.h", + "src/quic/core/qpack/qpack_required_insert_count.cc", + "src/quic/core/qpack/qpack_required_insert_count.h", + "src/quic/core/qpack/qpack_send_stream.cc", + "src/quic/core/qpack/qpack_send_stream.h", + "src/quic/core/qpack/qpack_static_table.cc", + "src/quic/core/qpack/qpack_static_table.h", + "src/quic/core/qpack/qpack_stream_receiver.h", + "src/quic/core/qpack/qpack_stream_sender_delegate.h", + "src/quic/core/qpack/value_splitting_header_list.cc", + "src/quic/core/qpack/value_splitting_header_list.h", + "src/quic/core/quic_ack_listener_interface.cc", + "src/quic/core/quic_ack_listener_interface.h", + "src/quic/core/quic_alarm.cc", + "src/quic/core/quic_alarm.h", + "src/quic/core/quic_alarm_factory.h", + "src/quic/core/quic_arena_scoped_ptr.h", + "src/quic/core/quic_bandwidth.cc", + "src/quic/core/quic_bandwidth.h", + "src/quic/core/quic_blocked_writer_interface.h", + "src/quic/core/quic_buffer_allocator.cc", + "src/quic/core/quic_buffer_allocator.h", + "src/quic/core/quic_chaos_protector.cc", + "src/quic/core/quic_chaos_protector.h", + "src/quic/core/quic_clock.cc", + "src/quic/core/quic_clock.h", + "src/quic/core/quic_coalesced_packet.cc", + "src/quic/core/quic_coalesced_packet.h", + "src/quic/core/quic_config.cc", + "src/quic/core/quic_config.h", + "src/quic/core/quic_connection.cc", + "src/quic/core/quic_connection.h", + "src/quic/core/quic_connection_id.cc", + "src/quic/core/quic_connection_id.h", + "src/quic/core/quic_connection_id_manager.cc", + "src/quic/core/quic_connection_id_manager.h", + "src/quic/core/quic_connection_stats.cc", + "src/quic/core/quic_connection_stats.h", + "src/quic/core/quic_constants.cc", + "src/quic/core/quic_constants.h", + "src/quic/core/quic_control_frame_manager.cc", + "src/quic/core/quic_control_frame_manager.h", + "src/quic/core/quic_crypto_client_handshaker.cc", + "src/quic/core/quic_crypto_client_handshaker.h", + "src/quic/core/quic_crypto_client_stream.cc", + "src/quic/core/quic_crypto_client_stream.h", + "src/quic/core/quic_crypto_handshaker.cc", + "src/quic/core/quic_crypto_handshaker.h", + "src/quic/core/quic_crypto_server_stream.cc", + "src/quic/core/quic_crypto_server_stream.h", + "src/quic/core/quic_crypto_server_stream_base.cc", + "src/quic/core/quic_crypto_server_stream_base.h", + "src/quic/core/quic_crypto_stream.cc", + "src/quic/core/quic_crypto_stream.h", + "src/quic/core/quic_data_reader.cc", + "src/quic/core/quic_data_reader.h", + "src/quic/core/quic_data_writer.cc", + "src/quic/core/quic_data_writer.h", + "src/quic/core/quic_datagram_queue.cc", + "src/quic/core/quic_datagram_queue.h", "src/quic/core/quic_error_codes.cc", "src/quic/core/quic_error_codes.h", + "src/quic/core/quic_flow_controller.cc", + "src/quic/core/quic_flow_controller.h", + "src/quic/core/quic_framer.cc", + "src/quic/core/quic_framer.h", + "src/quic/core/quic_idle_network_detector.cc", + "src/quic/core/quic_idle_network_detector.h", + "src/quic/core/quic_interval.h", + "src/quic/core/quic_interval_deque.h", + "src/quic/core/quic_interval_set.h", + "src/quic/core/quic_legacy_version_encapsulator.cc", + "src/quic/core/quic_legacy_version_encapsulator.h", + "src/quic/core/quic_lru_cache.h", + "src/quic/core/quic_mtu_discovery.cc", + "src/quic/core/quic_mtu_discovery.h", + "src/quic/core/quic_network_blackhole_detector.cc", + "src/quic/core/quic_network_blackhole_detector.h", + "src/quic/core/quic_one_block_arena.h", + "src/quic/core/quic_packet_creator.cc", + "src/quic/core/quic_packet_creator.h", + "src/quic/core/quic_packet_number.cc", + "src/quic/core/quic_packet_number.h", + "src/quic/core/quic_packet_writer.h", + "src/quic/core/quic_packets.cc", + "src/quic/core/quic_packets.h", + "src/quic/core/quic_path_validator.cc", + "src/quic/core/quic_path_validator.h", + "src/quic/core/quic_protocol_flags_list.h", + "src/quic/core/quic_received_packet_manager.cc", + "src/quic/core/quic_received_packet_manager.h", + "src/quic/core/quic_sent_packet_manager.cc", + "src/quic/core/quic_sent_packet_manager.h", + "src/quic/core/quic_server_id.cc", + "src/quic/core/quic_server_id.h", + "src/quic/core/quic_session.cc", + "src/quic/core/quic_session.h", + "src/quic/core/quic_simple_buffer_allocator.cc", + "src/quic/core/quic_simple_buffer_allocator.h", + "src/quic/core/quic_socket_address_coder.cc", + "src/quic/core/quic_socket_address_coder.h", + "src/quic/core/quic_stream.cc", + "src/quic/core/quic_stream.h", + "src/quic/core/quic_stream_frame_data_producer.h", + "src/quic/core/quic_stream_id_manager.cc", + "src/quic/core/quic_stream_id_manager.h", + "src/quic/core/quic_stream_send_buffer.cc", + "src/quic/core/quic_stream_send_buffer.h", + "src/quic/core/quic_stream_sequencer.cc", + "src/quic/core/quic_stream_sequencer.h", + "src/quic/core/quic_stream_sequencer_buffer.cc", + "src/quic/core/quic_stream_sequencer_buffer.h", + "src/quic/core/quic_sustained_bandwidth_recorder.cc", + "src/quic/core/quic_sustained_bandwidth_recorder.h", + "src/quic/core/quic_tag.cc", + "src/quic/core/quic_tag.h", + "src/quic/core/quic_time.cc", + "src/quic/core/quic_time.h", + "src/quic/core/quic_time_accumulator.h", + "src/quic/core/quic_transmission_info.cc", + "src/quic/core/quic_transmission_info.h", + "src/quic/core/quic_types.cc", + "src/quic/core/quic_types.h", + "src/quic/core/quic_unacked_packet_map.cc", + "src/quic/core/quic_unacked_packet_map.h", + "src/quic/core/quic_utils.cc", + "src/quic/core/quic_utils.h", + "src/quic/core/quic_version_manager.cc", + "src/quic/core/quic_version_manager.h", + "src/quic/core/quic_versions.cc", + "src/quic/core/quic_versions.h", + "src/quic/core/quic_write_blocked_list.cc", + "src/quic/core/quic_write_blocked_list.h", + "src/quic/core/session_notifier_interface.h", + "src/quic/core/stream_delegate_interface.h", + "src/quic/core/tls_client_handshaker.cc", + "src/quic/core/tls_client_handshaker.h", + "src/quic/core/tls_handshaker.cc", + "src/quic/core/tls_handshaker.h", + "src/quic/core/tls_server_handshaker.cc", + "src/quic/core/tls_server_handshaker.h", + "src/quic/core/uber_quic_stream_id_manager.cc", + "src/quic/core/uber_quic_stream_id_manager.h", + "src/quic/core/uber_received_packet_manager.cc", + "src/quic/core/uber_received_packet_manager.h", + "src/quic/core/web_transport_stream_adapter.cc", + "src/quic/core/web_transport_stream_adapter.h", + "src/quic/platform/api/quic_bug_tracker.h", + "src/quic/platform/api/quic_client_stats.h", + "src/quic/platform/api/quic_containers.h", + "src/quic/platform/api/quic_error_code_wrappers.h", + "src/quic/platform/api/quic_estimate_memory_usage.h", + "src/quic/platform/api/quic_export.h", + "src/quic/platform/api/quic_exported_stats.h", + "src/quic/platform/api/quic_file_utils.cc", + "src/quic/platform/api/quic_file_utils.h", + "src/quic/platform/api/quic_flag_utils.h", + "src/quic/platform/api/quic_flags.h", + "src/quic/platform/api/quic_hostname_utils.cc", + "src/quic/platform/api/quic_hostname_utils.h", + "src/quic/platform/api/quic_iovec.h", + "src/quic/platform/api/quic_ip_address.cc", + "src/quic/platform/api/quic_ip_address.h", + "src/quic/platform/api/quic_ip_address_family.h", + "src/quic/platform/api/quic_logging.h", + "src/quic/platform/api/quic_map_util.h", + "src/quic/platform/api/quic_mem_slice.h", + "src/quic/platform/api/quic_mem_slice_span.h", + "src/quic/platform/api/quic_mem_slice_storage.h", + "src/quic/platform/api/quic_mutex.cc", + "src/quic/platform/api/quic_mutex.h", + "src/quic/platform/api/quic_prefetch.h", + "src/quic/platform/api/quic_reference_counted.h", + "src/quic/platform/api/quic_server_stats.h", + "src/quic/platform/api/quic_sleep.h", + "src/quic/platform/api/quic_socket_address.cc", + "src/quic/platform/api/quic_socket_address.h", + "src/quic/platform/api/quic_stack_trace.h", + "src/quic/platform/api/quic_thread.h", + "src/quic/quic_transport/quic_transport_client_session.cc", + "src/quic/quic_transport/quic_transport_client_session.h", + "src/quic/quic_transport/quic_transport_protocol.h", + "src/quic/quic_transport/quic_transport_server_session.cc", + "src/quic/quic_transport/quic_transport_server_session.h", + "src/quic/quic_transport/quic_transport_session_interface.h", + "src/quic/quic_transport/quic_transport_stream.cc", + "src/quic/quic_transport/quic_transport_stream.h", + "src/quic/quic_transport/web_transport_fingerprint_proof_verifier.cc", + "src/quic/quic_transport/web_transport_fingerprint_proof_verifier.h", + "src/spdy/core/hpack/hpack_constants.cc", + "src/spdy/core/hpack/hpack_constants.h", + "src/spdy/core/hpack/hpack_decoder_adapter.cc", + "src/spdy/core/hpack/hpack_decoder_adapter.h", + "src/spdy/core/hpack/hpack_encoder.cc", + "src/spdy/core/hpack/hpack_encoder.h", + "src/spdy/core/hpack/hpack_entry.cc", + "src/spdy/core/hpack/hpack_entry.h", + "src/spdy/core/hpack/hpack_header_table.cc", + "src/spdy/core/hpack/hpack_header_table.h", + "src/spdy/core/hpack/hpack_output_stream.cc", + "src/spdy/core/hpack/hpack_output_stream.h", + "src/spdy/core/hpack/hpack_static_table.cc", + "src/spdy/core/hpack/hpack_static_table.h", + "src/spdy/core/http2_frame_decoder_adapter.cc", + "src/spdy/core/http2_frame_decoder_adapter.h", + "src/spdy/core/recording_headers_handler.cc", + "src/spdy/core/recording_headers_handler.h", + "src/spdy/core/spdy_alt_svc_wire_format.cc", + "src/spdy/core/spdy_alt_svc_wire_format.h", + "src/spdy/core/spdy_bitmasks.h", + "src/spdy/core/spdy_frame_builder.cc", + "src/spdy/core/spdy_frame_builder.h", + "src/spdy/core/spdy_frame_reader.cc", + "src/spdy/core/spdy_frame_reader.h", + "src/spdy/core/spdy_framer.cc", + "src/spdy/core/spdy_framer.h", + "src/spdy/core/spdy_header_block.cc", + "src/spdy/core/spdy_header_block.h", + "src/spdy/core/spdy_header_storage.cc", + "src/spdy/core/spdy_header_storage.h", + "src/spdy/core/spdy_headers_handler_interface.h", + "src/spdy/core/spdy_intrusive_list.h", + "src/spdy/core/spdy_no_op_visitor.cc", + "src/spdy/core/spdy_no_op_visitor.h", + "src/spdy/core/spdy_pinnable_buffer_piece.cc", + "src/spdy/core/spdy_pinnable_buffer_piece.h", + "src/spdy/core/spdy_prefixed_buffer_reader.cc", + "src/spdy/core/spdy_prefixed_buffer_reader.h", + "src/spdy/core/spdy_protocol.cc", + "src/spdy/core/spdy_protocol.h", + "src/spdy/core/spdy_simple_arena.cc", + "src/spdy/core/spdy_simple_arena.h", + "src/spdy/core/zero_copy_output_buffer.h", + "src/spdy/platform/api/spdy_containers.h", + "src/spdy/platform/api/spdy_estimate_memory_usage.h", ] - if (!is_nacl) { - sources += [ - "overrides/quiche_platform_impl/quic_mutex_impl.cc", - "overrides/quiche_platform_impl/quic_mutex_impl.h", - "overrides/quiche_platform_impl/quiche_logging_impl.h", - "overrides/quiche_platform_impl/quiche_time_utils_impl.cc", - "overrides/quiche_platform_impl/quiche_time_utils_impl.h", - "src/common/platform/api/quiche_export.h", - "src/common/platform/api/quiche_flag_utils.h", - "src/common/platform/api/quiche_flags.h", - "src/common/platform/api/quiche_logging.h", - "src/common/platform/api/quiche_time_utils.h", - "src/common/quiche_circular_deque.h", - "src/common/quiche_data_reader.cc", - "src/common/quiche_data_reader.h", - "src/common/quiche_data_writer.cc", - "src/common/quiche_data_writer.h", - "src/common/quiche_endian.h", - "src/common/quiche_linked_hash_map.h", - "src/common/quiche_text_utils.cc", - "src/common/quiche_text_utils.h", - "src/http2/core/http2_priority_write_scheduler.h", - "src/http2/core/priority_write_scheduler.h", - "src/http2/core/write_scheduler.h", - "src/http2/decoder/decode_buffer.cc", - "src/http2/decoder/decode_buffer.h", - "src/http2/decoder/decode_http2_structures.cc", - "src/http2/decoder/decode_http2_structures.h", - "src/http2/decoder/decode_status.cc", - "src/http2/decoder/decode_status.h", - "src/http2/decoder/frame_decoder_state.cc", - "src/http2/decoder/frame_decoder_state.h", - "src/http2/decoder/http2_frame_decoder.cc", - "src/http2/decoder/http2_frame_decoder.h", - "src/http2/decoder/http2_frame_decoder_listener.cc", - "src/http2/decoder/http2_frame_decoder_listener.h", - "src/http2/decoder/http2_structure_decoder.cc", - "src/http2/decoder/http2_structure_decoder.h", - "src/http2/decoder/payload_decoders/altsvc_payload_decoder.cc", - "src/http2/decoder/payload_decoders/altsvc_payload_decoder.h", - "src/http2/decoder/payload_decoders/continuation_payload_decoder.cc", - "src/http2/decoder/payload_decoders/continuation_payload_decoder.h", - "src/http2/decoder/payload_decoders/data_payload_decoder.cc", - "src/http2/decoder/payload_decoders/data_payload_decoder.h", - "src/http2/decoder/payload_decoders/goaway_payload_decoder.cc", - "src/http2/decoder/payload_decoders/goaway_payload_decoder.h", - "src/http2/decoder/payload_decoders/headers_payload_decoder.cc", - "src/http2/decoder/payload_decoders/headers_payload_decoder.h", - "src/http2/decoder/payload_decoders/ping_payload_decoder.cc", - "src/http2/decoder/payload_decoders/ping_payload_decoder.h", - "src/http2/decoder/payload_decoders/priority_payload_decoder.cc", - "src/http2/decoder/payload_decoders/priority_payload_decoder.h", - "src/http2/decoder/payload_decoders/priority_update_payload_decoder.cc", - "src/http2/decoder/payload_decoders/priority_update_payload_decoder.h", - "src/http2/decoder/payload_decoders/push_promise_payload_decoder.cc", - "src/http2/decoder/payload_decoders/push_promise_payload_decoder.h", - "src/http2/decoder/payload_decoders/rst_stream_payload_decoder.cc", - "src/http2/decoder/payload_decoders/rst_stream_payload_decoder.h", - "src/http2/decoder/payload_decoders/settings_payload_decoder.cc", - "src/http2/decoder/payload_decoders/settings_payload_decoder.h", - "src/http2/decoder/payload_decoders/unknown_payload_decoder.cc", - "src/http2/decoder/payload_decoders/unknown_payload_decoder.h", - "src/http2/decoder/payload_decoders/window_update_payload_decoder.cc", - "src/http2/decoder/payload_decoders/window_update_payload_decoder.h", - "src/http2/hpack/decoder/hpack_block_decoder.cc", - "src/http2/hpack/decoder/hpack_block_decoder.h", - "src/http2/hpack/decoder/hpack_decoder.cc", - "src/http2/hpack/decoder/hpack_decoder.h", - "src/http2/hpack/decoder/hpack_decoder_listener.cc", - "src/http2/hpack/decoder/hpack_decoder_listener.h", - "src/http2/hpack/decoder/hpack_decoder_state.cc", - "src/http2/hpack/decoder/hpack_decoder_state.h", - "src/http2/hpack/decoder/hpack_decoder_string_buffer.cc", - "src/http2/hpack/decoder/hpack_decoder_string_buffer.h", - "src/http2/hpack/decoder/hpack_decoder_tables.cc", - "src/http2/hpack/decoder/hpack_decoder_tables.h", - "src/http2/hpack/decoder/hpack_decoding_error.cc", - "src/http2/hpack/decoder/hpack_decoding_error.h", - "src/http2/hpack/decoder/hpack_entry_decoder.cc", - "src/http2/hpack/decoder/hpack_entry_decoder.h", - "src/http2/hpack/decoder/hpack_entry_decoder_listener.cc", - "src/http2/hpack/decoder/hpack_entry_decoder_listener.h", - "src/http2/hpack/decoder/hpack_entry_type_decoder.cc", - "src/http2/hpack/decoder/hpack_entry_type_decoder.h", - "src/http2/hpack/decoder/hpack_string_decoder.cc", - "src/http2/hpack/decoder/hpack_string_decoder.h", - "src/http2/hpack/decoder/hpack_string_decoder_listener.cc", - "src/http2/hpack/decoder/hpack_string_decoder_listener.h", - "src/http2/hpack/decoder/hpack_whole_entry_buffer.cc", - "src/http2/hpack/decoder/hpack_whole_entry_buffer.h", - "src/http2/hpack/decoder/hpack_whole_entry_listener.cc", - "src/http2/hpack/decoder/hpack_whole_entry_listener.h", - "src/http2/hpack/hpack_static_table_entries.inc", - "src/http2/hpack/http2_hpack_constants.cc", - "src/http2/hpack/http2_hpack_constants.h", - "src/http2/hpack/huffman/hpack_huffman_decoder.cc", - "src/http2/hpack/huffman/hpack_huffman_decoder.h", - "src/http2/hpack/huffman/hpack_huffman_encoder.cc", - "src/http2/hpack/huffman/hpack_huffman_encoder.h", - "src/http2/hpack/huffman/huffman_spec_tables.cc", - "src/http2/hpack/huffman/huffman_spec_tables.h", - "src/http2/hpack/varint/hpack_varint_decoder.cc", - "src/http2/hpack/varint/hpack_varint_decoder.h", - "src/http2/hpack/varint/hpack_varint_encoder.cc", - "src/http2/hpack/varint/hpack_varint_encoder.h", - "src/http2/http2_constants.cc", - "src/http2/http2_constants.h", - "src/http2/http2_structures.cc", - "src/http2/http2_structures.h", - "src/http2/platform/api/http2_bug_tracker.h", - "src/http2/platform/api/http2_containers.h", - "src/http2/platform/api/http2_estimate_memory_usage.h", - "src/http2/platform/api/http2_flag_utils.h", - "src/http2/platform/api/http2_flags.h", - "src/http2/platform/api/http2_logging.h", - "src/http2/platform/api/http2_macros.h", - "src/http2/platform/api/http2_string_utils.h", - "src/quic/core/congestion_control/bandwidth_sampler.cc", - "src/quic/core/congestion_control/bandwidth_sampler.h", - "src/quic/core/congestion_control/bbr2_drain.cc", - "src/quic/core/congestion_control/bbr2_drain.h", - "src/quic/core/congestion_control/bbr2_misc.cc", - "src/quic/core/congestion_control/bbr2_misc.h", - "src/quic/core/congestion_control/bbr2_probe_bw.cc", - "src/quic/core/congestion_control/bbr2_probe_bw.h", - "src/quic/core/congestion_control/bbr2_probe_rtt.cc", - "src/quic/core/congestion_control/bbr2_probe_rtt.h", - "src/quic/core/congestion_control/bbr2_sender.cc", - "src/quic/core/congestion_control/bbr2_sender.h", - "src/quic/core/congestion_control/bbr2_startup.cc", - "src/quic/core/congestion_control/bbr2_startup.h", - "src/quic/core/congestion_control/bbr_sender.cc", - "src/quic/core/congestion_control/bbr_sender.h", - "src/quic/core/congestion_control/cubic_bytes.cc", - "src/quic/core/congestion_control/cubic_bytes.h", - "src/quic/core/congestion_control/general_loss_algorithm.cc", - "src/quic/core/congestion_control/general_loss_algorithm.h", - "src/quic/core/congestion_control/hybrid_slow_start.cc", - "src/quic/core/congestion_control/hybrid_slow_start.h", - "src/quic/core/congestion_control/loss_detection_interface.h", - "src/quic/core/congestion_control/pacing_sender.cc", - "src/quic/core/congestion_control/pacing_sender.h", - "src/quic/core/congestion_control/prr_sender.cc", - "src/quic/core/congestion_control/prr_sender.h", - "src/quic/core/congestion_control/rtt_stats.cc", - "src/quic/core/congestion_control/rtt_stats.h", - "src/quic/core/congestion_control/send_algorithm_interface.cc", - "src/quic/core/congestion_control/send_algorithm_interface.h", - "src/quic/core/congestion_control/tcp_cubic_sender_bytes.cc", - "src/quic/core/congestion_control/tcp_cubic_sender_bytes.h", - "src/quic/core/congestion_control/uber_loss_algorithm.cc", - "src/quic/core/congestion_control/uber_loss_algorithm.h", - "src/quic/core/congestion_control/windowed_filter.h", - "src/quic/core/crypto/aead_base_decrypter.cc", - "src/quic/core/crypto/aead_base_decrypter.h", - "src/quic/core/crypto/aead_base_encrypter.cc", - "src/quic/core/crypto/aead_base_encrypter.h", - "src/quic/core/crypto/aes_128_gcm_12_decrypter.cc", - "src/quic/core/crypto/aes_128_gcm_12_decrypter.h", - "src/quic/core/crypto/aes_128_gcm_12_encrypter.cc", - "src/quic/core/crypto/aes_128_gcm_12_encrypter.h", - "src/quic/core/crypto/aes_128_gcm_decrypter.cc", - "src/quic/core/crypto/aes_128_gcm_decrypter.h", - "src/quic/core/crypto/aes_128_gcm_encrypter.cc", - "src/quic/core/crypto/aes_128_gcm_encrypter.h", - "src/quic/core/crypto/aes_256_gcm_decrypter.cc", - "src/quic/core/crypto/aes_256_gcm_decrypter.h", - "src/quic/core/crypto/aes_256_gcm_encrypter.cc", - "src/quic/core/crypto/aes_256_gcm_encrypter.h", - "src/quic/core/crypto/aes_base_decrypter.cc", - "src/quic/core/crypto/aes_base_decrypter.h", - "src/quic/core/crypto/aes_base_encrypter.cc", - "src/quic/core/crypto/aes_base_encrypter.h", - "src/quic/core/crypto/boring_utils.h", - "src/quic/core/crypto/cert_compressor.cc", - "src/quic/core/crypto/cert_compressor.h", - "src/quic/core/crypto/certificate_view.cc", - "src/quic/core/crypto/certificate_view.h", - "src/quic/core/crypto/chacha20_poly1305_decrypter.cc", - "src/quic/core/crypto/chacha20_poly1305_decrypter.h", - "src/quic/core/crypto/chacha20_poly1305_encrypter.cc", - "src/quic/core/crypto/chacha20_poly1305_encrypter.h", - "src/quic/core/crypto/chacha20_poly1305_tls_decrypter.cc", - "src/quic/core/crypto/chacha20_poly1305_tls_decrypter.h", - "src/quic/core/crypto/chacha20_poly1305_tls_encrypter.cc", - "src/quic/core/crypto/chacha20_poly1305_tls_encrypter.h", - "src/quic/core/crypto/chacha_base_decrypter.cc", - "src/quic/core/crypto/chacha_base_decrypter.h", - "src/quic/core/crypto/chacha_base_encrypter.cc", - "src/quic/core/crypto/chacha_base_encrypter.h", - "src/quic/core/crypto/channel_id.cc", - "src/quic/core/crypto/channel_id.h", - "src/quic/core/crypto/common_cert_set.cc", - "src/quic/core/crypto/common_cert_set.h", - "src/quic/core/crypto/crypto_framer.cc", - "src/quic/core/crypto/crypto_framer.h", - "src/quic/core/crypto/crypto_handshake.cc", - "src/quic/core/crypto/crypto_handshake.h", - "src/quic/core/crypto/crypto_handshake_message.cc", - "src/quic/core/crypto/crypto_handshake_message.h", - "src/quic/core/crypto/crypto_message_parser.h", - "src/quic/core/crypto/crypto_protocol.h", - "src/quic/core/crypto/crypto_secret_boxer.cc", - "src/quic/core/crypto/crypto_secret_boxer.h", - "src/quic/core/crypto/crypto_utils.cc", - "src/quic/core/crypto/crypto_utils.h", - "src/quic/core/crypto/curve25519_key_exchange.cc", - "src/quic/core/crypto/curve25519_key_exchange.h", - "src/quic/core/crypto/key_exchange.cc", - "src/quic/core/crypto/key_exchange.h", - "src/quic/core/crypto/null_decrypter.cc", - "src/quic/core/crypto/null_decrypter.h", - "src/quic/core/crypto/null_encrypter.cc", - "src/quic/core/crypto/null_encrypter.h", - "src/quic/core/crypto/p256_key_exchange.cc", - "src/quic/core/crypto/p256_key_exchange.h", - "src/quic/core/crypto/proof_source.cc", - "src/quic/core/crypto/proof_source.h", - "src/quic/core/crypto/proof_verifier.h", - "src/quic/core/crypto/quic_compressed_certs_cache.cc", - "src/quic/core/crypto/quic_compressed_certs_cache.h", - "src/quic/core/crypto/quic_crypter.cc", - "src/quic/core/crypto/quic_crypter.h", - "src/quic/core/crypto/quic_crypto_client_config.cc", - "src/quic/core/crypto/quic_crypto_client_config.h", - "src/quic/core/crypto/quic_crypto_proof.cc", - "src/quic/core/crypto/quic_crypto_proof.h", - "src/quic/core/crypto/quic_crypto_server_config.cc", - "src/quic/core/crypto/quic_crypto_server_config.h", - "src/quic/core/crypto/quic_decrypter.cc", - "src/quic/core/crypto/quic_decrypter.h", - "src/quic/core/crypto/quic_encrypter.cc", - "src/quic/core/crypto/quic_encrypter.h", - "src/quic/core/crypto/quic_hkdf.cc", - "src/quic/core/crypto/quic_hkdf.h", - "src/quic/core/crypto/quic_random.cc", - "src/quic/core/crypto/quic_random.h", - "src/quic/core/crypto/server_proof_verifier.h", - "src/quic/core/crypto/tls_client_connection.cc", - "src/quic/core/crypto/tls_client_connection.h", - "src/quic/core/crypto/tls_connection.cc", - "src/quic/core/crypto/tls_connection.h", - "src/quic/core/crypto/tls_server_connection.cc", - "src/quic/core/crypto/tls_server_connection.h", - "src/quic/core/crypto/transport_parameters.cc", - "src/quic/core/crypto/transport_parameters.h", - "src/quic/core/frames/quic_ack_frame.cc", - "src/quic/core/frames/quic_ack_frame.h", - "src/quic/core/frames/quic_ack_frequency_frame.cc", - "src/quic/core/frames/quic_ack_frequency_frame.h", - "src/quic/core/frames/quic_blocked_frame.cc", - "src/quic/core/frames/quic_blocked_frame.h", - "src/quic/core/frames/quic_connection_close_frame.cc", - "src/quic/core/frames/quic_connection_close_frame.h", - "src/quic/core/frames/quic_crypto_frame.cc", - "src/quic/core/frames/quic_crypto_frame.h", - "src/quic/core/frames/quic_frame.cc", - "src/quic/core/frames/quic_frame.h", - "src/quic/core/frames/quic_goaway_frame.cc", - "src/quic/core/frames/quic_goaway_frame.h", - "src/quic/core/frames/quic_handshake_done_frame.cc", - "src/quic/core/frames/quic_handshake_done_frame.h", - "src/quic/core/frames/quic_inlined_frame.h", - "src/quic/core/frames/quic_max_streams_frame.cc", - "src/quic/core/frames/quic_max_streams_frame.h", - "src/quic/core/frames/quic_message_frame.cc", - "src/quic/core/frames/quic_message_frame.h", - "src/quic/core/frames/quic_mtu_discovery_frame.h", - "src/quic/core/frames/quic_new_connection_id_frame.cc", - "src/quic/core/frames/quic_new_connection_id_frame.h", - "src/quic/core/frames/quic_new_token_frame.cc", - "src/quic/core/frames/quic_new_token_frame.h", - "src/quic/core/frames/quic_padding_frame.cc", - "src/quic/core/frames/quic_padding_frame.h", - "src/quic/core/frames/quic_path_challenge_frame.cc", - "src/quic/core/frames/quic_path_challenge_frame.h", - "src/quic/core/frames/quic_path_response_frame.cc", - "src/quic/core/frames/quic_path_response_frame.h", - "src/quic/core/frames/quic_ping_frame.cc", - "src/quic/core/frames/quic_ping_frame.h", - "src/quic/core/frames/quic_retire_connection_id_frame.cc", - "src/quic/core/frames/quic_retire_connection_id_frame.h", - "src/quic/core/frames/quic_rst_stream_frame.cc", - "src/quic/core/frames/quic_rst_stream_frame.h", - "src/quic/core/frames/quic_stop_sending_frame.cc", - "src/quic/core/frames/quic_stop_sending_frame.h", - "src/quic/core/frames/quic_stop_waiting_frame.cc", - "src/quic/core/frames/quic_stop_waiting_frame.h", - "src/quic/core/frames/quic_stream_frame.cc", - "src/quic/core/frames/quic_stream_frame.h", - "src/quic/core/frames/quic_streams_blocked_frame.cc", - "src/quic/core/frames/quic_streams_blocked_frame.h", - "src/quic/core/frames/quic_window_update_frame.cc", - "src/quic/core/frames/quic_window_update_frame.h", - "src/quic/core/handshaker_delegate_interface.h", - "src/quic/core/http/http_constants.cc", - "src/quic/core/http/http_constants.h", - "src/quic/core/http/http_decoder.cc", - "src/quic/core/http/http_decoder.h", - "src/quic/core/http/http_encoder.cc", - "src/quic/core/http/http_encoder.h", - "src/quic/core/http/http_frames.h", - "src/quic/core/http/quic_client_promised_info.cc", - "src/quic/core/http/quic_client_promised_info.h", - "src/quic/core/http/quic_client_push_promise_index.cc", - "src/quic/core/http/quic_client_push_promise_index.h", - "src/quic/core/http/quic_header_list.cc", - "src/quic/core/http/quic_header_list.h", - "src/quic/core/http/quic_headers_stream.cc", - "src/quic/core/http/quic_headers_stream.h", - "src/quic/core/http/quic_receive_control_stream.cc", - "src/quic/core/http/quic_receive_control_stream.h", - "src/quic/core/http/quic_send_control_stream.cc", - "src/quic/core/http/quic_send_control_stream.h", - "src/quic/core/http/quic_server_initiated_spdy_stream.cc", - "src/quic/core/http/quic_server_initiated_spdy_stream.h", - "src/quic/core/http/quic_server_session_base.cc", - "src/quic/core/http/quic_server_session_base.h", - "src/quic/core/http/quic_spdy_client_session.cc", - "src/quic/core/http/quic_spdy_client_session.h", - "src/quic/core/http/quic_spdy_client_session_base.cc", - "src/quic/core/http/quic_spdy_client_session_base.h", - "src/quic/core/http/quic_spdy_client_stream.cc", - "src/quic/core/http/quic_spdy_client_stream.h", - "src/quic/core/http/quic_spdy_session.cc", - "src/quic/core/http/quic_spdy_session.h", - "src/quic/core/http/quic_spdy_stream.cc", - "src/quic/core/http/quic_spdy_stream.h", - "src/quic/core/http/quic_spdy_stream_body_manager.cc", - "src/quic/core/http/quic_spdy_stream_body_manager.h", - "src/quic/core/http/spdy_server_push_utils.cc", - "src/quic/core/http/spdy_server_push_utils.h", - "src/quic/core/http/spdy_utils.cc", - "src/quic/core/http/spdy_utils.h", - "src/quic/core/http/web_transport_http3.cc", - "src/quic/core/http/web_transport_http3.h", - "src/quic/core/legacy_quic_stream_id_manager.cc", - "src/quic/core/legacy_quic_stream_id_manager.h", - "src/quic/core/packet_number_indexed_queue.h", - "src/quic/core/proto/cached_network_parameters_proto.h", - "src/quic/core/proto/crypto_server_config_proto.h", - "src/quic/core/proto/source_address_token_proto.h", - "src/quic/core/qpack/qpack_blocking_manager.cc", - "src/quic/core/qpack/qpack_blocking_manager.h", - "src/quic/core/qpack/qpack_decoded_headers_accumulator.cc", - "src/quic/core/qpack/qpack_decoded_headers_accumulator.h", - "src/quic/core/qpack/qpack_decoder.cc", - "src/quic/core/qpack/qpack_decoder.h", - "src/quic/core/qpack/qpack_decoder_stream_receiver.cc", - "src/quic/core/qpack/qpack_decoder_stream_receiver.h", - "src/quic/core/qpack/qpack_decoder_stream_sender.cc", - "src/quic/core/qpack/qpack_decoder_stream_sender.h", - "src/quic/core/qpack/qpack_encoder.cc", - "src/quic/core/qpack/qpack_encoder.h", - "src/quic/core/qpack/qpack_encoder_stream_receiver.cc", - "src/quic/core/qpack/qpack_encoder_stream_receiver.h", - "src/quic/core/qpack/qpack_encoder_stream_sender.cc", - "src/quic/core/qpack/qpack_encoder_stream_sender.h", - "src/quic/core/qpack/qpack_header_table.cc", - "src/quic/core/qpack/qpack_header_table.h", - "src/quic/core/qpack/qpack_index_conversions.cc", - "src/quic/core/qpack/qpack_index_conversions.h", - "src/quic/core/qpack/qpack_instruction_decoder.cc", - "src/quic/core/qpack/qpack_instruction_decoder.h", - "src/quic/core/qpack/qpack_instruction_encoder.cc", - "src/quic/core/qpack/qpack_instruction_encoder.h", - "src/quic/core/qpack/qpack_instructions.cc", - "src/quic/core/qpack/qpack_instructions.h", - "src/quic/core/qpack/qpack_progressive_decoder.cc", - "src/quic/core/qpack/qpack_progressive_decoder.h", - "src/quic/core/qpack/qpack_receive_stream.cc", - "src/quic/core/qpack/qpack_receive_stream.h", - "src/quic/core/qpack/qpack_required_insert_count.cc", - "src/quic/core/qpack/qpack_required_insert_count.h", - "src/quic/core/qpack/qpack_send_stream.cc", - "src/quic/core/qpack/qpack_send_stream.h", - "src/quic/core/qpack/qpack_static_table.cc", - "src/quic/core/qpack/qpack_static_table.h", - "src/quic/core/qpack/qpack_stream_receiver.h", - "src/quic/core/qpack/qpack_stream_sender_delegate.h", - "src/quic/core/qpack/value_splitting_header_list.cc", - "src/quic/core/qpack/value_splitting_header_list.h", - "src/quic/core/quic_ack_listener_interface.cc", - "src/quic/core/quic_ack_listener_interface.h", - "src/quic/core/quic_alarm.cc", - "src/quic/core/quic_alarm.h", - "src/quic/core/quic_alarm_factory.h", - "src/quic/core/quic_arena_scoped_ptr.h", - "src/quic/core/quic_bandwidth.cc", - "src/quic/core/quic_bandwidth.h", - "src/quic/core/quic_blocked_writer_interface.h", - "src/quic/core/quic_buffer_allocator.cc", - "src/quic/core/quic_buffer_allocator.h", - "src/quic/core/quic_chaos_protector.cc", - "src/quic/core/quic_chaos_protector.h", - "src/quic/core/quic_clock.cc", - "src/quic/core/quic_clock.h", - "src/quic/core/quic_coalesced_packet.cc", - "src/quic/core/quic_coalesced_packet.h", - "src/quic/core/quic_config.cc", - "src/quic/core/quic_config.h", - "src/quic/core/quic_connection.cc", - "src/quic/core/quic_connection.h", - "src/quic/core/quic_connection_id.cc", - "src/quic/core/quic_connection_id.h", - "src/quic/core/quic_connection_id_manager.cc", - "src/quic/core/quic_connection_id_manager.h", - "src/quic/core/quic_connection_stats.cc", - "src/quic/core/quic_connection_stats.h", - "src/quic/core/quic_constants.cc", - "src/quic/core/quic_constants.h", - "src/quic/core/quic_control_frame_manager.cc", - "src/quic/core/quic_control_frame_manager.h", - "src/quic/core/quic_crypto_client_handshaker.cc", - "src/quic/core/quic_crypto_client_handshaker.h", - "src/quic/core/quic_crypto_client_stream.cc", - "src/quic/core/quic_crypto_client_stream.h", - "src/quic/core/quic_crypto_handshaker.cc", - "src/quic/core/quic_crypto_handshaker.h", - "src/quic/core/quic_crypto_server_stream.cc", - "src/quic/core/quic_crypto_server_stream.h", - "src/quic/core/quic_crypto_server_stream_base.cc", - "src/quic/core/quic_crypto_server_stream_base.h", - "src/quic/core/quic_crypto_stream.cc", - "src/quic/core/quic_crypto_stream.h", - "src/quic/core/quic_data_reader.cc", - "src/quic/core/quic_data_reader.h", - "src/quic/core/quic_data_writer.cc", - "src/quic/core/quic_data_writer.h", - "src/quic/core/quic_datagram_queue.cc", - "src/quic/core/quic_datagram_queue.h", - "src/quic/core/quic_flow_controller.cc", - "src/quic/core/quic_flow_controller.h", - "src/quic/core/quic_framer.cc", - "src/quic/core/quic_framer.h", - "src/quic/core/quic_idle_network_detector.cc", - "src/quic/core/quic_idle_network_detector.h", - "src/quic/core/quic_interval.h", - "src/quic/core/quic_interval_deque.h", - "src/quic/core/quic_interval_set.h", - "src/quic/core/quic_legacy_version_encapsulator.cc", - "src/quic/core/quic_legacy_version_encapsulator.h", - "src/quic/core/quic_lru_cache.h", - "src/quic/core/quic_mtu_discovery.cc", - "src/quic/core/quic_mtu_discovery.h", - "src/quic/core/quic_network_blackhole_detector.cc", - "src/quic/core/quic_network_blackhole_detector.h", - "src/quic/core/quic_one_block_arena.h", - "src/quic/core/quic_packet_creator.cc", - "src/quic/core/quic_packet_creator.h", - "src/quic/core/quic_packet_number.cc", - "src/quic/core/quic_packet_number.h", - "src/quic/core/quic_packet_writer.h", - "src/quic/core/quic_packets.cc", - "src/quic/core/quic_packets.h", - "src/quic/core/quic_path_validator.cc", - "src/quic/core/quic_path_validator.h", - "src/quic/core/quic_protocol_flags_list.h", - "src/quic/core/quic_received_packet_manager.cc", - "src/quic/core/quic_received_packet_manager.h", - "src/quic/core/quic_sent_packet_manager.cc", - "src/quic/core/quic_sent_packet_manager.h", - "src/quic/core/quic_server_id.cc", - "src/quic/core/quic_server_id.h", - "src/quic/core/quic_session.cc", - "src/quic/core/quic_session.h", - "src/quic/core/quic_simple_buffer_allocator.cc", - "src/quic/core/quic_simple_buffer_allocator.h", - "src/quic/core/quic_socket_address_coder.cc", - "src/quic/core/quic_socket_address_coder.h", - "src/quic/core/quic_stream.cc", - "src/quic/core/quic_stream.h", - "src/quic/core/quic_stream_frame_data_producer.h", - "src/quic/core/quic_stream_id_manager.cc", - "src/quic/core/quic_stream_id_manager.h", - "src/quic/core/quic_stream_send_buffer.cc", - "src/quic/core/quic_stream_send_buffer.h", - "src/quic/core/quic_stream_sequencer.cc", - "src/quic/core/quic_stream_sequencer.h", - "src/quic/core/quic_stream_sequencer_buffer.cc", - "src/quic/core/quic_stream_sequencer_buffer.h", - "src/quic/core/quic_sustained_bandwidth_recorder.cc", - "src/quic/core/quic_sustained_bandwidth_recorder.h", - "src/quic/core/quic_tag.cc", - "src/quic/core/quic_tag.h", - "src/quic/core/quic_time.cc", - "src/quic/core/quic_time.h", - "src/quic/core/quic_time_accumulator.h", - "src/quic/core/quic_transmission_info.cc", - "src/quic/core/quic_transmission_info.h", - "src/quic/core/quic_types.cc", - "src/quic/core/quic_types.h", - "src/quic/core/quic_unacked_packet_map.cc", - "src/quic/core/quic_unacked_packet_map.h", - "src/quic/core/quic_utils.cc", - "src/quic/core/quic_utils.h", - "src/quic/core/quic_version_manager.cc", - "src/quic/core/quic_version_manager.h", - "src/quic/core/quic_versions.cc", - "src/quic/core/quic_versions.h", - "src/quic/core/quic_write_blocked_list.cc", - "src/quic/core/quic_write_blocked_list.h", - "src/quic/core/session_notifier_interface.h", - "src/quic/core/stream_delegate_interface.h", - "src/quic/core/tls_client_handshaker.cc", - "src/quic/core/tls_client_handshaker.h", - "src/quic/core/tls_handshaker.cc", - "src/quic/core/tls_handshaker.h", - "src/quic/core/tls_server_handshaker.cc", - "src/quic/core/tls_server_handshaker.h", - "src/quic/core/uber_quic_stream_id_manager.cc", - "src/quic/core/uber_quic_stream_id_manager.h", - "src/quic/core/uber_received_packet_manager.cc", - "src/quic/core/uber_received_packet_manager.h", - "src/quic/core/web_transport_stream_adapter.cc", - "src/quic/core/web_transport_stream_adapter.h", - "src/quic/platform/api/quic_bug_tracker.h", - "src/quic/platform/api/quic_client_stats.h", - "src/quic/platform/api/quic_containers.h", - "src/quic/platform/api/quic_error_code_wrappers.h", - "src/quic/platform/api/quic_estimate_memory_usage.h", - "src/quic/platform/api/quic_export.h", - "src/quic/platform/api/quic_exported_stats.h", - "src/quic/platform/api/quic_file_utils.cc", - "src/quic/platform/api/quic_file_utils.h", - "src/quic/platform/api/quic_flag_utils.h", - "src/quic/platform/api/quic_flags.h", - "src/quic/platform/api/quic_hostname_utils.cc", - "src/quic/platform/api/quic_hostname_utils.h", - "src/quic/platform/api/quic_iovec.h", - "src/quic/platform/api/quic_ip_address.cc", - "src/quic/platform/api/quic_ip_address.h", - "src/quic/platform/api/quic_ip_address_family.h", - "src/quic/platform/api/quic_logging.h", - "src/quic/platform/api/quic_map_util.h", - "src/quic/platform/api/quic_mem_slice.h", - "src/quic/platform/api/quic_mem_slice_span.h", - "src/quic/platform/api/quic_mem_slice_storage.h", - "src/quic/platform/api/quic_mutex.cc", - "src/quic/platform/api/quic_mutex.h", - "src/quic/platform/api/quic_prefetch.h", - "src/quic/platform/api/quic_reference_counted.h", - "src/quic/platform/api/quic_server_stats.h", - "src/quic/platform/api/quic_sleep.h", - "src/quic/platform/api/quic_socket_address.cc", - "src/quic/platform/api/quic_socket_address.h", - "src/quic/platform/api/quic_stack_trace.h", - "src/quic/platform/api/quic_thread.h", - "src/quic/quic_transport/quic_transport_client_session.cc", - "src/quic/quic_transport/quic_transport_client_session.h", - "src/quic/quic_transport/quic_transport_protocol.h", - "src/quic/quic_transport/quic_transport_server_session.cc", - "src/quic/quic_transport/quic_transport_server_session.h", - "src/quic/quic_transport/quic_transport_session_interface.h", - "src/quic/quic_transport/quic_transport_stream.cc", - "src/quic/quic_transport/quic_transport_stream.h", - "src/quic/quic_transport/web_transport_fingerprint_proof_verifier.cc", - "src/quic/quic_transport/web_transport_fingerprint_proof_verifier.h", - "src/spdy/core/hpack/hpack_constants.cc", - "src/spdy/core/hpack/hpack_constants.h", - "src/spdy/core/hpack/hpack_decoder_adapter.cc", - "src/spdy/core/hpack/hpack_decoder_adapter.h", - "src/spdy/core/hpack/hpack_encoder.cc", - "src/spdy/core/hpack/hpack_encoder.h", - "src/spdy/core/hpack/hpack_entry.cc", - "src/spdy/core/hpack/hpack_entry.h", - "src/spdy/core/hpack/hpack_header_table.cc", - "src/spdy/core/hpack/hpack_header_table.h", - "src/spdy/core/hpack/hpack_output_stream.cc", - "src/spdy/core/hpack/hpack_output_stream.h", - "src/spdy/core/hpack/hpack_static_table.cc", - "src/spdy/core/hpack/hpack_static_table.h", - "src/spdy/core/http2_frame_decoder_adapter.cc", - "src/spdy/core/http2_frame_decoder_adapter.h", - "src/spdy/core/recording_headers_handler.cc", - "src/spdy/core/recording_headers_handler.h", - "src/spdy/core/spdy_alt_svc_wire_format.cc", - "src/spdy/core/spdy_alt_svc_wire_format.h", - "src/spdy/core/spdy_bitmasks.h", - "src/spdy/core/spdy_frame_builder.cc", - "src/spdy/core/spdy_frame_builder.h", - "src/spdy/core/spdy_frame_reader.cc", - "src/spdy/core/spdy_frame_reader.h", - "src/spdy/core/spdy_framer.cc", - "src/spdy/core/spdy_framer.h", - "src/spdy/core/spdy_header_block.cc", - "src/spdy/core/spdy_header_block.h", - "src/spdy/core/spdy_header_storage.cc", - "src/spdy/core/spdy_header_storage.h", - "src/spdy/core/spdy_headers_handler_interface.h", - "src/spdy/core/spdy_intrusive_list.h", - "src/spdy/core/spdy_no_op_visitor.cc", - "src/spdy/core/spdy_no_op_visitor.h", - "src/spdy/core/spdy_pinnable_buffer_piece.cc", - "src/spdy/core/spdy_pinnable_buffer_piece.h", - "src/spdy/core/spdy_prefixed_buffer_reader.cc", - "src/spdy/core/spdy_prefixed_buffer_reader.h", - "src/spdy/core/spdy_protocol.cc", - "src/spdy/core/spdy_protocol.h", - "src/spdy/core/spdy_simple_arena.cc", - "src/spdy/core/spdy_simple_arena.h", - "src/spdy/core/zero_copy_output_buffer.h", - "src/spdy/platform/api/spdy_containers.h", - "src/spdy/platform/api/spdy_estimate_memory_usage.h", - ] - } - deps = [ "//net:net_deps" ] public_deps = [ "//net:net_public_deps" ] }
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index c57f8c5..deed3ce 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -95,7 +95,7 @@ #include "net/cookies/test_cookie_access_delegate.h" #include "net/disk_cache/disk_cache.h" #include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" +#include "net/dns/public/secure_dns_policy.h" #include "net/http/http_byte_range.h" #include "net/http/http_cache.h" #include "net/http/http_network_layer.h" @@ -1346,7 +1346,7 @@ req->Start(); d.RunUntilComplete(); - EXPECT_FALSE(host_resolver.last_secure_dns_mode_override().has_value()); + EXPECT_EQ(SecureDnsPolicy::kAllow, host_resolver.last_secure_dns_policy()); } TEST_F(URLRequestTest, SkipSecureDnsEnabled) { @@ -1365,8 +1365,7 @@ req->Start(); d.RunUntilComplete(); - EXPECT_EQ(net::SecureDnsMode::kOff, - host_resolver.last_secure_dns_mode_override().value()); + EXPECT_EQ(SecureDnsPolicy::kDisable, host_resolver.last_secure_dns_policy()); } // Make sure that NetworkDelegate::NotifyCompleted is called if
diff --git a/net/websockets/websocket_frame.cc b/net/websockets/websocket_frame.cc index d858e060..6995fae05 100644 --- a/net/websockets/websocket_frame.cc +++ b/net/websockets/websocket_frame.cc
@@ -12,6 +12,7 @@ #include "base/big_endian.h" #include "base/check_op.h" #include "base/rand_util.h" +#include "build/build_config.h" #include "net/base/net_errors.h" namespace net { @@ -21,9 +22,8 @@ // GCC (and Clang) can transparently use vector ops. Only try to do this on // architectures where we know it works, otherwise gcc will attempt to emulate // the vector ops, which is unlikely to be efficient. -#if defined(COMPILER_GCC) && \ - (defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY)) && \ - !defined(OS_NACL) +#if defined(COMPILER_GCC) && \ + (defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY)) using PackedMaskType = uint32_t __attribute__((vector_size(16))); @@ -32,8 +32,7 @@ using PackedMaskType = size_t; #endif // defined(COMPILER_GCC) && - // (defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY)) && - // !defined(OS_NACL) + // (defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY)) const uint8_t kFinalBit = 0x80; const uint8_t kReserved1Bit = 0x40;
diff --git a/pdf/pdf_view_web_plugin.cc b/pdf/pdf_view_web_plugin.cc index 68b9644..97b8624b9 100644 --- a/pdf/pdf_view_web_plugin.cc +++ b/pdf/pdf_view_web_plugin.cc
@@ -61,6 +61,7 @@ #include "ui/events/blink/blink_event_util.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" +#include "ui/gfx/range/range.h" #include "ui/gfx/skia_util.h" #include "v8/include/v8.h" @@ -289,6 +290,18 @@ void PdfViewWebPlugin::DidFailLoading(const blink::WebURLError& error) {} +bool PdfViewWebPlugin::HasSelection() const { + return !selected_text_.IsEmpty(); +} + +blink::WebString PdfViewWebPlugin::SelectionAsText() const { + return selected_text_; +} + +blink::WebString PdfViewWebPlugin::SelectionAsMarkup() const { + return selected_text_; +} + blink::WebTextInputType PdfViewWebPlugin::GetPluginTextInputType() { return text_input_type_; } @@ -347,7 +360,9 @@ void PdfViewWebPlugin::EnteredEditMode() {} void PdfViewWebPlugin::SetSelectedText(const std::string& selected_text) { - NOTIMPLEMENTED(); + selected_text_ = blink::WebString::FromUTF8(selected_text); + GetValidContainerFrame()->TextSelectionChanged( + selected_text_, /*offset=*/0, gfx::Range(0, selected_text_.length())); } void PdfViewWebPlugin::SetLinkUnderCursor(
diff --git a/pdf/pdf_view_web_plugin.h b/pdf/pdf_view_web_plugin.h index 385b2e3..d0ce2ca6 100644 --- a/pdf/pdf_view_web_plugin.h +++ b/pdf/pdf_view_web_plugin.h
@@ -14,6 +14,7 @@ #include "pdf/post_message_sender.h" #include "pdf/ppapi_migration/graphics.h" #include "pdf/ppapi_migration/url_loader.h" +#include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_text_input_type.h" #include "third_party/blink/public/web/web_plugin.h" #include "third_party/blink/public/web/web_plugin_params.h" @@ -73,6 +74,9 @@ void DidReceiveData(const char* data, size_t data_length) override; void DidFinishLoading() override; void DidFailLoading(const blink::WebURLError& error) override; + bool HasSelection() const override; + blink::WebString SelectionAsText() const override; + blink::WebString SelectionAsMarkup() const override; blink::WebTextInputType GetPluginTextInputType() override; // PdfViewPluginBase: @@ -166,6 +170,8 @@ // page in it. void InvalidatePluginContainer(); + blink::WebString selected_text_; + blink::WebTextInputType text_input_type_ = blink::WebTextInputType::kWebTextInputTypeNone;
diff --git a/printing/BUILD.gn b/printing/BUILD.gn index 9cc6521..02c0d92 100644 --- a/printing/BUILD.gn +++ b/printing/BUILD.gn
@@ -256,6 +256,7 @@ test("printing_unittests") { sources = [ "backend/mojom/print_backend_mojom_traits_unittest.cc", + "backend/print_backend_unittest.cc", "backend/print_backend_utils_unittest.cc", "backend/test_print_backend_unittest.cc", "metafile_skia_unittest.cc",
diff --git a/printing/backend/cups_connection.cc b/printing/backend/cups_connection.cc index 294923a..ac31022 100644 --- a/printing/backend/cups_connection.cc +++ b/printing/backend/cups_connection.cc
@@ -176,6 +176,9 @@ std::string server_name() const override { return print_server_url_.host(); } int last_error() const override { return cupsLastError(); } + std::string last_error_message() const override { + return cupsLastErrorString(); + } private: // lazily initialize http connection
diff --git a/printing/backend/cups_connection.h b/printing/backend/cups_connection.h index 1d08c90..eb45523 100644 --- a/printing/backend/cups_connection.h +++ b/printing/backend/cups_connection.h
@@ -62,6 +62,7 @@ virtual std::string server_name() const = 0; virtual int last_error() const = 0; + virtual std::string last_error_message() const = 0; }; } // namespace printing
diff --git a/printing/backend/print_backend.h b/printing/backend/print_backend.h index 1ca5a20..8ddfc549 100644 --- a/printing/backend/print_backend.h +++ b/printing/backend/print_backend.h
@@ -172,7 +172,13 @@ class COMPONENT_EXPORT(PRINT_BACKEND) PrintBackend : public base::RefCountedThreadSafe<PrintBackend> { public: - // Enumerates the list of installed local and network printers. + // Enumerates the list of installed local and network printers. It will + // return true when the available installed printers have been enumerated + // into `printer_list`. Note that `printer_list` must not be null and also + // should be empty prior to this call. If there are no printers installed + // then it will still return true, and `printer_list` remains empty. It + // returns false when an error has occurred trying to get the list of + // printers. virtual bool EnumeratePrinters(PrinterList* printer_list) = 0; // Gets the default printer name. Empty string if no default printer.
diff --git a/printing/backend/print_backend_cups.cc b/printing/backend/print_backend_cups.cc index 802dd93..1b8ae05 100644 --- a/printing/backend/print_backend_cups.cc +++ b/printing/backend/print_backend_cups.cc
@@ -125,11 +125,22 @@ cups_dest_t* destinations = nullptr; int num_dests = GetDests(&destinations); - if (!num_dests && cupsLastError() > IPP_OK_EVENTS_COMPLETE) { - VLOG(1) << "CUPS: Error getting printers from CUPS server" - << ", server: " << print_server_url_ - << ", error: " << static_cast<int>(cupsLastError()); - return false; + DCHECK_GE(num_dests, 0); + if (!num_dests) { + // No destinations could mean the operation failed or that there are simply + // no printer drivers installed. Rely upon CUPS error code to distinguish + // between these. + DCHECK(!destinations); + const ipp_status_t last_error = cupsLastError(); + if (last_error != IPP_STATUS_ERROR_NOT_FOUND) { + VLOG(1) << "CUPS: Error getting printers from CUPS server" + << ", server: " << print_server_url_ + << ", error: " << static_cast<int>(last_error) << " - " + << cupsLastErrorString(); + return false; + } + VLOG(1) << "CUPS: No printers found for CUPS server: " << print_server_url_; + return true; } for (int printer_index = 0; printer_index < num_dests; ++printer_index) {
diff --git a/printing/backend/print_backend_cups_ipp.cc b/printing/backend/print_backend_cups_ipp.cc index 2ad1d5b7..fff28ecb 100644 --- a/printing/backend/print_backend_cups_ipp.cc +++ b/printing/backend/print_backend_cups_ipp.cc
@@ -35,14 +35,24 @@ std::vector<std::unique_ptr<CupsPrinter>> printers = cups_connection_->GetDests(); if (printers.empty()) { - LOG(WARNING) << "CUPS: Error getting printers from CUPS server" - << ", server: " << cups_connection_->server_name() - << ", error: " - << static_cast<int>(cups_connection_->last_error()); - - return false; + // No destinations could mean the operation failed or that there are simply + // no printer drivers installed. Rely upon CUPS error code to distinguish + // between these. + const int last_error = cups_connection_->last_error(); + if (last_error != IPP_STATUS_ERROR_NOT_FOUND) { + LOG(WARNING) << "CUPS: Error getting printers from CUPS server" + << ", server: " << cups_connection_->server_name() + << ", error: " << last_error << " - " + << cups_connection_->last_error_message(); + return false; + } + VLOG(1) << "CUPS: No printers found for CUPS server: " + << cups_connection_->server_name(); + return true; } + VLOG(1) << "CUPS: found " << printers.size() + << " printers from CUPS server: " << cups_connection_->server_name(); for (const auto& printer : printers) { PrinterBasicInfo basic_info; if (printer->ToPrinterInfo(&basic_info)) {
diff --git a/printing/backend/print_backend_unittest.cc b/printing/backend/print_backend_unittest.cc new file mode 100644 index 0000000..d3b65e0 --- /dev/null +++ b/printing/backend/print_backend_unittest.cc
@@ -0,0 +1,56 @@ +// Copyright 2021 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 "printing/backend/print_backend.h" + +#include "base/memory/scoped_refptr.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace printing { + +// PrintBackendTest makes use of a real print backend instance, and thus will +// interact with printer drivers installed on a system. This can be useful on +// machines which a developer has control over the driver installations, but is +// less useful on bots which are managed by the infra team. +// These tests are all disabled by default to avoid causing problems on the +// bots. Use with the --gtest_also_run_disabled_tests flag to locally test +// these interactions. +class PrintBackendTest : public testing::Test { + public: + void SetUp() override { + print_backend_ = PrintBackend::CreateInstance(/*locale=*/""); + } + + PrintBackend* GetPrintBackend() { return print_backend_.get(); } + + private: + scoped_refptr<PrintBackend> print_backend_; +}; + +// Check behavior of `EnumeratePrinters()`. At least one of the tests +// {EnumeratePrintersSomeInstalled, EnumeratePrintersNoneInstalled} should +// fail, since a single machine can't have both some and no printers installed. +// A developer running these manually can verify that the appropriate test is +// passing for the given state of installed printer drivers on the system being +// checked. +TEST_F(PrintBackendTest, DISABLED_EnumeratePrintersSomeInstalled) { + PrinterList printer_list; + + EXPECT_TRUE(GetPrintBackend()->EnumeratePrinters(&printer_list)); + EXPECT_FALSE(printer_list.empty()); + + DLOG(WARNING) << "Number of printers found: " << printer_list.size(); + for (const auto& printer : printer_list) { + DLOG(WARNING) << "Found printer: `" << printer.printer_name << "`"; + } +} + +TEST_F(PrintBackendTest, DISABLED_EnumeratePrintersNoneInstalled) { + PrinterList printer_list; + + EXPECT_TRUE(GetPrintBackend()->EnumeratePrinters(&printer_list)); + EXPECT_TRUE(printer_list.empty()); +} + +} // namespace printing
diff --git a/printing/backend/print_backend_win.cc b/printing/backend/print_backend_win.cc index b74a3e3d..7591fbe7 100644 --- a/printing/backend/print_backend_win.cc +++ b/printing/backend/print_backend_win.cc
@@ -11,6 +11,7 @@ #include <memory> +#include "base/logging.h" #include "base/memory/free_deleter.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_number_conversions.h" @@ -20,6 +21,7 @@ #include "base/threading/scoped_blocking_call.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_hglobal.h" +#include "base/win/windows_types.h" #include "printing/backend/print_backend_consts.h" #include "printing/backend/printing_info_win.h" #include "printing/backend/win_helper.h" @@ -195,8 +197,12 @@ const DWORD kLevel = 4; EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, nullptr, kLevel, nullptr, 0, &bytes_needed, &count_returned); - if (!bytes_needed) - return false; + if (!bytes_needed) { + // No bytes needed could mean the operation failed or that there are simply + // no printer drivers installed. Rely upon system error code to + // distinguish between these. + return logging::GetLastSystemErrorCode() == ERROR_SUCCESS; + } auto printer_info_buffer = std::make_unique<BYTE[]>(bytes_needed); if (!EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, nullptr,
diff --git a/printing/backend/test_print_backend.cc b/printing/backend/test_print_backend.cc index 5e43888..49b27599 100644 --- a/printing/backend/test_print_backend.cc +++ b/printing/backend/test_print_backend.cc
@@ -20,8 +20,9 @@ TestPrintBackend::~TestPrintBackend() = default; bool TestPrintBackend::EnumeratePrinters(PrinterList* printer_list) { + DCHECK(printer_list->empty()); if (printer_map_.empty()) - return false; + return true; for (const auto& entry : printer_map_) { const std::unique_ptr<PrinterData>& data = entry.second;
diff --git a/printing/backend/test_print_backend_unittest.cc b/printing/backend/test_print_backend_unittest.cc index 5628819df..a2506699 100644 --- a/printing/backend/test_print_backend_unittest.cc +++ b/printing/backend/test_print_backend_unittest.cc
@@ -78,9 +78,7 @@ } // Get the test print backend. - TestPrintBackend* GetPrintBackend() const { - return test_print_backend_.get(); - } + TestPrintBackend* GetPrintBackend() { return test_print_backend_.get(); } private: scoped_refptr<TestPrintBackend> test_print_backend_; @@ -90,15 +88,21 @@ const PrinterList kPrinterList{kAlternatePrinterInfo, kDefaultPrinterInfo}; PrinterList printer_list; - // Should return false when there are no printers in the environment. - EXPECT_FALSE(GetPrintBackend()->EnumeratePrinters(&printer_list)); - AddPrinters(); EXPECT_TRUE(GetPrintBackend()->EnumeratePrinters(&printer_list)); EXPECT_THAT(printer_list, testing::ContainerEq(kPrinterList)); } +TEST_F(TestPrintBackendTest, EnumeratePrintersNoneFound) { + const PrinterList kPrinterList{kAlternatePrinterInfo, kDefaultPrinterInfo}; + PrinterList printer_list; + + // Should return true even when there are no printers in the environment. + EXPECT_TRUE(GetPrintBackend()->EnumeratePrinters(&printer_list)); + EXPECT_TRUE(printer_list.empty()); +} + TEST_F(TestPrintBackendTest, DefaultPrinterName) { // If no printers added then no default. EXPECT_TRUE(GetPrintBackend()->GetDefaultPrinterName().empty());
diff --git a/printing/printing_context_chromeos_unittest.cc b/printing/printing_context_chromeos_unittest.cc index 72c4099..9db836d 100644 --- a/printing/printing_context_chromeos_unittest.cc +++ b/printing/printing_context_chromeos_unittest.cc
@@ -91,6 +91,7 @@ PrinterStatus* printer_status)); MOCK_CONST_METHOD0(server_name, std::string()); MOCK_CONST_METHOD0(last_error, int()); + MOCK_CONST_METHOD0(last_error_message, std::string()); MOCK_METHOD1(GetPrinter, std::unique_ptr<CupsPrinter>(const std::string& printer_name));
diff --git a/services/network/host_resolver.cc b/services/network/host_resolver.cc index 0168bde..3ff345b 100644 --- a/services/network/host_resolver.cc +++ b/services/network/host_resolver.cc
@@ -15,7 +15,6 @@ #include "net/base/net_errors.h" #include "net/dns/host_resolver.h" #include "net/dns/host_resolver_source.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/log/net_log.h" #include "net/net_buildflags.h" @@ -59,15 +58,8 @@ parameters.include_canonical_name = mojo_parameters->include_canonical_name; parameters.loopback_only = mojo_parameters->loopback_only; parameters.is_speculative = mojo_parameters->is_speculative; - - // TODO(crbug.com/1200908): Pass the SecureDnsPolicy through unmodified. - net::SecureDnsPolicy secure_dns_policy; mojo::EnumTraits<mojom::SecureDnsPolicy, net::SecureDnsPolicy>::FromMojom( - mojo_parameters->secure_dns_policy, &secure_dns_policy); - - if (secure_dns_policy == net::SecureDnsPolicy::kDisable) { - parameters.secure_dns_mode_override = net::SecureDnsMode::kOff; - } + mojo_parameters->secure_dns_policy, ¶meters.secure_dns_policy); return parameters; } } // namespace
diff --git a/services/network/host_resolver_unittest.cc b/services/network/host_resolver_unittest.cc index 4f592c68..61a8a7b9 100644 --- a/services/network/host_resolver_unittest.cc +++ b/services/network/host_resolver_unittest.cc
@@ -30,7 +30,7 @@ #include "net/dns/host_resolver_manager.h" #include "net/dns/mock_host_resolver.h" #include "net/dns/public/dns_protocol.h" -#include "net/dns/public/secure_dns_mode.h" +#include "net/dns/public/secure_dns_policy.h" #include "net/log/net_log.h" #include "net/net_buildflags.h" #include "net/test/gtest_util.h" @@ -709,7 +709,7 @@ testing::ElementsAre(CreateExpectedEndPoint("127.0.12.24", 80))); } -TEST_F(HostResolverTest, SecureDnsModeOverride) { +TEST_F(HostResolverTest, HandlesSecureDnsPolicyParameter) { auto inner_resolver = std::make_unique<net::MockHostResolver>(); HostResolver resolver(inner_resolver.get(), net::NetLog::Get()); @@ -731,8 +731,8 @@ EXPECT_EQ(net::OK, response_client.result_error()); EXPECT_THAT(response_client.result_addresses().value().endpoints(), testing::ElementsAre(CreateExpectedEndPoint("127.0.0.1", 80))); - EXPECT_EQ(net::SecureDnsMode::kOff, - inner_resolver->last_secure_dns_mode_override().value()); + EXPECT_EQ(net::SecureDnsPolicy::kDisable, + inner_resolver->last_secure_dns_policy()); } TEST_F(HostResolverTest, Failure_Sync) {
diff --git a/services/network/network_context_unittest.cc b/services/network/network_context_unittest.cc index e64e7ec..e8351a3 100644 --- a/services/network/network_context_unittest.cc +++ b/services/network/network_context_unittest.cc
@@ -80,7 +80,6 @@ #include "net/dns/host_resolver_source.h" #include "net/dns/mock_host_resolver.h" #include "net/dns/public/dns_query_type.h" -#include "net/dns/public/secure_dns_mode.h" #include "net/dns/public/secure_dns_policy.h" #include "net/dns/resolve_context.h" #include "net/http/http_auth.h" @@ -4563,11 +4562,12 @@ net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS)); client.RunUntilComplete(); - EXPECT_EQ(disable_secure_dns, - resolver->last_secure_dns_mode_override().has_value()); if (disable_secure_dns) { - EXPECT_EQ(net::SecureDnsMode::kOff, - resolver->last_secure_dns_mode_override().value()); + EXPECT_EQ(net::SecureDnsPolicy::kDisable, + resolver->last_secure_dns_policy()); + } else { + EXPECT_EQ(net::SecureDnsPolicy::kAllow, + resolver->last_secure_dns_policy()); } } } @@ -4609,11 +4609,12 @@ net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS)); client->RunUntilComplete(); - EXPECT_EQ(disable_secure_dns, - resolver.last_secure_dns_mode_override().has_value()); if (disable_secure_dns) { - EXPECT_EQ(net::SecureDnsMode::kOff, - resolver.last_secure_dns_mode_override().value()); + EXPECT_EQ(net::SecureDnsPolicy::kDisable, + resolver.last_secure_dns_policy()); + } else { + EXPECT_EQ(net::SecureDnsPolicy::kAllow, + resolver.last_secure_dns_policy()); } } }
diff --git a/services/tracing/perfetto/privacy_filtered_fields-inl.h b/services/tracing/perfetto/privacy_filtered_fields-inl.h index 52cc53ab..6ffeaaaa 100644 --- a/services/tracing/perfetto/privacy_filtered_fields-inl.h +++ b/services/tracing/perfetto/privacy_filtered_fields-inl.h
@@ -356,7 +356,7 @@ constexpr MessageInfo kHistogramRule = {kHistogramRuleIndices, nullptr}; // Proto Message: NamedRule -constexpr int kNamedRuleIndices[] = {1, -1}; +constexpr int kNamedRuleIndices[] = {1, 2, -1}; constexpr MessageInfo kNamedRule = {kNamedRuleIndices, nullptr}; // Proto Message: TriggerRule
diff --git a/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc b/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc index c7c3b30..2c064ab 100644 --- a/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc +++ b/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc
@@ -1052,8 +1052,8 @@ auto* category_group_enabled = TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(kCategoryGroup); - trace_event_internal::TraceID trace_event_trace_id = - trace_event_internal::kNoId; + trace_event_internal::TraceID trace_event_trace_id( + trace_event_internal::kNoId); // COMPLETE events are split into a BEGIN/END event pair. Adding the event // writes the BEGIN event immediately. @@ -1134,8 +1134,8 @@ auto* category_group_enabled = TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(kCategoryGroup); - trace_event_internal::TraceID trace_event_trace_id = - trace_event_internal::kNoId; + trace_event_internal::TraceID trace_event_trace_id( + trace_event_internal::kNoId); // Chrome's main thread buffers and later flushes EarlyJava events on behalf // of other threads, including explicit thread time values. Such an event
diff --git a/sql/BUILD.gn b/sql/BUILD.gn index e589f9a..c7fd00f 100644 --- a/sql/BUILD.gn +++ b/sql/BUILD.gn
@@ -121,6 +121,8 @@ "test/paths.cc", "test/paths.h", "test/run_all_unittests.cc", + "test/sql_test_base.cc", + "test/sql_test_base.h", "test/sql_test_suite.cc", "test/sql_test_suite.h", "transaction_unittest.cc",
diff --git a/sql/database_unittest.cc b/sql/database_unittest.cc index ace0362..9ae6a17 100644 --- a/sql/database_unittest.cc +++ b/sql/database_unittest.cc
@@ -2,20 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "sql/database.h" - #include <stddef.h> #include <stdint.h> #include "base/bind.h" #include "base/files/file_util.h" +#include "base/files/scoped_file.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" +#include "base/macros.h" #include "base/strings/string_number_conversions.h" #include "base/test/gtest_util.h" #include "base/test/metrics/histogram_tester.h" #include "base/trace_event/process_memory_dump.h" #include "build/build_config.h" +#include "sql/database.h" #include "sql/database_memory_dump_provider.h" #include "sql/meta_table.h" #include "sql/sql_features.h" @@ -23,6 +24,7 @@ #include "sql/test/database_test_peer.h" #include "sql/test/error_callback_support.h" #include "sql/test/scoped_error_expecter.h" +#include "sql/test/sql_test_base.h" #include "sql/test/test_helpers.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/sqlite/sqlite3.h" @@ -35,9 +37,9 @@ // Helper to return the count of items in sqlite_master. Return -1 in // case of error. -int SqliteMasterCount(Database* db) { +int SqliteMasterCount(sql::Database* db) { const char* kMasterCount = "SELECT COUNT(*) FROM sqlite_master"; - Statement s(db->GetUniqueStatement(kMasterCount)); + sql::Statement s(db->GetUniqueStatement(kMasterCount)); return s.Step() ? s.ColumnInt(0) : -1; } @@ -46,7 +48,7 @@ // explicitly having the ref count live longer than the object. class RefCounter { public: - explicit RefCounter(size_t* counter) : counter_(counter) { (*counter_)++; } + RefCounter(size_t* counter) : counter_(counter) { (*counter_)++; } RefCounter(const RefCounter& other) : counter_(other.counter_) { (*counter_)++; } @@ -59,24 +61,24 @@ }; // Empty callback for implementation of ErrorCallbackSetHelper(). -void IgnoreErrorCallback(int error, Statement* stmt) {} +void IgnoreErrorCallback(int error, sql::Statement* stmt) {} -void ErrorCallbackSetHelper(Database* db, +void ErrorCallbackSetHelper(sql::Database* db, size_t* counter, const RefCounter& r, int error, - Statement* stmt) { + sql::Statement* stmt) { // The ref count should not go to zero when changing the callback. EXPECT_GT(*counter, 0u); db->set_error_callback(base::BindRepeating(&IgnoreErrorCallback)); EXPECT_GT(*counter, 0u); } -void ErrorCallbackResetHelper(Database* db, +void ErrorCallbackResetHelper(sql::Database* db, size_t* counter, const RefCounter& r, int error, - Statement* stmt) { + sql::Statement* stmt) { // The ref count should not go to zero when clearing the callback. EXPECT_GT(*counter, 0u); db->reset_error_callback(); @@ -84,10 +86,10 @@ } // Handle errors by blowing away the database. -void RazeErrorCallback(Database* db, +void RazeErrorCallback(sql::Database* db, int expected_error, int error, - Statement* stmt) { + sql::Statement* stmt) { // Nothing here needs extended errors at this time. EXPECT_EQ(expected_error, expected_error & 0xff); EXPECT_EQ(expected_error, error & 0xff); @@ -104,36 +106,23 @@ } ~ScopedUmaskSetter() { umask(old_umask_); } - ScopedUmaskSetter(const ScopedUmaskSetter&) = delete; - ScopedUmaskSetter& operator=(const ScopedUmaskSetter&) = delete; - private: mode_t old_umask_; + DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedUmaskSetter); }; #endif // defined(OS_POSIX) } // namespace // We use the parameter to run all tests with WAL mode on and off. -class SQLDatabaseTest : public testing::Test, +class SQLDatabaseTest : public SQLTestBase, public testing::WithParamInterface<bool> { public: - enum class OverwriteType { - kTruncate, - kOverwrite, - }; + SQLDatabaseTest() : SQLTestBase(GetDBOptions()) {} + explicit SQLDatabaseTest(DatabaseOptions options) : SQLTestBase(options) {} - SQLDatabaseTest() : SQLDatabaseTest(GetDBOptions()) {} - ~SQLDatabaseTest() override = default; - - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - db_path_ = temp_dir_.GetPath().AppendASCII("recovery_test.sqlite"); - ASSERT_TRUE(db_.Open(db_path_)); - } - - DatabaseOptions GetDBOptions() { - DatabaseOptions options; + sql::DatabaseOptions GetDBOptions() { + sql::DatabaseOptions options; options.wal_mode = IsWALEnabled(); // TODO(crbug.com/1120969): Remove after switching to exclusive mode on by // default. @@ -146,213 +135,186 @@ #endif // defined(OS_FUCHSIA) return options; } - bool IsWALEnabled() { return GetParam(); } - - bool TruncateDatabase() { - base::File file(db_path_, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - return file.SetLength(0); - } - - bool OverwriteDatabaseHeader(OverwriteType type) { - base::File file(db_path_, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - if (type == OverwriteType::kTruncate) { - if (!file.SetLength(0)) - return false; - } - - static constexpr char kText[] = "Now is the winter of our discontent."; - constexpr int kTextBytes = sizeof(kText) - 1; - return file.Write(0, kText, kTextBytes) == kTextBytes; - } - - protected: - explicit SQLDatabaseTest(DatabaseOptions options) : db_(options) {} - - base::ScopedTempDir temp_dir_; - base::FilePath db_path_; - Database db_; }; TEST_P(SQLDatabaseTest, Execute) { // Valid statement should return true. - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - EXPECT_EQ(SQLITE_OK, db_.GetErrorCode()); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); + EXPECT_EQ(SQLITE_OK, db().GetErrorCode()); // Invalid statement should fail. ASSERT_EQ(SQLITE_ERROR, - db_.ExecuteAndReturnErrorCode("CREATE TAB foo (a, b")); - EXPECT_EQ(SQLITE_ERROR, db_.GetErrorCode()); + db().ExecuteAndReturnErrorCode("CREATE TAB foo (a, b")); + EXPECT_EQ(SQLITE_ERROR, db().GetErrorCode()); } TEST_P(SQLDatabaseTest, ExecuteWithErrorCode) { ASSERT_EQ(SQLITE_OK, - db_.ExecuteAndReturnErrorCode("CREATE TABLE foo (a, b)")); - ASSERT_EQ(SQLITE_ERROR, db_.ExecuteAndReturnErrorCode("CREATE TABLE TABLE")); - ASSERT_EQ(SQLITE_ERROR, db_.ExecuteAndReturnErrorCode( + db().ExecuteAndReturnErrorCode("CREATE TABLE foo (a, b)")); + ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode("CREATE TABLE TABLE")); + ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode( "INSERT INTO foo(a, b) VALUES (1, 2, 3, 4)")); } TEST_P(SQLDatabaseTest, CachedStatement) { - StatementID id1 = SQL_FROM_HERE; - StatementID id2 = SQL_FROM_HERE; + sql::StatementID id1 = SQL_FROM_HERE; + sql::StatementID id2 = SQL_FROM_HERE; static const char kId1Sql[] = "SELECT a FROM foo"; static const char kId2Sql[] = "SELECT b FROM foo"; - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - ASSERT_TRUE(db_.Execute("INSERT INTO foo(a, b) VALUES (12, 13)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("INSERT INTO foo(a, b) VALUES (12, 13)")); sqlite3_stmt* raw_id1_statement; sqlite3_stmt* raw_id2_statement; { - scoped_refptr<Database::StatementRef> ref_from_id1 = - db_.GetCachedStatement(id1, kId1Sql); + scoped_refptr<sql::Database::StatementRef> ref_from_id1 = + db().GetCachedStatement(id1, kId1Sql); raw_id1_statement = ref_from_id1->stmt(); - Statement from_id1(std::move(ref_from_id1)); + sql::Statement from_id1(std::move(ref_from_id1)); ASSERT_TRUE(from_id1.is_valid()); ASSERT_TRUE(from_id1.Step()); EXPECT_EQ(12, from_id1.ColumnInt(0)); - scoped_refptr<Database::StatementRef> ref_from_id2 = - db_.GetCachedStatement(id2, kId2Sql); + scoped_refptr<sql::Database::StatementRef> ref_from_id2 = + db().GetCachedStatement(id2, kId2Sql); raw_id2_statement = ref_from_id2->stmt(); EXPECT_NE(raw_id1_statement, raw_id2_statement); - Statement from_id2(std::move(ref_from_id2)); + sql::Statement from_id2(std::move(ref_from_id2)); ASSERT_TRUE(from_id2.is_valid()); ASSERT_TRUE(from_id2.Step()); EXPECT_EQ(13, from_id2.ColumnInt(0)); } { - scoped_refptr<Database::StatementRef> ref_from_id1 = - db_.GetCachedStatement(id1, kId1Sql); + scoped_refptr<sql::Database::StatementRef> ref_from_id1 = + db().GetCachedStatement(id1, kId1Sql); EXPECT_EQ(raw_id1_statement, ref_from_id1->stmt()) << "statement was not cached"; - Statement from_id1(std::move(ref_from_id1)); + sql::Statement from_id1(std::move(ref_from_id1)); ASSERT_TRUE(from_id1.is_valid()); ASSERT_TRUE(from_id1.Step()) << "cached statement was not reset"; EXPECT_EQ(12, from_id1.ColumnInt(0)); - scoped_refptr<Database::StatementRef> ref_from_id2 = - db_.GetCachedStatement(id2, kId2Sql); + scoped_refptr<sql::Database::StatementRef> ref_from_id2 = + db().GetCachedStatement(id2, kId2Sql); EXPECT_EQ(raw_id2_statement, ref_from_id2->stmt()) << "statement was not cached"; - Statement from_id2(std::move(ref_from_id2)); + sql::Statement from_id2(std::move(ref_from_id2)); ASSERT_TRUE(from_id2.is_valid()); ASSERT_TRUE(from_id2.Step()) << "cached statement was not reset"; EXPECT_EQ(13, from_id2.ColumnInt(0)); } - EXPECT_DCHECK_DEATH(db_.GetCachedStatement(id1, kId2Sql)) + EXPECT_DCHECK_DEATH(db().GetCachedStatement(id1, kId2Sql)) << "Using a different SQL with the same statement ID should DCHECK"; - EXPECT_DCHECK_DEATH(db_.GetCachedStatement(id2, kId1Sql)) + EXPECT_DCHECK_DEATH(db().GetCachedStatement(id2, kId1Sql)) << "Using a different SQL with the same statement ID should DCHECK"; } TEST_P(SQLDatabaseTest, IsSQLValidTest) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - ASSERT_TRUE(db_.IsSQLValid("SELECT a FROM foo")); - ASSERT_FALSE(db_.IsSQLValid("SELECT no_exist FROM foo")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().IsSQLValid("SELECT a FROM foo")); + ASSERT_FALSE(db().IsSQLValid("SELECT no_exist FROM foo")); } TEST_P(SQLDatabaseTest, DoesTableExist) { - EXPECT_FALSE(db_.DoesTableExist("foo")); - EXPECT_FALSE(db_.DoesTableExist("foo_index")); + EXPECT_FALSE(db().DoesTableExist("foo")); + EXPECT_FALSE(db().DoesTableExist("foo_index")); - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - ASSERT_TRUE(db_.Execute("CREATE INDEX foo_index ON foo (a)")); - EXPECT_TRUE(db_.DoesTableExist("foo")); - EXPECT_FALSE(db_.DoesTableExist("foo_index")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("CREATE INDEX foo_index ON foo (a)")); + EXPECT_TRUE(db().DoesTableExist("foo")); + EXPECT_FALSE(db().DoesTableExist("foo_index")); // DoesTableExist() is case-sensitive. - EXPECT_FALSE(db_.DoesTableExist("Foo")); - EXPECT_FALSE(db_.DoesTableExist("FOO")); + EXPECT_FALSE(db().DoesTableExist("Foo")); + EXPECT_FALSE(db().DoesTableExist("FOO")); } TEST_P(SQLDatabaseTest, DoesIndexExist) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - EXPECT_FALSE(db_.DoesIndexExist("foo")); - EXPECT_FALSE(db_.DoesIndexExist("foo_ubdex")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); + EXPECT_FALSE(db().DoesIndexExist("foo")); + EXPECT_FALSE(db().DoesIndexExist("foo_ubdex")); - ASSERT_TRUE(db_.Execute("CREATE INDEX foo_index ON foo (a)")); - EXPECT_TRUE(db_.DoesIndexExist("foo_index")); - EXPECT_FALSE(db_.DoesIndexExist("foo")); + ASSERT_TRUE(db().Execute("CREATE INDEX foo_index ON foo (a)")); + EXPECT_TRUE(db().DoesIndexExist("foo_index")); + EXPECT_FALSE(db().DoesIndexExist("foo")); // DoesIndexExist() is case-sensitive. - EXPECT_FALSE(db_.DoesIndexExist("Foo_index")); - EXPECT_FALSE(db_.DoesIndexExist("Foo_Index")); - EXPECT_FALSE(db_.DoesIndexExist("FOO_INDEX")); + EXPECT_FALSE(db().DoesIndexExist("Foo_index")); + EXPECT_FALSE(db().DoesIndexExist("Foo_Index")); + EXPECT_FALSE(db().DoesIndexExist("FOO_INDEX")); } TEST_P(SQLDatabaseTest, DoesViewExist) { - EXPECT_FALSE(db_.DoesViewExist("voo")); - ASSERT_TRUE(db_.Execute("CREATE VIEW voo (a) AS SELECT 1")); - EXPECT_FALSE(db_.DoesIndexExist("voo")); - EXPECT_FALSE(db_.DoesTableExist("voo")); - EXPECT_TRUE(db_.DoesViewExist("voo")); + EXPECT_FALSE(db().DoesViewExist("voo")); + ASSERT_TRUE(db().Execute("CREATE VIEW voo (a) AS SELECT 1")); + EXPECT_FALSE(db().DoesIndexExist("voo")); + EXPECT_FALSE(db().DoesTableExist("voo")); + EXPECT_TRUE(db().DoesViewExist("voo")); // DoesTableExist() is case-sensitive. - EXPECT_FALSE(db_.DoesViewExist("Voo")); - EXPECT_FALSE(db_.DoesViewExist("VOO")); + EXPECT_FALSE(db().DoesViewExist("Voo")); + EXPECT_FALSE(db().DoesViewExist("VOO")); } TEST_P(SQLDatabaseTest, DoesColumnExist) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); - EXPECT_FALSE(db_.DoesColumnExist("foo", "bar")); - EXPECT_TRUE(db_.DoesColumnExist("foo", "a")); + EXPECT_FALSE(db().DoesColumnExist("foo", "bar")); + EXPECT_TRUE(db().DoesColumnExist("foo", "a")); - ASSERT_FALSE(db_.DoesTableExist("bar")); - EXPECT_FALSE(db_.DoesColumnExist("bar", "b")); + ASSERT_FALSE(db().DoesTableExist("bar")); + EXPECT_FALSE(db().DoesColumnExist("bar", "b")); // SQLite resolves table/column names without case sensitivity. - EXPECT_TRUE(db_.DoesColumnExist("FOO", "A")); - EXPECT_TRUE(db_.DoesColumnExist("FOO", "a")); - EXPECT_TRUE(db_.DoesColumnExist("foo", "A")); + EXPECT_TRUE(db().DoesColumnExist("FOO", "A")); + EXPECT_TRUE(db().DoesColumnExist("FOO", "a")); + EXPECT_TRUE(db().DoesColumnExist("foo", "A")); } TEST_P(SQLDatabaseTest, GetLastInsertRowId) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, value)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, value)")); - ASSERT_TRUE(db_.Execute("INSERT INTO foo (value) VALUES (12)")); + ASSERT_TRUE(db().Execute("INSERT INTO foo (value) VALUES (12)")); // Last insert row ID should be valid. - int64_t row = db_.GetLastInsertRowId(); + int64_t row = db().GetLastInsertRowId(); EXPECT_LT(0, row); // It should be the primary key of the row we just inserted. - Statement s(db_.GetUniqueStatement("SELECT value FROM foo WHERE id=?")); + sql::Statement s(db().GetUniqueStatement("SELECT value FROM foo WHERE id=?")); s.BindInt64(0, row); ASSERT_TRUE(s.Step()); EXPECT_EQ(12, s.ColumnInt(0)); } TEST_P(SQLDatabaseTest, Rollback) { - ASSERT_TRUE(db_.BeginTransaction()); - ASSERT_TRUE(db_.BeginTransaction()); - EXPECT_EQ(2, db_.transaction_nesting()); - db_.RollbackTransaction(); - EXPECT_FALSE(db_.CommitTransaction()); - EXPECT_TRUE(db_.BeginTransaction()); + ASSERT_TRUE(db().BeginTransaction()); + ASSERT_TRUE(db().BeginTransaction()); + EXPECT_EQ(2, db().transaction_nesting()); + db().RollbackTransaction(); + EXPECT_FALSE(db().CommitTransaction()); + EXPECT_TRUE(db().BeginTransaction()); } // Test the scoped error expecter by attempting to insert a duplicate // value into an index. TEST_P(SQLDatabaseTest, ScopedErrorExpecter) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute("INSERT INTO foo (id) VALUES (12)")); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute("INSERT INTO foo (id) VALUES (12)")); { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CONSTRAINT); - ASSERT_FALSE(db_.Execute("INSERT INTO foo (id) VALUES (12)")); + ASSERT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)")); ASSERT_TRUE(expecter.SawExpectedErrors()); } } @@ -361,36 +323,36 @@ // with ScopedErrorExpecter. TEST_P(SQLDatabaseTest, ScopedIgnoreUntracked) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_FALSE(db_.DoesTableExist("bar")); - ASSERT_TRUE(db_.DoesTableExist("foo")); - ASSERT_TRUE(db_.DoesColumnExist("foo", "id")); - db_.Close(); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_FALSE(db().DoesTableExist("bar")); + ASSERT_TRUE(db().DoesTableExist("foo")); + ASSERT_TRUE(db().DoesColumnExist("foo", "id")); + db().Close(); // Corrupt the database so that nothing works, including PRAGMAs. - ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_)); + ASSERT_TRUE(CorruptSizeInHeaderOfDB()); { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - ASSERT_TRUE(db_.Open(db_path_)); - ASSERT_FALSE(db_.DoesTableExist("bar")); - ASSERT_FALSE(db_.DoesTableExist("foo")); - ASSERT_FALSE(db_.DoesColumnExist("foo", "id")); + ASSERT_TRUE(db().Open(db_path())); + ASSERT_FALSE(db().DoesTableExist("bar")); + ASSERT_FALSE(db().DoesTableExist("foo")); + ASSERT_FALSE(db().DoesColumnExist("foo", "id")); ASSERT_TRUE(expecter.SawExpectedErrors()); } } TEST_P(SQLDatabaseTest, ErrorCallback) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute("INSERT INTO foo (id) VALUES (12)")); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute("INSERT INTO foo (id) VALUES (12)")); int error = SQLITE_OK; { - ScopedErrorCallback sec(&db_, - base::BindRepeating(&CaptureErrorCallback, &error)); - EXPECT_FALSE(db_.Execute("INSERT INTO foo (id) VALUES (12)")); + sql::ScopedErrorCallback sec( + &db(), base::BindRepeating(&sql::CaptureErrorCallback, &error)); + EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)")); // Later versions of SQLite throw SQLITE_CONSTRAINT_UNIQUE. The specific // sub-error isn't really important. @@ -402,7 +364,7 @@ error = SQLITE_OK; sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CONSTRAINT); - ASSERT_FALSE(db_.Execute("INSERT INTO foo (id) VALUES (12)")); + ASSERT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)")); ASSERT_TRUE(expecter.SawExpectedErrors()); EXPECT_EQ(SQLITE_OK, error); } @@ -418,34 +380,34 @@ // live. { size_t count = 0; - ScopedErrorCallback sec( - &db_, base::BindRepeating(&ErrorCallbackSetHelper, &db_, &count, - RefCounter(&count))); + sql::ScopedErrorCallback sec( + &db(), base::BindRepeating(&ErrorCallbackSetHelper, &db(), &count, + RefCounter(&count))); - EXPECT_FALSE(db_.Execute("INSERT INTO foo (id) VALUES (12)")); + EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)")); } // Same test, but reset_error_callback() case. { size_t count = 0; - ScopedErrorCallback sec( - &db_, base::BindRepeating(&ErrorCallbackResetHelper, &db_, &count, - RefCounter(&count))); + sql::ScopedErrorCallback sec( + &db(), base::BindRepeating(&ErrorCallbackResetHelper, &db(), &count, + RefCounter(&count))); - EXPECT_FALSE(db_.Execute("INSERT INTO foo (id) VALUES (12)")); + EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)")); } } -// Test that Database::Raze() results in a database without the +// Test that sql::Database::Raze() results in a database without the // tables from the original database. TEST_P(SQLDatabaseTest, Raze) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute("INSERT INTO foo (value) VALUES (12)")); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute("INSERT INTO foo (value) VALUES (12)")); int pragma_auto_vacuum = 0; { - Statement s(db_.GetUniqueStatement("PRAGMA auto_vacuum")); + sql::Statement s(db().GetUniqueStatement("PRAGMA auto_vacuum")); ASSERT_TRUE(s.Step()); pragma_auto_vacuum = s.ColumnInt(0); ASSERT_TRUE(pragma_auto_vacuum == 0 || pragma_auto_vacuum == 1); @@ -455,13 +417,13 @@ const int kExpectedPageCount = 2 + pragma_auto_vacuum; { - Statement s(db_.GetUniqueStatement("PRAGMA page_count")); + sql::Statement s(db().GetUniqueStatement("PRAGMA page_count")); ASSERT_TRUE(s.Step()); EXPECT_EQ(kExpectedPageCount, s.ColumnInt(0)); } { - Statement s(db_.GetUniqueStatement("SELECT * FROM sqlite_master")); + sql::Statement s(db().GetUniqueStatement("SELECT * FROM sqlite_master")); ASSERT_TRUE(s.Step()); EXPECT_EQ("table", s.ColumnString(0)); EXPECT_EQ("foo", s.ColumnString(1)); @@ -471,18 +433,18 @@ EXPECT_EQ(kCreateSql, s.ColumnString(4)); } - ASSERT_TRUE(db_.Raze()); + ASSERT_TRUE(db().Raze()); { - Statement s(db_.GetUniqueStatement("PRAGMA page_count")); + sql::Statement s(db().GetUniqueStatement("PRAGMA page_count")); ASSERT_TRUE(s.Step()); EXPECT_EQ(1, s.ColumnInt(0)); } - ASSERT_EQ(0, SqliteMasterCount(&db_)); + ASSERT_EQ(0, SqliteMasterCount(&db())); { - Statement s(db_.GetUniqueStatement("PRAGMA auto_vacuum")); + sql::Statement s(db().GetUniqueStatement("PRAGMA auto_vacuum")); ASSERT_TRUE(s.Step()); // The new database has the same auto_vacuum as a fresh database. EXPECT_EQ(pragma_auto_vacuum, s.ColumnInt(0)); @@ -504,8 +466,8 @@ const base::FilePath db_path = db_prefix.InsertBeforeExtensionASCII( base::NumberToString(initial_page_size)); - Database::Delete(db_path); - Database db({.page_size = initial_page_size}); + sql::Database::Delete(db_path); + sql::Database db({.page_size = initial_page_size}); ASSERT_TRUE(db.Open(db_path)); ASSERT_TRUE(db.Execute(kCreateSql)); ASSERT_TRUE(db.Execute(kInsertSql1)); @@ -515,7 +477,7 @@ db.Close(); // Re-open the database while setting a new |options.page_size| in the object. - Database razed_db({.page_size = final_page_size}); + sql::Database razed_db({.page_size = final_page_size}); ASSERT_TRUE(razed_db.Open(db_path)); // Raze will use the page size set in the connection object, which may not // match the file's page size. @@ -533,29 +495,29 @@ EXPECT_EQ("1", ExecuteWithResult(&razed_db, "PRAGMA page_count")); } -// Verify that Recovery maintains the page size, and the virtual table +// Verify that sql::Recovery maintains the page size, and the virtual table // works with page sizes other than SQLite's default. Also verify the case // where the default page size has changed. TEST_P(SQLDatabaseTest, RazePageSize) { const std::string default_page_size = - ExecuteWithResult(&db_, "PRAGMA page_size"); + ExecuteWithResult(&db(), "PRAGMA page_size"); // Sync uses 32k pages. EXPECT_NO_FATAL_FAILURE( - TestPageSize(db_path_, 32768, "32768", 32768, "32768")); + TestPageSize(db_path(), 32768, "32768", 32768, "32768")); // Many clients use 4k pages. This is the SQLite default after 3.12.0. - EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 4096, "4096", 4096, "4096")); + EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 4096, "4096", 4096, "4096")); // 1k is the default page size before 3.12.0. - EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 1024, "1024", 1024, "1024")); + EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 1024, "1024", 1024, "1024")); - EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048", 4096, "4096")); + EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 2048, "2048", 4096, "4096")); // Databases with no page size specified should result in the default // page size. 2k has never been the default page size. ASSERT_NE("2048", default_page_size); - EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048", + EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 2048, "2048", DatabaseOptions::kDefaultPageSize, default_page_size)); } @@ -563,15 +525,15 @@ // Test that Raze() results are seen in other connections. TEST_P(SQLDatabaseTest, RazeMultiple) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kCreateSql)); - Database other_db(GetDBOptions()); - ASSERT_TRUE(other_db.Open(db_path_)); + sql::Database other_db(GetDBOptions()); + ASSERT_TRUE(other_db.Open(db_path())); // Check that the second connection sees the table. ASSERT_EQ(1, SqliteMasterCount(&other_db)); - ASSERT_TRUE(db_.Raze()); + ASSERT_TRUE(db().Raze()); // The second connection sees the updated database. ASSERT_EQ(0, SqliteMasterCount(&other_db)); @@ -579,26 +541,26 @@ TEST_P(SQLDatabaseTest, RazeLocked) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kCreateSql)); // Open a transaction and write some data in a second connection. // This will acquire a PENDING or EXCLUSIVE transaction, which will // cause the raze to fail. - Database other_db(GetDBOptions()); - ASSERT_TRUE(other_db.Open(db_path_)); + sql::Database other_db(GetDBOptions()); + ASSERT_TRUE(other_db.Open(db_path())); ASSERT_TRUE(other_db.BeginTransaction()); const char* kInsertSql = "INSERT INTO foo VALUES (1, 'data')"; ASSERT_TRUE(other_db.Execute(kInsertSql)); - ASSERT_FALSE(db_.Raze()); + ASSERT_FALSE(db().Raze()); // Works after COMMIT. ASSERT_TRUE(other_db.CommitTransaction()); - ASSERT_TRUE(db_.Raze()); + ASSERT_TRUE(db().Raze()); // Re-create the database. - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute(kInsertSql)); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kInsertSql)); // An unfinished read transaction in the other connection also // blocks raze. @@ -606,13 +568,13 @@ // write operations when using a WAL. if (!IsWALEnabled()) { const char* kQuery = "SELECT COUNT(*) FROM foo"; - Statement s(other_db.GetUniqueStatement(kQuery)); + sql::Statement s(other_db.GetUniqueStatement(kQuery)); ASSERT_TRUE(s.Step()); - ASSERT_FALSE(db_.Raze()); + ASSERT_FALSE(db().Raze()); // Completing the statement unlocks the database. ASSERT_FALSE(s.Step()); - ASSERT_TRUE(db_.Raze()); + ASSERT_TRUE(db().Raze()); } } @@ -620,26 +582,26 @@ // this as an empty database. TEST_P(SQLDatabaseTest, RazeEmptyDB) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - db_.Close(); + ASSERT_TRUE(db().Execute(kCreateSql)); + db().Close(); - ASSERT_TRUE(TruncateDatabase()); + TruncateDatabase(); - ASSERT_TRUE(db_.Open(db_path_)); - ASSERT_TRUE(db_.Raze()); - EXPECT_EQ(0, SqliteMasterCount(&db_)); + ASSERT_TRUE(db().Open(db_path())); + ASSERT_TRUE(db().Raze()); + EXPECT_EQ(0, SqliteMasterCount(&db())); } // Verify that Raze() can handle a file of junk. // Need exclusive mode off here as there are some subtleties (by design) around // how the cache is used with it on which causes the test to fail. TEST_P(SQLDatabaseTest, RazeNOTADB) { - db_.Close(); - Database::Delete(db_path_); - ASSERT_FALSE(base::PathExists(db_path_)); + db().Close(); + sql::Database::Delete(db_path()); + ASSERT_FALSE(GetPathExists(db_path())); - ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kTruncate)); - ASSERT_TRUE(base::PathExists(db_path_)); + WriteJunkToDatabase(SQLTestBase::TYPE_OVERWRITE_AND_TRUNCATE); + ASSERT_TRUE(GetPathExists(db_path())); // SQLite will successfully open the handle, but fail when running PRAGMA // statements that access the database. @@ -647,25 +609,25 @@ sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_NOTADB); - EXPECT_TRUE(db_.Open(db_path_)); + EXPECT_TRUE(db().Open(db_path())); ASSERT_TRUE(expecter.SawExpectedErrors()); } - EXPECT_TRUE(db_.Raze()); - db_.Close(); + EXPECT_TRUE(db().Raze()); + db().Close(); // Now empty, the open should open an empty database. - EXPECT_TRUE(db_.Open(db_path_)); - EXPECT_EQ(0, SqliteMasterCount(&db_)); + EXPECT_TRUE(db().Open(db_path())); + EXPECT_EQ(0, SqliteMasterCount(&db())); } // Verify that Raze() can handle a database overwritten with garbage. TEST_P(SQLDatabaseTest, RazeNOTADB2) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_EQ(1, SqliteMasterCount(&db_)); - db_.Close(); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_EQ(1, SqliteMasterCount(&db())); + db().Close(); - ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kOverwrite)); + WriteJunkToDatabase(SQLTestBase::TYPE_OVERWRITE); // SQLite will successfully open the handle, but will fail with // SQLITE_NOTADB on pragma statemenets which attempt to read the @@ -673,15 +635,15 @@ { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_NOTADB); - EXPECT_TRUE(db_.Open(db_path_)); + EXPECT_TRUE(db().Open(db_path())); ASSERT_TRUE(expecter.SawExpectedErrors()); } - EXPECT_TRUE(db_.Raze()); - db_.Close(); + EXPECT_TRUE(db().Raze()); + db().Close(); // Now empty, the open should succeed with an empty database. - EXPECT_TRUE(db_.Open(db_path_)); - EXPECT_EQ(0, SqliteMasterCount(&db_)); + EXPECT_TRUE(db().Open(db_path())); + EXPECT_EQ(0, SqliteMasterCount(&db())); } // Test that a callback from Open() can raze the database. This is @@ -690,34 +652,34 @@ // callback does this during Open(), the open is retried and succeeds. TEST_P(SQLDatabaseTest, RazeCallbackReopen) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_EQ(1, SqliteMasterCount(&db_)); - db_.Close(); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_EQ(1, SqliteMasterCount(&db())); + db().Close(); // Corrupt the database so that nothing works, including PRAGMAs. - ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_)); + ASSERT_TRUE(CorruptSizeInHeaderOfDB()); // Open() will succeed, even though the PRAGMA calls within will // fail with SQLITE_CORRUPT, as will this PRAGMA. { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - ASSERT_TRUE(db_.Open(db_path_)); - ASSERT_FALSE(db_.Execute("PRAGMA auto_vacuum")); - db_.Close(); + ASSERT_TRUE(db().Open(db_path())); + ASSERT_FALSE(db().Execute("PRAGMA auto_vacuum")); + db().Close(); ASSERT_TRUE(expecter.SawExpectedErrors()); } - db_.set_error_callback( - base::BindRepeating(&RazeErrorCallback, &db_, SQLITE_CORRUPT)); + db().set_error_callback( + base::BindRepeating(&RazeErrorCallback, &db(), SQLITE_CORRUPT)); // When the PRAGMA calls in Open() raise SQLITE_CORRUPT, the error // callback will call RazeAndClose(). Open() will then fail and be // retried. The second Open() on the empty database will succeed // cleanly. - ASSERT_TRUE(db_.Open(db_path_)); - ASSERT_TRUE(db_.Execute("PRAGMA auto_vacuum")); - EXPECT_EQ(0, SqliteMasterCount(&db_)); + ASSERT_TRUE(db().Open(db_path())); + ASSERT_TRUE(db().Execute("PRAGMA auto_vacuum")); + EXPECT_EQ(0, SqliteMasterCount(&db())); } // Basic test of RazeAndClose() operation. @@ -727,24 +689,24 @@ // Test that RazeAndClose() closes the database, and that the // database is empty when re-opened. - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute(kPopulateSql)); - ASSERT_TRUE(db_.RazeAndClose()); - ASSERT_FALSE(db_.is_open()); - db_.Close(); - ASSERT_TRUE(db_.Open(db_path_)); - ASSERT_EQ(0, SqliteMasterCount(&db_)); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kPopulateSql)); + ASSERT_TRUE(db().RazeAndClose()); + ASSERT_FALSE(db().is_open()); + db().Close(); + ASSERT_TRUE(db().Open(db_path())); + ASSERT_EQ(0, SqliteMasterCount(&db())); // Test that RazeAndClose() can break transactions. - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute(kPopulateSql)); - ASSERT_TRUE(db_.BeginTransaction()); - ASSERT_TRUE(db_.RazeAndClose()); - ASSERT_FALSE(db_.is_open()); - ASSERT_FALSE(db_.CommitTransaction()); - db_.Close(); - ASSERT_TRUE(db_.Open(db_path_)); - ASSERT_EQ(0, SqliteMasterCount(&db_)); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kPopulateSql)); + ASSERT_TRUE(db().BeginTransaction()); + ASSERT_TRUE(db().RazeAndClose()); + ASSERT_FALSE(db().is_open()); + ASSERT_FALSE(db().CommitTransaction()); + db().Close(); + ASSERT_TRUE(db().Open(db_path())); + ASSERT_EQ(0, SqliteMasterCount(&db())); } // Test that various operations fail without crashing after @@ -754,53 +716,53 @@ const char* kPopulateSql = "INSERT INTO foo (value) VALUES (12)"; const char* kSimpleSql = "SELECT 1"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute(kPopulateSql)); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kPopulateSql)); // Test baseline expectations. - db_.Preload(); - ASSERT_TRUE(db_.DoesTableExist("foo")); - ASSERT_TRUE(db_.IsSQLValid(kSimpleSql)); - ASSERT_EQ(SQLITE_OK, db_.ExecuteAndReturnErrorCode(kSimpleSql)); - ASSERT_TRUE(db_.Execute(kSimpleSql)); - ASSERT_TRUE(db_.is_open()); + db().Preload(); + ASSERT_TRUE(db().DoesTableExist("foo")); + ASSERT_TRUE(db().IsSQLValid(kSimpleSql)); + ASSERT_EQ(SQLITE_OK, db().ExecuteAndReturnErrorCode(kSimpleSql)); + ASSERT_TRUE(db().Execute(kSimpleSql)); + ASSERT_TRUE(db().is_open()); { - Statement s(db_.GetUniqueStatement(kSimpleSql)); + sql::Statement s(db().GetUniqueStatement(kSimpleSql)); ASSERT_TRUE(s.Step()); } { - Statement s(db_.GetCachedStatement(SQL_FROM_HERE, kSimpleSql)); + sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql)); ASSERT_TRUE(s.Step()); } - ASSERT_TRUE(db_.BeginTransaction()); - ASSERT_TRUE(db_.CommitTransaction()); - ASSERT_TRUE(db_.BeginTransaction()); - db_.RollbackTransaction(); + ASSERT_TRUE(db().BeginTransaction()); + ASSERT_TRUE(db().CommitTransaction()); + ASSERT_TRUE(db().BeginTransaction()); + db().RollbackTransaction(); - ASSERT_TRUE(db_.RazeAndClose()); + ASSERT_TRUE(db().RazeAndClose()); // At this point, they should all fail, but not crash. - db_.Preload(); - ASSERT_FALSE(db_.DoesTableExist("foo")); - ASSERT_FALSE(db_.IsSQLValid(kSimpleSql)); - ASSERT_EQ(SQLITE_ERROR, db_.ExecuteAndReturnErrorCode(kSimpleSql)); - ASSERT_FALSE(db_.Execute(kSimpleSql)); - ASSERT_FALSE(db_.is_open()); + db().Preload(); + ASSERT_FALSE(db().DoesTableExist("foo")); + ASSERT_FALSE(db().IsSQLValid(kSimpleSql)); + ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(kSimpleSql)); + ASSERT_FALSE(db().Execute(kSimpleSql)); + ASSERT_FALSE(db().is_open()); { - Statement s(db_.GetUniqueStatement(kSimpleSql)); + sql::Statement s(db().GetUniqueStatement(kSimpleSql)); ASSERT_FALSE(s.Step()); } { - Statement s(db_.GetCachedStatement(SQL_FROM_HERE, kSimpleSql)); + sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql)); ASSERT_FALSE(s.Step()); } - ASSERT_FALSE(db_.BeginTransaction()); - ASSERT_FALSE(db_.CommitTransaction()); - ASSERT_FALSE(db_.BeginTransaction()); - db_.RollbackTransaction(); + ASSERT_FALSE(db().BeginTransaction()); + ASSERT_FALSE(db().CommitTransaction()); + ASSERT_FALSE(db().BeginTransaction()); + db().RollbackTransaction(); // Close normally to reset the poisoned flag. - db_.Close(); + db().Close(); // DEATH tests not supported on Android, iOS, or Fuchsia. #if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_FUCHSIA) @@ -808,7 +770,7 @@ // usage by becoming fatal in debug mode. Since DEATH tests are // expensive, just test one of them. if (DLOG_IS_ON(FATAL)) { - ASSERT_DEATH({ db_.IsSQLValid(kSimpleSql); }, + ASSERT_DEATH({ db().IsSQLValid(kSimpleSql); }, "Illegal use of Database without a db"); } #endif // !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_FUCHSIA) @@ -827,75 +789,75 @@ // The empty database has 0 or 1 pages. Raze() should leave it with exactly 1 // page. Not checking directly because auto_vacuum on Android adds a freelist // page. - ASSERT_TRUE(db_.Raze()); + ASSERT_TRUE(db().Raze()); int64_t expected_size; - ASSERT_TRUE(base::GetFileSize(db_path_, &expected_size)); + ASSERT_TRUE(base::GetFileSize(db_path(), &expected_size)); ASSERT_GT(expected_size, 0); // Cause the database to take a few pages. const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kCreateSql)); for (size_t i = 0; i < 24; ++i) { ASSERT_TRUE( - db_.Execute("INSERT INTO foo (value) VALUES (randomblob(1024))")); + db().Execute("INSERT INTO foo (value) VALUES (randomblob(1024))")); } // In WAL mode, writes don't reach the database file until a checkpoint // happens. - ASSERT_TRUE(db_.CheckpointDatabase()); + ASSERT_TRUE(db().CheckpointDatabase()); int64_t db_size; - ASSERT_TRUE(base::GetFileSize(db_path_, &db_size)); + ASSERT_TRUE(base::GetFileSize(db_path(), &db_size)); ASSERT_GT(db_size, expected_size); // Make a query covering most of the database file to make sure that the // blocks are actually mapped into memory. Empirically, the truncate problem // doesn't seem to happen if no blocks are mapped. EXPECT_EQ("24576", - ExecuteWithResult(&db_, "SELECT SUM(LENGTH(value)) FROM foo")); + ExecuteWithResult(&db(), "SELECT SUM(LENGTH(value)) FROM foo")); - ASSERT_TRUE(db_.Raze()); - ASSERT_TRUE(base::GetFileSize(db_path_, &db_size)); + ASSERT_TRUE(db().Raze()); + ASSERT_TRUE(base::GetFileSize(db_path(), &db_size)); ASSERT_EQ(expected_size, db_size); } #if defined(OS_ANDROID) TEST_P(SQLDatabaseTest, SetTempDirForSQL) { - MetaTable meta_table; + sql::MetaTable meta_table; // Below call needs a temporary directory in sqlite3 // On Android, it can pass only when the temporary directory is set. // Otherwise, sqlite3 doesn't find the correct directory to store // temporary files and will report the error 'unable to open // database file'. - ASSERT_TRUE(meta_table.Init(&db_, 4, 4)); + ASSERT_TRUE(meta_table.Init(&db(), 4, 4)); } #endif // defined(OS_ANDROID) TEST_P(SQLDatabaseTest, Delete) { - EXPECT_TRUE(db_.Execute("CREATE TABLE x (x)")); - db_.Close(); + EXPECT_TRUE(db().Execute("CREATE TABLE x (x)")); + db().Close(); - base::FilePath journal_path = Database::JournalPath(db_path_); - base::FilePath wal_path = Database::WriteAheadLogPath(db_path_); + base::FilePath journal_path = sql::Database::JournalPath(db_path()); + base::FilePath wal_path = sql::Database::WriteAheadLogPath(db_path()); // Should have both a main database file and a journal file if // journal_mode is TRUNCATE. There is no WAL file as it is deleted on Close. - ASSERT_TRUE(base::PathExists(db_path_)); + ASSERT_TRUE(GetPathExists(db_path())); if (!IsWALEnabled()) { // TRUNCATE mode - ASSERT_TRUE(base::PathExists(journal_path)); + ASSERT_TRUE(GetPathExists(journal_path)); } - Database::Delete(db_path_); - EXPECT_FALSE(base::PathExists(db_path_)); - EXPECT_FALSE(base::PathExists(journal_path)); - EXPECT_FALSE(base::PathExists(wal_path)); + sql::Database::Delete(db_path()); + EXPECT_FALSE(GetPathExists(db_path())); + EXPECT_FALSE(GetPathExists(journal_path)); + EXPECT_FALSE(GetPathExists(wal_path)); } #if defined(OS_POSIX) // This test operates on POSIX file permissions. TEST_P(SQLDatabaseTest, PosixFilePermissions) { - db_.Close(); - Database::Delete(db_path_); - ASSERT_FALSE(base::PathExists(db_path_)); + db().Close(); + sql::Database::Delete(db_path()); + ASSERT_FALSE(GetPathExists(db_path())); // If the bots all had a restrictive umask setting such that databases are // always created with only the owner able to read them, then the code could @@ -903,37 +865,37 @@ // umask. ScopedUmaskSetter permissive_umask(S_IWGRP | S_IWOTH); - ASSERT_TRUE(db_.Open(db_path_)); + ASSERT_TRUE(db().Open(db_path())); // Cause the journal file to be created. If the default journal_mode is // changed back to DELETE, this test will need to be updated. - EXPECT_TRUE(db_.Execute("CREATE TABLE x (x)")); + EXPECT_TRUE(db().Execute("CREATE TABLE x (x)")); int mode; - ASSERT_TRUE(base::PathExists(db_path_)); - EXPECT_TRUE(base::GetPosixFilePermissions(db_path_, &mode)); + ASSERT_TRUE(GetPathExists(db_path())); + EXPECT_TRUE(base::GetPosixFilePermissions(db_path(), &mode)); ASSERT_EQ(mode, 0600); if (IsWALEnabled()) { // WAL mode // The WAL file is created lazily on first change. - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); - base::FilePath wal_path = Database::WriteAheadLogPath(db_path_); - ASSERT_TRUE(base::PathExists(wal_path)); + base::FilePath wal_path = sql::Database::WriteAheadLogPath(db_path()); + ASSERT_TRUE(GetPathExists(wal_path)); EXPECT_TRUE(base::GetPosixFilePermissions(wal_path, &mode)); ASSERT_EQ(mode, 0600); // The shm file doesn't exist in exclusive locking mode. - if (ExecuteWithResult(&db_, "PRAGMA locking_mode") == "normal") { - base::FilePath shm_path = Database::SharedMemoryFilePath(db_path_); - ASSERT_TRUE(base::PathExists(shm_path)); + if (ExecuteWithResult(&db(), "PRAGMA locking_mode") == "normal") { + base::FilePath shm_path = sql::Database::SharedMemoryFilePath(db_path()); + ASSERT_TRUE(GetPathExists(shm_path)); EXPECT_TRUE(base::GetPosixFilePermissions(shm_path, &mode)); ASSERT_EQ(mode, 0600); } } else { // Truncate mode - base::FilePath journal_path = Database::JournalPath(db_path_); + base::FilePath journal_path = sql::Database::JournalPath(db_path()); DLOG(ERROR) << "journal_path: " << journal_path; - ASSERT_TRUE(base::PathExists(journal_path)); + ASSERT_TRUE(GetPathExists(journal_path)); EXPECT_TRUE(base::GetPosixFilePermissions(journal_path, &mode)); ASSERT_EQ(mode, 0600); } @@ -942,31 +904,31 @@ // Test that errors start happening once Poison() is called. TEST_P(SQLDatabaseTest, Poison) { - EXPECT_TRUE(db_.Execute("CREATE TABLE x (x)")); + EXPECT_TRUE(db().Execute("CREATE TABLE x (x)")); // Before the Poison() call, things generally work. - EXPECT_TRUE(db_.IsSQLValid("INSERT INTO x VALUES ('x')")); - EXPECT_TRUE(db_.Execute("INSERT INTO x VALUES ('x')")); + EXPECT_TRUE(db().IsSQLValid("INSERT INTO x VALUES ('x')")); + EXPECT_TRUE(db().Execute("INSERT INTO x VALUES ('x')")); { - Statement s(db_.GetUniqueStatement("SELECT COUNT(*) FROM x")); + sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM x")); ASSERT_TRUE(s.is_valid()); ASSERT_TRUE(s.Step()); } // Get a statement which is valid before and will exist across Poison(). - Statement valid_statement( - db_.GetUniqueStatement("SELECT COUNT(*) FROM sqlite_master")); + sql::Statement valid_statement( + db().GetUniqueStatement("SELECT COUNT(*) FROM sqlite_master")); ASSERT_TRUE(valid_statement.is_valid()); ASSERT_TRUE(valid_statement.Step()); valid_statement.Reset(true); - db_.Poison(); + db().Poison(); // After the Poison() call, things fail. - EXPECT_FALSE(db_.IsSQLValid("INSERT INTO x VALUES ('x')")); - EXPECT_FALSE(db_.Execute("INSERT INTO x VALUES ('x')")); + EXPECT_FALSE(db().IsSQLValid("INSERT INTO x VALUES ('x')")); + EXPECT_FALSE(db().Execute("INSERT INTO x VALUES ('x')")); { - Statement s(db_.GetUniqueStatement("SELECT COUNT(*) FROM x")); + sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM x")); ASSERT_FALSE(s.is_valid()); ASSERT_FALSE(s.Step()); } @@ -977,77 +939,77 @@ // Test that poisoning the database during a transaction works (with errors). // RazeErrorCallback() poisons the database, the extra COMMIT causes - // CommitTransaction() to throw an error while committing. - db_.set_error_callback( - base::BindRepeating(&RazeErrorCallback, &db_, SQLITE_ERROR)); - db_.Close(); - ASSERT_TRUE(db_.Open(db_path_)); - EXPECT_TRUE(db_.BeginTransaction()); - EXPECT_TRUE(db_.Execute("INSERT INTO x VALUES ('x')")); - EXPECT_TRUE(db_.Execute("COMMIT")); - EXPECT_FALSE(db_.CommitTransaction()); + // CommitTransaction() to throw an error while commiting. + db().set_error_callback( + base::BindRepeating(&RazeErrorCallback, &db(), SQLITE_ERROR)); + db().Close(); + ASSERT_TRUE(db().Open(db_path())); + EXPECT_TRUE(db().BeginTransaction()); + EXPECT_TRUE(db().Execute("INSERT INTO x VALUES ('x')")); + EXPECT_TRUE(db().Execute("COMMIT")); + EXPECT_FALSE(db().CommitTransaction()); } TEST_P(SQLDatabaseTest, AttachDatabase) { - EXPECT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); + EXPECT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); // Create a database to attach to. base::FilePath attach_path = - db_path_.DirName().AppendASCII("SQLDatabaseAttach.db"); + db_path().DirName().AppendASCII("SQLDatabaseAttach.db"); static const char kAttachmentPoint[] = "other"; { - Database other_db; + sql::Database other_db; ASSERT_TRUE(other_db.Open(attach_path)); EXPECT_TRUE(other_db.Execute("CREATE TABLE bar (a, b)")); EXPECT_TRUE(other_db.Execute("INSERT INTO bar VALUES ('hello', 'world')")); } // Cannot see the attached database, yet. - EXPECT_FALSE(db_.IsSQLValid("SELECT count(*) from other.bar")); + EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar")); EXPECT_TRUE( - DatabaseTestPeer::AttachDatabase(&db_, attach_path, kAttachmentPoint)); - EXPECT_TRUE(db_.IsSQLValid("SELECT count(*) from other.bar")); + DatabaseTestPeer::AttachDatabase(&db(), attach_path, kAttachmentPoint)); + EXPECT_TRUE(db().IsSQLValid("SELECT count(*) from other.bar")); // Queries can touch both databases after the ATTACH. - EXPECT_TRUE(db_.Execute("INSERT INTO foo SELECT a, b FROM other.bar")); + EXPECT_TRUE(db().Execute("INSERT INTO foo SELECT a, b FROM other.bar")); { - Statement s(db_.GetUniqueStatement("SELECT COUNT(*) FROM foo")); + sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM foo")); ASSERT_TRUE(s.Step()); EXPECT_EQ(1, s.ColumnInt(0)); } - EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(&db_, kAttachmentPoint)); - EXPECT_FALSE(db_.IsSQLValid("SELECT count(*) from other.bar")); + EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(&db(), kAttachmentPoint)); + EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar")); } TEST_P(SQLDatabaseTest, AttachDatabaseWithOpenTransaction) { - EXPECT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); + EXPECT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); // Create a database to attach to. base::FilePath attach_path = - db_path_.DirName().AppendASCII("SQLDatabaseAttach.db"); + db_path().DirName().AppendASCII("SQLDatabaseAttach.db"); static const char kAttachmentPoint[] = "other"; { - Database other_db; + sql::Database other_db; ASSERT_TRUE(other_db.Open(attach_path)); EXPECT_TRUE(other_db.Execute("CREATE TABLE bar (a, b)")); EXPECT_TRUE(other_db.Execute("INSERT INTO bar VALUES ('hello', 'world')")); } // Cannot see the attached database, yet. - EXPECT_FALSE(db_.IsSQLValid("SELECT count(*) from other.bar")); + EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar")); // Attach succeeds in a transaction. - EXPECT_TRUE(db_.BeginTransaction()); + EXPECT_TRUE(db().BeginTransaction()); EXPECT_TRUE( - DatabaseTestPeer::AttachDatabase(&db_, attach_path, kAttachmentPoint)); - EXPECT_TRUE(db_.IsSQLValid("SELECT count(*) from other.bar")); + DatabaseTestPeer::AttachDatabase(&db(), attach_path, kAttachmentPoint)); + EXPECT_TRUE(db().IsSQLValid("SELECT count(*) from other.bar")); // Queries can touch both databases after the ATTACH. - EXPECT_TRUE(db_.Execute("INSERT INTO foo SELECT a, b FROM other.bar")); + EXPECT_TRUE(db().Execute("INSERT INTO foo SELECT a, b FROM other.bar")); { - Statement s(db_.GetUniqueStatement("SELECT COUNT(*) FROM foo")); + sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM foo")); ASSERT_TRUE(s.Step()); EXPECT_EQ(1, s.ColumnInt(0)); } @@ -1056,30 +1018,30 @@ { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_ERROR); - EXPECT_FALSE(DatabaseTestPeer::DetachDatabase(&db_, kAttachmentPoint)); - EXPECT_TRUE(db_.IsSQLValid("SELECT count(*) from other.bar")); + EXPECT_FALSE(DatabaseTestPeer::DetachDatabase(&db(), kAttachmentPoint)); + EXPECT_TRUE(db().IsSQLValid("SELECT count(*) from other.bar")); ASSERT_TRUE(expecter.SawExpectedErrors()); } // Detach succeeds when the transaction is closed. - db_.RollbackTransaction(); - EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(&db_, kAttachmentPoint)); - EXPECT_FALSE(db_.IsSQLValid("SELECT count(*) from other.bar")); + db().RollbackTransaction(); + EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(&db(), kAttachmentPoint)); + EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar")); } TEST_P(SQLDatabaseTest, Basic_QuickIntegrityCheck) { const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - EXPECT_TRUE(db_.QuickIntegrityCheck()); - db_.Close(); + ASSERT_TRUE(db().Execute(kCreateSql)); + EXPECT_TRUE(db().QuickIntegrityCheck()); + db().Close(); - ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_)); + ASSERT_TRUE(CorruptSizeInHeaderOfDB()); { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - ASSERT_TRUE(db_.Open(db_path_)); - EXPECT_FALSE(db_.QuickIntegrityCheck()); + ASSERT_TRUE(db().Open(db_path())); + EXPECT_FALSE(db().QuickIntegrityCheck()); ASSERT_TRUE(expecter.SawExpectedErrors()); } } @@ -1089,19 +1051,19 @@ std::vector<std::string> messages; const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - EXPECT_TRUE(db_.FullIntegrityCheck(&messages)); + ASSERT_TRUE(db().Execute(kCreateSql)); + EXPECT_TRUE(db().FullIntegrityCheck(&messages)); EXPECT_EQ(1u, messages.size()); EXPECT_EQ(kOk, messages[0]); - db_.Close(); + db().Close(); - ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_)); + ASSERT_TRUE(CorruptSizeInHeaderOfDB()); { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - ASSERT_TRUE(db_.Open(db_path_)); - EXPECT_TRUE(db_.FullIntegrityCheck(&messages)); + ASSERT_TRUE(db().Open(db_path())); + EXPECT_TRUE(db().FullIntegrityCheck(&messages)); EXPECT_LT(1u, messages.size()); EXPECT_NE(kOk, messages[0]); ASSERT_TRUE(expecter.SawExpectedErrors()); @@ -1115,38 +1077,38 @@ base::trace_event::MemoryDumpArgs args = { base::trace_event::MemoryDumpLevelOfDetail::DETAILED}; base::trace_event::ProcessMemoryDump pmd(args); - ASSERT_TRUE(db_.memory_dump_provider_->OnMemoryDump(args, &pmd)); + ASSERT_TRUE(db().memory_dump_provider_->OnMemoryDump(args, &pmd)); EXPECT_GE(pmd.allocator_dumps().size(), 1u); } // Test that the functions to collect diagnostic data run to completion, without // worrying too much about what they generate (since that will change). TEST_P(SQLDatabaseTest, CollectDiagnosticInfo) { - const std::string corruption_info = db_.CollectCorruptionInfo(); + const std::string corruption_info = db().CollectCorruptionInfo(); EXPECT_NE(std::string::npos, corruption_info.find("SQLITE_CORRUPT")); EXPECT_NE(std::string::npos, corruption_info.find("integrity_check")); // A statement to see in the results. const char* kSimpleSql = "SELECT 'mountain'"; - Statement s(db_.GetCachedStatement(SQL_FROM_HERE, kSimpleSql)); + Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql)); // Error includes the statement. - const std::string readonly_info = db_.CollectErrorInfo(SQLITE_READONLY, &s); + const std::string readonly_info = db().CollectErrorInfo(SQLITE_READONLY, &s); EXPECT_NE(std::string::npos, readonly_info.find(kSimpleSql)); // Some other error doesn't include the statment. // TODO(shess): This is weak. - const std::string full_info = db_.CollectErrorInfo(SQLITE_FULL, nullptr); + const std::string full_info = db().CollectErrorInfo(SQLITE_FULL, nullptr); EXPECT_EQ(std::string::npos, full_info.find(kSimpleSql)); // A table to see in the SQLITE_ERROR results. - EXPECT_TRUE(db_.Execute("CREATE TABLE volcano (x)")); + EXPECT_TRUE(db().Execute("CREATE TABLE volcano (x)")); // Version info to see in the SQLITE_ERROR results. - MetaTable meta_table; - ASSERT_TRUE(meta_table.Init(&db_, 4, 4)); + sql::MetaTable meta_table; + ASSERT_TRUE(meta_table.Init(&db(), 4, 4)); - const std::string error_info = db_.CollectErrorInfo(SQLITE_ERROR, &s); + const std::string error_info = db().CollectErrorInfo(SQLITE_ERROR, &s); EXPECT_NE(std::string::npos, error_info.find(kSimpleSql)); EXPECT_NE(std::string::npos, error_info.find("volcano")); EXPECT_NE(std::string::npos, error_info.find("version: 4")); @@ -1156,7 +1118,7 @@ // enabled by SQLite. TEST_P(SQLDatabaseTest, MmapInitiallyEnabled) { { - Statement s(db_.GetUniqueStatement("PRAGMA mmap_size")); + sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size")); ASSERT_TRUE(s.Step()) << "All supported SQLite versions should have mmap support"; @@ -1165,7 +1127,7 @@ // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for // instance MojoVFS), -1 is returned. if (s.ColumnInt(0) <= 0) { - ASSERT_TRUE(db_.Execute("PRAGMA mmap_size = 1048576")); + ASSERT_TRUE(db().Execute("PRAGMA mmap_size = 1048576")); s.Reset(true); ASSERT_TRUE(s.Step()); EXPECT_LE(s.ColumnInt(0), 0); @@ -1173,24 +1135,24 @@ } // Test that explicit disable prevents mmap'ed I/O. - db_.Close(); - Database::Delete(db_path_); - db_.set_mmap_disabled(); - ASSERT_TRUE(db_.Open(db_path_)); - EXPECT_EQ("0", ExecuteWithResult(&db_, "PRAGMA mmap_size")); + db().Close(); + sql::Database::Delete(db_path()); + db().set_mmap_disabled(); + ASSERT_TRUE(db().Open(db_path())); + EXPECT_EQ("0", ExecuteWithResult(&db(), "PRAGMA mmap_size")); } // Test whether a fresh database gets mmap enabled when using alternate status // storage. TEST_P(SQLDatabaseTest, MmapInitiallyEnabledAltStatus) { // Re-open fresh database with alt-status flag set. - db_.Close(); - Database::Delete(db_path_); - db_.set_mmap_alt_status(); - ASSERT_TRUE(db_.Open(db_path_)); + db().Close(); + sql::Database::Delete(db_path()); + db().set_mmap_alt_status(); + ASSERT_TRUE(db().Open(db_path())); { - Statement s(db_.GetUniqueStatement("PRAGMA mmap_size")); + sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size")); ASSERT_TRUE(s.Step()) << "All supported SQLite versions should have mmap support"; @@ -1199,7 +1161,7 @@ // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for // instance MojoVFS), -1 is returned. if (s.ColumnInt(0) <= 0) { - ASSERT_TRUE(db_.Execute("PRAGMA mmap_size = 1048576")); + ASSERT_TRUE(db().Execute("PRAGMA mmap_size = 1048576")); s.Reset(true); ASSERT_TRUE(s.Step()); EXPECT_LE(s.ColumnInt(0), 0); @@ -1207,11 +1169,11 @@ } // Test that explicit disable overrides set_mmap_alt_status(). - db_.Close(); - Database::Delete(db_path_); - db_.set_mmap_disabled(); - ASSERT_TRUE(db_.Open(db_path_)); - EXPECT_EQ("0", ExecuteWithResult(&db_, "PRAGMA mmap_size")); + db().Close(); + sql::Database::Delete(db_path()); + db().set_mmap_disabled(); + ASSERT_TRUE(db().Open(db_path())); + EXPECT_EQ("0", ExecuteWithResult(&db(), "PRAGMA mmap_size")); } TEST_P(SQLDatabaseTest, GetAppropriateMmapSize) { @@ -1220,40 +1182,40 @@ // If there is no meta table (as for a fresh database), assume that everything // should be mapped, and the status of the meta table is not affected. - ASSERT_TRUE(!db_.DoesTableExist("meta")); - ASSERT_GT(db_.GetAppropriateMmapSize(), kMmapAlot); - ASSERT_TRUE(!db_.DoesTableExist("meta")); + ASSERT_TRUE(!db().DoesTableExist("meta")); + ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot); + ASSERT_TRUE(!db().DoesTableExist("meta")); // When the meta table is first created, it sets up to map everything. - MetaTable().Init(&db_, 1, 1); - ASSERT_TRUE(db_.DoesTableExist("meta")); - ASSERT_GT(db_.GetAppropriateMmapSize(), kMmapAlot); - ASSERT_TRUE(MetaTable::GetMmapStatus(&db_, &mmap_status)); + MetaTable().Init(&db(), 1, 1); + ASSERT_TRUE(db().DoesTableExist("meta")); + ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot); + ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status)); ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status); // Preload with partial progress of one page. Should map everything. - ASSERT_TRUE(db_.Execute("REPLACE INTO meta VALUES ('mmap_status', 1)")); - ASSERT_GT(db_.GetAppropriateMmapSize(), kMmapAlot); - ASSERT_TRUE(MetaTable::GetMmapStatus(&db_, &mmap_status)); + ASSERT_TRUE(db().Execute("REPLACE INTO meta VALUES ('mmap_status', 1)")); + ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot); + ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status)); ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status); // Failure status maps nothing. - ASSERT_TRUE(db_.Execute("REPLACE INTO meta VALUES ('mmap_status', -2)")); - ASSERT_EQ(0UL, db_.GetAppropriateMmapSize()); + ASSERT_TRUE(db().Execute("REPLACE INTO meta VALUES ('mmap_status', -2)")); + ASSERT_EQ(0UL, db().GetAppropriateMmapSize()); // Re-initializing the meta table does not re-create the key if the table // already exists. - ASSERT_TRUE(db_.Execute("DELETE FROM meta WHERE key = 'mmap_status'")); - MetaTable().Init(&db_, 1, 1); + ASSERT_TRUE(db().Execute("DELETE FROM meta WHERE key = 'mmap_status'")); + MetaTable().Init(&db(), 1, 1); ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status); - ASSERT_TRUE(MetaTable::GetMmapStatus(&db_, &mmap_status)); + ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status)); ASSERT_EQ(0, mmap_status); // With no key, map everything and create the key. // TODO(shess): This really should be "maps everything after validating it", // but that is more complicated to structure. - ASSERT_GT(db_.GetAppropriateMmapSize(), kMmapAlot); - ASSERT_TRUE(MetaTable::GetMmapStatus(&db_, &mmap_status)); + ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot); + ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status)); ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status); } @@ -1261,57 +1223,57 @@ const size_t kMmapAlot = 25 * 1024 * 1024; // At this point, Database still expects a future [meta] table. - ASSERT_FALSE(db_.DoesTableExist("meta")); - ASSERT_FALSE(db_.DoesViewExist("MmapStatus")); - ASSERT_GT(db_.GetAppropriateMmapSize(), kMmapAlot); - ASSERT_FALSE(db_.DoesTableExist("meta")); - ASSERT_FALSE(db_.DoesViewExist("MmapStatus")); + ASSERT_FALSE(db().DoesTableExist("meta")); + ASSERT_FALSE(db().DoesViewExist("MmapStatus")); + ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot); + ASSERT_FALSE(db().DoesTableExist("meta")); + ASSERT_FALSE(db().DoesViewExist("MmapStatus")); // Using alt status, everything should be mapped, with state in the view. - db_.set_mmap_alt_status(); - ASSERT_GT(db_.GetAppropriateMmapSize(), kMmapAlot); - ASSERT_FALSE(db_.DoesTableExist("meta")); - ASSERT_TRUE(db_.DoesViewExist("MmapStatus")); + db().set_mmap_alt_status(); + ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot); + ASSERT_FALSE(db().DoesTableExist("meta")); + ASSERT_TRUE(db().DoesViewExist("MmapStatus")); EXPECT_EQ(base::NumberToString(MetaTable::kMmapSuccess), - ExecuteWithResult(&db_, "SELECT * FROM MmapStatus")); + ExecuteWithResult(&db(), "SELECT * FROM MmapStatus")); // Also maps everything when kMmapSuccess is already in the view. - ASSERT_GT(db_.GetAppropriateMmapSize(), kMmapAlot); + ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot); // Preload with partial progress of one page. Should map everything. - ASSERT_TRUE(db_.Execute("DROP VIEW MmapStatus")); - ASSERT_TRUE(db_.Execute("CREATE VIEW MmapStatus (value) AS SELECT 1")); - ASSERT_GT(db_.GetAppropriateMmapSize(), kMmapAlot); + ASSERT_TRUE(db().Execute("DROP VIEW MmapStatus")); + ASSERT_TRUE(db().Execute("CREATE VIEW MmapStatus (value) AS SELECT 1")); + ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot); EXPECT_EQ(base::NumberToString(MetaTable::kMmapSuccess), - ExecuteWithResult(&db_, "SELECT * FROM MmapStatus")); + ExecuteWithResult(&db(), "SELECT * FROM MmapStatus")); // Failure status leads to nothing being mapped. - ASSERT_TRUE(db_.Execute("DROP VIEW MmapStatus")); - ASSERT_TRUE(db_.Execute("CREATE VIEW MmapStatus (value) AS SELECT -2")); - ASSERT_EQ(0UL, db_.GetAppropriateMmapSize()); + ASSERT_TRUE(db().Execute("DROP VIEW MmapStatus")); + ASSERT_TRUE(db().Execute("CREATE VIEW MmapStatus (value) AS SELECT -2")); + ASSERT_EQ(0UL, db().GetAppropriateMmapSize()); EXPECT_EQ(base::NumberToString(MetaTable::kMmapFailure), - ExecuteWithResult(&db_, "SELECT * FROM MmapStatus")); + ExecuteWithResult(&db(), "SELECT * FROM MmapStatus")); } TEST_P(SQLDatabaseTest, GetMemoryUsage) { // Databases with mmap enabled may not follow the assumptions below. - db_.Close(); - db_.set_mmap_disabled(); - ASSERT_TRUE(db_.Open(db_path_)); + db().Close(); + db().set_mmap_disabled(); + ASSERT_TRUE(db().Open(db_path())); - int initial_memory = db_.GetMemoryUsage(); + int initial_memory = db().GetMemoryUsage(); EXPECT_GT(initial_memory, 0) << "SQLite should always use some memory for a database"; - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - ASSERT_TRUE(db_.Execute("INSERT INTO foo(a, b) VALUES (12, 13)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("INSERT INTO foo(a, b) VALUES (12, 13)")); - int post_query_memory = db_.GetMemoryUsage(); + int post_query_memory = db().GetMemoryUsage(); EXPECT_GT(post_query_memory, initial_memory) << "Page cache usage should go up after executing queries"; - db_.TrimMemory(); - int post_trim_memory = db_.GetMemoryUsage(); + db().TrimMemory(); + int post_trim_memory = db().GetMemoryUsage(); EXPECT_GT(post_query_memory, post_trim_memory) << "Page cache usage should go down after calling TrimMemory()"; } @@ -1328,66 +1290,66 @@ }; TEST_P(SQLDatabaseTestExclusiveMode, LockingModeExclusive) { - EXPECT_EQ(ExecuteWithResult(&db_, "PRAGMA locking_mode"), "exclusive"); + EXPECT_EQ(ExecuteWithResult(&db(), "PRAGMA locking_mode"), "exclusive"); } TEST_P(SQLDatabaseTest, LockingModeNormal) { - EXPECT_EQ(ExecuteWithResult(&db_, "PRAGMA locking_mode"), "normal"); + EXPECT_EQ(ExecuteWithResult(&db(), "PRAGMA locking_mode"), "normal"); } TEST_P(SQLDatabaseTest, OpenedInCorrectMode) { std::string expected_mode = IsWALEnabled() ? "wal" : "truncate"; - EXPECT_EQ(ExecuteWithResult(&db_, "PRAGMA journal_mode"), expected_mode); + EXPECT_EQ(ExecuteWithResult(&db(), "PRAGMA journal_mode"), expected_mode); } TEST_P(SQLDatabaseTest, CheckpointDatabase) { if (!IsWALEnabled()) return; - base::FilePath wal_path = Database::WriteAheadLogPath(db_path_); + base::FilePath wal_path = sql::Database::WriteAheadLogPath(db_path()); int64_t wal_size = 0; // WAL file initially empty. - EXPECT_TRUE(base::PathExists(wal_path)); + EXPECT_TRUE(GetPathExists(wal_path)); base::GetFileSize(wal_path, &wal_size); EXPECT_EQ(wal_size, 0); ASSERT_TRUE( - db_.Execute("CREATE TABLE foo (id INTEGER UNIQUE, value INTEGER)")); - ASSERT_TRUE(db_.Execute("INSERT INTO foo VALUES (1, 1)")); - ASSERT_TRUE(db_.Execute("INSERT INTO foo VALUES (2, 2)")); + db().Execute("CREATE TABLE foo (id INTEGER UNIQUE, value INTEGER)")); + ASSERT_TRUE(db().Execute("INSERT INTO foo VALUES (1, 1)")); + ASSERT_TRUE(db().Execute("INSERT INTO foo VALUES (2, 2)")); // Writes reach WAL file but not db file. base::GetFileSize(wal_path, &wal_size); EXPECT_GT(wal_size, 0); int64_t db_size = 0; - base::GetFileSize(db_path_, &db_size); - EXPECT_EQ(db_size, db_.page_size()); + base::GetFileSize(db_path(), &db_size); + EXPECT_EQ(db_size, db().page_size()); // Checkpoint database to immediately propagate writes to DB file. - EXPECT_TRUE(db_.CheckpointDatabase()); + EXPECT_TRUE(db().CheckpointDatabase()); - base::GetFileSize(db_path_, &db_size); - EXPECT_GT(db_size, db_.page_size()); - EXPECT_EQ(ExecuteWithResult(&db_, "SELECT value FROM foo where id=1"), "1"); - EXPECT_EQ(ExecuteWithResult(&db_, "SELECT value FROM foo where id=2"), "2"); + base::GetFileSize(db_path(), &db_size); + EXPECT_GT(db_size, db().page_size()); + EXPECT_EQ(ExecuteWithResult(&db(), "SELECT value FROM foo where id=1"), "1"); + EXPECT_EQ(ExecuteWithResult(&db(), "SELECT value FROM foo where id=2"), "2"); } TEST_P(SQLDatabaseTest, CorruptSizeInHeaderTest) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (x)")); - ASSERT_TRUE(db_.Execute("CREATE TABLE bar (x)")); - db_.Close(); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (x)")); + ASSERT_TRUE(db().Execute("CREATE TABLE bar (x)")); + db().Close(); - ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_)); + ASSERT_TRUE(CorruptSizeInHeaderOfDB()); { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - ASSERT_TRUE(db_.Open(db_path_)); - EXPECT_FALSE(db_.Execute("INSERT INTO foo values (1)")); - EXPECT_FALSE(db_.DoesTableExist("foo")); - EXPECT_FALSE(db_.DoesTableExist("bar")); - EXPECT_FALSE(db_.Execute("SELECT * FROM foo")); + ASSERT_TRUE(db().Open(db_path())); + EXPECT_FALSE(db().Execute("INSERT INTO foo values (1)")); + EXPECT_FALSE(db().DoesTableExist("foo")); + EXPECT_FALSE(db().DoesTableExist("bar")); + EXPECT_FALSE(db().Execute("SELECT * FROM foo")); EXPECT_TRUE(expecter.SawExpectedErrors()); } } @@ -1399,8 +1361,8 @@ // DEATH tests not supported on Android, iOS, or Fuchsia. #if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_FUCHSIA) if (DLOG_IS_ON(FATAL)) { - db_.set_error_callback(base::BindRepeating(&IgnoreErrorCallback)); - ASSERT_DEATH({ db_.GetUniqueStatement("SELECT x"); }, + db().set_error_callback(base::BindRepeating(&IgnoreErrorCallback)); + ASSERT_DEATH({ db().GetUniqueStatement("SELECT x"); }, "SQL compile error no such column: x"); } #endif // !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_FUCHSIA)
diff --git a/sql/meta_table_unittest.cc b/sql/meta_table_unittest.cc index e91380b..928c0ed0 100644 --- a/sql/meta_table_unittest.cc +++ b/sql/meta_table_unittest.cc
@@ -10,36 +10,22 @@ #include "base/files/scoped_temp_dir.h" #include "sql/database.h" #include "sql/statement.h" +#include "sql/test/sql_test_base.h" #include "testing/gtest/include/gtest/gtest.h" -namespace sql { - namespace { -class SQLMetaTableTest : public testing::Test { - public: - ~SQLMetaTableTest() override = default; - - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE( - db_.Open(temp_dir_.GetPath().AppendASCII("meta_table_test.sqlite"))); - } - - protected: - base::ScopedTempDir temp_dir_; - Database db_; -}; +using SQLMetaTableTest = sql::SQLTestBase; TEST_F(SQLMetaTableTest, DoesTableExist) { - EXPECT_FALSE(MetaTable::DoesTableExist(&db_)); + EXPECT_FALSE(sql::MetaTable::DoesTableExist(&db())); { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); } - EXPECT_TRUE(MetaTable::DoesTableExist(&db_)); + EXPECT_TRUE(sql::MetaTable::DoesTableExist(&db())); } TEST_F(SQLMetaTableTest, RazeIfDeprecated) { @@ -48,45 +34,45 @@ // Setup a current database. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, kVersion, kVersion)); - EXPECT_TRUE(db_.Execute("CREATE TABLE t(c)")); - EXPECT_TRUE(db_.DoesTableExist("t")); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), kVersion, kVersion)); + EXPECT_TRUE(db().Execute("CREATE TABLE t(c)")); + EXPECT_TRUE(db().DoesTableExist("t")); } // Table should should still exist if the database version is new enough. - MetaTable::RazeIfDeprecated(&db_, kDeprecatedVersion); - EXPECT_TRUE(db_.DoesTableExist("t")); + sql::MetaTable::RazeIfDeprecated(&db(), kDeprecatedVersion); + EXPECT_TRUE(db().DoesTableExist("t")); // TODO(shess): It may make sense to Raze() if meta isn't present or // version isn't present. See meta_table.h TODO on RazeIfDeprecated(). // Table should still exist if the version is not available. - EXPECT_TRUE(db_.Execute("DELETE FROM meta WHERE key = 'version'")); + EXPECT_TRUE(db().Execute("DELETE FROM meta WHERE key = 'version'")); { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, kVersion, kVersion)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), kVersion, kVersion)); EXPECT_EQ(0, meta_table.GetVersionNumber()); } - MetaTable::RazeIfDeprecated(&db_, kDeprecatedVersion); - EXPECT_TRUE(db_.DoesTableExist("t")); + sql::MetaTable::RazeIfDeprecated(&db(), kDeprecatedVersion); + EXPECT_TRUE(db().DoesTableExist("t")); // Table should still exist if meta table is missing. - EXPECT_TRUE(db_.Execute("DROP TABLE meta")); - MetaTable::RazeIfDeprecated(&db_, kDeprecatedVersion); - EXPECT_TRUE(db_.DoesTableExist("t")); + EXPECT_TRUE(db().Execute("DROP TABLE meta")); + sql::MetaTable::RazeIfDeprecated(&db(), kDeprecatedVersion); + EXPECT_TRUE(db().DoesTableExist("t")); // Setup meta with deprecated version. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, kDeprecatedVersion, kDeprecatedVersion)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), kDeprecatedVersion, kDeprecatedVersion)); } // Deprecation check should remove the table. - EXPECT_TRUE(db_.DoesTableExist("t")); - MetaTable::RazeIfDeprecated(&db_, kDeprecatedVersion); - EXPECT_FALSE(MetaTable::DoesTableExist(&db_)); - EXPECT_FALSE(db_.DoesTableExist("t")); + EXPECT_TRUE(db().DoesTableExist("t")); + sql::MetaTable::RazeIfDeprecated(&db(), kDeprecatedVersion); + EXPECT_FALSE(sql::MetaTable::DoesTableExist(&db())); + EXPECT_FALSE(db().DoesTableExist("t")); } TEST_F(SQLMetaTableTest, VersionNumber) { @@ -101,16 +87,16 @@ // First Init() sets the version info as expected. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, kVersionFirst, kCompatVersionFirst)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), kVersionFirst, kCompatVersionFirst)); EXPECT_EQ(kVersionFirst, meta_table.GetVersionNumber()); EXPECT_EQ(kCompatVersionFirst, meta_table.GetCompatibleVersionNumber()); } // Second Init() does not change the version info. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, kVersionSecond, kCompatVersionSecond)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), kVersionSecond, kCompatVersionSecond)); EXPECT_EQ(kVersionFirst, meta_table.GetVersionNumber()); EXPECT_EQ(kCompatVersionFirst, meta_table.GetCompatibleVersionNumber()); @@ -120,8 +106,8 @@ // Version info from Set*() calls is seen. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, kVersionThird, kCompatVersionThird)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), kVersionThird, kCompatVersionThird)); EXPECT_EQ(kVersionSecond, meta_table.GetVersionNumber()); EXPECT_EQ(kCompatVersionSecond, meta_table.GetCompatibleVersionNumber()); } @@ -134,8 +120,8 @@ // Initially, the value isn't there until set. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); std::string value; EXPECT_FALSE(meta_table.GetValue(kKey, &value)); @@ -147,8 +133,8 @@ // Value is persistent across different instances. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); std::string value; EXPECT_TRUE(meta_table.GetValue(kKey, &value)); @@ -159,8 +145,8 @@ // Existing value was successfully changed. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); std::string value; EXPECT_TRUE(meta_table.GetValue(kKey, &value)); @@ -175,8 +161,8 @@ // Initially, the value isn't there until set. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); int value; EXPECT_FALSE(meta_table.GetValue(kKey, &value)); @@ -188,8 +174,8 @@ // Value is persistent across different instances. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); int value; EXPECT_TRUE(meta_table.GetValue(kKey, &value)); @@ -200,8 +186,8 @@ // Existing value was successfully changed. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); int value; EXPECT_TRUE(meta_table.GetValue(kKey, &value)); @@ -216,8 +202,8 @@ // Initially, the value isn't there until set. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); int64_t value; EXPECT_FALSE(meta_table.GetValue(kKey, &value)); @@ -229,8 +215,8 @@ // Value is persistent across different instances. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); int64_t value; EXPECT_TRUE(meta_table.GetValue(kKey, &value)); @@ -241,8 +227,8 @@ // Existing value was successfully changed. { - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); int64_t value; EXPECT_TRUE(meta_table.GetValue(kKey, &value)); @@ -254,8 +240,8 @@ static const char kKey[] = "String Key"; const std::string kValue("String Value"); - MetaTable meta_table; - EXPECT_TRUE(meta_table.Init(&db_, 1, 1)); + sql::MetaTable meta_table; + EXPECT_TRUE(meta_table.Init(&db(), 1, 1)); // Value isn't present. std::string value; @@ -272,5 +258,3 @@ } } // namespace - -} // namespace sql
diff --git a/sql/recover_module/module_unittest.cc b/sql/recover_module/module_unittest.cc index 2e0db47..a711756 100644 --- a/sql/recover_module/module_unittest.cc +++ b/sql/recover_module/module_unittest.cc
@@ -7,12 +7,12 @@ #include <tuple> #include <vector> -#include "base/files/scoped_temp_dir.h" #include "base/strings/stringprintf.h" #include "sql/database.h" #include "sql/statement.h" #include "sql/test/database_test_peer.h" #include "sql/test/scoped_error_expecter.h" +#include "sql/test/sql_test_base.h" #include "sql/test/test_helpers.h" #include "sql/transaction.h" #include "testing/gtest/include/gtest/gtest.h" @@ -21,131 +21,123 @@ namespace sql { namespace recover { -class RecoverModuleTest : public testing::Test { +class RecoverModuleTest : public sql::SQLTestBase { public: - ~RecoverModuleTest() override = default; - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE( - db_.Open(temp_dir_.GetPath().AppendASCII("recovery_test.sqlite"))); - ASSERT_TRUE(DatabaseTestPeer::EnableRecoveryExtension(&db_)); + SQLTestBase::SetUp(); + ASSERT_TRUE(DatabaseTestPeer::EnableRecoveryExtension(&db())); } - - protected: - base::ScopedTempDir temp_dir_; - sql::Database db_; }; TEST_F(RecoverModuleTest, CreateVtable) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); EXPECT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing, t TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing, t TEXT)")); } TEST_F(RecoverModuleTest, CreateVtableWithDatabaseSpecifier) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); EXPECT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(main.backing, t TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(main.backing, t TEXT)")); } TEST_F(RecoverModuleTest, CreateVtableOnSqliteMaster) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); EXPECT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing USING recover(" - "sqlite_master, type TEXT, name TEXT, tbl_name TEXT, " - "rootpage INTEGER, sql TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing USING recover(" + "sqlite_master, type TEXT, name TEXT, tbl_name TEXT, " + "rootpage INTEGER, sql TEXT)")); } TEST_F(RecoverModuleTest, CreateVtableFailsOnNonTempTable) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_MISUSE); - EXPECT_FALSE(db_.Execute( + EXPECT_FALSE(db().Execute( "CREATE VIRTUAL TABLE recover_backing USING recover(backing, t TEXT)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, CreateVtableFailsOnMissingTable) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_CORRUPT); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_missing " - "USING recover(missing, t TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_missing " + "USING recover(missing, t TEXT)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, DISABLED_CreateVtableFailsOnMissingDatabase) { // TODO(pwnall): Enable test after removing incorrect DLOG(FATAL) from // sql::Statement::Execute(). - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_ERROR); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(db.backing, t TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(db.backing, t TEXT)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, CreateVtableFailsOnTableWithInvalidQualifier) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_CORRUPT); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing invalid, t TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing invalid, t TEXT)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, DISABLED_CreateVtableFailsOnMissingTableName) { // TODO(pwnall): Enable test after removing incorrect DLOG(FATAL) from // sql::Statement::Execute(). - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_ERROR); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(main., t TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(main., t TEXT)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, CreateVtableFailsOnMissingSchemaSpec) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_MISUSE); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, CreateVtableFailsOnMissingDbName) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_MISUSE); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(.backing)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(.backing)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, ColumnTypeMappingAny) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); EXPECT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing, t ANY)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing, t ANY)")); sql::test::ColumnInfo column_info = - sql::test::ColumnInfo::Create(&db_, "temp", "recover_backing", "t"); + sql::test::ColumnInfo::Create(&db(), "temp", "recover_backing", "t"); EXPECT_EQ("(nullptr)", column_info.data_type); EXPECT_EQ("BINARY", column_info.collation_sequence); EXPECT_FALSE(column_info.has_non_null_constraint); @@ -153,13 +145,13 @@ EXPECT_FALSE(column_info.is_auto_incremented); } TEST_F(RecoverModuleTest, ColumnTypeMappingAnyNotNull) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); EXPECT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing, t ANY NOT NULL)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing, t ANY NOT NULL)")); sql::test::ColumnInfo column_info = - sql::test::ColumnInfo::Create(&db_, "temp", "recover_backing", "t"); + sql::test::ColumnInfo::Create(&db(), "temp", "recover_backing", "t"); EXPECT_EQ("(nullptr)", column_info.data_type); EXPECT_EQ("BINARY", column_info.collation_sequence); EXPECT_TRUE(column_info.has_non_null_constraint); @@ -167,58 +159,58 @@ EXPECT_FALSE(column_info.is_auto_incremented); } TEST_F(RecoverModuleTest, ColumnTypeMappingAnyStrict) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_MISUSE); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing, t ANY STRICT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing, t ANY STRICT)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, ColumnTypeExtraKeyword) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_MISUSE); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing, t INTEGER SOMETHING)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing, t INTEGER SOMETHING)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, ColumnTypeNotNullExtraKeyword) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_MISUSE); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing, t INTEGER NOT NULL SOMETHING)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing, t INTEGER NOT NULL SOMETHING)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, ColumnTypeDoubleTypes) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_MISUSE); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing " - "USING recover(backing, t INTEGER FLOAT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing " + "USING recover(backing, t INTEGER FLOAT)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } TEST_F(RecoverModuleTest, ColumnTypeNotNullDoubleTypes) { - ASSERT_TRUE(db_.Execute("CREATE TABLE backing(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE backing(t TEXT)")); { sql::test::ScopedErrorExpecter error_expecter; error_expecter.ExpectError(SQLITE_MISUSE); EXPECT_FALSE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_backing USING recover(" - "backing, t INTEGER NOT NULL TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_backing USING recover(" + "backing, t INTEGER NOT NULL TEXT)")); EXPECT_TRUE(error_expecter.SawExpectedErrors()); } } @@ -228,39 +220,30 @@ public ::testing::WithParamInterface< std::tuple<const char*, const char*, bool>> { public: - ~RecoverModuleColumnTypeMappingTest() override = default; - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE( - db_.Open(temp_dir_.GetPath().AppendASCII("recovery_test.sqlite"))); - ASSERT_TRUE(DatabaseTestPeer::EnableRecoveryExtension(&db_)); - + RecoverModuleTest::SetUp(); std::string sql = base::StringPrintf("CREATE TABLE backing(data %s)", SchemaType()); - ASSERT_TRUE(db_.Execute(sql.c_str())); + ASSERT_TRUE(db().Execute(sql.c_str())); } + protected: void CreateRecoveryTable(const char* suffix) { std::string sql = base::StringPrintf( "CREATE VIRTUAL TABLE temp.recover_backing " "USING recover(backing, data %s%s)", SchemaType(), suffix); - ASSERT_TRUE(db_.Execute(sql.c_str())); + ASSERT_TRUE(db().Execute(sql.c_str())); } const char* SchemaType() const { return std::get<0>(GetParam()); } const char* ExpectedType() const { return std::get<1>(GetParam()); } bool IsAlwaysNonNull() const { return std::get<2>(GetParam()); } - - protected: - base::ScopedTempDir temp_dir_; - sql::Database db_; }; TEST_P(RecoverModuleColumnTypeMappingTest, Unqualified) { CreateRecoveryTable(""); sql::test::ColumnInfo column_info = - sql::test::ColumnInfo::Create(&db_, "temp", "recover_backing", "data"); + sql::test::ColumnInfo::Create(&db(), "temp", "recover_backing", "data"); EXPECT_EQ(ExpectedType(), column_info.data_type); EXPECT_EQ("BINARY", column_info.collation_sequence); EXPECT_EQ(IsAlwaysNonNull(), column_info.has_non_null_constraint); @@ -270,7 +253,7 @@ TEST_P(RecoverModuleColumnTypeMappingTest, NotNull) { CreateRecoveryTable(" NOT NULL"); sql::test::ColumnInfo column_info = - sql::test::ColumnInfo::Create(&db_, "temp", "recover_backing", "data"); + sql::test::ColumnInfo::Create(&db(), "temp", "recover_backing", "data"); EXPECT_EQ(ExpectedType(), column_info.data_type); EXPECT_EQ("BINARY", column_info.collation_sequence); EXPECT_TRUE(column_info.has_non_null_constraint); @@ -280,7 +263,7 @@ TEST_P(RecoverModuleColumnTypeMappingTest, Strict) { CreateRecoveryTable(" STRICT"); sql::test::ColumnInfo column_info = - sql::test::ColumnInfo::Create(&db_, "temp", "recover_backing", "data"); + sql::test::ColumnInfo::Create(&db(), "temp", "recover_backing", "data"); EXPECT_EQ(ExpectedType(), column_info.data_type); EXPECT_EQ("BINARY", column_info.collation_sequence); EXPECT_EQ(IsAlwaysNonNull(), column_info.has_non_null_constraint); @@ -290,7 +273,7 @@ TEST_P(RecoverModuleColumnTypeMappingTest, StrictNotNull) { CreateRecoveryTable(" STRICT NOT NULL"); sql::test::ColumnInfo column_info = - sql::test::ColumnInfo::Create(&db_, "temp", "recover_backing", "data"); + sql::test::ColumnInfo::Create(&db(), "temp", "recover_backing", "data"); EXPECT_EQ(ExpectedType(), column_info.data_type); EXPECT_EQ("BINARY", column_info.collation_sequence); EXPECT_TRUE(column_info.has_non_null_constraint); @@ -322,12 +305,12 @@ } // namespace TEST_F(RecoverModuleTest, ReadFromAlteredTableNullDefaults) { - GenerateAlteredTable(&db_); + GenerateAlteredTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_altered " - "USING recover(altered, t TEXT, i INTEGER)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_altered " + "USING recover(altered, t TEXT, i INTEGER)")); - sql::Statement statement(db_.GetUniqueStatement( + sql::Statement statement(db().GetUniqueStatement( "SELECT t, i FROM recover_altered ORDER BY rowid")); ASSERT_TRUE(statement.Step()); EXPECT_EQ("a", statement.ColumnString(0)); @@ -346,12 +329,12 @@ } TEST_F(RecoverModuleTest, ReadFromAlteredTableSkipsNulls) { - GenerateAlteredTable(&db_); + GenerateAlteredTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_altered " - "USING recover(altered, t TEXT, i INTEGER NOT NULL)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_altered " + "USING recover(altered, t TEXT, i INTEGER NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + sql::Statement statement(db().GetUniqueStatement( "SELECT t, i FROM recover_altered ORDER BY rowid")); ASSERT_TRUE(statement.Step()); EXPECT_EQ("d", statement.ColumnString(0)); @@ -383,13 +366,13 @@ } // namespace TEST_F(RecoverModuleTest, LeafNodes) { - GenerateSizedTable(&db_, 10, "Leaf-node-generating line "); + GenerateSizedTable(&db(), 10, "Leaf-node-generating line "); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_sized " - "USING recover(sized, t TEXT, i INTEGER NOT NULL)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_sized " + "USING recover(sized, t TEXT, i INTEGER NOT NULL)")); sql::Statement statement( - db_.GetUniqueStatement("SELECT t, i FROM recover_sized ORDER BY rowid")); + db().GetUniqueStatement("SELECT t, i FROM recover_sized ORDER BY rowid")); for (int i = 0; i < 10; ++i) { ASSERT_TRUE(statement.Step()); EXPECT_EQ(base::StringPrintf("Leaf-node-generating line %d", i), @@ -400,22 +383,22 @@ } TEST_F(RecoverModuleTest, EmptyTable) { - GenerateSizedTable(&db_, 0, ""); + GenerateSizedTable(&db(), 0, ""); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_sized " - "USING recover(sized, t TEXT, i INTEGER NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_sized " + "USING recover(sized, t TEXT, i INTEGER NOT NULL)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, t, i FROM recover_sized ORDER BY rowid")); EXPECT_FALSE(statement.Step()); } TEST_F(RecoverModuleTest, SingleLevelInteriorNodes) { - GenerateSizedTable(&db_, 100, "Interior-node-generating line "); + GenerateSizedTable(&db(), 100, "Interior-node-generating line "); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_sized " - "USING recover(sized, t TEXT, i INTEGER NOT NULL)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_sized " + "USING recover(sized, t TEXT, i INTEGER NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, t, i FROM recover_sized ORDER BY rowid")); for (int i = 0; i < 100; ++i) { ASSERT_TRUE(statement.Step()); @@ -428,12 +411,12 @@ } TEST_F(RecoverModuleTest, MultiLevelInteriorNodes) { - GenerateSizedTable(&db_, 5000, "Interior-node-generating line "); + GenerateSizedTable(&db(), 5000, "Interior-node-generating line "); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_sized " - "USING recover(sized, t TEXT, i INTEGER NOT NULL)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_sized " + "USING recover(sized, t TEXT, i INTEGER NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, t, i FROM recover_sized ORDER BY rowid")); for (int i = 0; i < 5000; ++i) { ASSERT_TRUE(statement.Step()); @@ -461,11 +444,11 @@ } // namespace TEST_F(RecoverModuleTest, Any) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value ANY)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value ANY)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -499,11 +482,11 @@ } TEST_F(RecoverModuleTest, Integers) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value INTEGER)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value INTEGER)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -520,11 +503,11 @@ } TEST_F(RecoverModuleTest, NonNullIntegers) { - GenerateTypesTable(&db_); - ASSERT_TRUE(db_.Execute( + GenerateTypesTable(&db()); + ASSERT_TRUE(db().Execute( "CREATE VIRTUAL TABLE temp.recover_types " "USING recover(types, rowtype TEXT, value INTEGER NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -537,11 +520,11 @@ } TEST_F(RecoverModuleTest, Floats) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value FLOAT)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value FLOAT)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -563,11 +546,11 @@ } TEST_F(RecoverModuleTest, NonNullFloats) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value FLOAT NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value FLOAT NOT NULL)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -585,11 +568,11 @@ } TEST_F(RecoverModuleTest, FloatsStrict) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value FLOAT STRICT)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value FLOAT STRICT)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -606,11 +589,11 @@ } TEST_F(RecoverModuleTest, NonNullFloatsStrict) { - GenerateTypesTable(&db_); - ASSERT_TRUE(db_.Execute( + GenerateTypesTable(&db()); + ASSERT_TRUE(db().Execute( "CREATE VIRTUAL TABLE temp.recover_types " "USING recover(types, rowtype TEXT, value FLOAT STRICT NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -623,11 +606,11 @@ } TEST_F(RecoverModuleTest, Texts) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value TEXT)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value TEXT)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -651,11 +634,11 @@ } TEST_F(RecoverModuleTest, NonNullTexts) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value TEXT NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value TEXT NOT NULL)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -675,11 +658,11 @@ } TEST_F(RecoverModuleTest, TextsStrict) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value TEXT STRICT)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value TEXT STRICT)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -696,11 +679,11 @@ } TEST_F(RecoverModuleTest, NonNullTextsStrict) { - GenerateTypesTable(&db_); - ASSERT_TRUE(db_.Execute( + GenerateTypesTable(&db()); + ASSERT_TRUE(db().Execute( "CREATE VIRTUAL TABLE temp.recover_types " "USING recover(types, rowtype TEXT, value TEXT STRICT NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -713,11 +696,11 @@ } TEST_F(RecoverModuleTest, Blobs) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value BLOB)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value BLOB)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -736,11 +719,11 @@ } TEST_F(RecoverModuleTest, NonNullBlobs) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value BLOB NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value BLOB NOT NULL)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -755,11 +738,11 @@ } TEST_F(RecoverModuleTest, AnyNonNull) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_types " - "USING recover(types, rowtype TEXT, value ANY NOT NULL)")); - sql::Statement statement(db_.GetUniqueStatement( + db().Execute("CREATE VIRTUAL TABLE temp.recover_types " + "USING recover(types, rowtype TEXT, value ANY NOT NULL)")); + sql::Statement statement(db().GetUniqueStatement( "SELECT rowid, rowtype, value FROM recover_types")); ASSERT_TRUE(statement.Step()); @@ -789,20 +772,20 @@ } TEST_F(RecoverModuleTest, RowidAlias) { - GenerateTypesTable(&db_); + GenerateTypesTable(&db()); // The id column is an alias for rowid, and its values get serialized as NULL. - ASSERT_TRUE(db_.Execute( + ASSERT_TRUE(db().Execute( "CREATE TABLE types2(id INTEGER PRIMARY KEY, rowtype TEXT, value)")); ASSERT_TRUE( - db_.Execute("INSERT INTO types2(id, rowtype, value) " - "SELECT rowid, rowtype, value FROM types WHERE true")); - ASSERT_TRUE(db_.Execute( + db().Execute("INSERT INTO types2(id, rowtype, value) " + "SELECT rowid, rowtype, value FROM types WHERE true")); + ASSERT_TRUE(db().Execute( "CREATE VIRTUAL TABLE temp.recover_types2 " "USING recover(types2, id ROWID NOT NULL, rowtype TEXT, value ANY)")); sql::Statement statement( - db_.GetUniqueStatement("SELECT id, rowid, rowtype, value FROM types2")); + db().GetUniqueStatement("SELECT id, rowid, rowtype, value FROM types2")); ASSERT_TRUE(statement.Step()); EXPECT_EQ(1, statement.ColumnInt(0)); @@ -836,7 +819,7 @@ } TEST_F(RecoverModuleTest, IntegerEncodings) { - ASSERT_TRUE(db_.Execute("CREATE TABLE integers(value)")); + ASSERT_TRUE(db().Execute("CREATE TABLE integers(value)")); const std::vector<int64_t> values = { // Encoded directly in type info. @@ -874,7 +857,7 @@ -9223372036854775807, }; sql::Statement insert( - db_.GetUniqueStatement("INSERT INTO integers VALUES(?)")); + db().GetUniqueStatement("INSERT INTO integers VALUES(?)")); for (int64_t value : values) { insert.BindInt64(0, value); ASSERT_TRUE(insert.Run()); @@ -882,10 +865,10 @@ } ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_integers " - "USING recover(integers, value INTEGER)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_integers " + "USING recover(integers, value INTEGER)")); sql::Statement select( - db_.GetUniqueStatement("SELECT rowid, value FROM recover_integers")); + db().GetUniqueStatement("SELECT rowid, value FROM recover_integers")); for (size_t i = 0; i < values.size(); ++i) { ASSERT_TRUE(select.Step()) << "Was attemping to read " << values[i]; EXPECT_EQ(static_cast<int>(i + 1), select.ColumnInt(0)); @@ -984,30 +967,30 @@ -0x8000000000000000, }; - ASSERT_TRUE(db_.Execute("CREATE TABLE varints(value INTEGER PRIMARY KEY)")); + ASSERT_TRUE(db().Execute("CREATE TABLE varints(value INTEGER PRIMARY KEY)")); ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_varints " - "USING recover(varints, value ROWID)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_varints " + "USING recover(varints, value ROWID)")); for (int64_t value : values) { sql::Statement insert( - db_.GetUniqueStatement("INSERT INTO varints VALUES(?)")); + db().GetUniqueStatement("INSERT INTO varints VALUES(?)")); insert.BindInt64(0, value); ASSERT_TRUE(insert.Run()); sql::Statement select( - db_.GetUniqueStatement("SELECT rowid, value FROM recover_varints")); + db().GetUniqueStatement("SELECT rowid, value FROM recover_varints")); ASSERT_TRUE(select.Step()) << "Was attemping to read " << value; EXPECT_EQ(value, select.ColumnInt64(0)); EXPECT_EQ(value, select.ColumnInt64(1)); EXPECT_FALSE(select.Step()); - ASSERT_TRUE(db_.Execute("DELETE FROM varints")); + ASSERT_TRUE(db().Execute("DELETE FROM varints")); } } TEST_F(RecoverModuleTest, TextEncodings) { - ASSERT_TRUE(db_.Execute("CREATE TABLE encodings(t TEXT)")); + ASSERT_TRUE(db().Execute("CREATE TABLE encodings(t TEXT)")); const std::vector<std::string> values = { "", "a", u8"ö", u8"Mjollnir", u8"Mjölnir", @@ -1015,7 +998,7 @@ }; sql::Statement insert( - db_.GetUniqueStatement("INSERT INTO encodings VALUES(?)")); + db().GetUniqueStatement("INSERT INTO encodings VALUES(?)")); for (const std::string& value : values) { insert.BindString(0, value); ASSERT_TRUE(insert.Run()); @@ -1023,10 +1006,10 @@ } ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_encodings " - "USING recover(encodings, t TEXT)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_encodings " + "USING recover(encodings, t TEXT)")); sql::Statement select( - db_.GetUniqueStatement("SELECT rowid, t FROM recover_encodings")); + db().GetUniqueStatement("SELECT rowid, t FROM recover_encodings")); for (size_t i = 0; i < values.size(); ++i) { ASSERT_TRUE(select.Step()); EXPECT_EQ(static_cast<int>(i + 1), select.ColumnInt(0)); @@ -1036,7 +1019,7 @@ } TEST_F(RecoverModuleTest, BlobEncodings) { - ASSERT_TRUE(db_.Execute("CREATE TABLE blob_encodings(t BLOB)")); + ASSERT_TRUE(db().Execute("CREATE TABLE blob_encodings(t BLOB)")); const std::vector<std::vector<uint8_t>> values = { {}, {0x00}, {0x01}, @@ -1045,7 +1028,7 @@ }; sql::Statement insert( - db_.GetUniqueStatement("INSERT INTO blob_encodings VALUES(?)")); + db().GetUniqueStatement("INSERT INTO blob_encodings VALUES(?)")); for (const std::vector<uint8_t>& value : values) { // std::vector::data() returns nullptr for empty vectors. Unfortunately, // sqlite3_bind_blob() always interprets null data as a NULL value. In this @@ -1060,10 +1043,10 @@ } ASSERT_TRUE( - db_.Execute("CREATE VIRTUAL TABLE temp.recover_blob_encodings " - "USING recover(blob_encodings, t BLOB)")); + db().Execute("CREATE VIRTUAL TABLE temp.recover_blob_encodings " + "USING recover(blob_encodings, t BLOB)")); sql::Statement select( - db_.GetUniqueStatement("SELECT rowid, t FROM recover_blob_encodings")); + db().GetUniqueStatement("SELECT rowid, t FROM recover_blob_encodings")); for (size_t i = 0; i < values.size(); ++i) { ASSERT_TRUE(select.Step()); EXPECT_EQ(static_cast<int>(i + 1), select.ColumnInt(0)); @@ -1130,60 +1113,60 @@ } // namespace TEST_F(RecoverModuleTest, ValueWithoutOverflow) { - CheckLargeValueRecovery(&db_, db_.page_size() - kRecordOverhead); - int auto_vacuum_pages = HasEnabledAutoVacuum(&db_) ? 1 : 0; - ASSERT_EQ(2 + auto_vacuum_pages, sql::test::GetPageCount(&db_)) + CheckLargeValueRecovery(&db(), db().page_size() - kRecordOverhead); + int auto_vacuum_pages = HasEnabledAutoVacuum(&db()) ? 1 : 0; + ASSERT_EQ(2 + auto_vacuum_pages, sql::test::GetPageCount(&db())) << "Database should have a root page and a leaf page"; } TEST_F(RecoverModuleTest, ValueWithOneByteOverflow) { - CheckLargeValueRecovery(&db_, db_.page_size() - kRecordOverhead + 1); - int auto_vacuum_pages = HasEnabledAutoVacuum(&db_) ? 1 : 0; - ASSERT_EQ(3 + auto_vacuum_pages, sql::test::GetPageCount(&db_)) + CheckLargeValueRecovery(&db(), db().page_size() - kRecordOverhead + 1); + int auto_vacuum_pages = HasEnabledAutoVacuum(&db()) ? 1 : 0; + ASSERT_EQ(3 + auto_vacuum_pages, sql::test::GetPageCount(&db())) << "Database should have a root page, a leaf page, and 1 overflow page"; } TEST_F(RecoverModuleTest, ValueWithOneOverflowPage) { CheckLargeValueRecovery( - &db_, db_.page_size() - kRecordOverhead + db_.page_size() / 2); - int auto_vacuum_pages = HasEnabledAutoVacuum(&db_) ? 1 : 0; - ASSERT_EQ(3 + auto_vacuum_pages, sql::test::GetPageCount(&db_)) + &db(), db().page_size() - kRecordOverhead + db().page_size() / 2); + int auto_vacuum_pages = HasEnabledAutoVacuum(&db()) ? 1 : 0; + ASSERT_EQ(3 + auto_vacuum_pages, sql::test::GetPageCount(&db())) << "Database should have a root page, a leaf page, and 1 overflow page"; } TEST_F(RecoverModuleTest, ValueWithOneFullOverflowPage) { - CheckLargeValueRecovery(&db_, db_.page_size() - kRecordOverhead + - db_.page_size() - kOverflowOverhead); - int auto_vacuum_pages = HasEnabledAutoVacuum(&db_) ? 1 : 0; - ASSERT_EQ(3 + auto_vacuum_pages, sql::test::GetPageCount(&db_)) + CheckLargeValueRecovery(&db(), db().page_size() - kRecordOverhead + + db().page_size() - kOverflowOverhead); + int auto_vacuum_pages = HasEnabledAutoVacuum(&db()) ? 1 : 0; + ASSERT_EQ(3 + auto_vacuum_pages, sql::test::GetPageCount(&db())) << "Database should have a root page, a leaf page, and 1 overflow page"; } TEST_F(RecoverModuleTest, ValueWithOneByteSecondOverflowPage) { - CheckLargeValueRecovery(&db_, db_.page_size() - kRecordOverhead + - db_.page_size() - kOverflowOverhead + 1); - int auto_vacuum_pages = HasEnabledAutoVacuum(&db_) ? 1 : 0; - ASSERT_EQ(4 + auto_vacuum_pages, sql::test::GetPageCount(&db_)) + CheckLargeValueRecovery(&db(), db().page_size() - kRecordOverhead + + db().page_size() - kOverflowOverhead + 1); + int auto_vacuum_pages = HasEnabledAutoVacuum(&db()) ? 1 : 0; + ASSERT_EQ(4 + auto_vacuum_pages, sql::test::GetPageCount(&db())) << "Database should have a root page, a leaf page, and 2 overflow pages"; } TEST_F(RecoverModuleTest, ValueWithTwoOverflowPages) { - CheckLargeValueRecovery(&db_, db_.page_size() - kRecordOverhead + - db_.page_size() - kOverflowOverhead + - db_.page_size() / 2); - int auto_vacuum_pages = HasEnabledAutoVacuum(&db_) ? 1 : 0; - ASSERT_EQ(4 + auto_vacuum_pages, sql::test::GetPageCount(&db_)) + CheckLargeValueRecovery(&db(), db().page_size() - kRecordOverhead + + db().page_size() - kOverflowOverhead + + db().page_size() / 2); + int auto_vacuum_pages = HasEnabledAutoVacuum(&db()) ? 1 : 0; + ASSERT_EQ(4 + auto_vacuum_pages, sql::test::GetPageCount(&db())) << "Database should have a root page, a leaf page, and 2 overflow pages"; } TEST_F(RecoverModuleTest, ValueWithTwoFullOverflowPages) { // This value is large enough that the varint encoding of its type ID takes up // 3 bytes, instead of 2. - CheckLargeValueRecovery(&db_, db_.page_size() - kRecordOverhead + - (db_.page_size() - kOverflowOverhead) * 2 - - 1); - int auto_vacuum_pages = HasEnabledAutoVacuum(&db_) ? 1 : 0; - ASSERT_EQ(4 + auto_vacuum_pages, sql::test::GetPageCount(&db_)) + CheckLargeValueRecovery(&db(), + db().page_size() - kRecordOverhead + + (db().page_size() - kOverflowOverhead) * 2 - 1); + int auto_vacuum_pages = HasEnabledAutoVacuum(&db()) ? 1 : 0; + ASSERT_EQ(4 + auto_vacuum_pages, sql::test::GetPageCount(&db())) << "Database should have a root page, a leaf page, and 2 overflow pages"; }
diff --git a/sql/recovery_unittest.cc b/sql/recovery_unittest.cc index f402907..afd3865 100644 --- a/sql/recovery_unittest.cc +++ b/sql/recovery_unittest.cc
@@ -22,12 +22,11 @@ #include "sql/statement.h" #include "sql/test/paths.h" #include "sql/test/scoped_error_expecter.h" +#include "sql/test/sql_test_base.h" #include "sql/test/test_helpers.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/sqlite/sqlite3.h" -namespace sql { - namespace { using sql::test::ExecuteWithResult; @@ -37,104 +36,81 @@ // schema. For tables or indices, this will contain the sql command // to create the table or index. For certain automatic SQLite // structures with no sql, the name is used. -std::string GetSchema(Database* db) { +std::string GetSchema(sql::Database* db) { static const char kSql[] = "SELECT COALESCE(sql, name) FROM sqlite_master ORDER BY 1"; return ExecuteWithResults(db, kSql, "|", "\n"); } -class SQLRecoveryTest : public testing::Test { - public: - ~SQLRecoveryTest() override = default; +using SQLRecoveryTest = sql::SQLTestBase; - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - db_path_ = temp_dir_.GetPath().AppendASCII("recovery_test.sqlite"); - ASSERT_TRUE(db_.Open(db_path_)); - } - - bool Reopen() { - db_.Close(); - return db_.Open(db_path_); - } - - bool OverwriteDatabaseHeader() { - base::File file(db_path_, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - static constexpr char kText[] = "Now is the winter of our discontent."; - constexpr int kTextBytes = sizeof(kText) - 1; - return file.Write(0, kText, kTextBytes) == kTextBytes; - } - - protected: - base::ScopedTempDir temp_dir_; - base::FilePath db_path_; - Database db_; -}; - -// Baseline Recovery test covering the different ways to dispose of the -// scoped pointer received from Recovery::Begin(). +// Baseline sql::Recovery test covering the different ways to dispose of the +// scoped pointer received from sql::Recovery::Begin(). TEST_F(SQLRecoveryTest, RecoverBasic) { static const char kCreateSql[] = "CREATE TABLE x (t TEXT)"; static const char kInsertSql[] = "INSERT INTO x VALUES ('This is a test')"; static const char kAltInsertSql[] = "INSERT INTO x VALUES ('That was a test')"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute(kInsertSql)); - ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db_)); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kInsertSql)); + ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); // If the Recovery handle goes out of scope without being // Recovered(), the database is razed. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery.get()); } - EXPECT_FALSE(db_.is_open()); + EXPECT_FALSE(db().is_open()); ASSERT_TRUE(Reopen()); - EXPECT_TRUE(db_.is_open()); - ASSERT_EQ("", GetSchema(&db_)); + EXPECT_TRUE(db().is_open()); + ASSERT_EQ("", GetSchema(&db())); // Recreate the database. - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute(kInsertSql)); - ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db_)); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kInsertSql)); + ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); // Unrecoverable() also razes. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery.get()); - Recovery::Unrecoverable(std::move(recovery)); + sql::Recovery::Unrecoverable(std::move(recovery)); - // TODO(shess): Test that calls to recover.db_ start failing. + // TODO(shess): Test that calls to recover.db() start failing. } - EXPECT_FALSE(db_.is_open()); + EXPECT_FALSE(db().is_open()); ASSERT_TRUE(Reopen()); - EXPECT_TRUE(db_.is_open()); - ASSERT_EQ("", GetSchema(&db_)); + EXPECT_TRUE(db().is_open()); + ASSERT_EQ("", GetSchema(&db())); // Attempting to recover a previously-recovered handle fails early. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery.get()); recovery.reset(); - recovery = Recovery::Begin(&db_, db_path_); + recovery = sql::Recovery::Begin(&db(), db_path()); ASSERT_FALSE(recovery.get()); } ASSERT_TRUE(Reopen()); // Recreate the database. - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute(kInsertSql)); - ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db_)); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kInsertSql)); + ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); // Unrecovered table to distinguish from recovered database. - ASSERT_TRUE(db_.Execute("CREATE TABLE y (c INTEGER)")); - ASSERT_NE("CREATE TABLE x (t TEXT)", GetSchema(&db_)); + ASSERT_TRUE(db().Execute("CREATE TABLE y (c INTEGER)")); + ASSERT_NE("CREATE TABLE x (t TEXT)", GetSchema(&db())); // Recovered() replaces the original with the "recovered" version. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery.get()); // Create the new version of the table. @@ -144,48 +120,50 @@ ASSERT_TRUE(recovery->db()->Execute(kAltInsertSql)); // Successfully recovered. - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } - EXPECT_FALSE(db_.is_open()); + EXPECT_FALSE(db().is_open()); ASSERT_TRUE(Reopen()); - EXPECT_TRUE(db_.is_open()); - ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db_)); + EXPECT_TRUE(db().is_open()); + ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); const char* kXSql = "SELECT * FROM x ORDER BY 1"; - ASSERT_EQ("That was a test", ExecuteWithResult(&db_, kXSql)); + ASSERT_EQ("That was a test", ExecuteWithResult(&db(), kXSql)); // Reset the database contents. - ASSERT_TRUE(db_.Execute("DELETE FROM x")); - ASSERT_TRUE(db_.Execute(kInsertSql)); + ASSERT_TRUE(db().Execute("DELETE FROM x")); + ASSERT_TRUE(db().Execute(kInsertSql)); // Rollback() discards recovery progress and leaves the database as it was. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery.get()); ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); ASSERT_TRUE(recovery->db()->Execute(kAltInsertSql)); - Recovery::Rollback(std::move(recovery)); + sql::Recovery::Rollback(std::move(recovery)); } - EXPECT_FALSE(db_.is_open()); + EXPECT_FALSE(db().is_open()); ASSERT_TRUE(Reopen()); - EXPECT_TRUE(db_.is_open()); - ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db_)); + EXPECT_TRUE(db().is_open()); + ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); - ASSERT_EQ("This is a test", ExecuteWithResult(&db_, kXSql)); + ASSERT_EQ("This is a test", ExecuteWithResult(&db(), kXSql)); } -// Test operation of the virtual table used by Recovery. +// Test operation of the virtual table used by sql::Recovery. TEST_F(SQLRecoveryTest, VirtualTable) { static const char kCreateSql[] = "CREATE TABLE x (t TEXT)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES ('This is a test')")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES ('That was a test')")); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('This is a test')")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('That was a test')")); // Successfully recover the database. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); // Tables to recover original DB, now at [corrupt]. static const char kRecoveryCreateSql[] = @@ -204,32 +182,32 @@ ASSERT_TRUE(recovery->db()->Execute(kRecoveryCopySql)); // Successfully recovered. - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } // Since the database was not corrupt, the entire schema and all // data should be recovered. ASSERT_TRUE(Reopen()); - ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db_)); + ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); static const char* kXSql = "SELECT * FROM x ORDER BY 1"; ASSERT_EQ("That was a test\nThis is a test", - ExecuteWithResults(&db_, kXSql, "|", "\n")); + ExecuteWithResults(&db(), kXSql, "|", "\n")); } -void RecoveryCallback(Database* db, +void RecoveryCallback(sql::Database* db, const base::FilePath& db_path, const char* create_table, const char* create_index, int* record_error, int error, - Statement* stmt) { + sql::Statement* stmt) { *record_error = error; // Clear the error callback to prevent reentrancy. db->reset_error_callback(); - std::unique_ptr<Recovery> recovery = Recovery::Begin(db, db_path); + std::unique_ptr<sql::Recovery> recovery = sql::Recovery::Begin(db, db_path); ASSERT_TRUE(recovery.get()); ASSERT_TRUE(recovery->db()->Execute(create_table)); @@ -238,7 +216,7 @@ size_t rows = 0; ASSERT_TRUE(recovery->AutoRecoverTable("x", &rows)); - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } // Build a database, corrupt it by making an index reference to @@ -246,15 +224,15 @@ TEST_F(SQLRecoveryTest, RecoverCorruptIndex) { static const char kCreateTable[] = "CREATE TABLE x (id INTEGER, v INTEGER)"; static const char kCreateIndex[] = "CREATE UNIQUE INDEX x_id ON x (id)"; - ASSERT_TRUE(db_.Execute(kCreateTable)); - ASSERT_TRUE(db_.Execute(kCreateIndex)); + ASSERT_TRUE(db().Execute(kCreateTable)); + ASSERT_TRUE(db().Execute(kCreateIndex)); // Insert a bit of data. { - ASSERT_TRUE(db_.BeginTransaction()); + ASSERT_TRUE(db().BeginTransaction()); static const char kInsertSql[] = "INSERT INTO x (id, v) VALUES (?, ?)"; - Statement s(db_.GetUniqueStatement(kInsertSql)); + sql::Statement s(db().GetUniqueStatement(kInsertSql)); for (int i = 0; i < 10; ++i) { s.Reset(true); s.BindInt(0, i); @@ -263,42 +241,42 @@ EXPECT_TRUE(s.Succeeded()); } - ASSERT_TRUE(db_.CommitTransaction()); + ASSERT_TRUE(db().CommitTransaction()); } - db_.Close(); + db().Close(); // Delete a row from the table, while leaving the index entry which // references it. static const char kDeleteSql[] = "DELETE FROM x WHERE id = 0"; - ASSERT_TRUE(sql::test::CorruptTableOrIndex(db_path_, "x_id", kDeleteSql)); + ASSERT_TRUE(sql::test::CorruptTableOrIndex(db_path(), "x_id", kDeleteSql)); ASSERT_TRUE(Reopen()); int error = SQLITE_OK; - db_.set_error_callback(base::BindRepeating( - &RecoveryCallback, &db_, db_path_, kCreateTable, kCreateIndex, &error)); + db().set_error_callback(base::BindRepeating( + &RecoveryCallback, &db(), db_path(), kCreateTable, kCreateIndex, &error)); // This works before the callback is called. static const char kTrivialSql[] = "SELECT COUNT(*) FROM sqlite_master"; - EXPECT_TRUE(db_.IsSQLValid(kTrivialSql)); + EXPECT_TRUE(db().IsSQLValid(kTrivialSql)); // TODO(shess): Could this be delete? Anything which fails should work. static const char kSelectSql[] = "SELECT v FROM x WHERE id = 0"; - ASSERT_FALSE(db_.Execute(kSelectSql)); + ASSERT_FALSE(db().Execute(kSelectSql)); EXPECT_EQ(SQLITE_CORRUPT, error); // Database handle has been poisoned. - EXPECT_FALSE(db_.IsSQLValid(kTrivialSql)); + EXPECT_FALSE(db().IsSQLValid(kTrivialSql)); ASSERT_TRUE(Reopen()); // The recovered table should reflect the deletion. static const char kSelectAllSql[] = "SELECT v FROM x ORDER BY id"; EXPECT_EQ("1,2,3,4,5,6,7,8,9", - ExecuteWithResults(&db_, kSelectAllSql, "|", ",")); + ExecuteWithResults(&db(), kSelectAllSql, "|", ",")); // The failing statement should now succeed, with no results. - EXPECT_EQ("", ExecuteWithResults(&db_, kSelectSql, "|", ",")); + EXPECT_EQ("", ExecuteWithResults(&db(), kSelectSql, "|", ",")); } // Build a database, corrupt it by making a table contain a row not @@ -306,15 +284,15 @@ TEST_F(SQLRecoveryTest, RecoverCorruptTable) { static const char kCreateTable[] = "CREATE TABLE x (id INTEGER, v INTEGER)"; static const char kCreateIndex[] = "CREATE UNIQUE INDEX x_id ON x (id)"; - ASSERT_TRUE(db_.Execute(kCreateTable)); - ASSERT_TRUE(db_.Execute(kCreateIndex)); + ASSERT_TRUE(db().Execute(kCreateTable)); + ASSERT_TRUE(db().Execute(kCreateIndex)); // Insert a bit of data. { - ASSERT_TRUE(db_.BeginTransaction()); + ASSERT_TRUE(db().BeginTransaction()); static const char kInsertSql[] = "INSERT INTO x (id, v) VALUES (?, ?)"; - Statement s(db_.GetUniqueStatement(kInsertSql)); + sql::Statement s(db().GetUniqueStatement(kInsertSql)); for (int i = 0; i < 10; ++i) { s.Reset(true); s.BindInt(0, i); @@ -323,62 +301,62 @@ EXPECT_TRUE(s.Succeeded()); } - ASSERT_TRUE(db_.CommitTransaction()); + ASSERT_TRUE(db().CommitTransaction()); } - db_.Close(); + db().Close(); // Delete a row from the index while leaving a table entry. static const char kDeleteSql[] = "DELETE FROM x WHERE id = 0"; - ASSERT_TRUE(sql::test::CorruptTableOrIndex(db_path_, "x", kDeleteSql)); + ASSERT_TRUE(sql::test::CorruptTableOrIndex(db_path(), "x", kDeleteSql)); ASSERT_TRUE(Reopen()); int error = SQLITE_OK; - db_.set_error_callback(base::BindRepeating( - &RecoveryCallback, &db_, db_path_, kCreateTable, kCreateIndex, &error)); + db().set_error_callback(base::BindRepeating( + &RecoveryCallback, &db(), db_path(), kCreateTable, kCreateIndex, &error)); // Index shows one less than originally inserted. static const char kCountSql[] = "SELECT COUNT (*) FROM x"; - EXPECT_EQ("9", ExecuteWithResult(&db_, kCountSql)); + EXPECT_EQ("9", ExecuteWithResult(&db(), kCountSql)); // A full table scan shows all of the original data. Using column [v] to // force use of the table rather than the index. static const char kDistinctSql[] = "SELECT DISTINCT COUNT (v) FROM x"; - EXPECT_EQ("10", ExecuteWithResult(&db_, kDistinctSql)); + EXPECT_EQ("10", ExecuteWithResult(&db(), kDistinctSql)); // Insert id 0 again. Since it is not in the index, the insert // succeeds, but results in a duplicate value in the table. static const char kInsertSql[] = "INSERT INTO x (id, v) VALUES (0, 100)"; - ASSERT_TRUE(db_.Execute(kInsertSql)); + ASSERT_TRUE(db().Execute(kInsertSql)); // Duplication is visible. - EXPECT_EQ("10", ExecuteWithResult(&db_, kCountSql)); - EXPECT_EQ("11", ExecuteWithResult(&db_, kDistinctSql)); + EXPECT_EQ("10", ExecuteWithResult(&db(), kCountSql)); + EXPECT_EQ("11", ExecuteWithResult(&db(), kDistinctSql)); // This works before the callback is called. static const char kTrivialSql[] = "SELECT COUNT(*) FROM sqlite_master"; - EXPECT_TRUE(db_.IsSQLValid(kTrivialSql)); + EXPECT_TRUE(db().IsSQLValid(kTrivialSql)); // TODO(shess): Figure out a statement which causes SQLite to notice the // corruption. SELECT doesn't see errors because missing index values aren't // visible. UPDATE or DELETE against v=0 don't see errors, even though the // index item is missing. I suspect SQLite only deletes the key in these // cases, but doesn't verify that one or more keys were deleted. - ASSERT_FALSE(db_.Execute("INSERT INTO x (id, v) VALUES (0, 101)")); + ASSERT_FALSE(db().Execute("INSERT INTO x (id, v) VALUES (0, 101)")); EXPECT_EQ(SQLITE_CONSTRAINT_UNIQUE, error); // Database handle has been poisoned. - EXPECT_FALSE(db_.IsSQLValid(kTrivialSql)); + EXPECT_FALSE(db().IsSQLValid(kTrivialSql)); ASSERT_TRUE(Reopen()); // The recovered table has consistency between the index and the table. - EXPECT_EQ("10", ExecuteWithResult(&db_, kCountSql)); - EXPECT_EQ("10", ExecuteWithResult(&db_, kDistinctSql)); + EXPECT_EQ("10", ExecuteWithResult(&db(), kCountSql)); + EXPECT_EQ("10", ExecuteWithResult(&db(), kDistinctSql)); // Only one of the values is retained. static const char kSelectSql[] = "SELECT v FROM x WHERE id = 0"; - const std::string results = ExecuteWithResult(&db_, kSelectSql); + const std::string results = ExecuteWithResult(&db(), kSelectSql); EXPECT_TRUE(results=="100" || results=="0") << "Actual results: " << results; } @@ -387,42 +365,45 @@ const int kCompatibleVersion = 2; { - MetaTable meta; - EXPECT_TRUE(meta.Init(&db_, kVersion, kCompatibleVersion)); + sql::MetaTable meta; + EXPECT_TRUE(meta.Init(&db(), kVersion, kCompatibleVersion)); EXPECT_EQ(kVersion, meta.GetVersionNumber()); } // Test expected case where everything works. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); EXPECT_TRUE(recovery->SetupMeta()); int version = 0; EXPECT_TRUE(recovery->GetMetaVersionNumber(&version)); EXPECT_EQ(kVersion, version); - Recovery::Rollback(std::move(recovery)); + sql::Recovery::Rollback(std::move(recovery)); } ASSERT_TRUE(Reopen()); // Handle was poisoned. // Test version row missing. - EXPECT_TRUE(db_.Execute("DELETE FROM meta WHERE key = 'version'")); + EXPECT_TRUE(db().Execute("DELETE FROM meta WHERE key = 'version'")); { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); EXPECT_TRUE(recovery->SetupMeta()); int version = 0; EXPECT_FALSE(recovery->GetMetaVersionNumber(&version)); EXPECT_EQ(0, version); - Recovery::Rollback(std::move(recovery)); + sql::Recovery::Rollback(std::move(recovery)); } ASSERT_TRUE(Reopen()); // Handle was poisoned. // Test meta table missing. - EXPECT_TRUE(db_.Execute("DROP TABLE meta")); + EXPECT_TRUE(db().Execute("DROP TABLE meta")); { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); // From virtual table. - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); EXPECT_FALSE(recovery->SetupMeta()); ASSERT_TRUE(expecter.SawExpectedErrors()); } @@ -433,22 +414,23 @@ // BIGINT and VARCHAR to test type affinity. static const char kCreateSql[] = "CREATE TABLE x (id BIGINT, t TEXT, v VARCHAR)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (11, 'This is', 'a test')")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (5, 'That was', 'a test')")); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (11, 'This is', 'a test')")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (5, 'That was', 'a test')")); // Save aside a copy of the original schema and data. - const std::string orig_schema(GetSchema(&db_)); + const std::string orig_schema(GetSchema(&db())); static const char kXSql[] = "SELECT * FROM x ORDER BY 1"; - const std::string orig_data(ExecuteWithResults(&db_, kXSql, "|", "\n")); + const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); // Create a lame-duck table which will not be propagated by recovery to // detect that the recovery code actually ran. - ASSERT_TRUE(db_.Execute("CREATE TABLE y (c TEXT)")); - ASSERT_NE(orig_schema, GetSchema(&db_)); + ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); + ASSERT_NE(orig_schema, GetSchema(&db())); { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); // Save a copy of the temp db's schema before recovering the table. @@ -465,25 +447,26 @@ EXPECT_EQ(temp_schema, ExecuteWithResults(recovery->db(), kTempSchemaSql, "|", "\n")); - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } // Since the database was not corrupt, the entire schema and all // data should be recovered. ASSERT_TRUE(Reopen()); - ASSERT_EQ(orig_schema, GetSchema(&db_)); - ASSERT_EQ(orig_data, ExecuteWithResults(&db_, kXSql, "|", "\n")); + ASSERT_EQ(orig_schema, GetSchema(&db())); + ASSERT_EQ(orig_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); // Recovery fails if the target table doesn't exist. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); // TODO(shess): Should this failure implicitly lead to Raze()? size_t rows = 0; EXPECT_FALSE(recovery->AutoRecoverTable("y", &rows)); - Recovery::Unrecoverable(std::move(recovery)); + sql::Recovery::Unrecoverable(std::move(recovery)); } } @@ -491,30 +474,30 @@ // virtual table reads directly from the database, so DEFAULT is not // interpretted at that level. TEST_F(SQLRecoveryTest, AutoRecoverTableWithDefault) { - ASSERT_TRUE(db_.Execute("CREATE TABLE x (id INTEGER)")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (5)")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (15)")); + ASSERT_TRUE(db().Execute("CREATE TABLE x (id INTEGER)")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (5)")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (15)")); // ALTER effectively leaves the new columns NULL in the first two // rows. The row with 17 will get the default injected at insert // time, while the row with 42 will get the actual value provided. // Embedded "'" to make sure default-handling continues to be quoted // correctly. - ASSERT_TRUE(db_.Execute("ALTER TABLE x ADD COLUMN t TEXT DEFAULT 'a''a'")); - ASSERT_TRUE(db_.Execute("ALTER TABLE x ADD COLUMN b BLOB DEFAULT x'AA55'")); - ASSERT_TRUE(db_.Execute("ALTER TABLE x ADD COLUMN i INT DEFAULT 93")); - ASSERT_TRUE(db_.Execute("INSERT INTO x (id) VALUES (17)")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (42, 'b', x'1234', 12)")); + ASSERT_TRUE(db().Execute("ALTER TABLE x ADD COLUMN t TEXT DEFAULT 'a''a'")); + ASSERT_TRUE(db().Execute("ALTER TABLE x ADD COLUMN b BLOB DEFAULT x'AA55'")); + ASSERT_TRUE(db().Execute("ALTER TABLE x ADD COLUMN i INT DEFAULT 93")); + ASSERT_TRUE(db().Execute("INSERT INTO x (id) VALUES (17)")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (42, 'b', x'1234', 12)")); // Save aside a copy of the original schema and data. - const std::string orig_schema(GetSchema(&db_)); + const std::string orig_schema(GetSchema(&db())); static const char kXSql[] = "SELECT * FROM x ORDER BY 1"; - const std::string orig_data(ExecuteWithResults(&db_, kXSql, "|", "\n")); + const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); // Create a lame-duck table which will not be propagated by recovery to // detect that the recovery code actually ran. - ASSERT_TRUE(db_.Execute("CREATE TABLE y (c TEXT)")); - ASSERT_NE(orig_schema, GetSchema(&db_)); + ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); + ASSERT_NE(orig_schema, GetSchema(&db())); // Mechanically adjust the stored schema and data to allow detecting // where the default value is coming from. The target table is just @@ -533,7 +516,8 @@ } { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); // Different default to detect which table provides the default. ASSERT_TRUE(recovery->db()->Execute(final_schema.c_str())); @@ -541,14 +525,14 @@ EXPECT_TRUE(recovery->AutoRecoverTable("x", &rows)); EXPECT_EQ(4u, rows); - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } // Since the database was not corrupt, the entire schema and all // data should be recovered. ASSERT_TRUE(Reopen()); - ASSERT_EQ(final_schema, GetSchema(&db_)); - ASSERT_EQ(final_data, ExecuteWithResults(&db_, kXSql, "|", "\n")); + ASSERT_EQ(final_schema, GetSchema(&db())); + ASSERT_EQ(final_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); } // Test that rows with NULL in a NOT NULL column are filtered @@ -560,33 +544,34 @@ static const char kFinalSchema[] = "CREATE TABLE x (id INTEGER, t TEXT NOT NULL)"; - ASSERT_TRUE(db_.Execute(kOrigSchema)); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (5, NULL)")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (15, 'this is a test')")); + ASSERT_TRUE(db().Execute(kOrigSchema)); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (5, NULL)")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (15, 'this is a test')")); // Create a lame-duck table which will not be propagated by recovery to // detect that the recovery code actually ran. - ASSERT_EQ(kOrigSchema, GetSchema(&db_)); - ASSERT_TRUE(db_.Execute("CREATE TABLE y (c TEXT)")); - ASSERT_NE(kOrigSchema, GetSchema(&db_)); + ASSERT_EQ(kOrigSchema, GetSchema(&db())); + ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); + ASSERT_NE(kOrigSchema, GetSchema(&db())); { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery->db()->Execute(kFinalSchema)); size_t rows = 0; EXPECT_TRUE(recovery->AutoRecoverTable("x", &rows)); EXPECT_EQ(1u, rows); - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } // The schema should be the same, but only one row of data should // have been recovered. ASSERT_TRUE(Reopen()); - ASSERT_EQ(kFinalSchema, GetSchema(&db_)); + ASSERT_EQ(kFinalSchema, GetSchema(&db())); static const char kXSql[] = "SELECT * FROM x ORDER BY 1"; - ASSERT_EQ("15|this is a test", ExecuteWithResults(&db_, kXSql, "|", "\n")); + ASSERT_EQ("15|this is a test", ExecuteWithResults(&db(), kXSql, "|", "\n")); } // Test AutoRecoverTable with a ROWID alias. @@ -595,36 +580,37 @@ // put it later. static const char kCreateSql[] = "CREATE TABLE x (t TEXT, id INTEGER PRIMARY KEY NOT NULL)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES ('This is a test', NULL)")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES ('That was a test', NULL)")); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('This is a test', NULL)")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('That was a test', NULL)")); // Save aside a copy of the original schema and data. - const std::string orig_schema(GetSchema(&db_)); + const std::string orig_schema(GetSchema(&db())); static const char kXSql[] = "SELECT * FROM x ORDER BY 1"; - const std::string orig_data(ExecuteWithResults(&db_, kXSql, "|", "\n")); + const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); // Create a lame-duck table which will not be propagated by recovery to // detect that the recovery code actually ran. - ASSERT_TRUE(db_.Execute("CREATE TABLE y (c TEXT)")); - ASSERT_NE(orig_schema, GetSchema(&db_)); + ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); + ASSERT_NE(orig_schema, GetSchema(&db())); { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); size_t rows = 0; EXPECT_TRUE(recovery->AutoRecoverTable("x", &rows)); EXPECT_EQ(2u, rows); - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } // Since the database was not corrupt, the entire schema and all // data should be recovered. ASSERT_TRUE(Reopen()); - ASSERT_EQ(orig_schema, GetSchema(&db_)); - ASSERT_EQ(orig_data, ExecuteWithResults(&db_, kXSql, "|", "\n")); + ASSERT_EQ(orig_schema, GetSchema(&db())); + ASSERT_EQ(orig_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); } // Test that a compound primary key doesn't fire the ROWID code. @@ -636,40 +622,41 @@ "t TEXT," "PRIMARY KEY (id, id2)" ")"; - ASSERT_TRUE(db_.Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kCreateSql)); // NOTE(shess): Do not accidentally use [id] 1, 2, 3, as those will // be the ROWID values. - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (1, 'a', 'This is a test')")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (1, 'b', 'That was a test')")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (2, 'a', 'Another test')")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (1, 'a', 'This is a test')")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (1, 'b', 'That was a test')")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (2, 'a', 'Another test')")); // Save aside a copy of the original schema and data. - const std::string orig_schema(GetSchema(&db_)); + const std::string orig_schema(GetSchema(&db())); static const char kXSql[] = "SELECT * FROM x ORDER BY 1"; - const std::string orig_data(ExecuteWithResults(&db_, kXSql, "|", "\n")); + const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); // Create a lame-duck table which will not be propagated by recovery to // detect that the recovery code actually ran. - ASSERT_TRUE(db_.Execute("CREATE TABLE y (c TEXT)")); - ASSERT_NE(orig_schema, GetSchema(&db_)); + ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); + ASSERT_NE(orig_schema, GetSchema(&db())); { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); size_t rows = 0; EXPECT_TRUE(recovery->AutoRecoverTable("x", &rows)); EXPECT_EQ(3u, rows); - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } // Since the database was not corrupt, the entire schema and all // data should be recovered. ASSERT_TRUE(Reopen()); - ASSERT_EQ(orig_schema, GetSchema(&db_)); - ASSERT_EQ(orig_data, ExecuteWithResults(&db_, kXSql, "|", "\n")); + ASSERT_EQ(orig_schema, GetSchema(&db())); + ASSERT_EQ(orig_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); } // Test recovering from a table with fewer columns than the target. @@ -678,45 +665,46 @@ "CREATE TABLE x (id INTEGER PRIMARY KEY, t0 TEXT)"; static const char kAlterSql[] = "ALTER TABLE x ADD COLUMN t1 TEXT DEFAULT 't'"; - ASSERT_TRUE(db_.Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (1, 'This is')")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES (2, 'That was')")); + ASSERT_TRUE(db().Execute(kCreateSql)); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (1, 'This is')")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (2, 'That was')")); // Generate the expected info by faking a table to match what recovery will // create. - const std::string orig_schema(GetSchema(&db_)); + const std::string orig_schema(GetSchema(&db())); static const char kXSql[] = "SELECT * FROM x ORDER BY 1"; std::string expected_schema; std::string expected_data; { - ASSERT_TRUE(db_.BeginTransaction()); - ASSERT_TRUE(db_.Execute(kAlterSql)); + ASSERT_TRUE(db().BeginTransaction()); + ASSERT_TRUE(db().Execute(kAlterSql)); - expected_schema = GetSchema(&db_); - expected_data = ExecuteWithResults(&db_, kXSql, "|", "\n"); + expected_schema = GetSchema(&db()); + expected_data = ExecuteWithResults(&db(), kXSql, "|", "\n"); - db_.RollbackTransaction(); + db().RollbackTransaction(); } // Following tests are pointless if the rollback didn't work. - ASSERT_EQ(orig_schema, GetSchema(&db_)); + ASSERT_EQ(orig_schema, GetSchema(&db())); // Recover the previous version of the table into the altered version. { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); ASSERT_TRUE(recovery->db()->Execute(kAlterSql)); size_t rows = 0; EXPECT_TRUE(recovery->AutoRecoverTable("x", &rows)); EXPECT_EQ(2u, rows); - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } // Since the database was not corrupt, the entire schema and all // data should be recovered. ASSERT_TRUE(Reopen()); - ASSERT_EQ(expected_schema, GetSchema(&db_)); - ASSERT_EQ(expected_data, ExecuteWithResults(&db_, kXSql, "|", "\n")); + ASSERT_EQ(expected_schema, GetSchema(&db())); + ASSERT_EQ(expected_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); } // Recover a golden file where an interior page has been manually modified so @@ -726,12 +714,13 @@ base::FilePath golden_path; ASSERT_TRUE(base::PathService::Get(sql::test::DIR_TEST_DATA, &golden_path)); golden_path = golden_path.AppendASCII("recovery_387868"); - db_.Close(); - ASSERT_TRUE(base::CopyFile(golden_path, db_path_)); + db().Close(); + ASSERT_TRUE(base::CopyFile(golden_path, db_path())); ASSERT_TRUE(Reopen()); { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery.get()); // Create the new version of the table. @@ -744,95 +733,96 @@ EXPECT_EQ(43u, rows); // Successfully recovered. - EXPECT_TRUE(Recovery::Recovered(std::move(recovery))); + EXPECT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } } // Memory-mapped I/O interacts poorly with I/O errors. Make sure the recovery // database doesn't accidentally enable it. TEST_F(SQLRecoveryTest, NoMmap) { - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::Begin(&db(), db_path()); ASSERT_TRUE(recovery.get()); // In the current implementation, the PRAGMA successfully runs with no result // rows. Running with a single result of |0| is also acceptable. - Statement s(recovery->db()->GetUniqueStatement("PRAGMA mmap_size")); + sql::Statement s(recovery->db()->GetUniqueStatement("PRAGMA mmap_size")); EXPECT_TRUE(!s.Step() || !s.ColumnInt64(0)); } TEST_F(SQLRecoveryTest, RecoverDatabase) { // As a side effect, AUTOINCREMENT creates the sqlite_sequence table for // RecoverDatabase() to handle. - ASSERT_TRUE(db_.Execute( + ASSERT_TRUE(db().Execute( "CREATE TABLE x (id INTEGER PRIMARY KEY AUTOINCREMENT, v TEXT)")); - EXPECT_TRUE(db_.Execute("INSERT INTO x (v) VALUES ('turtle')")); - EXPECT_TRUE(db_.Execute("INSERT INTO x (v) VALUES ('truck')")); - EXPECT_TRUE(db_.Execute("INSERT INTO x (v) VALUES ('trailer')")); + EXPECT_TRUE(db().Execute("INSERT INTO x (v) VALUES ('turtle')")); + EXPECT_TRUE(db().Execute("INSERT INTO x (v) VALUES ('truck')")); + EXPECT_TRUE(db().Execute("INSERT INTO x (v) VALUES ('trailer')")); // This table needs index and a unique index to work. - ASSERT_TRUE(db_.Execute("CREATE TABLE y (name TEXT, v TEXT)")); - ASSERT_TRUE(db_.Execute("CREATE UNIQUE INDEX y_name ON y(name)")); - ASSERT_TRUE(db_.Execute("CREATE INDEX y_v ON y(v)")); - EXPECT_TRUE(db_.Execute("INSERT INTO y VALUES ('jim', 'telephone')")); - EXPECT_TRUE(db_.Execute("INSERT INTO y VALUES ('bob', 'truck')")); - EXPECT_TRUE(db_.Execute("INSERT INTO y VALUES ('dean', 'trailer')")); + ASSERT_TRUE(db().Execute("CREATE TABLE y (name TEXT, v TEXT)")); + ASSERT_TRUE(db().Execute("CREATE UNIQUE INDEX y_name ON y(name)")); + ASSERT_TRUE(db().Execute("CREATE INDEX y_v ON y(v)")); + EXPECT_TRUE(db().Execute("INSERT INTO y VALUES ('jim', 'telephone')")); + EXPECT_TRUE(db().Execute("INSERT INTO y VALUES ('bob', 'truck')")); + EXPECT_TRUE(db().Execute("INSERT INTO y VALUES ('dean', 'trailer')")); // View which is the intersection of [x.v] and [y.v]. - ASSERT_TRUE( - db_.Execute("CREATE VIEW v AS SELECT x.v FROM x, y WHERE x.v = y.v")); + ASSERT_TRUE(db().Execute( + "CREATE VIEW v AS SELECT x.v FROM x, y WHERE x.v = y.v")); // When an element is deleted from [x], trigger a delete on [y]. Between the // BEGIN and END, [old] stands for the deleted rows from [x]. - ASSERT_TRUE( - db_.Execute("CREATE TRIGGER t AFTER DELETE ON x " - "BEGIN DELETE FROM y WHERE y.v = old.v; END")); + ASSERT_TRUE(db().Execute("CREATE TRIGGER t AFTER DELETE ON x " + "BEGIN DELETE FROM y WHERE y.v = old.v; END")); // Save aside a copy of the original schema, verifying that it has the created // items plus the sqlite_sequence table. - const std::string orig_schema(GetSchema(&db_)); + const std::string orig_schema(GetSchema(&db())); ASSERT_EQ(6, std::count(orig_schema.begin(), orig_schema.end(), '\n')); static const char kXSql[] = "SELECT * FROM x ORDER BY 1"; static const char kYSql[] = "SELECT * FROM y ORDER BY 1"; static const char kVSql[] = "SELECT * FROM v ORDER BY 1"; EXPECT_EQ("1|turtle\n2|truck\n3|trailer", - ExecuteWithResults(&db_, kXSql, "|", "\n")); + ExecuteWithResults(&db(), kXSql, "|", "\n")); EXPECT_EQ("bob|truck\ndean|trailer\njim|telephone", - ExecuteWithResults(&db_, kYSql, "|", "\n")); - EXPECT_EQ("trailer\ntruck", ExecuteWithResults(&db_, kVSql, "|", "\n")); + ExecuteWithResults(&db(), kYSql, "|", "\n")); + EXPECT_EQ("trailer\ntruck", ExecuteWithResults(&db(), kVSql, "|", "\n")); // Database handle is valid before recovery, poisoned after. static const char kTrivialSql[] = "SELECT COUNT(*) FROM sqlite_master"; - EXPECT_TRUE(db_.IsSQLValid(kTrivialSql)); - Recovery::RecoverDatabase(&db_, db_path_); - EXPECT_FALSE(db_.IsSQLValid(kTrivialSql)); + EXPECT_TRUE(db().IsSQLValid(kTrivialSql)); + sql::Recovery::RecoverDatabase(&db(), db_path()); + EXPECT_FALSE(db().IsSQLValid(kTrivialSql)); // Since the database was not corrupt, the entire schema and all // data should be recovered. ASSERT_TRUE(Reopen()); - ASSERT_EQ(orig_schema, GetSchema(&db_)); + ASSERT_EQ(orig_schema, GetSchema(&db())); EXPECT_EQ("1|turtle\n2|truck\n3|trailer", - ExecuteWithResults(&db_, kXSql, "|", "\n")); + ExecuteWithResults(&db(), kXSql, "|", "\n")); EXPECT_EQ("bob|truck\ndean|trailer\njim|telephone", - ExecuteWithResults(&db_, kYSql, "|", "\n")); - EXPECT_EQ("trailer\ntruck", ExecuteWithResults(&db_, kVSql, "|", "\n")); + ExecuteWithResults(&db(), kYSql, "|", "\n")); + EXPECT_EQ("trailer\ntruck", ExecuteWithResults(&db(), kVSql, "|", "\n")); // Test that the trigger works. - ASSERT_TRUE(db_.Execute("DELETE FROM x WHERE v = 'truck'")); - EXPECT_EQ("1|turtle\n3|trailer", ExecuteWithResults(&db_, kXSql, "|", "\n")); + ASSERT_TRUE(db().Execute("DELETE FROM x WHERE v = 'truck'")); + EXPECT_EQ("1|turtle\n3|trailer", + ExecuteWithResults(&db(), kXSql, "|", "\n")); EXPECT_EQ("dean|trailer\njim|telephone", - ExecuteWithResults(&db_, kYSql, "|", "\n")); - EXPECT_EQ("trailer", ExecuteWithResults(&db_, kVSql, "|", "\n")); + ExecuteWithResults(&db(), kYSql, "|", "\n")); + EXPECT_EQ("trailer", ExecuteWithResults(&db(), kVSql, "|", "\n")); } // When RecoverDatabase() encounters SQLITE_NOTADB, the database is deleted. TEST_F(SQLRecoveryTest, RecoverDatabaseDelete) { // Create a valid database, then write junk over the header. This should lead // to SQLITE_NOTADB, which will cause ATTACH to fail. - ASSERT_TRUE(db_.Execute("CREATE TABLE x (t TEXT)")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES ('This is a test')")); - db_.Close(); - ASSERT_TRUE(OverwriteDatabaseHeader()); + ASSERT_TRUE(db().Execute("CREATE TABLE x (t TEXT)")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('This is a test')")); + db().Close(); + WriteJunkToDatabase(SQLTestBase::TYPE_OVERWRITE); { sql::test::ScopedErrorExpecter expecter; @@ -842,74 +832,74 @@ ASSERT_TRUE(Reopen()); // This should "recover" the database by making it valid, but empty. - Recovery::RecoverDatabase(&db_, db_path_); + sql::Recovery::RecoverDatabase(&db(), db_path()); ASSERT_TRUE(expecter.SawExpectedErrors()); } // Recovery poisoned the handle, must re-open. - db_.Close(); + db().Close(); ASSERT_TRUE(Reopen()); - EXPECT_EQ("", GetSchema(&db_)); + EXPECT_EQ("", GetSchema(&db())); } // Allow callers to validate the database between recovery and commit. TEST_F(SQLRecoveryTest, BeginRecoverDatabase) { // Create a table with a broken index. - ASSERT_TRUE(db_.Execute("CREATE TABLE t (id INTEGER PRIMARY KEY, c TEXT)")); - ASSERT_TRUE(db_.Execute("CREATE UNIQUE INDEX t_id ON t (id)")); - ASSERT_TRUE(db_.Execute("INSERT INTO t VALUES (1, 'hello world')")); - ASSERT_TRUE(db_.Execute("INSERT INTO t VALUES (2, 'testing')")); - ASSERT_TRUE(db_.Execute("INSERT INTO t VALUES (3, 'nope')")); + ASSERT_TRUE(db().Execute("CREATE TABLE t (id INTEGER PRIMARY KEY, c TEXT)")); + ASSERT_TRUE(db().Execute("CREATE UNIQUE INDEX t_id ON t (id)")); + ASSERT_TRUE(db().Execute("INSERT INTO t VALUES (1, 'hello world')")); + ASSERT_TRUE(db().Execute("INSERT INTO t VALUES (2, 'testing')")); + ASSERT_TRUE(db().Execute("INSERT INTO t VALUES (3, 'nope')")); // Inject corruption into the index. - db_.Close(); + db().Close(); static const char kDeleteSql[] = "DELETE FROM t WHERE id = 3"; - ASSERT_TRUE(sql::test::CorruptTableOrIndex(db_path_, "t_id", kDeleteSql)); + ASSERT_TRUE(sql::test::CorruptTableOrIndex(db_path(), "t_id", kDeleteSql)); ASSERT_TRUE(Reopen()); // id as read from index. static const char kSelectIndexIdSql[] = "SELECT id FROM t INDEXED BY t_id"; - EXPECT_EQ("1,2,3", ExecuteWithResults(&db_, kSelectIndexIdSql, "|", ",")); + EXPECT_EQ("1,2,3", ExecuteWithResults(&db(), kSelectIndexIdSql, "|", ",")); // id as read from table. static const char kSelectTableIdSql[] = "SELECT id FROM t NOT INDEXED"; - EXPECT_EQ("1,2", ExecuteWithResults(&db_, kSelectTableIdSql, "|", ",")); + EXPECT_EQ("1,2", ExecuteWithResults(&db(), kSelectTableIdSql, "|", ",")); // Run recovery code, then rollback. Database remains the same. { - std::unique_ptr<Recovery> recovery = - Recovery::BeginRecoverDatabase(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::BeginRecoverDatabase(&db(), db_path()); ASSERT_TRUE(recovery); - Recovery::Rollback(std::move(recovery)); + sql::Recovery::Rollback(std::move(recovery)); } - db_.Close(); + db().Close(); ASSERT_TRUE(Reopen()); - EXPECT_EQ("1,2,3", ExecuteWithResults(&db_, kSelectIndexIdSql, "|", ",")); - EXPECT_EQ("1,2", ExecuteWithResults(&db_, kSelectTableIdSql, "|", ",")); + EXPECT_EQ("1,2,3", ExecuteWithResults(&db(), kSelectIndexIdSql, "|", ",")); + EXPECT_EQ("1,2", ExecuteWithResults(&db(), kSelectTableIdSql, "|", ",")); // Run recovery code, then commit. The failing row is dropped. { - std::unique_ptr<Recovery> recovery = - Recovery::BeginRecoverDatabase(&db_, db_path_); + std::unique_ptr<sql::Recovery> recovery = + sql::Recovery::BeginRecoverDatabase(&db(), db_path()); ASSERT_TRUE(recovery); - ASSERT_TRUE(Recovery::Recovered(std::move(recovery))); + ASSERT_TRUE(sql::Recovery::Recovered(std::move(recovery))); } - db_.Close(); + db().Close(); ASSERT_TRUE(Reopen()); - EXPECT_EQ("1,2", ExecuteWithResults(&db_, kSelectIndexIdSql, "|", ",")); - EXPECT_EQ("1,2", ExecuteWithResults(&db_, kSelectTableIdSql, "|", ",")); + EXPECT_EQ("1,2", ExecuteWithResults(&db(), kSelectIndexIdSql, "|", ",")); + EXPECT_EQ("1,2", ExecuteWithResults(&db(), kSelectTableIdSql, "|", ",")); } // Test histograms recorded when the invalid database cannot be attached. TEST_F(SQLRecoveryTest, AttachFailure) { // Create a valid database, then write junk over the header. This should lead // to SQLITE_NOTADB, which will cause ATTACH to fail. - ASSERT_TRUE(db_.Execute("CREATE TABLE x (t TEXT)")); - ASSERT_TRUE(db_.Execute("INSERT INTO x VALUES ('This is a test')")); - db_.Close(); - ASSERT_TRUE(OverwriteDatabaseHeader()); + ASSERT_TRUE(db().Execute("CREATE TABLE x (t TEXT)")); + ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('This is a test')")); + db().Close(); + WriteJunkToDatabase(SQLTestBase::TYPE_OVERWRITE); static const char kEventHistogramName[] = "Sqlite.RecoveryEvents"; const int kEventEnum = 5; // RECOVERY_FAILED_ATTACH @@ -924,7 +914,8 @@ ASSERT_TRUE(Reopen()); // Begin() should fail. - std::unique_ptr<Recovery> recovery = Recovery::Begin(&db_, db_path_); + std::unique_ptr<sql::Recovery> + recovery = sql::Recovery::Begin(&db(), db_path()); ASSERT_FALSE(recovery.get()); ASSERT_TRUE(expecter.SawExpectedErrors()); @@ -951,8 +942,8 @@ const base::FilePath db_path = db_prefix.InsertBeforeExtensionASCII( base::NumberToString(initial_page_size)); - Database::Delete(db_path); - Database db({.page_size = initial_page_size}); + sql::Database::Delete(db_path); + sql::Database db({.page_size = initial_page_size}); ASSERT_TRUE(db.Open(db_path)); ASSERT_TRUE(db.Execute(kCreateSql)); ASSERT_TRUE(db.Execute(kInsertSql1)); @@ -962,17 +953,18 @@ db.Close(); // Re-open the database while setting a new |options.page_size| in the object. - Database recover_db({.page_size = final_page_size}); + sql::Database recover_db({.page_size = final_page_size}); ASSERT_TRUE(recover_db.Open(db_path)); // Recovery will use the page size set in the database object, which may not // match the file's page size. - Recovery::RecoverDatabase(&recover_db, db_path); + sql::Recovery::RecoverDatabase(&recover_db, db_path); // Recovery poisoned the handle, must re-open. recover_db.Close(); // Make sure the page size is read from the file. - Database recovered_db({.page_size = DatabaseOptions::kDefaultPageSize}); + sql::Database recovered_db( + {.page_size = sql::DatabaseOptions::kDefaultPageSize}); ASSERT_TRUE(recovered_db.Open(db_path)); ASSERT_EQ(expected_final_page_size, ExecuteWithResult(&recovered_db, "PRAGMA page_size")); @@ -980,36 +972,34 @@ ExecuteWithResults(&recovered_db, kSelectSql, "|", "\n")); } -// Verify that Recovery maintains the page size, and the virtual table +// Verify that sql::Recovery maintains the page size, and the virtual table // works with page sizes other than SQLite's default. Also verify the case // where the default page size has changed. TEST_F(SQLRecoveryTest, PageSize) { const std::string default_page_size = - ExecuteWithResult(&db_, "PRAGMA page_size"); + ExecuteWithResult(&db(), "PRAGMA page_size"); // Check the default page size first. EXPECT_NO_FATAL_FAILURE(TestPageSize( - db_path_, DatabaseOptions::kDefaultPageSize, default_page_size, - DatabaseOptions::kDefaultPageSize, default_page_size)); + db_path(), sql::DatabaseOptions::kDefaultPageSize, default_page_size, + sql::DatabaseOptions::kDefaultPageSize, default_page_size)); // Sync uses 32k pages. EXPECT_NO_FATAL_FAILURE( - TestPageSize(db_path_, 32768, "32768", 32768, "32768")); + TestPageSize(db_path(), 32768, "32768", 32768, "32768")); // Many clients use 4k pages. This is the SQLite default after 3.12.0. - EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 4096, "4096", 4096, "4096")); + EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 4096, "4096", 4096, "4096")); // 1k is the default page size before 3.12.0. - EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 1024, "1024", 1024, "1024")); + EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 1024, "1024", 1024, "1024")); // Databases with no page size specified should recover with the new default // page size. 2k has never been the default page size. ASSERT_NE("2048", default_page_size); - EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048", - DatabaseOptions::kDefaultPageSize, + EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 2048, "2048", + sql::DatabaseOptions::kDefaultPageSize, default_page_size)); } } // namespace - -} // namespace sql
diff --git a/sql/sql_memory_dump_provider_unittest.cc b/sql/sql_memory_dump_provider_unittest.cc index 6929639..c361253 100644 --- a/sql/sql_memory_dump_provider_unittest.cc +++ b/sql/sql_memory_dump_provider_unittest.cc
@@ -4,41 +4,19 @@ #include "sql/sql_memory_dump_provider.h" -#include "base/files/scoped_temp_dir.h" -#include "base/trace_event/memory_dump_request_args.h" #include "base/trace_event/process_memory_dump.h" -#include "sql/database.h" +#include "sql/test/sql_test_base.h" #include "testing/gtest/include/gtest/gtest.h" -namespace sql { - namespace { - -class SQLMemoryDumpProviderTest : public testing::Test { - public: - ~SQLMemoryDumpProviderTest() override = default; - - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE(db_.Open( - temp_dir_.GetPath().AppendASCII("memory_dump_provider_test.sqlite"))); - - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - } - - protected: - base::ScopedTempDir temp_dir_; - Database db_; -}; +using SQLMemoryDumpProviderTest = sql::SQLTestBase; +} TEST_F(SQLMemoryDumpProviderTest, OnMemoryDump) { base::trace_event::MemoryDumpArgs args = { base::trace_event::MemoryDumpLevelOfDetail::DETAILED}; base::trace_event::ProcessMemoryDump pmd(args); - ASSERT_TRUE(SqlMemoryDumpProvider::GetInstance()->OnMemoryDump(args, &pmd)); + ASSERT_TRUE( + sql::SqlMemoryDumpProvider::GetInstance()->OnMemoryDump(args, &pmd)); ASSERT_TRUE(pmd.GetAllocatorDump("sqlite")); } - -} // namespace - -} // namespace sql
diff --git a/sql/sqlite_features_unittest.cc b/sql/sqlite_features_unittest.cc index a84a51b..877ec67 100644 --- a/sql/sqlite_features_unittest.cc +++ b/sql/sqlite_features_unittest.cc
@@ -8,13 +8,13 @@ #include <string> #include "base/bind.h" -#include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/memory_mapped_file.h" #include "base/files/scoped_temp_dir.h" #include "build/build_config.h" #include "sql/database.h" #include "sql/statement.h" +#include "sql/test/sql_test_base.h" #include "sql/test/test_helpers.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/sqlite/sqlite3.h" @@ -40,18 +40,16 @@ } // namespace -class SQLiteFeaturesTest : public testing::Test { +class SQLiteFeaturesTest : public sql::SQLTestBase { public: - ~SQLiteFeaturesTest() override = default; + SQLiteFeaturesTest() : error_(SQLITE_OK) {} void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - db_path_ = temp_dir_.GetPath().AppendASCII("sqlite_features_test.sqlite"); - ASSERT_TRUE(db_.Open(db_path_)); + SQLTestBase::SetUp(); // The error delegate will set |error_| and |sql_text_| when any sqlite // statement operation returns an error code. - db_.set_error_callback( + db().set_error_callback( base::BindRepeating(&CaptureErrorCallback, &error_, &sql_text_)); } @@ -59,20 +57,15 @@ // If any error happened the original sql statement can be found in // |sql_text_|. EXPECT_EQ(SQLITE_OK, error_) << sql_text_; + + SQLTestBase::TearDown(); } - bool Reopen() { - db_.Close(); - return db_.Open(db_path_); - } + int error() { return error_; } - protected: - base::ScopedTempDir temp_dir_; - base::FilePath db_path_; - Database db_; - + private: // The error code of the most recent error. - int error_ = SQLITE_OK; + int error_; // Original statement which has caused the error. std::string sql_text_; }; @@ -80,20 +73,21 @@ // Do not include fts1 support, it is not useful, and nobody is // looking at it. TEST_F(SQLiteFeaturesTest, NoFTS1) { - ASSERT_EQ(SQLITE_ERROR, db_.ExecuteAndReturnErrorCode( - "CREATE VIRTUAL TABLE foo USING fts1(x)")); + ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode( + "CREATE VIRTUAL TABLE foo USING fts1(x)")); } // Do not include fts2 support, it is not useful, and nobody is // looking at it. TEST_F(SQLiteFeaturesTest, NoFTS2) { - ASSERT_EQ(SQLITE_ERROR, db_.ExecuteAndReturnErrorCode( - "CREATE VIRTUAL TABLE foo USING fts2(x)")); + ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode( + "CREATE VIRTUAL TABLE foo USING fts2(x)")); } -// fts3 is exposed in WebSQL. +// fts3 used to be used for history files, and may also be used by WebDatabase +// clients. TEST_F(SQLiteFeaturesTest, FTS3) { - ASSERT_TRUE(db_.Execute("CREATE VIRTUAL TABLE foo USING fts3(x)")); + ASSERT_TRUE(db().Execute("CREATE VIRTUAL TABLE foo USING fts3(x)")); } // Originally history used fts2, which Chromium patched to treat "foo*" as a @@ -102,12 +96,12 @@ TEST_F(SQLiteFeaturesTest, FTS3_Prefix) { static const char kCreateSql[] = "CREATE VIRTUAL TABLE foo USING fts3(x, tokenize icu)"; - ASSERT_TRUE(db_.Execute(kCreateSql)); + ASSERT_TRUE(db().Execute(kCreateSql)); - ASSERT_TRUE(db_.Execute("INSERT INTO foo (x) VALUES ('test')")); + ASSERT_TRUE(db().Execute("INSERT INTO foo (x) VALUES ('test')")); EXPECT_EQ("test", - ExecuteWithResult(&db_, "SELECT x FROM foo WHERE x MATCH 'te*'")); + ExecuteWithResult(&db(), "SELECT x FROM foo WHERE x MATCH 'te*'")); } // Verify that Chromium's SQLite is compiled with HAVE_USLEEP defined. With @@ -127,9 +121,9 @@ // Ensure that our SQLite version has working foreign key support with cascade // delete support. TEST_F(SQLiteFeaturesTest, ForeignKeySupport) { - ASSERT_TRUE(db_.Execute("PRAGMA foreign_keys=1")); - ASSERT_TRUE(db_.Execute("CREATE TABLE parents (id INTEGER PRIMARY KEY)")); - ASSERT_TRUE(db_.Execute( + ASSERT_TRUE(db().Execute("PRAGMA foreign_keys=1")); + ASSERT_TRUE(db().Execute("CREATE TABLE parents (id INTEGER PRIMARY KEY)")); + ASSERT_TRUE(db().Execute( "CREATE TABLE children (" " id INTEGER PRIMARY KEY," " pid INTEGER NOT NULL REFERENCES parents(id) ON DELETE CASCADE)")); @@ -137,40 +131,40 @@ static const char kSelectChildrenSql[] = "SELECT * FROM children ORDER BY id"; // Inserting without a matching parent should fail with constraint violation. - EXPECT_EQ("", ExecuteWithResult(&db_, kSelectParentsSql)); + EXPECT_EQ("", ExecuteWithResult(&db(), kSelectParentsSql)); const int insert_error = - db_.ExecuteAndReturnErrorCode("INSERT INTO children VALUES (10, 1)"); + db().ExecuteAndReturnErrorCode("INSERT INTO children VALUES (10, 1)"); EXPECT_EQ(SQLITE_CONSTRAINT | SQLITE_CONSTRAINT_FOREIGNKEY, insert_error); - EXPECT_EQ("", ExecuteWithResult(&db_, kSelectChildrenSql)); + EXPECT_EQ("", ExecuteWithResult(&db(), kSelectChildrenSql)); // Inserting with a matching parent should work. - ASSERT_TRUE(db_.Execute("INSERT INTO parents VALUES (1)")); - EXPECT_EQ("1", ExecuteWithResults(&db_, kSelectParentsSql, "|", "\n")); - EXPECT_TRUE(db_.Execute("INSERT INTO children VALUES (11, 1)")); - EXPECT_TRUE(db_.Execute("INSERT INTO children VALUES (12, 1)")); + ASSERT_TRUE(db().Execute("INSERT INTO parents VALUES (1)")); + EXPECT_EQ("1", ExecuteWithResults(&db(), kSelectParentsSql, "|", "\n")); + EXPECT_TRUE(db().Execute("INSERT INTO children VALUES (11, 1)")); + EXPECT_TRUE(db().Execute("INSERT INTO children VALUES (12, 1)")); EXPECT_EQ("11|1\n12|1", - ExecuteWithResults(&db_, kSelectChildrenSql, "|", "\n")); + ExecuteWithResults(&db(), kSelectChildrenSql, "|", "\n")); // Deleting the parent should cascade, deleting the children as well. - ASSERT_TRUE(db_.Execute("DELETE FROM parents")); - EXPECT_EQ("", ExecuteWithResult(&db_, kSelectParentsSql)); - EXPECT_EQ("", ExecuteWithResult(&db_, kSelectChildrenSql)); + ASSERT_TRUE(db().Execute("DELETE FROM parents")); + EXPECT_EQ("", ExecuteWithResult(&db(), kSelectParentsSql)); + EXPECT_EQ("", ExecuteWithResult(&db(), kSelectChildrenSql)); } // Ensure that our SQLite version supports booleans. TEST_F(SQLiteFeaturesTest, BooleanSupport) { ASSERT_TRUE( - db_.Execute("CREATE TABLE flags (" - " id INTEGER PRIMARY KEY," - " true_flag BOOL NOT NULL DEFAULT TRUE," - " false_flag BOOL NOT NULL DEFAULT FALSE)")); - ASSERT_TRUE(db_.Execute( + db().Execute("CREATE TABLE flags (" + " id INTEGER PRIMARY KEY," + " true_flag BOOL NOT NULL DEFAULT TRUE," + " false_flag BOOL NOT NULL DEFAULT FALSE)")); + ASSERT_TRUE(db().Execute( "ALTER TABLE flags ADD COLUMN true_flag2 BOOL NOT NULL DEFAULT TRUE")); - ASSERT_TRUE(db_.Execute( + ASSERT_TRUE(db().Execute( "ALTER TABLE flags ADD COLUMN false_flag2 BOOL NOT NULL DEFAULT FALSE")); - ASSERT_TRUE(db_.Execute("INSERT INTO flags (id) VALUES (1)")); + ASSERT_TRUE(db().Execute("INSERT INTO flags (id) VALUES (1)")); - sql::Statement s(db_.GetUniqueStatement( + sql::Statement s(db().GetUniqueStatement( "SELECT true_flag, false_flag, true_flag2, false_flag2" " FROM flags WHERE id=1;")); ASSERT_TRUE(s.Step()); @@ -183,11 +177,13 @@ } TEST_F(SQLiteFeaturesTest, IcuEnabled) { - sql::Statement lower_en(db_.GetUniqueStatement("SELECT lower('I', 'en_us')")); + sql::Statement lower_en( + db().GetUniqueStatement("SELECT lower('I', 'en_us')")); ASSERT_TRUE(lower_en.Step()); EXPECT_EQ("i", lower_en.ColumnString(0)); - sql::Statement lower_tr(db_.GetUniqueStatement("SELECT lower('I', 'tr_tr')")); + sql::Statement lower_tr( + db().GetUniqueStatement("SELECT lower('I', 'tr_tr')")); ASSERT_TRUE(lower_tr.Step()); EXPECT_EQ("\u0131", lower_tr.ColumnString(0)); } @@ -200,14 +196,14 @@ // be disabled on this platform using SQLITE_MAX_MMAP_SIZE=0. TEST_F(SQLiteFeaturesTest, Mmap) { // Try to turn on mmap'ed I/O. - ignore_result(db_.Execute("PRAGMA mmap_size = 1048576")); + ignore_result(db().Execute("PRAGMA mmap_size = 1048576")); { - sql::Statement s(db_.GetUniqueStatement("PRAGMA mmap_size")); + sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size")); ASSERT_TRUE(s.Step()); ASSERT_GT(s.ColumnInt64(0), 0); } - db_.Close(); + db().Close(); const uint32_t kFlags = base::File::FLAG_OPEN | base::File::FLAG_READ | base::File::FLAG_WRITE; @@ -215,7 +211,7 @@ // Create a file with a block of '0', a block of '1', and a block of '2'. { - base::File f(db_path_, kFlags); + base::File f(db_path(), kFlags); ASSERT_TRUE(f.IsValid()); memset(buf, '0', sizeof(buf)); ASSERT_EQ(f.Write(0*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf)); @@ -230,7 +226,7 @@ // mmap the file and verify that everything looks right. { base::MemoryMappedFile m; - ASSERT_TRUE(m.Initialize(db_path_)); + ASSERT_TRUE(m.Initialize(db_path())); memset(buf, '0', sizeof(buf)); ASSERT_EQ(0, memcmp(buf, m.data() + 0*sizeof(buf), sizeof(buf))); @@ -244,7 +240,7 @@ // Scribble some '3' into the first page of the file, and verify that it // looks the same in the memory mapping. { - base::File f(db_path_, kFlags); + base::File f(db_path(), kFlags); ASSERT_TRUE(f.IsValid()); memset(buf, '3', sizeof(buf)); ASSERT_EQ(f.Write(0*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf)); @@ -255,7 +251,7 @@ const size_t kOffset = 1*sizeof(buf) + 123; ASSERT_NE('4', m.data()[kOffset]); { - base::File f(db_path_, kFlags); + base::File f(db_path(), kFlags); ASSERT_TRUE(f.IsValid()); buf[0] = '4'; ASSERT_EQ(f.Write(kOffset, buf, 1), 1); @@ -268,14 +264,14 @@ // compiled regular expression is effectively cached with the prepared // statement, causing errors if the regular expression is rebound. TEST_F(SQLiteFeaturesTest, CachedRegexp) { - ASSERT_TRUE(db_.Execute("CREATE TABLE r (id INTEGER UNIQUE, x TEXT)")); - ASSERT_TRUE(db_.Execute("INSERT INTO r VALUES (1, 'this is a test')")); - ASSERT_TRUE(db_.Execute("INSERT INTO r VALUES (2, 'that was a test')")); - ASSERT_TRUE(db_.Execute("INSERT INTO r VALUES (3, 'this is a stickup')")); - ASSERT_TRUE(db_.Execute("INSERT INTO r VALUES (4, 'that sucks')")); + ASSERT_TRUE(db().Execute("CREATE TABLE r (id INTEGER UNIQUE, x TEXT)")); + ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (1, 'this is a test')")); + ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (2, 'that was a test')")); + ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (3, 'this is a stickup')")); + ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (4, 'that sucks')")); static const char kSimpleSql[] = "SELECT SUM(id) FROM r WHERE x REGEXP ?"; - sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE, kSimpleSql)); + sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql)); s.BindString(0, "this.*"); ASSERT_TRUE(s.Step()); @@ -301,26 +297,26 @@ // If a database file is marked to be excluded from Time Machine, verify that // journal files are also excluded. TEST_F(SQLiteFeaturesTest, TimeMachine) { - ASSERT_TRUE(db_.Execute("CREATE TABLE t (id INTEGER PRIMARY KEY)")); - db_.Close(); + ASSERT_TRUE(db().Execute("CREATE TABLE t (id INTEGER PRIMARY KEY)")); + db().Close(); - base::FilePath journal_path = sql::Database::JournalPath(db_path_); - ASSERT_TRUE(base::PathExists(db_path_)); - ASSERT_TRUE(base::PathExists(journal_path)); + base::FilePath journal_path = sql::Database::JournalPath(db_path()); + ASSERT_TRUE(GetPathExists(db_path())); + ASSERT_TRUE(GetPathExists(journal_path)); // Not excluded to start. - EXPECT_FALSE(base::mac::GetFileBackupExclusion(db_path_)); + EXPECT_FALSE(base::mac::GetFileBackupExclusion(db_path())); EXPECT_FALSE(base::mac::GetFileBackupExclusion(journal_path)); // Exclude the main database file. - EXPECT_TRUE(base::mac::SetFileBackupExclusion(db_path_)); + EXPECT_TRUE(base::mac::SetFileBackupExclusion(db_path())); - EXPECT_TRUE(base::mac::GetFileBackupExclusion(db_path_)); + EXPECT_TRUE(base::mac::GetFileBackupExclusion(db_path())); EXPECT_FALSE(base::mac::GetFileBackupExclusion(journal_path)); - EXPECT_TRUE(db_.Open(db_path_)); - ASSERT_TRUE(db_.Execute("INSERT INTO t VALUES (1)")); - EXPECT_TRUE(base::mac::GetFileBackupExclusion(db_path_)); + EXPECT_TRUE(db().Open(db_path())); + ASSERT_TRUE(db().Execute("INSERT INTO t VALUES (1)")); + EXPECT_TRUE(base::mac::GetFileBackupExclusion(db_path())); EXPECT_TRUE(base::mac::GetFileBackupExclusion(journal_path)); // TODO(shess): In WAL mode this will touch -wal and -shm files. -shm files @@ -333,30 +329,30 @@ // additional work into Chromium shutdown. Verify that SQLite supports a config // option to not checkpoint on close. TEST_F(SQLiteFeaturesTest, WALNoClose) { - base::FilePath wal_path = sql::Database::WriteAheadLogPath(db_path_); + base::FilePath wal_path = sql::Database::WriteAheadLogPath(db_path()); // Turn on WAL mode, then verify that the mode changed (WAL is supported). - ASSERT_TRUE(db_.Execute("PRAGMA journal_mode = WAL")); - ASSERT_EQ("wal", ExecuteWithResult(&db_, "PRAGMA journal_mode")); + ASSERT_TRUE(db().Execute("PRAGMA journal_mode = WAL")); + ASSERT_EQ("wal", ExecuteWithResult(&db(), "PRAGMA journal_mode")); // The WAL file is created lazily on first change. - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); // By default, the WAL is checkpointed then deleted on close. - ASSERT_TRUE(base::PathExists(wal_path)); - db_.Close(); - ASSERT_FALSE(base::PathExists(wal_path)); + ASSERT_TRUE(GetPathExists(wal_path)); + db().Close(); + ASSERT_FALSE(GetPathExists(wal_path)); // Reopen and configure the database to not checkpoint WAL on close. ASSERT_TRUE(Reopen()); - ASSERT_TRUE(db_.Execute("PRAGMA journal_mode = WAL")); - ASSERT_TRUE(db_.Execute("ALTER TABLE foo ADD COLUMN c")); - ASSERT_EQ( - SQLITE_OK, - sqlite3_db_config(db_.db_, SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, 1, nullptr)); - ASSERT_TRUE(base::PathExists(wal_path)); - db_.Close(); - ASSERT_TRUE(base::PathExists(wal_path)); + ASSERT_TRUE(db().Execute("PRAGMA journal_mode = WAL")); + ASSERT_TRUE(db().Execute("ALTER TABLE foo ADD COLUMN c")); + ASSERT_EQ(SQLITE_OK, + sqlite3_db_config(db().db_, SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, 1, + nullptr)); + ASSERT_TRUE(GetPathExists(wal_path)); + db().Close(); + ASSERT_TRUE(GetPathExists(wal_path)); } #endif
diff --git a/sql/statement_unittest.cc b/sql/statement_unittest.cc index af85326..2033ee3 100644 --- a/sql/statement_unittest.cc +++ b/sql/statement_unittest.cc
@@ -11,40 +11,29 @@ #include "sql/statement.h" #include "sql/test/error_callback_support.h" #include "sql/test/scoped_error_expecter.h" +#include "sql/test/sql_test_base.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/sqlite/sqlite3.h" -namespace sql { namespace { -class SQLStatementTest : public testing::Test { - public: - ~SQLStatementTest() override = default; +using SQLStatementTest = sql::SQLTestBase; - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE( - db_.Open(temp_dir_.GetPath().AppendASCII("statement_test.sqlite"))); - } - - protected: - base::ScopedTempDir temp_dir_; - Database db_; -}; +} // namespace TEST_F(SQLStatementTest, Assign) { - Statement s; + sql::Statement s; EXPECT_FALSE(s.is_valid()); - s.Assign(db_.GetUniqueStatement("CREATE TABLE foo (a, b)")); + s.Assign(db().GetUniqueStatement("CREATE TABLE foo (a, b)")); EXPECT_TRUE(s.is_valid()); } TEST_F(SQLStatementTest, Run) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - ASSERT_TRUE(db_.Execute("INSERT INTO foo (a, b) VALUES (3, 12)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (3, 12)")); - Statement s(db_.GetUniqueStatement("SELECT b FROM foo WHERE a=?")); + sql::Statement s(db().GetUniqueStatement("SELECT b FROM foo WHERE a=?")); EXPECT_FALSE(s.Succeeded()); // Stepping it won't work since we haven't bound the value. @@ -55,7 +44,7 @@ s.Reset(true); s.BindInt(0, 3); EXPECT_FALSE(s.Run()); - EXPECT_EQ(SQLITE_ROW, db_.GetErrorCode()); + EXPECT_EQ(SQLITE_ROW, db().GetErrorCode()); EXPECT_TRUE(s.Succeeded()); // Resetting it should put it back to the previous state (not runnable). @@ -73,16 +62,16 @@ // Error callback called for error running a statement. TEST_F(SQLStatementTest, ErrorCallback) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a INTEGER PRIMARY KEY, b)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a INTEGER PRIMARY KEY, b)")); int error = SQLITE_OK; - ScopedErrorCallback sec(&db_, - base::BindRepeating(&CaptureErrorCallback, &error)); + sql::ScopedErrorCallback sec( + &db(), base::BindRepeating(&sql::CaptureErrorCallback, &error)); // Insert in the foo table the primary key. It is an error to insert // something other than an number. This error causes the error callback // handler to be called with SQLITE_MISMATCH as error code. - Statement s(db_.GetUniqueStatement("INSERT INTO foo (a) VALUES (?)")); + sql::Statement s(db().GetUniqueStatement("INSERT INTO foo (a) VALUES (?)")); EXPECT_TRUE(s.is_valid()); s.BindCString(0, "bad bad"); EXPECT_FALSE(s.Run()); @@ -91,9 +80,9 @@ // Error expecter works for error running a statement. TEST_F(SQLStatementTest, ScopedIgnoreError) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a INTEGER PRIMARY KEY, b)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a INTEGER PRIMARY KEY, b)")); - Statement s(db_.GetUniqueStatement("INSERT INTO foo (a) VALUES (?)")); + sql::Statement s(db().GetUniqueStatement("INSERT INTO foo (a) VALUES (?)")); EXPECT_TRUE(s.is_valid()); { @@ -106,11 +95,12 @@ } TEST_F(SQLStatementTest, Reset) { - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); - ASSERT_TRUE(db_.Execute("INSERT INTO foo (a, b) VALUES (3, 12)")); - ASSERT_TRUE(db_.Execute("INSERT INTO foo (a, b) VALUES (4, 13)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (3, 12)")); + ASSERT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (4, 13)")); - Statement s(db_.GetUniqueStatement("SELECT b FROM foo WHERE a = ? ")); + sql::Statement s(db().GetUniqueStatement( + "SELECT b FROM foo WHERE a = ? ")); s.BindInt(0, 3); ASSERT_TRUE(s.Step()); EXPECT_EQ(12, s.ColumnInt(0)); @@ -125,6 +115,3 @@ s.Reset(true); ASSERT_FALSE(s.Step()); } - -} // namespace -} // namespace sql
diff --git a/sql/test/sql_test_base.cc b/sql/test/sql_test_base.cc new file mode 100644 index 0000000..ef32741 --- /dev/null +++ b/sql/test/sql_test_base.cc
@@ -0,0 +1,66 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "sql/test/sql_test_base.h" + +#include "base/files/file_util.h" +#include "sql/test/test_helpers.h" + +namespace sql { + +SQLTestBase::SQLTestBase() = default; + +SQLTestBase::SQLTestBase(sql::DatabaseOptions options) : db_(options) {} + +SQLTestBase::~SQLTestBase() = default; + +base::FilePath SQLTestBase::db_path() { + return temp_dir_.GetPath().AppendASCII("SQLTest.db"); +} + +sql::Database& SQLTestBase::db() { + return db_; +} + +bool SQLTestBase::Reopen() { + db_.Close(); + return db_.Open(db_path()); +} + +bool SQLTestBase::GetPathExists(const base::FilePath& path) { + return base::PathExists(path); +} + +bool SQLTestBase::CorruptSizeInHeaderOfDB() { + return sql::test::CorruptSizeInHeader(db_path()); +} + +void SQLTestBase::WriteJunkToDatabase(WriteJunkType type) { + base::ScopedFILE file(base::OpenFile( + db_path(), + type == TYPE_OVERWRITE_AND_TRUNCATE ? "wb" : "rb+")); + ASSERT_TRUE(file.get()); + ASSERT_EQ(0, fseek(file.get(), 0, SEEK_SET)); + + const char* kJunk = "Now is the winter of our discontent."; + fputs(kJunk, file.get()); +} + +void SQLTestBase::TruncateDatabase() { + base::ScopedFILE file(base::OpenFile(db_path(), "rb+")); + ASSERT_TRUE(file); + ASSERT_EQ(0, fseek(file.get(), 0, SEEK_SET)); + ASSERT_TRUE(base::TruncateFile(file.get())); +} + +void SQLTestBase::SetUp() { + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + ASSERT_TRUE(db_.Open(db_path())); +} + +void SQLTestBase::TearDown() { + db_.Close(); +} + +} // namespace sql
diff --git a/sql/test/sql_test_base.h b/sql/test/sql_test_base.h new file mode 100644 index 0000000..cf35f1e --- /dev/null +++ b/sql/test/sql_test_base.h
@@ -0,0 +1,77 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SQL_TEST_SQL_TEST_BASE_H_ +#define SQL_TEST_SQL_TEST_BASE_H_ + +#include "base/files/file_path.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "sql/database.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace sql { + +// Base class for SQL tests. +// +// WARNING: We want to run the same gtest based unit test code both against +// chromium (which uses this implementation here), and the mojo code (which +// uses a different class named SQLTestBase). These two classes need to have +// the same interface because we compile time switch them based on a +// #define. We need to have two different implementations because the mojo +// version derives from mojo::test::ApplicationTestBase instead of +// testing::Test. +class SQLTestBase : public testing::Test { + public: + SQLTestBase(); + explicit SQLTestBase(sql::DatabaseOptions options); + ~SQLTestBase() override; + + enum WriteJunkType { + TYPE_OVERWRITE_AND_TRUNCATE, + TYPE_OVERWRITE + }; + + // Returns the path to the database. + base::FilePath db_path(); + + // Returns a connection to the database at db_path(). + sql::Database& db(); + + // Closes the current connection to the database and reopens it. + bool Reopen(); + + // Proxying method around base::PathExists. + bool GetPathExists(const base::FilePath& path); + + // SQLite stores the database size in the header, and if the actual + // OS-derived size is smaller, the database is considered corrupt. + // [This case is actually a common form of corruption in the wild.] + // This helper sets the in-header size to one page larger than the + // actual file size. The resulting file will return SQLITE_CORRUPT + // for most operations unless PRAGMA writable_schema is turned ON. + // + // Returns false if any error occurs accessing the file. + bool CorruptSizeInHeaderOfDB(); + + // Writes junk to the start of the file. + void WriteJunkToDatabase(WriteJunkType type); + + // Sets the database file size to 0. + void TruncateDatabase(); + + // Overridden from testing::Test: + void SetUp() override; + void TearDown() override; + + private: + base::ScopedTempDir temp_dir_; + sql::Database db_; + + DISALLOW_COPY_AND_ASSIGN(SQLTestBase); +}; + +} // namespace sql + +#endif // SQL_TEST_SQL_TEST_BASE_H_
diff --git a/sql/transaction_unittest.cc b/sql/transaction_unittest.cc index 48f75da2..bcc05f58 100644 --- a/sql/transaction_unittest.cc +++ b/sql/transaction_unittest.cc
@@ -3,50 +3,38 @@ // found in the LICENSE file. #include "sql/transaction.h" - #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "sql/database.h" #include "sql/statement.h" +#include "sql/test/sql_test_base.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/sqlite/sqlite3.h" -namespace sql { - -namespace { - -class SQLTransactionTest : public testing::Test { +class SQLTransactionTest : public sql::SQLTestBase { public: - ~SQLTransactionTest() override = default; - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE( - db_.Open(temp_dir_.GetPath().AppendASCII("transaction_test.sqlite"))); + SQLTestBase::SetUp(); - ASSERT_TRUE(db_.Execute("CREATE TABLE foo (a, b)")); + ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); } // Returns the number of rows in table "foo". int CountFoo() { - Statement count(db_.GetUniqueStatement("SELECT count(*) FROM foo")); + sql::Statement count(db().GetUniqueStatement("SELECT count(*) FROM foo")); count.Step(); return count.ColumnInt(0); } - - protected: - base::ScopedTempDir temp_dir_; - Database db_; }; TEST_F(SQLTransactionTest, Commit) { { - Transaction t(&db_); + sql::Transaction t(&db()); EXPECT_FALSE(t.is_open()); EXPECT_TRUE(t.Begin()); EXPECT_TRUE(t.is_open()); - EXPECT_TRUE(db_.Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); + EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); t.Commit(); EXPECT_FALSE(t.is_open()); @@ -59,23 +47,23 @@ // Test some basic initialization, and that rollback runs when you exit the // scope. { - Transaction t(&db_); + sql::Transaction t(&db()); EXPECT_FALSE(t.is_open()); EXPECT_TRUE(t.Begin()); EXPECT_TRUE(t.is_open()); - EXPECT_TRUE(db_.Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); + EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); } // Nothing should have been committed since it was implicitly rolled back. EXPECT_EQ(0, CountFoo()); // Test explicit rollback. - Transaction t2(&db_); + sql::Transaction t2(&db()); EXPECT_FALSE(t2.is_open()); EXPECT_TRUE(t2.Begin()); - EXPECT_TRUE(db_.Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); + EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); t2.Rollback(); EXPECT_FALSE(t2.is_open()); @@ -85,23 +73,23 @@ // Rolling back any part of a transaction should roll back all of them. TEST_F(SQLTransactionTest, NestedRollback) { - EXPECT_EQ(0, db_.transaction_nesting()); + EXPECT_EQ(0, db().transaction_nesting()); // Outermost transaction. { - Transaction outer(&db_); + sql::Transaction outer(&db()); EXPECT_TRUE(outer.Begin()); - EXPECT_EQ(1, db_.transaction_nesting()); + EXPECT_EQ(1, db().transaction_nesting()); // The first inner one gets committed. { - Transaction inner1(&db_); + sql::Transaction inner1(&db()); EXPECT_TRUE(inner1.Begin()); - EXPECT_TRUE(db_.Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); - EXPECT_EQ(2, db_.transaction_nesting()); + EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); + EXPECT_EQ(2, db().transaction_nesting()); inner1.Commit(); - EXPECT_EQ(1, db_.transaction_nesting()); + EXPECT_EQ(1, db().transaction_nesting()); } // One row should have gotten inserted. @@ -109,28 +97,24 @@ // The second inner one gets rolled back. { - Transaction inner2(&db_); + sql::Transaction inner2(&db()); EXPECT_TRUE(inner2.Begin()); - EXPECT_TRUE(db_.Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); - EXPECT_EQ(2, db_.transaction_nesting()); + EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); + EXPECT_EQ(2, db().transaction_nesting()); inner2.Rollback(); - EXPECT_EQ(1, db_.transaction_nesting()); + EXPECT_EQ(1, db().transaction_nesting()); } // A third inner one will fail in Begin since one has already been rolled // back. - EXPECT_EQ(1, db_.transaction_nesting()); + EXPECT_EQ(1, db().transaction_nesting()); { - Transaction inner3(&db_); + sql::Transaction inner3(&db()); EXPECT_FALSE(inner3.Begin()); - EXPECT_EQ(1, db_.transaction_nesting()); + EXPECT_EQ(1, db().transaction_nesting()); } } - EXPECT_EQ(0, db_.transaction_nesting()); + EXPECT_EQ(0, db().transaction_nesting()); EXPECT_EQ(0, CountFoo()); } - -} // namespace - -} // namespace sql
diff --git a/storage/BUILD.gn b/storage/BUILD.gn index d6208ef4..2378954 100644 --- a/storage/BUILD.gn +++ b/storage/BUILD.gn
@@ -8,4 +8,6 @@ "//storage/browser:unittests", "//storage/common:unittests", ] + + data = [ "//storage/test/data/" ] }
diff --git a/storage/browser/BUILD.gn b/storage/browser/BUILD.gn index 6ff0d10..4829ac5 100644 --- a/storage/browser/BUILD.gn +++ b/storage/browser/BUILD.gn
@@ -188,6 +188,8 @@ "quota/quota_client_type.h", "quota/quota_database.cc", "quota/quota_database.h", + "quota/quota_database_migrations.cc", + "quota/quota_database_migrations.h", "quota/quota_device_info_helper.cc", "quota/quota_device_info_helper.h", "quota/quota_features.cc", @@ -318,6 +320,7 @@ "file_system/sandbox_file_system_backend_unittest.cc", "file_system/sandbox_origin_database_unittest.cc", "file_system/transient_file_util_unittest.cc", + "quota/quota_database_migrations_unittest.cc", "quota/quota_database_unittest.cc", "quota/quota_manager_unittest.cc", "quota/quota_settings_unittest.cc",
diff --git a/storage/browser/quota/quota_database.cc b/storage/browser/quota/quota_database.cc index ceba2033..9bee4ea 100644 --- a/storage/browser/quota/quota_database.cc +++ b/storage/browser/quota/quota_database.cc
@@ -14,14 +14,15 @@ #include "base/auto_reset.h" #include "base/bind.h" #include "base/containers/contains.h" +#include "base/dcheck_is_on.h" #include "base/files/file_util.h" #include "base/metrics/histogram_macros.h" #include "sql/database.h" #include "sql/meta_table.h" #include "sql/statement.h" #include "sql/transaction.h" +#include "storage/browser/quota/quota_database_migrations.h" #include "storage/browser/quota/special_storage_policy.h" -#include "third_party/blink/public/mojom/quota/quota_types.mojom-shared.h" #include "url/gurl.h" using blink::mojom::StorageType; @@ -29,90 +30,97 @@ namespace storage { namespace { +// Version number of the database schema. +// +// We support migrating the database schema from versions that are at most 2 +// years old. Older versions are unsupported, and will cause the database to get +// razed. +// +// Version 1 - 2011-03-17 - http://crrev.com/78521 (unsupported) +// Version 2 - 2010-04-25 - http://crrev.com/82847 (unsupported) +// Version 3 - 2011-07-08 - http://crrev.com/91835 (unsupported) +// Version 4 - 2011-10-17 - http://crrev.com/105822 (unsupported) +// Version 5 - 2015-10-19 - https://crrev.com/354932 +// Version 6 - 2021-04-27 - https://crrev.com/c/2757450 +const int kQuotaDatabaseCurrentSchemaVersion = 6; +const int kQuotaDatabaseCompatibleVersion = 6; + // Definitions for database schema. - -const int kQuotaDatabaseCurrentSchemaVersion = 5; -const int kQuotaDatabaseCompatibleVersion = 2; - -const char kHostQuotaTable[] = "HostQuotaTable"; -const char kOriginInfoTable[] = "OriginInfoTable"; -const char kEvictionInfoTable[] = "EvictionInfoTable"; +const char kHostQuotaTable[] = "quota"; +const char kBucketTable[] = "buckets"; +const char kEvictionInfoTable[] = "eviction_info"; const char kIsOriginTableBootstrapped[] = "IsOriginTableBootstrapped"; const int kCommitIntervalMs = 30000; } // anonymous namespace +// static +const char QuotaDatabase::kDefaultBucket[] = "default"; + const QuotaDatabase::TableSchema QuotaDatabase::kTables[] = { {kHostQuotaTable, "(host TEXT NOT NULL," " type INTEGER NOT NULL," - " quota INTEGER DEFAULT 0," - " UNIQUE(host, type))"}, - {kOriginInfoTable, - "(origin TEXT NOT NULL," + " quota INTEGER NOT NULL," + " PRIMARY KEY(host, type))" + " WITHOUT ROWID"}, + {kBucketTable, + "(id INTEGER PRIMARY KEY," + " origin TEXT NOT NULL," " type INTEGER NOT NULL," - " used_count INTEGER DEFAULT 0," - " last_access_time INTEGER DEFAULT 0," - " last_modified_time INTEGER DEFAULT 0," - " UNIQUE(origin, type))"}, + " name TEXT NOT NULL," + " use_count INTEGER NOT NULL," + " last_accessed INTEGER NOT NULL," + " last_modified INTEGER NOT NULL," + " expiration INTEGER NOT NULL," + " quota INTEGER NOT NULL)"}, {kEvictionInfoTable, "(origin TEXT NOT NULL," " type INTEGER NOT NULL," - " last_eviction_time INTEGER DEFAULT 0," - " UNIQUE(origin, type))"}}; + " last_eviction_time INTEGER NOT NULL," + " PRIMARY KEY(origin, type))"}}; +const size_t QuotaDatabase::kTableCount = base::size(QuotaDatabase::kTables); // static const QuotaDatabase::IndexSchema QuotaDatabase::kIndexes[] = { - { "HostIndex", - kHostQuotaTable, - "(host)", - false }, - { "OriginInfoIndex", - kOriginInfoTable, - "(origin)", - false }, - { "OriginLastAccessTimeIndex", - kOriginInfoTable, - "(last_access_time)", - false }, - { "OriginLastModifiedTimeIndex", - kOriginInfoTable, - "(last_modified_time)", - false }, + {"buckets_by_storage_key", kBucketTable, "(origin, type, name)", true}, + {"buckets_by_last_accessed", kBucketTable, "(type, last_accessed)", false}, + {"buckets_by_last_modified", kBucketTable, "(type, last_modified)", false}, + {"buckets_by_expiration", kBucketTable, "(expiration)", false}, }; - -struct QuotaDatabase::QuotaTableImporter { - bool Append(const QuotaTableEntry& entry) { - entries.push_back(entry); - return true; - } - std::vector<QuotaTableEntry> entries; -}; +const size_t QuotaDatabase::kIndexCount = base::size(QuotaDatabase::kIndexes); // Clang requires explicit out-of-line constructors for them. -QuotaDatabase::QuotaTableEntry::QuotaTableEntry() - : type(StorageType::kUnknown), quota(0) {} +QuotaDatabase::QuotaTableEntry::QuotaTableEntry() = default; QuotaDatabase::QuotaTableEntry::QuotaTableEntry(const std::string& host, StorageType type, int64_t quota) : host(host), type(type), quota(quota) {} -QuotaDatabase::OriginInfoTableEntry::OriginInfoTableEntry() - : type(StorageType::kUnknown), used_count(0) {} +QuotaDatabase::BucketTableEntry::BucketTableEntry() = default; -QuotaDatabase::OriginInfoTableEntry::OriginInfoTableEntry( - const url::Origin& origin, +QuotaDatabase::BucketTableEntry::BucketTableEntry(const BucketTableEntry&) = + default; +QuotaDatabase::BucketTableEntry& QuotaDatabase::BucketTableEntry::operator=( + const QuotaDatabase::BucketTableEntry&) = default; + +QuotaDatabase::BucketTableEntry::BucketTableEntry( + const int64_t bucket_id, + url::Origin origin, StorageType type, - int used_count, - const base::Time& last_access_time, - const base::Time& last_modified_time) - : origin(origin), + std::string name, + int use_count, + const base::Time& last_accessed, + const base::Time& last_modified) + : bucket_id(bucket_id), + origin(std::move(origin)), type(type), - used_count(used_count), - last_access_time(last_access_time), - last_modified_time(last_modified_time) {} + name(std::move(name)), + use_count(use_count), + last_accessed(last_accessed), + last_modified(last_modified) {} // QuotaDatabase ------------------------------------------------------------ QuotaDatabase::QuotaDatabase(const base::FilePath& path) @@ -137,11 +145,8 @@ if (!LazyOpen(false)) return false; - const char* kSql = - "SELECT quota" - " FROM HostQuotaTable" - " WHERE host = ? AND type = ?"; - + static constexpr char kSql[] = + "SELECT quota FROM quota WHERE host = ? AND type = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindString(0, host); statement.BindInt(1, static_cast<int>(type)); @@ -170,34 +175,74 @@ bool QuotaDatabase::SetOriginLastAccessTime(const url::Origin& origin, StorageType type, - base::Time last_access_time) { + base::Time last_accessed) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!LazyOpen(true)) return false; sql::Statement statement; - OriginInfoTableEntry entry; + BucketTableEntry entry; if (GetOriginInfo(origin, type, &entry)) { - ++entry.used_count; - const char* kSql = - "UPDATE OriginInfoTable" - " SET used_count = ?, last_access_time = ?" - " WHERE origin = ? AND type = ?"; + ++entry.use_count; + static constexpr char kSql[] = + // clang-format off + "UPDATE buckets " + "SET use_count = ?, last_accessed = ? " + "WHERE origin = ? AND type = ? AND name = ?"; + // clang-format on statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); } else { - entry.used_count = 1; - const char* kSql = - "INSERT INTO OriginInfoTable" - " (used_count, last_access_time, origin, type, last_modified_time)" - " VALUES (?, ?, ?, ?, ?)"; + entry.use_count = 1; + // INSERT statement column ordering matches UPDATE statement above for + // reuse of binding values. + static constexpr char kSql[] = + // clang-format off + "INSERT INTO buckets(" + "use_count," + "last_accessed," + "origin," + "type," + "name," + "last_modified," + "expiration," + "quota) " + "VALUES (?, ?, ?, ?, ?, ?, ?, 0)"; + // clang-format on statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); - statement.BindTime(4, last_access_time); + statement.BindTime(5, last_accessed); + statement.BindTime(6, base::Time::Max()); } - statement.BindInt(0, entry.used_count); - statement.BindTime(1, last_access_time); + statement.BindInt(0, entry.use_count); + statement.BindTime(1, last_accessed); statement.BindString(2, origin.GetURL().spec()); statement.BindInt(3, static_cast<int>(type)); + statement.BindString(4, kDefaultBucket); + + if (!statement.Run()) + return false; + + ScheduleCommit(); + return true; +} + +bool QuotaDatabase::SetBucketLastAccessTime(const int64_t bucket_id, + base::Time last_accessed) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!LazyOpen(true)) + return false; + + BucketTableEntry entry; + if (!GetBucketInfo(bucket_id, &entry)) + return false; + + ++entry.use_count; + static constexpr char kSql[] = + "UPDATE buckets SET use_count = ?, last_accessed = ? WHERE id = ?"; + sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindInt(0, entry.use_count); + statement.BindTime(1, last_accessed); + statement.BindInt64(2, bucket_id); if (!statement.Run()) return false; @@ -208,31 +253,68 @@ bool QuotaDatabase::SetOriginLastModifiedTime(const url::Origin& origin, StorageType type, - base::Time last_modified_time) { + base::Time last_modified) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!LazyOpen(true)) return false; sql::Statement statement; - OriginInfoTableEntry entry; + BucketTableEntry entry; if (GetOriginInfo(origin, type, &entry)) { - const char* kSql = - "UPDATE OriginInfoTable" - " SET last_modified_time = ?" - " WHERE origin = ? AND type = ?"; + static constexpr char kSql[] = + // clang-format off + "UPDATE buckets " + "SET last_modified = ? " + "WHERE origin = ? AND type = ? AND name = ?"; + // clang-format on statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); } else { - const char* kSql = - "INSERT INTO OriginInfoTable" - " (last_modified_time, origin, type, last_access_time) VALUES (?, ?, ?, ?)"; + static constexpr char kSql[] = + // clang-format off + "INSERT INTO buckets(" + "last_modified," + "origin," + "type," + "name," + "last_accessed," + "use_count," + "expiration," + "quota) " + "VALUES (?, ?, ?, ?, ?, 0, ?, 0)"; + // clang-format on statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); - statement.BindTime(3, last_modified_time); + statement.BindTime(4, last_modified); + statement.BindTime(5, base::Time::Max()); } - statement.BindTime(0, last_modified_time); + statement.BindTime(0, last_modified); statement.BindString(1, origin.GetURL().spec()); statement.BindInt(2, static_cast<int>(type)); + statement.BindString(3, kDefaultBucket); + + if (!statement.Run()) + return false; + + ScheduleCommit(); + return true; +} + +bool QuotaDatabase::SetBucketLastModifiedTime(const int64_t bucket_id, + base::Time last_modified) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!LazyOpen(true)) + return false; + + BucketTableEntry entry; + if (!GetBucketInfo(bucket_id, &entry)) + return false; + + static constexpr char kSql[] = + "UPDATE buckets SET last_modified = ? WHERE id = ?"; + sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindTime(0, last_modified); + statement.BindInt64(1, bucket_id); if (!statement.Run()) return false; @@ -243,17 +325,18 @@ bool QuotaDatabase::GetOriginLastEvictionTime(const url::Origin& origin, StorageType type, - base::Time* last_modified_time) { + base::Time* last_modified) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(last_modified_time); + DCHECK(last_modified); if (!LazyOpen(false)) return false; - static const char kSql[] = - "SELECT last_eviction_time" - " FROM EvictionInfoTable" - " WHERE origin = ? AND type = ?"; - + static constexpr char kSql[] = + // clang-format off + "SELECT last_eviction_time " + "FROM eviction_info " + "WHERE origin = ? AND type = ?"; + // clang-format on sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindString(0, origin.GetURL().spec()); statement.BindInt(1, static_cast<int>(type)); @@ -261,23 +344,24 @@ if (!statement.Step()) return false; - *last_modified_time = statement.ColumnTime(0); + *last_modified = statement.ColumnTime(0); return true; } bool QuotaDatabase::SetOriginLastEvictionTime(const url::Origin& origin, StorageType type, - base::Time last_modified_time) { + base::Time last_modified) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!LazyOpen(true)) return false; - static const char kSql[] = - "INSERT OR REPLACE INTO EvictionInfoTable" - " (last_eviction_time, origin, type)" - " VALUES (?, ?, ?)"; + static constexpr char kSql[] = + // clang-format off + "INSERT OR REPLACE INTO eviction_info(last_eviction_time, origin, type) " + "VALUES (?, ?, ?)"; + // clang-format on sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); - statement.BindTime(0, last_modified_time); + statement.BindTime(0, last_modified); statement.BindString(1, origin.GetURL().spec()); statement.BindInt(2, static_cast<int>(type)); @@ -294,10 +378,8 @@ if (!LazyOpen(false)) return false; - static const char kSql[] = - "DELETE FROM EvictionInfoTable" - " WHERE origin = ? AND type = ?"; - + static constexpr char kSql[] = + "DELETE FROM eviction_info WHERE origin = ? AND type = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindString(0, origin.GetURL().spec()); statement.BindInt(1, static_cast<int>(type)); @@ -317,12 +399,24 @@ return false; for (const auto& origin : origins) { - const char* kSql = - "INSERT OR IGNORE INTO OriginInfoTable" - " (origin, type) VALUES (?, ?)"; + static constexpr char kSql[] = + // clang-format off + "INSERT OR IGNORE INTO buckets(" + "origin," + "type," + "name," + "use_count," + "last_accessed," + "last_modified," + "expiration," + "quota) " + "VALUES (?, ?, ?, 0, 0, 0, ?, 0)"; + // clang-format on sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindString(0, origin.GetURL().spec()); statement.BindInt(1, static_cast<int>(type)); + statement.BindString(2, kDefaultBucket); + statement.BindTime(3, base::Time::Max()); if (!statement.Run()) return false; @@ -334,27 +428,66 @@ bool QuotaDatabase::GetOriginInfo(const url::Origin& origin, StorageType type, - QuotaDatabase::OriginInfoTableEntry* entry) { + QuotaDatabase::BucketTableEntry* entry) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!LazyOpen(false)) return false; - const char* kSql = - "SELECT * FROM OriginInfoTable" - " WHERE origin = ? AND type = ?"; + static constexpr char kSql[] = + // clang-format off + "SELECT " + "id," + "use_count," + "last_accessed," + "last_modified " + "FROM buckets " + "WHERE origin = ? AND type = ? AND name = ?"; + // clang-format on sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindString(0, origin.GetURL().spec()); statement.BindInt(1, static_cast<int>(type)); + statement.BindString(2, kDefaultBucket); if (!statement.Step()) return false; // TODO(crbug.com/889590): Use helper for url::Origin creation from string. - *entry = OriginInfoTableEntry( - url::Origin::Create(GURL(statement.ColumnString(0))), - static_cast<StorageType>(statement.ColumnInt(1)), statement.ColumnInt(2), - statement.ColumnTime(3), statement.ColumnTime(4)); + *entry = BucketTableEntry(statement.ColumnInt64(0), origin, type, + kDefaultBucket, statement.ColumnInt(1), + statement.ColumnTime(2), statement.ColumnTime(3)); + return true; +} +bool QuotaDatabase::GetBucketInfo(const int64_t bucket_id, + QuotaDatabase::BucketTableEntry* entry) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!LazyOpen(false)) + return false; + + static constexpr char kSql[] = + // clang-format off + "SELECT " + "origin," + "type," + "name," + "use_count," + "last_accessed," + "last_modified " + "FROM buckets " + "WHERE id = ?"; + // clang-format on + sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindInt64(0, bucket_id); + + if (!statement.Step()) + return false; + + // TODO(crbug.com/889590): Use helper for url::Origin creation from string. + *entry = BucketTableEntry( + bucket_id, url::Origin::Create(GURL(statement.ColumnString(0))), + static_cast<StorageType>(statement.ColumnInt(1)), + statement.ColumnString(2), statement.ColumnInt(3), + statement.ColumnTime(4), statement.ColumnTime(5)); return true; } @@ -364,10 +497,8 @@ if (!LazyOpen(false)) return false; - const char* kSql = - "DELETE FROM HostQuotaTable" - " WHERE host = ? AND type = ?"; - + static constexpr char kSql[] = + "DELETE FROM quota WHERE host = ? AND type = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindString(0, host); statement.BindInt(1, static_cast<int>(type)); @@ -385,13 +516,28 @@ if (!LazyOpen(false)) return false; - const char* kSql = - "DELETE FROM OriginInfoTable" - " WHERE origin = ? AND type = ?"; - + static constexpr char kSql[] = + "DELETE FROM buckets WHERE origin = ? AND type = ? AND name = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindString(0, origin.GetURL().spec()); statement.BindInt(1, static_cast<int>(type)); + statement.BindString(2, kDefaultBucket); + + if (!statement.Run()) + return false; + + ScheduleCommit(); + return true; +} + +bool QuotaDatabase::DeleteBucketInfo(const int64_t bucket_id) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!LazyOpen(false)) + return false; + + static constexpr char kSql[] = "DELETE FROM buckets WHERE id = ?"; + sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindInt64(0, bucket_id); if (!statement.Run()) return false; @@ -409,13 +555,16 @@ if (!LazyOpen(false)) return false; - static const char kSql[] = - "SELECT origin FROM OriginInfoTable" - " WHERE type = ?" - " ORDER BY last_access_time ASC"; + static constexpr char kSql[] = + // clang-format off + "SELECT origin FROM buckets " + "WHERE type = ? AND name = ? " + "ORDER BY last_accessed"; + // clang-format on sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt(0, static_cast<int>(type)); + statement.BindString(1, kDefaultBucket); while (statement.Step()) { url::Origin read_origin = @@ -437,6 +586,48 @@ return statement.Succeeded(); } +bool QuotaDatabase::GetLRUBucket(StorageType type, + const std::set<url::Origin>& exceptions, + SpecialStoragePolicy* special_storage_policy, + base::Optional<int64_t>* bucket_id) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(bucket_id); + if (!LazyOpen(false)) + return false; + + static constexpr char kSql[] = + // clang-format off + "SELECT id, origin FROM buckets " + "WHERE type = ? " + "ORDER BY last_accessed"; + // clang-format on + + sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindInt(0, static_cast<int>(type)); + + while (statement.Step()) { + int64_t read_bucket_id = statement.ColumnInt64(0); + url::Origin read_origin = + url::Origin::Create(GURL(statement.ColumnString(1))); + if (base::Contains(exceptions, read_origin)) + continue; + + // TODO(crbug/1176774): Once BucketTable holds bucket durability info, + // add logic to allow durable buckets to also bypass eviction. + if (special_storage_policy && + (special_storage_policy->IsStorageDurable(read_origin.GetURL()) || + special_storage_policy->IsStorageUnlimited(read_origin.GetURL()))) { + continue; + } + + *bucket_id = read_bucket_id; + return true; + } + + bucket_id->reset(); + return statement.Succeeded(); +} + bool QuotaDatabase::GetOriginsModifiedBetween(StorageType type, std::set<url::Origin>* origins, base::Time begin, @@ -446,25 +637,20 @@ if (!LazyOpen(false)) return false; - DCHECK(!begin.is_max() && end != base::Time()); - static constexpr char kSqlQuerySince[] = - "SELECT origin FROM OriginInfoTable" - " WHERE type = ? AND last_modified_time >= ?"; + DCHECK(!begin.is_max()); + DCHECK(end != base::Time()); + static constexpr char kSql[] = + // clang-format off + "SELECT origin FROM buckets " + "WHERE type = ? AND name = ?" + "AND last_modified >= ? AND last_modified < ?"; + // clang-format on - static constexpr char kSqlQueryBetween[] = - "SELECT origin FROM OriginInfoTable" - " WHERE type = ? AND last_modified_time >= ? AND last_modified_time < ?"; - - sql::Statement statement; - if (end.is_max()) { - statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSqlQuerySince)); - } else { - statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSqlQueryBetween)); - } + sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt(0, static_cast<int>(type)); - statement.BindTime(1, begin); - if (!end.is_max()) - statement.BindTime(2, end); + statement.BindString(1, kDefaultBucket); + statement.BindTime(2, begin); + statement.BindTime(3, end); origins->clear(); while (statement.Step()) @@ -473,6 +659,35 @@ return statement.Succeeded(); } +bool QuotaDatabase::GetBucketsModifiedBetween(StorageType type, + std::set<int64_t>* bucket_ids, + base::Time begin, + base::Time end) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(bucket_ids); + if (!LazyOpen(false)) + return false; + + DCHECK(!begin.is_max()); + DCHECK(end != base::Time()); + static constexpr char kSql[] = + // clang-format off + "SELECT id FROM buckets " + "WHERE type = ? AND last_modified >= ? AND last_modified < ?"; + // clang-format on + + sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindInt(0, static_cast<int>(type)); + statement.BindTime(1, begin); + statement.BindTime(2, end); + + bucket_ids->clear(); + while (statement.Step()) + bucket_ids->insert(statement.ColumnInt64(0)); + + return statement.Succeeded(); +} + bool QuotaDatabase::IsOriginDatabaseBootstrapped() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!LazyOpen(true)) @@ -564,13 +779,8 @@ bool QuotaDatabase::EnsureDatabaseVersion() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - static const size_t kTableCount = base::size(kTables); - static const size_t kIndexCount = base::size(kIndexes); if (!sql::MetaTable::DoesTableExist(db_.get())) - return CreateSchema(db_.get(), meta_table_.get(), - kQuotaDatabaseCurrentSchemaVersion, - kQuotaDatabaseCompatibleVersion, kTables, kTableCount, - kIndexes, kIndexCount); + return CreateSchema(); if (!meta_table_->Init(db_.get(), kQuotaDatabaseCurrentSchemaVersion, kQuotaDatabaseCompatibleVersion)) @@ -583,66 +793,71 @@ } if (meta_table_->GetVersionNumber() < kQuotaDatabaseCurrentSchemaVersion) { - if (!UpgradeSchema(meta_table_->GetVersionNumber())) + if (!QuotaDatabaseMigrations::UpgradeSchema(*this)) return ResetSchema(); } -#ifndef NDEBUG +#if DCHECK_IS_ON() DCHECK(sql::MetaTable::DoesTableExist(db_.get())); - for (size_t i = 0; i < kTableCount; ++i) { - DCHECK(db_->DoesTableExist(kTables[i].table_name)); - } + for (const TableSchema& table : kTables) + DCHECK(db_->DoesTableExist(table.table_name)); #endif return true; } -// static -bool QuotaDatabase::CreateSchema(sql::Database* database, - sql::MetaTable* meta_table, - int schema_version, - int compatible_version, - const TableSchema* tables, - size_t tables_size, - const IndexSchema* indexes, - size_t indexes_size) { +bool QuotaDatabase::CreateSchema() { // TODO(kinuko): Factor out the common code to create databases. - sql::Transaction transaction(database); + sql::Transaction transaction(db_.get()); if (!transaction.Begin()) return false; - if (!meta_table->Init(database, schema_version, compatible_version)) + if (!meta_table_->Init(db_.get(), kQuotaDatabaseCurrentSchemaVersion, + kQuotaDatabaseCompatibleVersion)) { return false; - - for (size_t i = 0; i < tables_size; ++i) { - std::string sql("CREATE TABLE "); - sql += tables[i].table_name; - sql += tables[i].columns; - if (!database->Execute(sql.c_str())) { - VLOG(1) << "Failed to execute " << sql; - return false; - } } - for (size_t i = 0; i < indexes_size; ++i) { - std::string sql; - if (indexes[i].unique) - sql += "CREATE UNIQUE INDEX "; - else - sql += "CREATE INDEX "; - sql += indexes[i].index_name; - sql += " ON "; - sql += indexes[i].table_name; - sql += indexes[i].columns; - if (!database->Execute(sql.c_str())) { - VLOG(1) << "Failed to execute " << sql; + for (const TableSchema& table : kTables) { + if (!CreateTable(table)) return false; - } + } + + for (const IndexSchema& index : kIndexes) { + if (!CreateIndex(index)) + return false; } return transaction.Commit(); } +bool QuotaDatabase::CreateTable(const TableSchema& table) { + std::string sql("CREATE TABLE "); + sql += table.table_name; + sql += table.columns; + if (!db_->Execute(sql.c_str())) { + VLOG(1) << "Failed to execute " << sql; + return false; + } + return true; +} + +bool QuotaDatabase::CreateIndex(const IndexSchema& index) { + std::string sql; + if (index.unique) + sql += "CREATE UNIQUE INDEX "; + else + sql += "CREATE INDEX "; + sql += index.index_name; + sql += " ON "; + sql += index.table_name; + sql += index.columns; + if (!db_->Execute(sql.c_str())) { + VLOG(1) << "Failed to execute " << sql; + return false; + } + return true; +} + bool QuotaDatabase::ResetSchema() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!db_file_path_.empty()); @@ -664,57 +879,16 @@ return LazyOpen(true); } -bool QuotaDatabase::UpgradeSchema(int current_version) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(0, db_->transaction_nesting()); - - if (current_version == 2) { - QuotaTableImporter importer; - if (!DumpQuotaTable(base::BindRepeating(&QuotaTableImporter::Append, - base::Unretained(&importer)))) { - return false; - } - ResetSchema(); - - sql::Transaction transaction(db_.get()); - if (!transaction.Begin()) - return false; - for (const auto& entry : importer.entries) { - if (!InsertOrReplaceHostQuota(entry.host, entry.type, entry.quota)) - return false; - } - return transaction.Commit(); - } else if (current_version < 5) { - sql::Transaction transaction(db_.get()); - if (!transaction.Begin()) - return false; - - const QuotaDatabase::TableSchema& eviction_table_schema = kTables[2]; - DCHECK_EQ(strcmp(kEvictionInfoTable, eviction_table_schema.table_name), 0); - - std::string sql("CREATE TABLE "); - sql += eviction_table_schema.table_name; - sql += eviction_table_schema.columns; - if (!db_->Execute(sql.c_str())) { - VLOG(1) << "Failed to execute " << sql; - return false; - } - - meta_table_->SetVersionNumber(5); - return transaction.Commit(); - } - return false; -} - bool QuotaDatabase::InsertOrReplaceHostQuota(const std::string& host, StorageType type, int64_t quota) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(db_.get()); - const char* kSql = - "INSERT OR REPLACE INTO HostQuotaTable" - " (quota, host, type)" - " VALUES (?, ?, ?)"; + static constexpr char kSql[] = + // clang-format off + "INSERT OR REPLACE INTO quota(quota, host, type)" + "VALUES (?, ?, ?)"; + // clang-format on sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, quota); statement.BindString(1, host); @@ -727,7 +901,7 @@ if (!LazyOpen(true)) return false; - const char* kSql = "SELECT * FROM HostQuotaTable"; + static constexpr char kSql[] = "SELECT * FROM quota"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); while (statement.Step()) { @@ -743,22 +917,32 @@ return statement.Succeeded(); } -bool QuotaDatabase::DumpOriginInfoTable( - const OriginInfoTableCallback& callback) { +bool QuotaDatabase::DumpBucketTable(const BucketTableCallback& callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!LazyOpen(true)) return false; - const char* kSql = "SELECT * FROM OriginInfoTable"; + static constexpr char kSql[] = + // clang-format off + "SELECT " + "id," + "origin," + "type," + "name," + "use_count," + "last_accessed," + "last_modified " + "FROM buckets"; + // clang-format on sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); while (statement.Step()) { - OriginInfoTableEntry entry( - url::Origin::Create(GURL(statement.ColumnString(0))), - static_cast<StorageType>(statement.ColumnInt(1)), - statement.ColumnInt(2), statement.ColumnTime(3), - statement.ColumnTime(4)); + BucketTableEntry entry(statement.ColumnInt64(0), + url::Origin::Create(GURL(statement.ColumnString(1))), + static_cast<StorageType>(statement.ColumnInt(2)), + statement.ColumnString(3), statement.ColumnInt(4), + statement.ColumnTime(5), statement.ColumnTime(6)); if (!callback.Run(entry)) return true; @@ -773,10 +957,10 @@ std::tie(rhs.host, rhs.type, rhs.quota); } -bool operator<(const QuotaDatabase::OriginInfoTableEntry& lhs, - const QuotaDatabase::OriginInfoTableEntry& rhs) { - return std::tie(lhs.origin, lhs.type, lhs.used_count, lhs.last_access_time) < - std::tie(rhs.origin, rhs.type, rhs.used_count, rhs.last_access_time); +bool operator<(const QuotaDatabase::BucketTableEntry& lhs, + const QuotaDatabase::BucketTableEntry& rhs) { + return std::tie(lhs.origin, lhs.type, lhs.use_count, lhs.last_accessed) < + std::tie(rhs.origin, rhs.type, rhs.use_count, rhs.last_accessed); } } // namespace storage
diff --git a/storage/browser/quota/quota_database.h b/storage/browser/quota/quota_database.h index 764216d..d91a6c7 100644 --- a/storage/browser/quota/quota_database.h +++ b/storage/browser/quota/quota_database.h
@@ -19,7 +19,7 @@ #include "base/sequence_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "third_party/blink/public/mojom/quota/quota_types.mojom-forward.h" +#include "third_party/blink/public/mojom/quota/quota_types.mojom-shared.h" #include "url/origin.h" namespace sql { @@ -31,25 +31,33 @@ class SpecialStoragePolicy; -// Stores all origin scoped quota managed data and metadata. +// Stores all quota managed origin bucket data and metadata. // // Instances are owned by QuotaManagerImpl. There is one instance per // QuotaManagerImpl instance. All the methods of this class, except the // constructor, must called on the DB thread. class COMPONENT_EXPORT(STORAGE_BROWSER) QuotaDatabase { public: - struct COMPONENT_EXPORT(STORAGE_BROWSER) OriginInfoTableEntry { - OriginInfoTableEntry(); - OriginInfoTableEntry(const url::Origin& origin, - blink::mojom::StorageType type, - int used_count, - const base::Time& last_access_time, - const base::Time& last_modified_time); + struct COMPONENT_EXPORT(STORAGE_BROWSER) BucketTableEntry { + BucketTableEntry(); + BucketTableEntry(int64_t bucket_id, + url::Origin origin, + blink::mojom::StorageType type, + std::string name, + int use_count, + const base::Time& last_accessed, + const base::Time& last_modified); + + BucketTableEntry(const BucketTableEntry&); + BucketTableEntry& operator=(const BucketTableEntry&); + + int64_t bucket_id = -1; url::Origin origin; - blink::mojom::StorageType type; - int used_count; - base::Time last_access_time; - base::Time last_modified_time; + blink::mojom::StorageType type = blink::mojom::StorageType::kUnknown; + std::string name; + int use_count = 0; + base::Time last_accessed; + base::Time last_modified; }; // If 'path' is empty, an in memory database will be used. @@ -67,16 +75,26 @@ int64_t quota); bool DeleteHostQuota(const std::string& host, blink::mojom::StorageType type); + // TODO(crbug.com/1202167): Remove once all usages have updated to use + // SetBucketLastAccessTime. bool SetOriginLastAccessTime(const url::Origin& origin, blink::mojom::StorageType type, - base::Time last_access_time); + base::Time last_accessed); + // Called by QuotaClient implementers to update when the bucket was last + // accessed. + bool SetBucketLastAccessTime(int64_t bucket_id, base::Time last_accessed); + + // TODO(crbug.com/1202167): Remove once all usages have updated to use + // SetBucketLastModifiedTime. bool SetOriginLastModifiedTime(const url::Origin& origin, blink::mojom::StorageType type, - base::Time last_modified_time); + base::Time last_modified); - // Gets the time |origin| was last evicted. Returns whether the record could - // be found. + // Called by QuotaClient implementers to update when the bucket was last + // modified. + bool SetBucketLastModifiedTime(int64_t bucket_id, base::Time last_modified); + bool GetOriginLastEvictionTime(const url::Origin& origin, blink::mojom::StorageType type, base::Time* last_eviction_time); @@ -89,38 +107,67 @@ bool DeleteOriginLastEvictionTime(const url::Origin& origin, blink::mojom::StorageType type); - // Register initial |origins| info |type| to the database. + // Register initial `origins` info `type` to the database. // This method is assumed to be called only after the installation or // the database schema reset. bool RegisterInitialOriginInfo(const std::set<url::Origin>& origins, blink::mojom::StorageType type); - // Gets the OriginInfoTableEntry for |origin|. Returns whether the record - // could be found. + // TODO(crbug.com/1202167): Remove once all usages have been updated to use + // GetBucketInfo. Gets the BucketTableEntry for `origin`. Returns whether the + // record for an origin's default bucket could be found. bool GetOriginInfo(const url::Origin& origin, blink::mojom::StorageType type, - OriginInfoTableEntry* entry); + BucketTableEntry* entry); + // Gets the table entry for `bucket`. Returns whether the record for an + // origin bucket can be found. + bool GetBucketInfo(int64_t bucket_id, BucketTableEntry* entry); + + // TODO(crbug.com/1202167): Remove once all usages have been updated to use + // DeleteBucketInfo. Deletes the default bucket for `origin`. bool DeleteOriginInfo(const url::Origin& origin, blink::mojom::StorageType type); - // Sets |origin| to the least recently used origin of origins not included - // in |exceptions| and not granted the special unlimited storage right. - // It returns false when it failed in accessing the database. - // |origin| is set to nullopt when there is no matching origin. + // Deletes the specified bucket. + bool DeleteBucketInfo(int64_t bucket_id); + + // TODO(crbug.com/1202167): Remove once all usages have been updated to use + // GetLRUBucket. Sets `origin` to the least recently used origin of origins + // not included in `exceptions` and not granted the special unlimited storage + // right. Returns false when it fails in accessing the database. + // `origin` is set to nullopt when there is no matching origin. + // This is limited to the origin's default bucket. bool GetLRUOrigin(blink::mojom::StorageType type, const std::set<url::Origin>& exceptions, SpecialStoragePolicy* special_storage_policy, base::Optional<url::Origin>* origin); - // Populates |origins| with the ones that have been modified since - // the |begin| and until the |end|. Returns whether the - // operation succeeded. + // Sets `bucket_id` to the least recently used bucket from origins not + // included in `exceptions` and not granted special unlimited storage right. + // Returns false when it fails in accessing the database. `bucket_id` is + // set to nullopt when there is no matching bucket. + bool GetLRUBucket(blink::mojom::StorageType type, + const std::set<url::Origin>& exceptions, + SpecialStoragePolicy* special_storage_policy, + base::Optional<int64_t>* bucket_id); + + // TODO(crbug.com/1202167): Remove once all usages have been updated to use + // GetBucketsModifiedBetween. Populates `origins` with the ones that have had + // their default bucket modified since the `begin` and until the `end`. + // Returns whether the operation succeeded. bool GetOriginsModifiedBetween(blink::mojom::StorageType type, std::set<url::Origin>* origins, base::Time begin, base::Time end); + // Populates `bucket_ids` with the buckets that have been modified since the + // `begin` and until the `end`. Returns whether the operation succeeded. + bool GetBucketsModifiedBetween(blink::mojom::StorageType type, + std::set<int64_t>* bucket_ids, + base::Time begin, + base::Time end); + // Returns false if SetOriginDatabaseBootstrapped has never // been called before, which means existing origins may not have been // registered. @@ -134,15 +181,15 @@ blink::mojom::StorageType type, int64_t quota); std::string host; - blink::mojom::StorageType type; - int64_t quota; + blink::mojom::StorageType type{blink::mojom::StorageType::kUnknown}; + int64_t quota{0}; }; friend COMPONENT_EXPORT(STORAGE_BROWSER) bool operator<( const QuotaTableEntry& lhs, const QuotaTableEntry& rhs); friend COMPONENT_EXPORT(STORAGE_BROWSER) bool operator<( - const OriginInfoTableEntry& lhs, - const OriginInfoTableEntry& rhs); + const BucketTableEntry& lhs, + const BucketTableEntry& rhs); // Structures used for CreateSchema. struct TableSchema { @@ -158,10 +205,8 @@ using QuotaTableCallback = base::RepeatingCallback<bool(const QuotaTableEntry&)>; - using OriginInfoTableCallback = - base::RepeatingCallback<bool(const OriginInfoTableEntry&)>; - - struct QuotaTableImporter; + using BucketTableCallback = + base::RepeatingCallback<bool(const BucketTableEntry&)>; // For long-running transactions support. We always keep a transaction open // so that multiple transactions can be batched. They are flushed @@ -178,19 +223,13 @@ blink::mojom::StorageType type, int64_t quota); - static bool CreateSchema(sql::Database* database, - sql::MetaTable* meta_table, - int schema_version, - int compatible_version, - const TableSchema* tables, - size_t tables_size, - const IndexSchema* indexes, - size_t indexes_size); + bool CreateSchema(); + bool CreateTable(const TableSchema& table); + bool CreateIndex(const IndexSchema& index); - // |callback| may return false to stop reading data. + // `callback` may return false to stop reading data. bool DumpQuotaTable(const QuotaTableCallback& callback); - bool DumpOriginInfoTable(const OriginInfoTableCallback& callback); - + bool DumpBucketTable(const BucketTableCallback& callback); const base::FilePath db_file_path_; @@ -202,10 +241,15 @@ base::OneShotTimer timer_; friend class QuotaDatabaseTest; + friend class QuotaDatabaseMigrations; + friend class QuotaDatabaseMigrationsTest; friend class QuotaManagerImpl; + static const char kDefaultBucket[]; static const TableSchema kTables[]; + static const size_t kTableCount; static const IndexSchema kIndexes[]; + static const size_t kIndexCount; SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(QuotaDatabase);
diff --git a/storage/browser/quota/quota_database_migrations.cc b/storage/browser/quota/quota_database_migrations.cc new file mode 100644 index 0000000..44f892a --- /dev/null +++ b/storage/browser/quota/quota_database_migrations.cc
@@ -0,0 +1,124 @@ +// Copyright 2021 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 "storage/browser/quota/quota_database_migrations.h" + +#include <string> + +#include "sql/database.h" +#include "sql/meta_table.h" +#include "sql/statement.h" +#include "sql/transaction.h" +#include "storage/browser/quota/quota_database.h" + +namespace storage { + +// static +bool QuotaDatabaseMigrations::UpgradeSchema(QuotaDatabase& quota_database) { + DCHECK_EQ(0, quota_database.db_->transaction_nesting()); + + // Reset tables for versions lower than 5 since they are unsupported. + if (quota_database.meta_table_->GetVersionNumber() < 5) + return quota_database.ResetSchema(); + + if (quota_database.meta_table_->GetVersionNumber() == 5) { + if (!MigrateToVersion6(quota_database)) + return false; + } + + return quota_database.meta_table_->GetVersionNumber() == 6; +} + +bool QuotaDatabaseMigrations::MigrateToVersion6(QuotaDatabase& quota_database) { + sql::Database* db = quota_database.db_.get(); + sql::Transaction transaction(db); + if (!transaction.Begin()) + return false; + + // Create tables with latest schema. + for (size_t i = 0; i < QuotaDatabase::kTableCount; ++i) { + if (!quota_database.CreateTable(QuotaDatabase::kTables[i])) + return false; + } + + // Create all indexes for tables. + for (size_t i = 0; i < QuotaDatabase::kIndexCount; ++i) { + if (!quota_database.CreateIndex(QuotaDatabase::kIndexes[i])) + return false; + } + + // Copy OriginInfoTable data into new bucket table. + const char kImportOriginInfoSql[] = + // clang-format off + "INSERT INTO buckets(" + "origin," + "type," + "name," + "use_count," + "last_accessed," + "last_modified," + "expiration," + "quota) " + "SELECT " + "origin," + "type," + "?," + "used_count," + "last_access_time," + "last_modified_time," + "?," + "0 " + "FROM OriginInfoTable"; + // clang-format on + sql::Statement import_origin_info_statement( + db->GetCachedStatement(SQL_FROM_HERE, kImportOriginInfoSql)); + import_origin_info_statement.BindString(0, QuotaDatabase::kDefaultBucket); + import_origin_info_statement.BindTime(1, base::Time::Max()); + if (!import_origin_info_statement.Run()) + return false; + + // Delete OriginInfoTable. + const char kDeleteOriginInfoTableSql[] = "DROP TABLE OriginInfoTable"; + if (!db->Execute(kDeleteOriginInfoTableSql)) + return false; + + // Copy HostQuotaTable data into the new quota table. + const char kImportQuotaSql[] = + // clang-format off + "INSERT INTO quota(host, type, quota) " + "SELECT host, type, quota " + "FROM HostQuotaTable"; + // clang-format on + sql::Statement import_quota_statement( + db->GetCachedStatement(SQL_FROM_HERE, kImportQuotaSql)); + if (!import_quota_statement.Run()) + return false; + + // Delete HostQuotaTable. + const char kDeleteQuotaHostTableSql[] = "DROP TABLE HostQuotaTable"; + if (!db->Execute(kDeleteQuotaHostTableSql)) + return false; + + // Copy EvictionInfoTable data into the new eviction_info table. + const char kImportEvictionInfoSql[] = + // clang-format off + "INSERT INTO eviction_info(origin, type, last_eviction_time) " + "SELECT origin, type, last_eviction_time " + "FROM EvictionInfoTable"; + // clang-format on + sql::Statement import_eviction_info_statement( + db->GetCachedStatement(SQL_FROM_HERE, kImportEvictionInfoSql)); + if (!import_eviction_info_statement.Run()) + return false; + + // Delete EvictionInfoTable. + const char kDeleteEvictionInfoTableSql[] = "DROP TABLE EvictionInfoTable"; + if (!db->Execute(kDeleteEvictionInfoTableSql)) + return false; + + quota_database.meta_table_->SetVersionNumber(6); + return transaction.Commit(); +} + +} // namespace storage
diff --git a/storage/browser/quota/quota_database_migrations.h b/storage/browser/quota/quota_database_migrations.h new file mode 100644 index 0000000..97a5b1a --- /dev/null +++ b/storage/browser/quota/quota_database_migrations.h
@@ -0,0 +1,31 @@ +// Copyright 2021 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 STORAGE_BROWSER_QUOTA_QUOTA_DATABASE_MIGRATIONS_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_DATABASE_MIGRATIONS_H_ + +namespace storage { + +class QuotaDatabase; + +// Helper class of QuotaDatabase which handles the QuotaManager SQL database +// schema migrations. Any change that requires a change in the schema version +// and adds new tables, columns, or modifies existing data should have a +// migration to avoid data loss. +// +// QuotaDatabaseMigrations is a friended class of QuotaDatabase and updates the +// existing SQL QuotaManager database owned by the QuotaDatabase class. +class QuotaDatabaseMigrations { + public: + // Upgrades the SQL database owned by `quota_database` to the latest schema, + // and updates the sql::MetaTable version accordingly. + static bool UpgradeSchema(QuotaDatabase& quota_database); + + private: + static bool MigrateToVersion6(QuotaDatabase& quota_database); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_QUOTA_DATABASE_MIGRATIONS_H_
diff --git a/storage/browser/quota/quota_database_migrations_unittest.cc b/storage/browser/quota/quota_database_migrations_unittest.cc new file mode 100644 index 0000000..0752382b1f --- /dev/null +++ b/storage/browser/quota/quota_database_migrations_unittest.cc
@@ -0,0 +1,131 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/path_service.h" +#include "sql/database.h" +#include "sql/meta_table.h" +#include "sql/statement.h" +#include "sql/test/test_helpers.h" +#include "storage/browser/quota/quota_database.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace storage { + +class QuotaDatabaseMigrationsTest : public testing::Test { + public: + void SetUp() override { ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); } + + base::FilePath DbPath() { + return temp_directory_.GetPath().AppendASCII("quota_manager.db"); + } + + protected: + // The textual contents of |file| are read from + // "storage/test/data/quota_database/" and returned in the string + // |contents|. Returns true if the file exists and is read successfully, false + // otherwise. + std::string GetDatabaseData(const char* file) { + base::FilePath source_path; + base::PathService::Get(base::DIR_SOURCE_ROOT, &source_path); + source_path = source_path.AppendASCII("storage/test/data/quota_database"); + source_path = source_path.AppendASCII(file); + EXPECT_TRUE(base::PathExists(source_path)); + + std::string contents; + base::ReadFileToString(source_path, &contents); + return contents; + } + + bool LoadDatabase(const char* file, const base::FilePath& db_path) { + std::string contents = GetDatabaseData(file); + if (contents.empty()) + return false; + + sql::Database db; + if (!db.Open(db_path) || !db.Execute(contents.data())) + return false; + return true; + } + + void MigrateDatabase() { + QuotaDatabase db(DbPath()); + EXPECT_TRUE(db.LazyOpen(true)); + EXPECT_TRUE(db.db_.get()); + } + + std::string GetCurrentSchema() { + base::FilePath current_version_path = + temp_directory_.GetPath().AppendASCII("current_version.db"); + EXPECT_TRUE(LoadDatabase("version_6.sql", current_version_path)); + sql::Database db; + EXPECT_TRUE(db.Open(current_version_path)); + return db.GetSchema(); + } + + base::ScopedTempDir temp_directory_; +}; + +TEST_F(QuotaDatabaseMigrationsTest, UpgradeSchemaFromV5) { + ASSERT_TRUE(LoadDatabase("version_5.sql", DbPath())); + + { + sql::Database db; + ASSERT_TRUE(db.Open(DbPath())); + + ASSERT_TRUE(db.DoesTableExist("HostQuotaTable")); + ASSERT_TRUE(db.DoesTableExist("EvictionInfoTable")); + ASSERT_TRUE(db.DoesTableExist("OriginInfoTable")); + ASSERT_FALSE(db.DoesTableExist("buckets")); + + // Check populated data. + EXPECT_EQ( + "http://a/|0|123|13260644621105493|13242931862595604," + "http://b/|0|111|13250042735631065|13260999511438890," + "http://c/|1|321|13261163582572088|13261079941303629", + sql::test::ExecuteWithResults( + &db, "SELECT * FROM OriginInfoTable ORDER BY origin ASC", "|", + ",")); + EXPECT_EQ("a.com,b.com,c.com", + sql::test::ExecuteWithResults( + &db, "SELECT host FROM HostQuotaTable ORDER BY host ASC", "|", + ",")); + } + + MigrateDatabase(); + + // Verify upgraded schema. + { + sql::Database db; + ASSERT_TRUE(db.Open(DbPath())); + + ASSERT_TRUE(db.DoesTableExist("quota")); + ASSERT_TRUE(db.DoesTableExist("eviction_info")); + ASSERT_TRUE(db.DoesTableExist("buckets")); + ASSERT_FALSE(db.DoesTableExist("HostQuotaTable")); + ASSERT_FALSE(db.DoesTableExist("EvictionInfoTable")); + ASSERT_FALSE(db.DoesTableExist("OriginInfoTable")); + + // Check that OriginInfoTable data is migrated to bucket table. + EXPECT_EQ( + "1|http://a/|0|default|123|13260644621105493|13242931862595604|" + "9223372036854775807|0," + "2|http://b/|0|default|111|13250042735631065|13260999511438890|" + "9223372036854775807|0," + "3|http://c/|1|default|321|13261163582572088|13261079941303629|" + "9223372036854775807|0", + sql::test::ExecuteWithResults( + &db, "SELECT * FROM buckets ORDER BY origin ASC", "|", ",")); + + // Check that HostQuotaTable data is migrated to quota table. + EXPECT_EQ("a.com,b.com,c.com", + sql::test::ExecuteWithResults( + &db, "SELECT host FROM quota ORDER BY host ASC", "|", ",")); + + EXPECT_EQ(GetCurrentSchema(), db.GetSchema()); + } +} + +} // namespace storage
diff --git a/storage/browser/quota/quota_database_unittest.cc b/storage/browser/quota/quota_database_unittest.cc index 8ba2e04..08e24a3 100644 --- a/storage/browser/quota/quota_database_unittest.cc +++ b/storage/browser/quota/quota_database_unittest.cc
@@ -29,343 +29,40 @@ namespace storage { namespace { -const char kDBFileName[] = "quota_manager.db"; -} // namespace // Declared to shorten the line lengths. -static const blink::mojom::StorageType kTemporary = +static const blink::mojom::StorageType kTemp = blink::mojom::StorageType::kTemporary; -static const blink::mojom::StorageType kPersistent = +static const blink::mojom::StorageType kPerm = blink::mojom::StorageType::kPersistent; -class QuotaDatabaseTest : public testing::Test { +const char kDefaultBucket[] = "default"; + +// TODO(crbug.com/889590): Replace with common converter. +url::Origin ToOrigin(const std::string& url) { + return url::Origin::Create(GURL(url)); +} + +} // namespace + +// Test parameter indicates if the database should be created for incognito +// mode. True will create the database in memory. +class QuotaDatabaseTest : public testing::TestWithParam<bool> { protected: using QuotaTableEntry = QuotaDatabase::QuotaTableEntry; - using QuotaTableCallback = QuotaDatabase::QuotaTableCallback; - using OriginInfoTableCallback = QuotaDatabase::OriginInfoTableCallback; - void LazyOpen(const base::FilePath& kDbFile) { - QuotaDatabase db(kDbFile); - EXPECT_FALSE(db.LazyOpen(false)); - ASSERT_TRUE(db.LazyOpen(true)); - EXPECT_TRUE(db.db_.get()); - EXPECT_TRUE(kDbFile.empty() || base::PathExists(kDbFile)); + void SetUp() override { ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); } + + void TearDown() override { ASSERT_TRUE(temp_directory_.Delete()); } + + bool use_in_memory_db() const { return GetParam(); } + + base::FilePath DbPath() { + return temp_directory_.GetPath().AppendASCII("quota_manager.db"); } - void Reopen(const base::FilePath& kDbFile) { - QuotaDatabase db(kDbFile); - ASSERT_TRUE(db.LazyOpen(false)); - EXPECT_TRUE(db.db_.get()); - EXPECT_TRUE(kDbFile.empty() || base::PathExists(kDbFile)); - } - - void UpgradeSchemaV2toV5(const base::FilePath& kDbFile) { - const QuotaTableEntry entries[] = { - QuotaTableEntry("a", kTemporary, 1), - QuotaTableEntry("b", kTemporary, 2), - QuotaTableEntry("c", kPersistent, 3), - }; - - CreateV2Database(kDbFile, entries, base::size(entries)); - - QuotaDatabase db(kDbFile); - EXPECT_TRUE(db.LazyOpen(true)); - EXPECT_TRUE(db.db_.get()); - - using Verifier = EntryVerifier<QuotaTableEntry>; - Verifier verifier(entries, entries + base::size(entries)); - EXPECT_TRUE(db.DumpQuotaTable( - base::BindRepeating(&Verifier::Run, base::Unretained(&verifier)))); - EXPECT_TRUE(verifier.table.empty()); - - EXPECT_TRUE(db.db_->DoesTableExist("EvictionInfoTable")); - EXPECT_TRUE(db.db_->DoesIndexExist("sqlite_autoindex_EvictionInfoTable_1")); - } - - void HostQuota(const base::FilePath& kDbFile) { - QuotaDatabase db(kDbFile); - ASSERT_TRUE(db.LazyOpen(true)); - - const char* kHost = "foo.com"; - const int kQuota1 = 13579; - const int kQuota2 = kQuota1 + 1024; - - int64_t quota = -1; - EXPECT_FALSE(db.GetHostQuota(kHost, kTemporary, "a)); - EXPECT_FALSE(db.GetHostQuota(kHost, kPersistent, "a)); - - // Insert quota for temporary. - EXPECT_TRUE(db.SetHostQuota(kHost, kTemporary, kQuota1)); - EXPECT_TRUE(db.GetHostQuota(kHost, kTemporary, "a)); - EXPECT_EQ(kQuota1, quota); - - // Update quota for temporary. - EXPECT_TRUE(db.SetHostQuota(kHost, kTemporary, kQuota2)); - EXPECT_TRUE(db.GetHostQuota(kHost, kTemporary, "a)); - EXPECT_EQ(kQuota2, quota); - - // Quota for persistent must not be updated. - EXPECT_FALSE(db.GetHostQuota(kHost, kPersistent, "a)); - - // Delete temporary storage quota. - EXPECT_TRUE(db.DeleteHostQuota(kHost, kTemporary)); - EXPECT_FALSE(db.GetHostQuota(kHost, kTemporary, "a)); - - // Delete persistent quota by setting it to zero. - EXPECT_TRUE(db.SetHostQuota(kHost, kPersistent, 0)); - EXPECT_FALSE(db.GetHostQuota(kHost, kPersistent, "a)); - } - - void OriginLastAccessTimeLRU(const base::FilePath& kDbFile) { - QuotaDatabase db(kDbFile); - ASSERT_TRUE(db.LazyOpen(true)); - - std::set<url::Origin> exceptions; - base::Optional<url::Origin> origin; - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); - EXPECT_FALSE(origin.has_value()); - - // TODO(crbug.com/889590): Use helper for url::Origin creation from string. - const url::Origin kOrigin1 = url::Origin::Create(GURL("http://a/")); - const url::Origin kOrigin2 = url::Origin::Create(GURL("http://b/")); - const url::Origin kOrigin3 = url::Origin::Create(GURL("http://c/")); - const url::Origin kOrigin4 = url::Origin::Create(GURL("http://p/")); - - // Adding three temporary storages, and - EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin1, kTemporary, - base::Time::FromJavaTime(10))); - EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin2, kTemporary, - base::Time::FromJavaTime(20))); - EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin3, kTemporary, - base::Time::FromJavaTime(30))); - - // one persistent. - EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin4, kPersistent, - base::Time::FromJavaTime(40))); - - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); - EXPECT_EQ(kOrigin1, origin); - - // Test that unlimited origins are exluded from eviction, but - // protected origins are not excluded. - scoped_refptr<MockSpecialStoragePolicy> policy( - new MockSpecialStoragePolicy); - policy->AddUnlimited(kOrigin1.GetURL()); - policy->AddProtected(kOrigin2.GetURL()); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, policy.get(), &origin)); - EXPECT_EQ(kOrigin2, origin); - - // Test that durable origins are excluded from eviction. - policy->AddDurable(kOrigin2.GetURL()); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, policy.get(), &origin)); - EXPECT_EQ(kOrigin3, origin); - - exceptions.insert(kOrigin1); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); - EXPECT_EQ(kOrigin2, origin); - - exceptions.insert(kOrigin2); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); - EXPECT_EQ(kOrigin3, origin); - - exceptions.insert(kOrigin3); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); - EXPECT_FALSE(origin.has_value()); - - EXPECT_TRUE( - db.SetOriginLastAccessTime(kOrigin1, kTemporary, base::Time::Now())); - - // Delete origin/type last access time information. - EXPECT_TRUE(db.DeleteOriginInfo(kOrigin3, kTemporary)); - - // Querying again to see if the deletion has worked. - exceptions.clear(); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); - EXPECT_EQ(kOrigin2, origin); - - exceptions.insert(kOrigin1); - exceptions.insert(kOrigin2); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); - EXPECT_FALSE(origin.has_value()); - } - - void OriginLastModifiedBetween(const base::FilePath& kDbFile) { - QuotaDatabase db(kDbFile); - ASSERT_TRUE(db.LazyOpen(true)); - - std::set<url::Origin> origins; - EXPECT_TRUE(db.GetOriginsModifiedBetween(kTemporary, &origins, base::Time(), - base::Time::Max())); - EXPECT_TRUE(origins.empty()); - - const url::Origin kOrigin1 = url::Origin::Create(GURL("http://a/")); - const url::Origin kOrigin2 = url::Origin::Create(GURL("http://b/")); - const url::Origin kOrigin3 = url::Origin::Create(GURL("http://c/")); - - // Report last mod time for the test origins. - EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin1, kTemporary, - base::Time::FromJavaTime(0))); - EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin2, kTemporary, - base::Time::FromJavaTime(10))); - EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin3, kTemporary, - base::Time::FromJavaTime(20))); - - EXPECT_TRUE(db.GetOriginsModifiedBetween(kTemporary, &origins, base::Time(), - base::Time::Max())); - EXPECT_EQ(3U, origins.size()); - EXPECT_EQ(1U, origins.count(kOrigin1)); - EXPECT_EQ(1U, origins.count(kOrigin2)); - EXPECT_EQ(1U, origins.count(kOrigin3)); - - EXPECT_TRUE(db.GetOriginsModifiedBetween( - kTemporary, &origins, base::Time::FromJavaTime(5), base::Time::Max())); - EXPECT_EQ(2U, origins.size()); - EXPECT_EQ(0U, origins.count(kOrigin1)); - EXPECT_EQ(1U, origins.count(kOrigin2)); - EXPECT_EQ(1U, origins.count(kOrigin3)); - - EXPECT_TRUE(db.GetOriginsModifiedBetween( - kTemporary, &origins, base::Time::FromJavaTime(15), base::Time::Max())); - EXPECT_EQ(1U, origins.size()); - EXPECT_EQ(0U, origins.count(kOrigin1)); - EXPECT_EQ(0U, origins.count(kOrigin2)); - EXPECT_EQ(1U, origins.count(kOrigin3)); - - EXPECT_TRUE(db.GetOriginsModifiedBetween( - kTemporary, &origins, base::Time::FromJavaTime(25), base::Time::Max())); - EXPECT_TRUE(origins.empty()); - - EXPECT_TRUE(db.GetOriginsModifiedBetween(kTemporary, &origins, - base::Time::FromJavaTime(5), - base::Time::FromJavaTime(15))); - EXPECT_EQ(1U, origins.size()); - EXPECT_EQ(0U, origins.count(kOrigin1)); - EXPECT_EQ(1U, origins.count(kOrigin2)); - EXPECT_EQ(0U, origins.count(kOrigin3)); - - EXPECT_TRUE(db.GetOriginsModifiedBetween(kTemporary, &origins, - base::Time::FromJavaTime(0), - base::Time::FromJavaTime(20))); - EXPECT_EQ(2U, origins.size()); - EXPECT_EQ(1U, origins.count(kOrigin1)); - EXPECT_EQ(1U, origins.count(kOrigin2)); - EXPECT_EQ(0U, origins.count(kOrigin3)); - - // Update origin1's mod time but for persistent storage. - EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin1, kPersistent, - base::Time::FromJavaTime(30))); - - // Must have no effects on temporary origins info. - EXPECT_TRUE(db.GetOriginsModifiedBetween( - kTemporary, &origins, base::Time::FromJavaTime(5), base::Time::Max())); - EXPECT_EQ(2U, origins.size()); - EXPECT_EQ(0U, origins.count(kOrigin1)); - EXPECT_EQ(1U, origins.count(kOrigin2)); - EXPECT_EQ(1U, origins.count(kOrigin3)); - - // One more update for persistent origin2. - EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin2, kPersistent, - base::Time::FromJavaTime(40))); - - EXPECT_TRUE(db.GetOriginsModifiedBetween(kPersistent, &origins, - base::Time::FromJavaTime(25), - base::Time::Max())); - EXPECT_EQ(2U, origins.size()); - EXPECT_EQ(1U, origins.count(kOrigin1)); - EXPECT_EQ(1U, origins.count(kOrigin2)); - EXPECT_EQ(0U, origins.count(kOrigin3)); - - EXPECT_TRUE(db.GetOriginsModifiedBetween(kPersistent, &origins, - base::Time::FromJavaTime(35), - base::Time::Max())); - EXPECT_EQ(1U, origins.size()); - EXPECT_EQ(0U, origins.count(kOrigin1)); - EXPECT_EQ(1U, origins.count(kOrigin2)); - EXPECT_EQ(0U, origins.count(kOrigin3)); - } - - void OriginLastEvicted(const base::FilePath& kDbFile) { - QuotaDatabase db(kDbFile); - ASSERT_TRUE(db.LazyOpen(true)); - - const url::Origin kOrigin1 = url::Origin::Create(GURL("http://a/")); - const url::Origin kOrigin2 = url::Origin::Create(GURL("http://b/")); - const url::Origin kOrigin3 = url::Origin::Create(GURL("http://c/")); - - base::Time last_eviction_time; - EXPECT_FALSE(db.GetOriginLastEvictionTime(kOrigin1, kTemporary, - &last_eviction_time)); - EXPECT_EQ(base::Time(), last_eviction_time); - - // Report last eviction time for the test origins. - EXPECT_TRUE(db.SetOriginLastEvictionTime(kOrigin1, kTemporary, - base::Time::FromJavaTime(10))); - EXPECT_TRUE(db.SetOriginLastEvictionTime(kOrigin2, kTemporary, - base::Time::FromJavaTime(20))); - EXPECT_TRUE(db.SetOriginLastEvictionTime(kOrigin3, kTemporary, - base::Time::FromJavaTime(30))); - - EXPECT_TRUE(db.GetOriginLastEvictionTime(kOrigin1, kTemporary, - &last_eviction_time)); - EXPECT_EQ(base::Time::FromJavaTime(10), last_eviction_time); - EXPECT_TRUE(db.GetOriginLastEvictionTime(kOrigin2, kTemporary, - &last_eviction_time)); - EXPECT_EQ(base::Time::FromJavaTime(20), last_eviction_time); - EXPECT_TRUE(db.GetOriginLastEvictionTime(kOrigin3, kTemporary, - &last_eviction_time)); - EXPECT_EQ(base::Time::FromJavaTime(30), last_eviction_time); - - // Delete last eviction times for the test origins. - EXPECT_TRUE(db.DeleteOriginLastEvictionTime(kOrigin1, kTemporary)); - EXPECT_TRUE(db.DeleteOriginLastEvictionTime(kOrigin2, kTemporary)); - EXPECT_TRUE(db.DeleteOriginLastEvictionTime(kOrigin3, kTemporary)); - - last_eviction_time = base::Time(); - EXPECT_FALSE(db.GetOriginLastEvictionTime(kOrigin1, kTemporary, - &last_eviction_time)); - EXPECT_EQ(base::Time(), last_eviction_time); - EXPECT_FALSE(db.GetOriginLastEvictionTime(kOrigin2, kTemporary, - &last_eviction_time)); - EXPECT_EQ(base::Time(), last_eviction_time); - EXPECT_FALSE(db.GetOriginLastEvictionTime(kOrigin3, kTemporary, - &last_eviction_time)); - EXPECT_EQ(base::Time(), last_eviction_time); - - // Deleting an origin that is not present should not fail. - EXPECT_TRUE(db.DeleteOriginLastEvictionTime( - url::Origin::Create(GURL("http://notpresent.com")), kTemporary)); - } - - void RegisterInitialOriginInfo(const base::FilePath& kDbFile) { - QuotaDatabase db(kDbFile); - - const url::Origin kOrigins[] = {url::Origin::Create(GURL("http://a/")), - url::Origin::Create(GURL("http://b/")), - url::Origin::Create(GURL("http://c/"))}; - std::set<url::Origin> origins(kOrigins, kOrigins + base::size(kOrigins)); - - EXPECT_TRUE(db.RegisterInitialOriginInfo(origins, kTemporary)); - - QuotaDatabase::OriginInfoTableEntry info; - info.used_count = -1; - EXPECT_TRUE(db.GetOriginInfo(url::Origin::Create(GURL("http://a/")), - kTemporary, &info)); - EXPECT_EQ(0, info.used_count); - - EXPECT_TRUE( - db.SetOriginLastAccessTime(url::Origin::Create(GURL("http://a/")), - kTemporary, base::Time::FromDoubleT(1.0))); - info.used_count = -1; - EXPECT_TRUE(db.GetOriginInfo(url::Origin::Create(GURL("http://a/")), - kTemporary, &info)); - EXPECT_EQ(1, info.used_count); - - EXPECT_TRUE(db.RegisterInitialOriginInfo(origins, kTemporary)); - - info.used_count = -1; - EXPECT_TRUE(db.GetOriginInfo(url::Origin::Create(GURL("http://a/")), - kTemporary, &info)); - EXPECT_EQ(1, info.used_count); + bool LazyOpen(QuotaDatabase* db, bool create_if_needed) { + return db->LazyOpen(create_if_needed); } template <typename EntryType> @@ -382,93 +79,30 @@ } }; - void DumpQuotaTable(const base::FilePath& kDbFile) { - QuotaTableEntry kTableEntries[] = { - QuotaTableEntry("http://go/", kTemporary, 1), - QuotaTableEntry("http://oo/", kTemporary, 2), - QuotaTableEntry("http://gle/", kPersistent, 3)}; - QuotaTableEntry* begin = kTableEntries; - QuotaTableEntry* end = kTableEntries + base::size(kTableEntries); - - QuotaDatabase db(kDbFile); - EXPECT_TRUE(db.LazyOpen(true)); - AssignQuotaTable(db.db_.get(), begin, end); - db.Commit(); - - using Verifier = EntryVerifier<QuotaTableEntry>; - Verifier verifier(begin, end); - EXPECT_TRUE(db.DumpQuotaTable( - base::BindRepeating(&Verifier::Run, base::Unretained(&verifier)))); - EXPECT_TRUE(verifier.table.empty()); + bool DumpQuotaTable(QuotaDatabase* quota_database, + const QuotaDatabase::QuotaTableCallback& callback) { + return quota_database->DumpQuotaTable(callback); } - void DumpOriginInfoTable(const base::FilePath& kDbFile) { - base::Time now(base::Time::Now()); - using Entry = QuotaDatabase::OriginInfoTableEntry; - Entry kTableEntries[] = { - Entry(url::Origin::Create(GURL("http://go/")), kTemporary, 2147483647, - now, now), - Entry(url::Origin::Create(GURL("http://oo/")), kTemporary, 0, now, now), - Entry(url::Origin::Create(GURL("http://gle/")), kTemporary, 1, now, - now), - }; - Entry* begin = kTableEntries; - Entry* end = kTableEntries + base::size(kTableEntries); - - QuotaDatabase db(kDbFile); - EXPECT_TRUE(db.LazyOpen(true)); - AssignOriginInfoTable(db.db_.get(), begin, end); - db.Commit(); - - using Verifier = EntryVerifier<Entry>; - Verifier verifier(begin, end); - EXPECT_TRUE(db.DumpOriginInfoTable( - base::BindRepeating(&Verifier::Run, base::Unretained(&verifier)))); - EXPECT_TRUE(verifier.table.empty()); + bool DumpBucketTable(QuotaDatabase* quota_database, + const QuotaDatabase::BucketTableCallback& callback) { + return quota_database->DumpBucketTable(callback); } - void GetOriginInfo(const base::FilePath& kDbFile) { - const url::Origin kOrigin = url::Origin::Create(GURL("http://go/")); - using Entry = QuotaDatabase::OriginInfoTableEntry; - Entry kTableEntries[] = { - Entry(kOrigin, kTemporary, 100, base::Time(), base::Time())}; - Entry* begin = kTableEntries; - Entry* end = kTableEntries + base::size(kTableEntries); - - QuotaDatabase db(kDbFile); - EXPECT_TRUE(db.LazyOpen(true)); - AssignOriginInfoTable(db.db_.get(), begin, end); - db.Commit(); - - { - Entry entry; - EXPECT_TRUE(db.GetOriginInfo(kOrigin, kTemporary, &entry)); - EXPECT_EQ(kTableEntries[0].type, entry.type); - EXPECT_EQ(kTableEntries[0].origin, entry.origin); - EXPECT_EQ(kTableEntries[0].used_count, entry.used_count); - EXPECT_EQ(kTableEntries[0].last_access_time, entry.last_access_time); - EXPECT_EQ(kTableEntries[0].last_modified_time, entry.last_modified_time); - } - - { - Entry entry; - EXPECT_FALSE( - db.GetOriginInfo(url::Origin::Create(GURL("http://notpresent.org/")), - kTemporary, &entry)); - } - } - - private: template <typename Iterator> - void AssignQuotaTable(sql::Database* db, Iterator itr, Iterator end) { - ASSERT_NE(db, (sql::Database*)nullptr); + void AssignQuotaTable(QuotaDatabase* quota_database, + Iterator itr, + Iterator end) { + ASSERT_NE(quota_database->db_.get(), nullptr); for (; itr != end; ++itr) { const char* kSql = - "INSERT INTO HostQuotaTable" - " (host, type, quota)" - " VALUES (?, ?, ?)"; + // clang-format off + "INSERT INTO quota(host, type, quota) " + "VALUES (?, ?, ?)"; + // clang-format on sql::Statement statement; - statement.Assign(db->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.Assign( + quota_database->db_.get()->GetCachedStatement(SQL_FROM_HERE, kSql)); ASSERT_TRUE(statement.is_valid()); statement.BindString(0, itr->host); @@ -476,146 +110,608 @@ statement.BindInt64(2, itr->quota); EXPECT_TRUE(statement.Run()); } + quota_database->Commit(); } template <typename Iterator> - void AssignOriginInfoTable(sql::Database* db, Iterator itr, Iterator end) { - ASSERT_NE(db, (sql::Database*)nullptr); + void AssignBucketTable(QuotaDatabase* quota_database, + Iterator itr, + Iterator end) { + ASSERT_NE(quota_database->db_.get(), (sql::Database*)nullptr); for (; itr != end; ++itr) { const char* kSql = - "INSERT INTO OriginInfoTable" - " (origin, type, used_count, last_access_time, last_modified_time)" - " VALUES (?, ?, ?, ?, ?)"; + // clang-format off + "INSERT INTO buckets(" + "id," + "origin," + "type," + "name," + "use_count," + "last_accessed," + "last_modified," + "expiration," + "quota) " + "VALUES (?, ?, ?, ?, ?, ?, ?, 0, 0)"; + // clang-format on sql::Statement statement; - statement.Assign(db->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.Assign( + quota_database->db_->GetCachedStatement(SQL_FROM_HERE, kSql)); ASSERT_TRUE(statement.is_valid()); - statement.BindString(0, itr->origin.GetURL().spec()); - statement.BindInt(1, static_cast<int>(itr->type)); - statement.BindInt(2, itr->used_count); - statement.BindTime(3, itr->last_access_time); - statement.BindTime(4, itr->last_modified_time); + statement.BindInt64(0, itr->bucket_id); + statement.BindString(1, itr->origin.GetURL().spec()); + statement.BindInt(2, static_cast<int>(itr->type)); + statement.BindString(3, itr->name); + statement.BindInt(4, itr->use_count); + statement.BindTime(5, itr->last_accessed); + statement.BindTime(6, itr->last_modified); EXPECT_TRUE(statement.Run()); } + quota_database->Commit(); } - bool OpenDatabase(sql::Database* db, const base::FilePath& kDbFile) { - if (kDbFile.empty()) { - return db->OpenInMemory(); - } - if (!base::CreateDirectory(kDbFile.DirName())) - return false; - if (!db->Open(kDbFile)) - return false; - db->Preload(); - return true; - } - - // Create V2 database and populate some data. - void CreateV2Database( - const base::FilePath& kDbFile, - const QuotaTableEntry* entries, - size_t entries_size) { - std::unique_ptr<sql::Database> db(new sql::Database); - std::unique_ptr<sql::MetaTable> meta_table(new sql::MetaTable); - - // V2 schema definitions. - static const int kCurrentVersion = 2; - static const int kCompatibleVersion = 2; - static const char kHostQuotaTable[] = "HostQuotaTable"; - static const char kOriginLastAccessTable[] = "OriginLastAccessTable"; - static const QuotaDatabase::TableSchema kTables[] = { - { kHostQuotaTable, - "(host TEXT NOT NULL," - " type INTEGER NOT NULL," - " quota INTEGER," - " UNIQUE(host, type))" }, - { kOriginLastAccessTable, - "(origin TEXT NOT NULL," - " type INTEGER NOT NULL," - " used_count INTEGER," - " last_access_time INTEGER," - " UNIQUE(origin, type))" }, - }; - static const QuotaDatabase::IndexSchema kIndexes[] = { - { "HostIndex", - kHostQuotaTable, - "(host)", - false }, - { "OriginLastAccessIndex", - kOriginLastAccessTable, - "(origin, last_access_time)", - false }, - }; - - ASSERT_TRUE(OpenDatabase(db.get(), kDbFile)); - EXPECT_TRUE(QuotaDatabase::CreateSchema( - db.get(), meta_table.get(), kCurrentVersion, kCompatibleVersion, - kTables, base::size(kTables), kIndexes, base::size(kIndexes))); - - // V2 and V3 QuotaTable are compatible, so we can simply use - // AssignQuotaTable to poplulate v2 database here. - db->BeginTransaction(); - AssignQuotaTable(db.get(), entries, entries + entries_size); - db->CommitTransaction(); - } - + private: base::test::SingleThreadTaskEnvironment task_environment_; + base::ScopedTempDir temp_directory_; }; -TEST_F(QuotaDatabaseTest, LazyOpen) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - LazyOpen(kDbFile); - LazyOpen(base::FilePath()); +TEST_P(QuotaDatabaseTest, LazyOpen) { + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_FALSE(LazyOpen(&db, /*create_if_needed=*/false)); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + + if (GetParam()) { + // Path should not exist for incognito mode. + ASSERT_FALSE(base::PathExists(DbPath())); + } else { + ASSERT_TRUE(base::PathExists(DbPath())); + } } -TEST_F(QuotaDatabaseTest, UpgradeSchema) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - UpgradeSchemaV2toV5(kDbFile); +TEST_P(QuotaDatabaseTest, HostQuota) { + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + + const char* kHost = "foo.com"; + const int kQuota1 = 13579; + const int kQuota2 = kQuota1 + 1024; + + int64_t quota = -1; + EXPECT_FALSE(db.GetHostQuota(kHost, kTemp, "a)); + EXPECT_FALSE(db.GetHostQuota(kHost, kPerm, "a)); + + // Insert quota for temporary. + EXPECT_TRUE(db.SetHostQuota(kHost, kTemp, kQuota1)); + EXPECT_TRUE(db.GetHostQuota(kHost, kTemp, "a)); + EXPECT_EQ(kQuota1, quota); + + // Update quota for temporary. + EXPECT_TRUE(db.SetHostQuota(kHost, kTemp, kQuota2)); + EXPECT_TRUE(db.GetHostQuota(kHost, kTemp, "a)); + EXPECT_EQ(kQuota2, quota); + + // Quota for persistent must not be updated. + EXPECT_FALSE(db.GetHostQuota(kHost, kPerm, "a)); + + // Delete temporary storage quota. + EXPECT_TRUE(db.DeleteHostQuota(kHost, kTemp)); + EXPECT_FALSE(db.GetHostQuota(kHost, kTemp, "a)); + + // Delete persistent quota by setting it to zero. + EXPECT_TRUE(db.SetHostQuota(kHost, kPerm, 0)); + EXPECT_FALSE(db.GetHostQuota(kHost, kPerm, "a)); } -TEST_F(QuotaDatabaseTest, HostQuota) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - HostQuota(kDbFile); - HostQuota(base::FilePath()); +TEST_P(QuotaDatabaseTest, OriginLastAccessTimeLRU) { + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + + std::set<url::Origin> exceptions; + base::Optional<url::Origin> origin; + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, nullptr, &origin)); + EXPECT_FALSE(origin.has_value()); + + const url::Origin kOrigin1 = ToOrigin("http://a/"); + const url::Origin kOrigin2 = ToOrigin("http://b/"); + const url::Origin kOrigin3 = ToOrigin("http://c/"); + const url::Origin kOrigin4 = ToOrigin("http://p/"); + + // Adding three temporary storages, and + EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin1, kTemp, + base::Time::FromJavaTime(10))); + EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin2, kTemp, + base::Time::FromJavaTime(20))); + EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin3, kTemp, + base::Time::FromJavaTime(30))); + + // one persistent. + EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin4, kPerm, + base::Time::FromJavaTime(40))); + + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, nullptr, &origin)); + EXPECT_EQ(kOrigin1, origin); + + // Test that unlimited origins are excluded from eviction, but + // protected origins are not excluded. + scoped_refptr<MockSpecialStoragePolicy> policy(new MockSpecialStoragePolicy); + policy->AddUnlimited(kOrigin1.GetURL()); + policy->AddProtected(kOrigin2.GetURL()); + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, policy.get(), &origin)); + EXPECT_EQ(kOrigin2, origin); + + // Test that durable origins are excluded from eviction. + policy->AddDurable(kOrigin2.GetURL()); + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, policy.get(), &origin)); + EXPECT_EQ(kOrigin3, origin); + + exceptions.insert(kOrigin1); + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, nullptr, &origin)); + EXPECT_EQ(kOrigin2, origin); + + exceptions.insert(kOrigin2); + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, nullptr, &origin)); + EXPECT_EQ(kOrigin3, origin); + + exceptions.insert(kOrigin3); + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, nullptr, &origin)); + EXPECT_FALSE(origin.has_value()); + + EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin1, kTemp, base::Time::Now())); + + // Delete origin/type last access time information. + EXPECT_TRUE(db.DeleteOriginInfo(kOrigin3, kTemp)); + + // Querying again to see if the deletion has worked. + exceptions.clear(); + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, nullptr, &origin)); + EXPECT_EQ(kOrigin2, origin); + + exceptions.insert(kOrigin1); + exceptions.insert(kOrigin2); + EXPECT_TRUE(db.GetLRUOrigin(kTemp, exceptions, nullptr, &origin)); + EXPECT_FALSE(origin.has_value()); } -TEST_F(QuotaDatabaseTest, OriginLastAccessTimeLRU) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - OriginLastAccessTimeLRU(kDbFile); - OriginLastAccessTimeLRU(base::FilePath()); +TEST_P(QuotaDatabaseTest, BucketLastAccessTimeLRU) { + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + + std::set<url::Origin> exceptions; + base::Optional<int64_t> bucket_id; + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, nullptr, &bucket_id)); + EXPECT_FALSE(bucket_id.has_value()); + + // Insert bucket entries into BucketTable. + base::Time now(base::Time::Now()); + using Entry = QuotaDatabase::BucketTableEntry; + Entry bucket1 = Entry(0, ToOrigin("http://a/"), kTemp, "A", 99, now, now); + Entry bucket2 = Entry(1, ToOrigin("http://b/"), kTemp, "B", 0, now, now); + Entry bucket3 = Entry(2, ToOrigin("http://c/"), kTemp, "C", 1, now, now); + Entry bucket4 = Entry(3, ToOrigin("http://d/"), kPerm, "D", 5, now, now); + Entry kTableEntries[] = {bucket1, bucket2, bucket3, bucket4}; + Entry* begin = kTableEntries; + Entry* end = std::end(kTableEntries); + AssignBucketTable(&db, begin, end); + + // Update access time for three temporary storages, and + EXPECT_TRUE(db.SetBucketLastAccessTime(bucket1.bucket_id, + base::Time::FromJavaTime(10))); + EXPECT_TRUE(db.SetBucketLastAccessTime(bucket2.bucket_id, + base::Time::FromJavaTime(20))); + EXPECT_TRUE(db.SetBucketLastAccessTime(bucket3.bucket_id, + base::Time::FromJavaTime(30))); + + // one persistent. + EXPECT_TRUE(db.SetBucketLastAccessTime(bucket4.bucket_id, + base::Time::FromJavaTime(40))); + + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, nullptr, &bucket_id)); + EXPECT_EQ(bucket1.bucket_id, bucket_id); + + // Test that unlimited origins are excluded from eviction, but + // protected origins are not excluded. + scoped_refptr<MockSpecialStoragePolicy> policy(new MockSpecialStoragePolicy); + policy->AddUnlimited(bucket1.origin.GetURL()); + policy->AddProtected(bucket2.origin.GetURL()); + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, policy.get(), &bucket_id)); + EXPECT_EQ(bucket2.bucket_id, bucket_id); + + // Test that durable origins are excluded from eviction. + policy->AddDurable(bucket2.origin.GetURL()); + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, policy.get(), &bucket_id)); + EXPECT_EQ(bucket3.bucket_id, bucket_id); + + exceptions.insert(bucket1.origin); + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, nullptr, &bucket_id)); + EXPECT_EQ(bucket2.bucket_id, bucket_id); + + exceptions.insert(bucket2.origin); + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, nullptr, &bucket_id)); + EXPECT_EQ(bucket3.bucket_id, bucket_id); + + exceptions.insert(bucket3.origin); + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, nullptr, &bucket_id)); + EXPECT_FALSE(bucket_id.has_value()); + + EXPECT_TRUE(db.SetBucketLastAccessTime(bucket1.bucket_id, base::Time::Now())); + + // Delete origin/type last access time information. + EXPECT_TRUE(db.DeleteBucketInfo(bucket3.bucket_id)); + + // Querying again to see if the deletion has worked. + exceptions.clear(); + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, nullptr, &bucket_id)); + EXPECT_EQ(bucket2.bucket_id, bucket_id); + + exceptions.insert(bucket1.origin); + exceptions.insert(bucket2.origin); + EXPECT_TRUE(db.GetLRUBucket(kTemp, exceptions, nullptr, &bucket_id)); + EXPECT_FALSE(bucket_id.has_value()); } -TEST_F(QuotaDatabaseTest, OriginLastModifiedBetween) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - OriginLastModifiedBetween(kDbFile); - OriginLastModifiedBetween(base::FilePath()); +TEST_P(QuotaDatabaseTest, OriginLastModifiedBetween) { + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + + std::set<url::Origin> origins; + EXPECT_TRUE(db.GetOriginsModifiedBetween(kTemp, &origins, base::Time(), + base::Time::Max())); + EXPECT_TRUE(origins.empty()); + + const url::Origin kOrigin1 = ToOrigin("http://a/"); + const url::Origin kOrigin2 = ToOrigin("http://b/"); + const url::Origin kOrigin3 = ToOrigin("http://c/"); + + // Report last mod time for the test origins. + EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin1, kTemp, + base::Time::FromJavaTime(0))); + EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin2, kTemp, + base::Time::FromJavaTime(10))); + EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin3, kTemp, + base::Time::FromJavaTime(20))); + + EXPECT_TRUE(db.GetOriginsModifiedBetween(kTemp, &origins, base::Time(), + base::Time::Max())); + EXPECT_EQ(3U, origins.size()); + EXPECT_EQ(1U, origins.count(kOrigin1)); + EXPECT_EQ(1U, origins.count(kOrigin2)); + EXPECT_EQ(1U, origins.count(kOrigin3)); + + EXPECT_TRUE(db.GetOriginsModifiedBetween( + kTemp, &origins, base::Time::FromJavaTime(5), base::Time::Max())); + EXPECT_EQ(2U, origins.size()); + EXPECT_EQ(0U, origins.count(kOrigin1)); + EXPECT_EQ(1U, origins.count(kOrigin2)); + EXPECT_EQ(1U, origins.count(kOrigin3)); + + EXPECT_TRUE(db.GetOriginsModifiedBetween( + kTemp, &origins, base::Time::FromJavaTime(15), base::Time::Max())); + EXPECT_EQ(1U, origins.size()); + EXPECT_EQ(0U, origins.count(kOrigin1)); + EXPECT_EQ(0U, origins.count(kOrigin2)); + EXPECT_EQ(1U, origins.count(kOrigin3)); + + EXPECT_TRUE(db.GetOriginsModifiedBetween( + kTemp, &origins, base::Time::FromJavaTime(25), base::Time::Max())); + EXPECT_TRUE(origins.empty()); + + EXPECT_TRUE(db.GetOriginsModifiedBetween(kTemp, &origins, + base::Time::FromJavaTime(5), + base::Time::FromJavaTime(15))); + EXPECT_EQ(1U, origins.size()); + EXPECT_EQ(0U, origins.count(kOrigin1)); + EXPECT_EQ(1U, origins.count(kOrigin2)); + EXPECT_EQ(0U, origins.count(kOrigin3)); + + EXPECT_TRUE(db.GetOriginsModifiedBetween(kTemp, &origins, + base::Time::FromJavaTime(0), + base::Time::FromJavaTime(20))); + EXPECT_EQ(2U, origins.size()); + EXPECT_EQ(1U, origins.count(kOrigin1)); + EXPECT_EQ(1U, origins.count(kOrigin2)); + EXPECT_EQ(0U, origins.count(kOrigin3)); + + // Update origin1's mod time but for persistent storage. + EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin1, kPerm, + base::Time::FromJavaTime(30))); + + // Must have no effects on temporary origins info. + EXPECT_TRUE(db.GetOriginsModifiedBetween( + kTemp, &origins, base::Time::FromJavaTime(5), base::Time::Max())); + EXPECT_EQ(2U, origins.size()); + EXPECT_EQ(0U, origins.count(kOrigin1)); + EXPECT_EQ(1U, origins.count(kOrigin2)); + EXPECT_EQ(1U, origins.count(kOrigin3)); + + // One more update for persistent origin2. + EXPECT_TRUE(db.SetOriginLastModifiedTime(kOrigin2, kPerm, + base::Time::FromJavaTime(40))); + + EXPECT_TRUE(db.GetOriginsModifiedBetween( + kPerm, &origins, base::Time::FromJavaTime(25), base::Time::Max())); + EXPECT_EQ(2U, origins.size()); + EXPECT_EQ(1U, origins.count(kOrigin1)); + EXPECT_EQ(1U, origins.count(kOrigin2)); + EXPECT_EQ(0U, origins.count(kOrigin3)); + + EXPECT_TRUE(db.GetOriginsModifiedBetween( + kPerm, &origins, base::Time::FromJavaTime(35), base::Time::Max())); + EXPECT_EQ(1U, origins.size()); + EXPECT_EQ(0U, origins.count(kOrigin1)); + EXPECT_EQ(1U, origins.count(kOrigin2)); + EXPECT_EQ(0U, origins.count(kOrigin3)); } -TEST_F(QuotaDatabaseTest, OriginLastEvicted) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - OriginLastEvicted(kDbFile); - OriginLastEvicted(base::FilePath()); +TEST_P(QuotaDatabaseTest, BucketLastModifiedBetween) { + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + + std::set<int64_t> bucket_ids; + EXPECT_TRUE(db.GetBucketsModifiedBetween(kTemp, &bucket_ids, base::Time(), + base::Time::Max())); + EXPECT_TRUE(bucket_ids.empty()); + + // Insert bucket entries into BucketTable. + base::Time now(base::Time::Now()); + using Entry = QuotaDatabase::BucketTableEntry; + Entry bucket1 = Entry(0, ToOrigin("http://a/"), kTemp, "A", 0, now, now); + Entry bucket2 = Entry(1, ToOrigin("http://b/"), kTemp, "B", 0, now, now); + Entry bucket3 = Entry(2, ToOrigin("http://c/"), kTemp, "C", 0, now, now); + Entry bucket4 = Entry(3, ToOrigin("http://d/"), kPerm, "D", 0, now, now); + Entry kTableEntries[] = {bucket1, bucket2, bucket3, bucket4}; + Entry* begin = kTableEntries; + Entry* end = std::end(kTableEntries); + AssignBucketTable(&db, begin, end); + + // Report last mod time for the buckets. + EXPECT_TRUE(db.SetBucketLastModifiedTime(bucket1.bucket_id, + base::Time::FromJavaTime(0))); + EXPECT_TRUE(db.SetBucketLastModifiedTime(bucket2.bucket_id, + base::Time::FromJavaTime(10))); + EXPECT_TRUE(db.SetBucketLastModifiedTime(bucket3.bucket_id, + base::Time::FromJavaTime(20))); + EXPECT_TRUE(db.SetBucketLastModifiedTime(bucket4.bucket_id, + base::Time::FromJavaTime(30))); + + EXPECT_TRUE(db.GetBucketsModifiedBetween(kTemp, &bucket_ids, base::Time(), + base::Time::Max())); + EXPECT_EQ(3U, bucket_ids.size()); + EXPECT_EQ(1U, bucket_ids.count(bucket1.bucket_id)); + EXPECT_EQ(1U, bucket_ids.count(bucket2.bucket_id)); + EXPECT_EQ(1U, bucket_ids.count(bucket3.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket4.bucket_id)); + + EXPECT_TRUE(db.GetBucketsModifiedBetween( + kTemp, &bucket_ids, base::Time::FromJavaTime(5), base::Time::Max())); + EXPECT_EQ(2U, bucket_ids.size()); + EXPECT_EQ(0U, bucket_ids.count(bucket1.bucket_id)); + EXPECT_EQ(1U, bucket_ids.count(bucket2.bucket_id)); + EXPECT_EQ(1U, bucket_ids.count(bucket3.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket4.bucket_id)); + + EXPECT_TRUE(db.GetBucketsModifiedBetween( + kTemp, &bucket_ids, base::Time::FromJavaTime(15), base::Time::Max())); + EXPECT_EQ(1U, bucket_ids.size()); + EXPECT_EQ(0U, bucket_ids.count(bucket1.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket2.bucket_id)); + EXPECT_EQ(1U, bucket_ids.count(bucket3.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket4.bucket_id)); + + EXPECT_TRUE(db.GetBucketsModifiedBetween( + kTemp, &bucket_ids, base::Time::FromJavaTime(25), base::Time::Max())); + EXPECT_TRUE(bucket_ids.empty()); + + EXPECT_TRUE(db.GetBucketsModifiedBetween(kTemp, &bucket_ids, + base::Time::FromJavaTime(5), + base::Time::FromJavaTime(15))); + EXPECT_EQ(1U, bucket_ids.size()); + EXPECT_EQ(0U, bucket_ids.count(bucket1.bucket_id)); + EXPECT_EQ(1U, bucket_ids.count(bucket2.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket3.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket4.bucket_id)); + + EXPECT_TRUE(db.GetBucketsModifiedBetween(kTemp, &bucket_ids, + base::Time::FromJavaTime(0), + base::Time::FromJavaTime(20))); + EXPECT_EQ(2U, bucket_ids.size()); + EXPECT_EQ(1U, bucket_ids.count(bucket1.bucket_id)); + EXPECT_EQ(1U, bucket_ids.count(bucket2.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket3.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket4.bucket_id)); + + EXPECT_TRUE(db.GetBucketsModifiedBetween(kPerm, &bucket_ids, + base::Time::FromJavaTime(0), + base::Time::FromJavaTime(35))); + EXPECT_EQ(1U, bucket_ids.size()); + EXPECT_EQ(0U, bucket_ids.count(bucket1.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket2.bucket_id)); + EXPECT_EQ(0U, bucket_ids.count(bucket3.bucket_id)); + EXPECT_EQ(1U, bucket_ids.count(bucket4.bucket_id)); } +TEST_P(QuotaDatabaseTest, OriginLastEvicted) { + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + + const url::Origin kOrigin1 = ToOrigin("http://a/"); + const url::Origin kOrigin2 = ToOrigin("http://b/"); + const url::Origin kOrigin3 = ToOrigin("http://c/"); + + base::Time last_eviction_time; + EXPECT_FALSE( + db.GetOriginLastEvictionTime(kOrigin1, kTemp, &last_eviction_time)); + EXPECT_EQ(base::Time(), last_eviction_time); + + // Report last eviction time for the test origins. + EXPECT_TRUE(db.SetOriginLastEvictionTime(kOrigin1, kTemp, + base::Time::FromJavaTime(10))); + EXPECT_TRUE(db.SetOriginLastEvictionTime(kOrigin2, kTemp, + base::Time::FromJavaTime(20))); + EXPECT_TRUE(db.SetOriginLastEvictionTime(kOrigin3, kTemp, + base::Time::FromJavaTime(30))); + + EXPECT_TRUE( + db.GetOriginLastEvictionTime(kOrigin1, kTemp, &last_eviction_time)); + EXPECT_EQ(base::Time::FromJavaTime(10), last_eviction_time); + EXPECT_TRUE( + db.GetOriginLastEvictionTime(kOrigin2, kTemp, &last_eviction_time)); + EXPECT_EQ(base::Time::FromJavaTime(20), last_eviction_time); + EXPECT_TRUE( + db.GetOriginLastEvictionTime(kOrigin3, kTemp, &last_eviction_time)); + EXPECT_EQ(base::Time::FromJavaTime(30), last_eviction_time); + + // Delete last eviction times for the test origins. + EXPECT_TRUE(db.DeleteOriginLastEvictionTime(kOrigin1, kTemp)); + EXPECT_TRUE(db.DeleteOriginLastEvictionTime(kOrigin2, kTemp)); + EXPECT_TRUE(db.DeleteOriginLastEvictionTime(kOrigin3, kTemp)); + + last_eviction_time = base::Time(); + EXPECT_FALSE( + db.GetOriginLastEvictionTime(kOrigin1, kTemp, &last_eviction_time)); + EXPECT_EQ(base::Time(), last_eviction_time); + EXPECT_FALSE( + db.GetOriginLastEvictionTime(kOrigin2, kTemp, &last_eviction_time)); + EXPECT_EQ(base::Time(), last_eviction_time); + EXPECT_FALSE( + db.GetOriginLastEvictionTime(kOrigin3, kTemp, &last_eviction_time)); + EXPECT_EQ(base::Time(), last_eviction_time); + + // Deleting an origin that is not present should not fail. + EXPECT_TRUE(db.DeleteOriginLastEvictionTime(ToOrigin("http://notpresent.com"), + kTemp)); +} + +TEST_P(QuotaDatabaseTest, RegisterInitialOriginInfo) { + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + + const url::Origin kOrigins[] = {ToOrigin("http://a/"), ToOrigin("http://b/"), + ToOrigin("http://c/")}; + std::set<url::Origin> origins(kOrigins, std::end(kOrigins)); + + EXPECT_TRUE(db.RegisterInitialOriginInfo(origins, kTemp)); + + QuotaDatabase::BucketTableEntry info; + info.use_count = -1; + EXPECT_TRUE(db.GetOriginInfo(ToOrigin("http://a/"), kTemp, &info)); + EXPECT_EQ(0, info.use_count); + + EXPECT_TRUE(db.SetOriginLastAccessTime(ToOrigin("http://a/"), kTemp, + base::Time::FromDoubleT(1.0))); + info.use_count = -1; + EXPECT_TRUE(db.GetOriginInfo(ToOrigin("http://a/"), kTemp, &info)); + EXPECT_EQ(1, info.use_count); + + EXPECT_TRUE(db.RegisterInitialOriginInfo(origins, kTemp)); + + info.use_count = -1; + EXPECT_TRUE(db.GetOriginInfo(ToOrigin("http://a/"), kTemp, &info)); + EXPECT_EQ(1, info.use_count); +} + +TEST_P(QuotaDatabaseTest, DumpQuotaTable) { + QuotaTableEntry kTableEntries[] = {QuotaTableEntry("http://go/", kTemp, 1), + QuotaTableEntry("http://oo/", kTemp, 2), + QuotaTableEntry("http://gle/", kPerm, 3)}; + QuotaTableEntry* begin = kTableEntries; + QuotaTableEntry* end = std::end(kTableEntries); + + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + AssignQuotaTable(&db, begin, end); + + using Verifier = EntryVerifier<QuotaTableEntry>; + Verifier verifier(begin, end); + EXPECT_TRUE(DumpQuotaTable( + &db, base::BindRepeating(&Verifier::Run, base::Unretained(&verifier)))); + EXPECT_TRUE(verifier.table.empty()); +} + +TEST_P(QuotaDatabaseTest, DumpBucketTable) { + base::Time now(base::Time::Now()); + using Entry = QuotaDatabase::BucketTableEntry; + Entry kTableEntries[] = { + Entry(0, ToOrigin("http://go/"), kTemp, kDefaultBucket, 2147483647, now, + now), + Entry(1, ToOrigin("http://oo/"), kTemp, kDefaultBucket, 0, now, now), + Entry(2, ToOrigin("http://gle/"), kTemp, kDefaultBucket, 1, now, now), + }; + Entry* begin = kTableEntries; + Entry* end = std::end(kTableEntries); + + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + AssignBucketTable(&db, begin, end); + + using Verifier = EntryVerifier<Entry>; + Verifier verifier(begin, end); + EXPECT_TRUE(DumpBucketTable( + &db, base::BindRepeating(&Verifier::Run, base::Unretained(&verifier)))); + EXPECT_TRUE(verifier.table.empty()); +} + +TEST_P(QuotaDatabaseTest, GetOriginInfo) { + const url::Origin kOrigin = ToOrigin("http://go/"); + using Entry = QuotaDatabase::BucketTableEntry; + Entry kTableEntries[] = {Entry(0, kOrigin, kTemp, kDefaultBucket, 100, + base::Time(), base::Time())}; + Entry* begin = kTableEntries; + Entry* end = std::end(kTableEntries); + + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + AssignBucketTable(&db, begin, end); + + { + Entry entry; + EXPECT_TRUE(db.GetOriginInfo(kOrigin, kTemp, &entry)); + EXPECT_EQ(kTableEntries[0].type, entry.type); + EXPECT_EQ(kTableEntries[0].origin, entry.origin); + EXPECT_EQ(kTableEntries[0].name, entry.name); + EXPECT_EQ(kTableEntries[0].use_count, entry.use_count); + EXPECT_EQ(kTableEntries[0].last_accessed, entry.last_accessed); + EXPECT_EQ(kTableEntries[0].last_modified, entry.last_modified); + } + + { + Entry entry; + EXPECT_FALSE( + db.GetOriginInfo(ToOrigin("http://notpresent.org/"), kTemp, &entry)); + } +} + +TEST_P(QuotaDatabaseTest, GetBucketInfo) { + using Entry = QuotaDatabase::BucketTableEntry; + Entry kTableEntries[] = {Entry(123, ToOrigin("http://go/"), kTemp, + "TestBucket", 100, base::Time(), + base::Time())}; + Entry* begin = kTableEntries; + Entry* end = std::end(kTableEntries); + + QuotaDatabase db(use_in_memory_db() ? base::FilePath() : DbPath()); + EXPECT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + AssignBucketTable(&db, begin, end); + + { + Entry entry; + EXPECT_TRUE(db.GetBucketInfo(kTableEntries[0].bucket_id, &entry)); + EXPECT_EQ(kTableEntries[0].bucket_id, entry.bucket_id); + EXPECT_EQ(kTableEntries[0].type, entry.type); + EXPECT_EQ(kTableEntries[0].origin, entry.origin); + EXPECT_EQ(kTableEntries[0].name, entry.name); + EXPECT_EQ(kTableEntries[0].use_count, entry.use_count); + EXPECT_EQ(kTableEntries[0].last_accessed, entry.last_accessed); + EXPECT_EQ(kTableEntries[0].last_modified, entry.last_modified); + } + + { + Entry entry; + EXPECT_FALSE(db.GetBucketInfo(456, &entry)); + } +} + +// Non-parameterized tests. TEST_F(QuotaDatabaseTest, BootstrapFlag) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - QuotaDatabase db(kDbFile); + QuotaDatabase db(DbPath()); EXPECT_FALSE(db.IsOriginDatabaseBootstrapped()); EXPECT_TRUE(db.SetOriginDatabaseBootstrapped(true)); @@ -624,46 +720,25 @@ EXPECT_FALSE(db.IsOriginDatabaseBootstrapped()); } -TEST_F(QuotaDatabaseTest, RegisterInitialOriginInfo) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - RegisterInitialOriginInfo(kDbFile); - RegisterInitialOriginInfo(base::FilePath()); -} - -TEST_F(QuotaDatabaseTest, DumpQuotaTable) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - DumpQuotaTable(kDbFile); - DumpQuotaTable(base::FilePath()); -} - -TEST_F(QuotaDatabaseTest, DumpOriginInfoTable) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - DumpOriginInfoTable(kDbFile); - DumpOriginInfoTable(base::FilePath()); -} - -TEST_F(QuotaDatabaseTest, GetOriginInfo) { - GetOriginInfo(base::FilePath()); -} - TEST_F(QuotaDatabaseTest, OpenCorruptedDatabase) { - base::ScopedTempDir data_dir; - ASSERT_TRUE(data_dir.CreateUniqueTempDir()); - const base::FilePath kDbFile = data_dir.GetPath().AppendASCII(kDBFileName); - LazyOpen(kDbFile); - ASSERT_TRUE(sql::test::CorruptSizeInHeader(kDbFile)); + // Create database, force corruption and close db by leaving scope. + { + QuotaDatabase db(DbPath()); + ASSERT_TRUE(LazyOpen(&db, /*create_if_needed=*/true)); + ASSERT_TRUE(sql::test::CorruptSizeInHeader(DbPath())); + } + // Reopen database and verify schema reset on reopen. { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - Reopen(kDbFile); + QuotaDatabase db(DbPath()); + ASSERT_TRUE(LazyOpen(&db, /*create_if_needed=*/false)); EXPECT_TRUE(expecter.SawExpectedErrors()); } } +INSTANTIATE_TEST_SUITE_P(All, + QuotaDatabaseTest, + /* is_incognito */ testing::Bool()); + } // namespace storage
diff --git a/storage/browser/quota/quota_manager_impl.cc b/storage/browser/quota/quota_manager_impl.cc index 7275126..c6044f1 100644 --- a/storage/browser/quota/quota_manager_impl.cc +++ b/storage/browser/quota/quota_manager_impl.cc
@@ -127,14 +127,14 @@ base::Time now = base::Time::Now(); if (is_eviction) { - QuotaDatabase::OriginInfoTableEntry entry; + QuotaDatabase::BucketTableEntry entry; database->GetOriginInfo(origin, type, &entry); UMA_HISTOGRAM_COUNTS_1M( QuotaManagerImpl::kEvictedOriginAccessedCountHistogram, - entry.used_count); + entry.use_count); UMA_HISTOGRAM_COUNTS_1000( QuotaManagerImpl::kEvictedOriginDaysSinceAccessHistogram, - (now - entry.last_access_time).InDays()); + (now - entry.last_accessed).InDays()); } if (!database->DeleteOriginInfo(origin, type)) @@ -869,20 +869,20 @@ // goes out of scope, the object is deleted. // This class is not thread-safe because there can be races when entries_ is // modified. -class QuotaManagerImpl::DumpOriginInfoTableHelper { +class QuotaManagerImpl::DumpBucketTableHelper { public: - bool DumpOriginInfoTableOnDBThread(QuotaDatabase* database) { + bool DumpBucketTableOnDBThread(QuotaDatabase* database) { DCHECK(database); - return database->DumpOriginInfoTable(base::BindRepeating( - &DumpOriginInfoTableHelper::AppendEntry, base::Unretained(this))); + return database->DumpBucketTable(base::BindRepeating( + &DumpBucketTableHelper::AppendEntry, base::Unretained(this))); } - void DidDumpOriginInfoTable(const base::WeakPtr<QuotaManagerImpl>& manager, - DumpOriginInfoTableCallback callback, - bool success) { + void DidDumpBucketTable(const base::WeakPtr<QuotaManagerImpl>& manager, + DumpBucketTableCallback callback, + bool success) { if (!manager) { // The operation was aborted. - std::move(callback).Run(OriginInfoTableEntries()); + std::move(callback).Run(BucketTableEntries()); return; } manager->DidDatabaseWork(success); @@ -890,12 +890,12 @@ } private: - bool AppendEntry(const OriginInfoTableEntry& entry) { + bool AppendEntry(const BucketTableEntry& entry) { entries_.push_back(entry); return true; } - OriginInfoTableEntries entries_; + BucketTableEntries entries_; }; // QuotaManagerImpl ----------------------------------------------------------- @@ -1462,15 +1462,14 @@ std::move(callback))); } -void QuotaManagerImpl::DumpOriginInfoTable( - DumpOriginInfoTableCallback callback) { +void QuotaManagerImpl::DumpBucketTable(DumpBucketTableCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DumpOriginInfoTableHelper* helper = new DumpOriginInfoTableHelper; + DumpBucketTableHelper* helper = new DumpBucketTableHelper; PostTaskAndReplyWithResultForDBThread( FROM_HERE, - base::BindOnce(&DumpOriginInfoTableHelper::DumpOriginInfoTableOnDBThread, + base::BindOnce(&DumpBucketTableHelper::DumpBucketTableOnDBThread, base::Unretained(helper)), - base::BindOnce(&DumpOriginInfoTableHelper::DidDumpOriginInfoTable, + base::BindOnce(&DumpBucketTableHelper::DidDumpBucketTable, base::Owned(helper), weak_factory_.GetWeakPtr(), std::move(callback))); } @@ -1683,14 +1682,14 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); UMA_HISTOGRAM_MBYTES("Quota.GlobalUsageOfPersistentStorage", usage); - // We DumpOriginInfoTable last to ensure the trackers caches are loaded. - DumpOriginInfoTable( - base::BindOnce(&QuotaManagerImpl::DidDumpOriginInfoTableForHistogram, + // We DumpBucketTable last to ensure the trackers caches are loaded. + DumpBucketTable( + base::BindOnce(&QuotaManagerImpl::DidDumpBucketTableForHistogram, weak_factory_.GetWeakPtr())); } -void QuotaManagerImpl::DidDumpOriginInfoTableForHistogram( - const OriginInfoTableEntries& entries) { +void QuotaManagerImpl::DidDumpBucketTableForHistogram( + const BucketTableEntries& entries) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::map<url::Origin, int64_t> usage_map = GetUsageTracker(StorageType::kTemporary)->GetCachedOriginsUsage(); @@ -1705,8 +1704,8 @@ if (it == usage_map.end() || it->second == 0) continue; - base::TimeDelta age = now - std::max(info.last_access_time, - info.last_modified_time); + base::TimeDelta age = + now - std::max(info.last_accessed, info.last_modified); UMA_HISTOGRAM_COUNTS_1000("Quota.AgeOfOriginInDays", age.InDays()); int64_t kilobytes = std::max(it->second / INT64_C(1024), INT64_C(1));
diff --git a/storage/browser/quota/quota_manager_impl.h b/storage/browser/quota/quota_manager_impl.h index 817f16e..ea1fb23 100644 --- a/storage/browser/quota/quota_manager_impl.h +++ b/storage/browser/quota/quota_manager_impl.h
@@ -348,7 +348,7 @@ class HostDataDeleter; class GetModifiedSinceHelper; class DumpQuotaTableHelper; - class DumpOriginInfoTableHelper; + class DumpBucketTableHelper; class StorageCleanupHelper; struct QuotaOverride { @@ -365,16 +365,16 @@ }; using QuotaTableEntry = QuotaDatabase::QuotaTableEntry; - using OriginInfoTableEntry = QuotaDatabase::OriginInfoTableEntry; + using BucketTableEntry = QuotaDatabase::BucketTableEntry; using QuotaTableEntries = std::vector<QuotaTableEntry>; - using OriginInfoTableEntries = std::vector<OriginInfoTableEntry>; + using BucketTableEntries = std::vector<BucketTableEntry>; using QuotaSettingsCallback = base::OnceCallback<void(const QuotaSettings&)>; using DumpQuotaTableCallback = base::OnceCallback<void(const QuotaTableEntries&)>; - using DumpOriginInfoTableCallback = - base::OnceCallback<void(const OriginInfoTableEntries&)>; + using DumpBucketTableCallback = + base::OnceCallback<void(const BucketTableEntries&)>; // The values returned total_space, available_space. using StorageCapacityCallback = base::OnceCallback<void(int64_t, int64_t)>; @@ -422,7 +422,7 @@ std::set<url::Origin> GetCachedOrigins(blink::mojom::StorageType type); void DumpQuotaTable(DumpQuotaTableCallback callback); - void DumpOriginInfoTable(DumpOriginInfoTableCallback callback); + void DumpBucketTable(DumpBucketTableCallback callback); void DeleteOriginDataInternal(const url::Origin& origin, blink::mojom::StorageType type, @@ -446,8 +446,7 @@ int64_t available_space); void DidGetPersistentGlobalUsageForHistogram(int64_t usage, int64_t unlimited_usage); - void DidDumpOriginInfoTableForHistogram( - const OriginInfoTableEntries& entries); + void DidDumpBucketTableForHistogram(const BucketTableEntries& entries); std::set<url::Origin> GetEvictionOriginExceptions(); void DidGetEvictionOrigin(GetOriginCallback callback,
diff --git a/storage/browser/quota/quota_manager_unittest.cc b/storage/browser/quota/quota_manager_unittest.cc index 691e619..58a8565 100644 --- a/storage/browser/quota/quota_manager_unittest.cc +++ b/storage/browser/quota/quota_manager_unittest.cc
@@ -89,7 +89,7 @@ protected: using QuotaTableEntry = QuotaManagerImpl::QuotaTableEntry; using QuotaTableEntries = QuotaManagerImpl::QuotaTableEntries; - using OriginInfoTableEntries = QuotaManagerImpl::OriginInfoTableEntries; + using BucketTableEntries = QuotaManagerImpl::BucketTableEntries; public: QuotaManagerImplTest() : mock_time_counter_(0) {} @@ -142,7 +142,7 @@ // TODO(crbug.com/1163009): Remove this method and replace all calls with // CreateAndRegisterClient() after all QuotaClients - // have been mojofied + // have been mojofied. MockQuotaClient* CreateAndRegisterLegacyClient( base::span<const MockOriginData> mock_data, QuotaClientType client_type, @@ -365,11 +365,10 @@ &QuotaManagerImplTest::DidDumpQuotaTable, weak_factory_.GetWeakPtr())); } - void DumpOriginInfoTable() { - origin_info_entries_.clear(); - quota_manager_impl_->DumpOriginInfoTable( - base::BindOnce(&QuotaManagerImplTest::DidDumpOriginInfoTable, - weak_factory_.GetWeakPtr())); + void DumpBucketTable() { + bucket_entries_.clear(); + quota_manager_impl_->DumpBucketTable(base::BindOnce( + &QuotaManagerImplTest::DidDumpBucketTable, weak_factory_.GetWeakPtr())); } void DidGetUsageInfo(UsageInfoEntries entries) { @@ -457,8 +456,8 @@ quota_entries_ = entries; } - void DidDumpOriginInfoTable(const OriginInfoTableEntries& entries) { - origin_info_entries_ = entries; + void DidDumpBucketTable(const BucketTableEntries& entries) { + bucket_entries_ = entries; } void GetUsage_WithModifyTestBody(const StorageType type); @@ -520,9 +519,7 @@ } StorageType modified_origins_type() const { return modified_origins_type_; } const QuotaTableEntries& quota_entries() const { return quota_entries_; } - const OriginInfoTableEntries& origin_info_entries() const { - return origin_info_entries_; - } + const BucketTableEntries& bucket_entries() const { return bucket_entries_; } const QuotaSettings& settings() const { return settings_; } base::FilePath profile_path() const { return data_dir_.GetPath(); } int status_callback_count() const { return status_callback_count_; } @@ -560,7 +557,7 @@ std::set<url::Origin> modified_origins_; StorageType modified_origins_type_; QuotaTableEntries quota_entries_; - OriginInfoTableEntries origin_info_entries_; + BucketTableEntries bucket_entries_; QuotaSettings settings_; int status_callback_count_; @@ -1692,10 +1689,10 @@ EvictOriginData(ToOrigin("http://foo.com/"), kTemp); task_environment_.RunUntilIdle(); - DumpOriginInfoTable(); + DumpBucketTable(); task_environment_.RunUntilIdle(); - for (const auto& entry : origin_info_entries()) { + for (const auto& entry : bucket_entries()) { if (entry.type == kTemp) EXPECT_NE(std::string("http://foo.com/"), entry.origin.GetURL().spec()); } @@ -1817,11 +1814,11 @@ EXPECT_EQ(QuotaStatusCode::kErrorInvalidModification, status()); } - DumpOriginInfoTable(); + DumpBucketTable(); task_environment_.RunUntilIdle(); bool found_origin_in_database = false; - for (const auto& entry : origin_info_entries()) { + for (const auto& entry : bucket_entries()) { if (entry.type == kTemp && entry.origin == ToOrigin("http://foo.com/")) { found_origin_in_database = true; break; @@ -1994,10 +1991,10 @@ EXPECT_EQ(3, status_callback_count()); - DumpOriginInfoTable(); + DumpBucketTable(); task_environment_.RunUntilIdle(); - for (const auto& entry : origin_info_entries()) { + for (const auto& entry : bucket_entries()) { if (entry.type != kTemp) continue; @@ -2079,10 +2076,10 @@ EXPECT_EQ(2, status_callback_count()); - DumpOriginInfoTable(); + DumpBucketTable(); task_environment_.RunUntilIdle(); - for (const auto& entry : origin_info_entries()) { + for (const auto& entry : bucket_entries()) { if (entry.type != kTemp) continue; @@ -2185,10 +2182,10 @@ EXPECT_EQ(3, status_callback_count()); - DumpOriginInfoTable(); + DumpBucketTable(); task_environment_.RunUntilIdle(); - for (const auto& entry : origin_info_entries()) { + for (const auto& entry : bucket_entries()) { if (entry.type != kTemp) continue; @@ -2277,10 +2274,10 @@ EXPECT_EQ(2, status_callback_count()); - DumpOriginInfoTable(); + DumpBucketTable(); task_environment_.RunUntilIdle(); - for (const auto& entry : origin_info_entries()) { + for (const auto& entry : bucket_entries()) { if (entry.type != kPerm) continue; @@ -2531,7 +2528,7 @@ EXPECT_TRUE(entries.empty()); } -TEST_F(QuotaManagerImplTest, DumpOriginInfoTable) { +TEST_F(QuotaManagerImplTest, DumpBucketTable) { using std::make_pair; quota_manager_impl()->NotifyStorageAccessed(ToOrigin("http://example.com/"), @@ -2542,7 +2539,7 @@ kPerm, base::Time::Now()); task_environment_.RunUntilIdle(); - DumpOriginInfoTable(); + DumpBucketTable(); task_environment_.RunUntilIdle(); using TypedOrigin = std::pair<GURL, StorageType>; @@ -2553,14 +2550,14 @@ }; std::set<Entry> entries(kEntries, kEntries + base::size(kEntries)); - for (const auto& origin_info : origin_info_entries()) { + for (const auto& entry : bucket_entries()) { SCOPED_TRACE(testing::Message() - << "host = " << origin_info.origin << ", " - << "type = " << static_cast<int>(origin_info.type) << ", " - << "used_count = " << origin_info.used_count); - EXPECT_EQ(1u, entries.erase(make_pair( - make_pair(origin_info.origin.GetURL(), origin_info.type), - origin_info.used_count))); + << "host = " << entry.origin << ", " + << "type = " << static_cast<int>(entry.type) << ", " + << "use_count = " << entry.use_count); + EXPECT_EQ(1u, entries.erase( + make_pair(make_pair(entry.origin.GetURL(), entry.type), + entry.use_count))); } EXPECT_TRUE(entries.empty()); }
diff --git a/storage/test/data/quota_database/README.md b/storage/test/data/quota_database/README.md new file mode 100644 index 0000000..d6df7262 --- /dev/null +++ b/storage/test/data/quota_database/README.md
@@ -0,0 +1,5 @@ +# Quota Database Schema Files + +This directory contains sql database schemas for previous versions of the Quota +Database. The highest version sql should always reflect the current database +schema.
diff --git a/storage/test/data/quota_database/version_5.sql b/storage/test/data/quota_database/version_5.sql new file mode 100644 index 0000000..3ea20b3 --- /dev/null +++ b/storage/test/data/quota_database/version_5.sql
@@ -0,0 +1,36 @@ +PRAGMA foreign_keys=OFF; + +BEGIN TRANSACTION; + +CREATE TABLE HostQuotaTable(host TEXT NOT NULL, type INTEGER NOT NULL, quota INTEGER DEFAULT 0, UNIQUE(host, type)); + +CREATE TABLE OriginInfoTable(origin TEXT NOT NULL, type INTEGER NOT NULL, used_count INTEGER DEFAULT 0, last_access_time INTEGER DEFAULT 0, last_modified_time INTEGER DEFAULT 0, unique(origin, type)); + +CREATE TABLE EvictionInfoTable(origin TEXT NOT NULL, type INTEGER NOT NULL, last_eviction_time INTEGER DEFAULT 0, UNIQUE(origin, type)); + +CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR); + +INSERT INTO meta VALUES('mmap_status', '-1'); +INSERT INTO meta VALUES('last_compatible_version', '2'); +INSERT INTO meta VALUES('version', '5'); + +INSERT INTO HostQuotaTable(host, type, quota) VALUES('a.com', 0, 0); +INSERT INTO HostQuotaTable(host, type, quota) VALUES('b.com', 0, 1); +INSERT INTO HostQuotaTable(host, type, quota) VALUES('c.com', 1, 123); + +INSERT INTO OriginInfoTable(origin, type, used_count, last_access_time, last_modified_time) + VALUES('http://a/', 0, 123, 13260644621105493, 13242931862595604); +INSERT INTO OriginInfoTable(origin, type, used_count, last_access_time, last_modified_time) + VALUES('http://b/', 0, 111, 13250042735631065, 13260999511438890); +INSERT INTO OriginInfoTable(origin, type, used_count, last_access_time, last_modified_time) + VALUES('http://c/', 1, 321, 13261163582572088, 13261079941303629); + +CREATE INDEX HostIndex ON HostQuotaTable(host); + +CREATE INDEX OriginInfoIndex ON OriginInfoTable(origin); + +CREATE INDEX OriginLastAccessTimeIndex ON OriginInfoTable(last_access_time); + +CREATE INDEX OriginLastModifiedTimeIndex ON OriginInfoTable(last_modified_time); + +COMMIT;
diff --git a/storage/test/data/quota_database/version_6.sql b/storage/test/data/quota_database/version_6.sql new file mode 100644 index 0000000..2c5a2f10 --- /dev/null +++ b/storage/test/data/quota_database/version_6.sql
@@ -0,0 +1,25 @@ +PRAGMA foreign_keys=OFF; + +BEGIN TRANSACTION; + +CREATE TABLE quota(host TEXT NOT NULL, type INTEGER NOT NULL, quota INTEGER NOT NULL, PRIMARY KEY(host, type)) WITHOUT ROWID; + +CREATE TABLE buckets(id INTEGER PRIMARY KEY, origin TEXT NOT NULL, type INTEGER NOT NULL, name TEXT NOT NULL, use_count INTEGER NOT NULL, last_accessed INTEGER NOT NULL, last_modified INTEGER NOT NULL, expiration INTEGER NOT NULL, quota INTEGER NOT NULL); + +CREATE TABLE eviction_info(origin TEXT NOT NULL, type INTEGER NOT NULL, last_eviction_time INTEGER NOT NULL, PRIMARY KEY(origin, type)); + +CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR); + +INSERT INTO meta VALUES ('mmap_status', '-1'); +INSERT INTO meta VALUES ('last_compatible_version', '2'); +INSERT INTO meta VALUES ('version', '6'); + +CREATE UNIQUE INDEX buckets_by_storage_key ON buckets(origin, type, name); + +CREATE INDEX buckets_by_last_accessed ON buckets(type, last_accessed); + +CREATE INDEX buckets_by_last_modified ON buckets(type, last_modified); + +CREATE INDEX buckets_by_expiration ON buckets(expiration); + +COMMIT;
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index 00bf0a8..77d68933 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -1296,6 +1296,31 @@ }, "test": "cc_unittests", "test_id_prefix": "ninja://cc:cc_unittests/" + }, + { + "args": [ + "--board=amd64-generic", + "--use-vm", + "--test-launcher-filter-file=../../testing/buildbot/filters/device-lacros.ozone_unittests.filter" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "ozone_unittests_amd64-generic", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86", + "kvm": "1", + "os": "Ubuntu-18.04" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "ozone_unittests", + "test_id_prefix": "ninja://ui/ozone:ozone_unittests/" } ] }, @@ -3010,7 +3035,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3028,7 +3053,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3049,7 +3074,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3068,7 +3093,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3086,7 +3111,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3104,7 +3129,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3122,7 +3147,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3140,7 +3165,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3158,7 +3183,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3176,7 +3201,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3194,7 +3219,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3212,7 +3237,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3230,7 +3255,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3249,7 +3274,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3267,7 +3292,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3285,7 +3310,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3294,6 +3319,9 @@ "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" }, { + "args": [ + "--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter" + ], "isolate_profile_data": true, "merge": { "args": [], @@ -3304,7 +3332,7 @@ "dimension_sets": [ { "kvm": "1", - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -3326,7 +3354,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3344,7 +3372,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3362,7 +3390,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3380,7 +3408,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3398,7 +3426,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3416,7 +3444,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3434,7 +3462,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3452,7 +3480,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3470,7 +3498,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3488,7 +3516,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3506,7 +3534,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3543,7 +3571,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3561,7 +3589,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3579,7 +3607,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3597,7 +3625,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3615,7 +3643,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3633,7 +3661,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3651,7 +3679,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3669,7 +3697,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3687,7 +3715,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3705,7 +3733,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3723,7 +3751,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3741,7 +3769,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3759,7 +3787,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3777,7 +3805,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3795,7 +3823,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3813,7 +3841,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3831,7 +3859,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3849,7 +3877,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3886,7 +3914,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3904,7 +3932,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3922,7 +3950,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3940,7 +3968,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3958,7 +3986,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3976,7 +4004,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -3994,7 +4022,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4012,7 +4040,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4030,7 +4058,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4048,7 +4076,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4066,7 +4094,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4084,7 +4112,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4102,7 +4130,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4120,7 +4148,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4138,7 +4166,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4156,7 +4184,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4177,7 +4205,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4195,7 +4223,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4213,7 +4241,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4231,7 +4259,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4249,7 +4277,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4267,7 +4295,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4285,7 +4313,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4303,7 +4331,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4321,7 +4349,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4339,7 +4367,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4357,7 +4385,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4375,7 +4403,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4393,7 +4421,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4411,7 +4439,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4429,7 +4457,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4447,7 +4475,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4465,7 +4493,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4501,7 +4529,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4519,7 +4547,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4537,7 +4565,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4555,7 +4583,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4592,7 +4620,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4611,7 +4639,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4629,7 +4657,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4647,7 +4675,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4665,7 +4693,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4683,7 +4711,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4701,7 +4729,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4719,7 +4747,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4737,7 +4765,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4754,7 +4782,7 @@ "gtest_tests": [ { "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter" + "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter;../../testing/buildbot/filters/linux_bionic.browser_tests.filter" ], "merge": { "args": [], @@ -4762,6 +4790,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", "shards": 10 }, @@ -4775,6 +4808,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "chromeos_unittests", @@ -4790,6 +4828,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "components_unittests", @@ -4805,6 +4848,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "extensions_browsertests", @@ -4820,6 +4868,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", "shards": 3 }, @@ -4833,6 +4886,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "lacros_chrome_browsertests", @@ -4845,6 +4903,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "lacros_chrome_unittests", @@ -4860,6 +4923,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "sync_integration_tests", @@ -4872,6 +4940,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "ui_base_unittests", @@ -4887,6 +4960,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "unit_tests", @@ -4909,6 +4987,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "absl_hardening_tests", @@ -4921,6 +5004,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "accessibility_unittests", @@ -4933,6 +5021,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "app_shell_unittests", @@ -4945,6 +5038,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "aura_unittests", @@ -4957,6 +5055,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "base_unittests", @@ -4969,6 +5072,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "base_util_unittests", @@ -4981,6 +5089,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "blink_common_unittests", @@ -4993,6 +5106,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "blink_fuzzer_unittests", @@ -5005,6 +5123,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "blink_heap_unittests", @@ -5017,6 +5140,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "blink_platform_unittests", @@ -5030,6 +5158,11 @@ "name": "webkit_unit_tests", "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "blink_unittests", @@ -5042,6 +5175,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "boringssl_crypto_tests", @@ -5054,6 +5192,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "boringssl_ssl_tests", @@ -5061,7 +5204,7 @@ }, { "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter" + "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter;../../testing/buildbot/filters/linux_bionic.browser_tests.filter" ], "merge": { "args": [], @@ -5069,6 +5212,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", "shards": 10 }, @@ -5085,6 +5233,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "capture_unittests", @@ -5097,6 +5250,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "cast_unittests", @@ -5109,6 +5267,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "cc_unittests", @@ -5121,6 +5284,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "chrome_app_unittests", @@ -5133,6 +5301,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "chromedriver_unittests", @@ -5145,6 +5318,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "chromeos_unittests", @@ -5157,6 +5335,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "color_unittests", @@ -5169,6 +5352,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "components_browsertests", @@ -5184,6 +5372,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "components_unittests", @@ -5196,6 +5389,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "compositor_unittests", @@ -5211,6 +5409,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", "shards": 6 }, @@ -5224,6 +5427,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "content_unittests", @@ -5236,6 +5444,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "crashpad_tests", @@ -5248,6 +5461,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "crypto_unittests", @@ -5260,6 +5478,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "dbus_unittests", @@ -5272,6 +5495,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "device_unittests", @@ -5284,6 +5512,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "display_unittests", @@ -5296,6 +5529,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "events_unittests", @@ -5311,6 +5549,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "extensions_browsertests", @@ -5326,6 +5569,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "extensions_unittests", @@ -5338,6 +5586,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "filesystem_service_unittests", @@ -5350,6 +5603,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "gcm_unit_tests", @@ -5362,6 +5620,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "gfx_unittests", @@ -5374,6 +5637,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "gin_unittests", @@ -5386,6 +5654,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "google_apis_unittests", @@ -5398,6 +5671,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "gpu_unittests", @@ -5410,6 +5688,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "gwp_asan_unittests", @@ -5425,6 +5708,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", "shards": 3 }, @@ -5438,6 +5726,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "ipc_tests", @@ -5450,6 +5743,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "jingle_unittests", @@ -5462,6 +5760,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "lacros_chrome_browsertests", @@ -5474,6 +5777,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "lacros_chrome_unittests", @@ -5486,6 +5794,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "latency_unittests", @@ -5498,6 +5811,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "libjingle_xmpp_unittests", @@ -5510,6 +5828,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "liburlpattern_unittests", @@ -5522,6 +5845,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "media_blink_unittests", @@ -5534,6 +5862,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "media_unittests", @@ -5546,6 +5879,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "message_center_unittests", @@ -5558,6 +5896,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "midi_unittests", @@ -5570,6 +5913,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "mojo_core_unittests", @@ -5582,6 +5930,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "mojo_unittests", @@ -5594,6 +5947,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "nacl_helper_nonsfi_unittests", @@ -5606,6 +5964,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "nacl_loader_unittests", @@ -5618,6 +5981,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "native_theme_unittests", @@ -5630,6 +5998,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "net_unittests", @@ -5642,6 +6015,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "pdf_unittests", @@ -5654,6 +6032,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "perfetto_unittests", @@ -5666,6 +6049,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "ppapi_unittests", @@ -5678,6 +6066,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "printing_unittests", @@ -5690,6 +6083,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "remoting_unittests", @@ -5702,6 +6100,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "sandbox_linux_unittests", @@ -5714,6 +6117,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "service_manager_unittests", @@ -5726,6 +6134,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "services_unittests", @@ -5738,6 +6151,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "shell_dialogs_unittests", @@ -5750,6 +6168,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "skia_unittests", @@ -5762,6 +6185,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "snapshot_unittests", @@ -5774,6 +6202,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "sql_unittests", @@ -5786,6 +6219,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "storage_unittests", @@ -5801,6 +6239,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "sync_integration_tests", @@ -5813,6 +6256,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "traffic_annotation_auditor_unittests", @@ -5825,6 +6273,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "ui_base_unittests", @@ -5837,6 +6290,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "ui_touch_selection_unittests", @@ -5852,6 +6310,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "unit_tests", @@ -5864,6 +6327,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "url_unittests", @@ -5879,6 +6347,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "views_unittests", @@ -5891,6 +6364,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "viz_unittests", @@ -5903,6 +6381,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "wm_unittests", @@ -5915,6 +6398,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "wtf_unittests", @@ -5927,6 +6415,11 @@ }, "swarming": { "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-18.04" + } + ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "zlib_unittests",
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 39dd920..854f457 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -6,6 +6,21 @@ "chromium_builder_asan" ] }, + "Linux Builder (core-32) (goma)": { + "additional_compile_targets": [ + "all" + ] + }, + "Linux Builder (core-32) (reclient)": { + "additional_compile_targets": [ + "all" + ] + }, + "Linux Builder (core-32) (runsc) (reclient)": { + "additional_compile_targets": [ + "all" + ] + }, "Linux Builder (deps-cache) (reclient)": { "additional_compile_targets": [ "all" @@ -38755,8 +38770,7 @@ { "args": [ "--board=amd64-generic", - "--use-vm", - "--test-launcher-filter-file=../../testing/buildbot/filters/device-lacros.ozone_unittests.filter" + "--use-vm" ], "merge": { "args": [], @@ -50059,7 +50073,7 @@ }, { "args": [ - "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter" + "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter;../../testing/buildbot/filters/linux_bionic.browser_tests.filter" ], "isolate_profile_data": true, "merge": {
diff --git a/testing/buildbot/chromium.linux.json b/testing/buildbot/chromium.linux.json index 73b1c39..bb0fb9c 100644 --- a/testing/buildbot/chromium.linux.json +++ b/testing/buildbot/chromium.linux.json
@@ -4636,7 +4636,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4659,7 +4659,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4682,7 +4682,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4705,7 +4705,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4733,7 +4733,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4757,7 +4757,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4771,7 +4771,7 @@ "--use-weston", "--ozone-platform=wayland", "--enable-features=UseOzonePlatform", - "--test-launcher-filter-file=../../testing/buildbot/filters/ozone-linux.wayland_browser_tests.filter" + "--test-launcher-filter-file=../../testing/buildbot/filters/ozone-linux.wayland_browser_tests.filter;../../testing/buildbot/filters/linux_bionic.browser_tests.filter" ], "merge": { "args": [], @@ -4782,7 +4782,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -4807,7 +4807,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4832,7 +4832,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -4857,7 +4857,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4881,7 +4881,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4905,7 +4905,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4930,7 +4930,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -4955,7 +4955,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -4980,7 +4980,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5004,7 +5004,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5030,7 +5030,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5052,7 +5052,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5063,7 +5063,8 @@ { "args": [ "--ozone-platform=x11", - "--enable-features=UseOzonePlatform" + "--enable-features=UseOzonePlatform", + "--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter" ], "merge": { "args": [], @@ -5074,7 +5075,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -5097,7 +5098,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5119,7 +5120,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -5142,7 +5143,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5164,7 +5165,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5186,7 +5187,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5208,7 +5209,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -5231,7 +5232,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5253,7 +5254,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5275,7 +5276,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5297,7 +5298,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -5319,7 +5320,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -9961,6 +9962,9 @@ "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" }, { + "args": [ + "--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter" + ], "isolate_profile_data": true, "merge": { "args": [], @@ -9970,7 +9974,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -10551,7 +10555,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -11435,7 +11439,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -11624,7 +11628,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -12055,6 +12059,9 @@ "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" }, { + "args": [ + "--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter" + ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -12063,7 +12070,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -12612,7 +12619,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -13449,7 +13456,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-18.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com",
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index c289b111f..a1d12a1 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -236,26 +236,12 @@ "args": [ "--additional-env-var=LLVM_PROFILE_FILE=${ISOLATED_OUTDIR}/profraw/default-%2m.profraw", ], - # TODO(crbug/1200134): Remove it once blink tests is fixed on - # bionic bots. - 'swarming': { - 'dimension_sets': [ - { - 'os': 'Ubuntu-16.04', - } - ], - }, }, 'Linux Tests (dbg)(1)': { 'args': [ '--debug', ], 'swarming': { - 'dimension_sets': [ - { - 'os': 'Ubuntu-16.04', - } - ], 'shards': 25, }, }, @@ -609,25 +595,17 @@ '--test-launcher-filter-file=../../testing/buildbot/filters/chromeos.msan.browser_tests.oobe_negative.filter', ], }, - # TODO(crbug/1200334): Remove it once interactive_ui_tests is fixed on - # bionic bots. 'Linux Tests': { - 'swarming': { - 'dimension_sets': [ - { - 'os': 'Ubuntu-16.04', - } - ], - }, + 'args': [ + '--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter', + ], }, 'Linux Tests (dbg)(1)': { + 'args': [ + '--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter', + ], # crbug.com/1066161 'swarming': { - 'dimension_sets': [ - { - 'os': 'Ubuntu-16.04', - } - ], 'shards': 20, }, }, @@ -721,6 +699,9 @@ ], }, 'linux-chromeos-rel': { + 'args': [ + '--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter', + ], 'swarming': { 'shards': 20, 'dimension_sets': [ @@ -745,17 +726,17 @@ }, 'linux-lacros-code-coverage': { 'args': [ - '--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter', + '--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter;../../testing/buildbot/filters/linux_bionic.browser_tests.filter', ], }, 'linux-lacros-rel': { 'args': [ - '--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter', + '--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter;../../testing/buildbot/filters/linux_bionic.browser_tests.filter', ], }, 'linux-lacros-tester-rel': { 'args': [ - '--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter', + '--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.browser_tests.filter;../../testing/buildbot/filters/linux_bionic.browser_tests.filter', ], }, 'linux-trusty-rel': { @@ -778,6 +759,7 @@ 'Linux Ozone Tester (Wayland)': { 'args': [ '--test-launcher-filter-file=../../testing/buildbot/filters/ozone-linux.wayland_browser_tests.filter', + '--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter', ], }, # CI tester. @@ -788,6 +770,15 @@ }, }, }, + 'browser_tests_x11': { + 'modifications': { + 'Linux Ozone Tester (X11)': { + 'args': [ + '--test-launcher-filter-file=../../testing/buildbot/filters/linux_bionic.browser_tests.filter', + ], + }, + }, + }, 'cc_unittests': { 'modifications': { # TODO(crbug.com/1200904): Remove after migration @@ -1313,12 +1304,6 @@ }, 'linux-chromeos-rel': { 'swarming': { - # TODO(crbug.com/1202743): Remove this exception. - 'dimension_sets': [ - { - 'os': 'Ubuntu-18.04', - }, - ], 'shards': 3, }, }, @@ -1783,26 +1768,6 @@ 'shards': 32, # Adjusted for testing, see https://crbug.com/1179567 }, }, - # TODO(crbug/1199425): Remove it once interactive_ui_tests is fixed on - # bionic bots. - 'Linux Tests': { - 'swarming': { - 'dimension_sets': [ - { - 'os': 'Ubuntu-16.04', - } - ], - }, - }, - 'Linux Tests (dbg)(1)': { - 'swarming': { - 'dimension_sets': [ - { - 'os': 'Ubuntu-16.04', - } - ], - }, - }, 'ToTLinuxTSan': { # These are slow on the TSan bots for some reason, crbug.com/794372 'swarming': { @@ -1844,16 +1809,6 @@ '--gtest_filter=-SadTabViewInteractiveUITest.ReloadMultipleSadTabs', ], }, - 'linux-chromeos-rel': { - 'swarming': { - # TODO(crbug.com/1202743): Remove this exception. - 'dimension_sets': [ - { - 'os': 'Ubuntu-18.04', - }, - ], - } - }, 'linux-chromeos-stable': { 'args': [ '--gtest_filter=-SadTabViewInteractiveUITest.ReloadMultipleSadTabs', @@ -2284,24 +2239,6 @@ "args": [ "--additional-env-var=LLVM_PROFILE_FILE=${ISOLATED_OUTDIR}/profraw/default-%2m.profraw", ], - # TODO(crbug/1200134): Remove it once blink tests is fixed on - # bionic bots. - 'swarming': { - 'dimension_sets': [ - { - 'os': 'Ubuntu-16.04', - } - ], - }, - }, - 'Linux Tests (dbg)(1)': { - 'swarming': { - 'dimension_sets': [ - { - 'os': 'Ubuntu-16.04', - } - ], - }, }, 'linux-code-coverage': { 'args': [ @@ -2398,12 +2335,8 @@ }, }, 'ozone_unittests_amd64-generic': { - 'remove_from': [ - # TODO(crbug.com/1204231): Re-enable. - 'lacros-amd64-generic-rel', - ], 'modifications': { - 'lacros-amd64-generic-rel-fyi': { + 'lacros-amd64-generic-rel': { 'args': [ '--test-launcher-filter-file=../../testing/buildbot/filters/device-lacros.ozone_unittests.filter', ], @@ -2706,16 +2639,6 @@ 'shards': 4, }, }, - 'linux-chromeos-rel': { - 'swarming': { - # TODO(crbug.com/1202743): Remove this exception. - 'dimension_sets': [ - { - 'os': 'Ubuntu-18.04', - }, - ], - } - }, 'linux-code-coverage': { 'swarming': { 'shards': 4, @@ -2967,12 +2890,6 @@ }, 'linux-chromeos-rel': { 'swarming': { - # TODO(crbug.com/1202743): Remove this exception. - 'dimension_sets': [ - { - 'os': 'Ubuntu-18.04', - }, - ], 'shards': 2, }, },
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 31cffe10..c73074ad 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -1748,7 +1748,7 @@ 'linux-chromeos-rel': { 'mixins': [ 'isolate_profile_data', - 'linux-xenial', + 'linux-bionic', ], 'additional_compile_targets': [ 'all', @@ -1758,6 +1758,9 @@ }, }, 'linux-lacros-rel': { + 'mixins': [ + 'linux-bionic', + ], 'additional_compile_targets': [ 'all', ], @@ -1766,6 +1769,9 @@ }, }, 'linux-lacros-tester-rel': { + 'mixins': [ + 'linux-bionic', + ], 'additional_compile_targets': [ 'chrome', 'chrome_sandbox', @@ -2670,9 +2676,39 @@ 'chromium_builder_asan', ], }, + 'Linux Builder (core-32) (goma)': { + # Copied from + # https://source.chromium.org/chromium/chromium/src/+/main:testing/buildbot/waterfalls.pyl;l=4844-4854;drc=75f767e92e86611728189739fb26f4e2cdf212d9 + 'mixins': [ + 'isolate_profile_data', + ], + 'additional_compile_targets': [ + 'all' + ], + }, + 'Linux Builder (core-32) (reclient)': { + # Copied from + # https://source.chromium.org/chromium/chromium/src/+/main:testing/buildbot/waterfalls.pyl;l=4844-4854;drc=75f767e92e86611728189739fb26f4e2cdf212d9 + 'mixins': [ + 'isolate_profile_data', + ], + 'additional_compile_targets': [ + 'all' + ], + }, + 'Linux Builder (core-32) (runsc) (reclient)': { + # Copied from + # https://source.chromium.org/chromium/chromium/src/+/main:testing/buildbot/waterfalls.pyl;l=4844-4854;drc=75f767e92e86611728189739fb26f4e2cdf212d9 + 'mixins': [ + 'isolate_profile_data', + ], + 'additional_compile_targets': [ + 'all' + ], + }, 'Linux Builder (deps-cache) (reclient)': { # Copied from - # https://source.chromium.org/chromium/chromium/src/+/master:testing/buildbot/waterfalls.pyl;l=4844-4854;drc=75f767e92e86611728189739fb26f4e2cdf212d9 + # https://source.chromium.org/chromium/chromium/src/+/main:testing/buildbot/waterfalls.pyl;l=4844-4854;drc=75f767e92e86611728189739fb26f4e2cdf212d9 'mixins': [ 'isolate_profile_data', ], @@ -2685,7 +2721,7 @@ }, 'Linux Builder (j-500) (reclient)': { # Copied from - # https://source.chromium.org/chromium/chromium/src/+/master:testing/buildbot/waterfalls.pyl;l=4844-4854;drc=75f767e92e86611728189739fb26f4e2cdf212d9 + # https://source.chromium.org/chromium/chromium/src/+/main:testing/buildbot/waterfalls.pyl;l=4844-4854;drc=75f767e92e86611728189739fb26f4e2cdf212d9 'mixins': [ 'isolate_profile_data', ], @@ -4979,7 +5015,7 @@ }, 'Linux Ozone Tester (Headless)': { 'mixins': [ - 'linux-xenial', + 'linux-bionic', ], 'test_suites': { 'gtest_tests': 'linux_ozone_headless_tests', @@ -4987,7 +5023,7 @@ }, 'Linux Ozone Tester (Wayland)': { 'mixins': [ - 'linux-xenial', + 'linux-bionic', ], 'test_suites': { 'gtest_tests': 'linux_ozone_wayland_tests', @@ -4995,7 +5031,7 @@ }, 'Linux Ozone Tester (X11)': { 'mixins': [ - 'linux-xenial', + 'linux-bionic', ], 'test_suites': { 'gtest_tests': 'linux_ozone_x11_tests',
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index fcd3415..d328f919 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -50,6 +50,69 @@ ] } ], + "AddToHomescreenIPH": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "EnabledMessage", + "params": { + "use_message": "true", + "use_text_bubble": "false" + }, + "enable_features": [ + "AddToHomescreenIPH" + ] + } + ] + } + ], + "AddToHomescreenMessage": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "params": { + "availability": ">=0", + "event_1": "name:add_to_homescreen_message_iph_trigger;comparator:==0;window:15;storage:90", + "event_trigger": "name:add_to_homescreen_message_iph_trigger;comparator:<2;window:90;storage:90", + "event_used": "name:add_to_homescreen_dialog_shown;comparator:==0;window:90;storage:90", + "session_rate": "<1" + }, + "enable_features": [ + "IPH_AddToHomescreenMessage" + ] + } + ] + } + ], + "AddToHomescreenTextBubble": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "params": { + "availability": ">=0", + "event_1": "name:add_to_homescreen_text_bubble_iph_trigger;comparator:==0;window:15;storage:90", + "event_trigger": "name:add_to_homescreen_text_bubble_iph_trigger;comparator:<2;window:90;storage:90", + "event_used": "name:add_to_homescreen_dialog_shown;comparator:==0;window:90;storage:90", + "session_rate": "<1" + }, + "enable_features": [ + "IPH_AddToHomescreenTextBubble" + ] + } + ] + } + ], "AmpBackgroundTab": [ { "platforms": [
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index 65097d3..330c64d 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -43,6 +43,7 @@ "clipboard/clipboard.mojom", "clipboard/raw_clipboard.mojom", "commit_result/commit_result.mojom", + "compute_pressure/compute_pressure.mojom", "content_index/content_index.mojom", "context_menu/context_menu.mojom", "conversions/conversions.mojom",
diff --git a/third_party/blink/public/mojom/compute_pressure/DIR_METADATA b/third_party/blink/public/mojom/compute_pressure/DIR_METADATA new file mode 100644 index 0000000..40a233c --- /dev/null +++ b/third_party/blink/public/mojom/compute_pressure/DIR_METADATA
@@ -0,0 +1,5 @@ +monorail { + component: "Blink>PerformanceAPIs>ComputePressure" +} + +team_email: "storage-dev@chromium.org"
diff --git a/third_party/blink/public/mojom/compute_pressure/OWNERS b/third_party/blink/public/mojom/compute_pressure/OWNERS new file mode 100644 index 0000000..32024c4 --- /dev/null +++ b/third_party/blink/public/mojom/compute_pressure/OWNERS
@@ -0,0 +1,4 @@ +file://content/browser/compute_pressure/OWNERS + +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom b/third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom new file mode 100644 index 0000000..9284c2b --- /dev/null +++ b/third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom
@@ -0,0 +1,107 @@ +// Copyright 2021 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; + +// Represents availability of compute resources. +struct ComputePressureState { + // Average utilization of all CPU cores. + // + // Values use a scale from 0.0 (no utilization) to 1.0 (100% utilization). + double cpu_utilization; + + // Average normalized clock speed over all CPU cores. + // + // The normalized clock speed for each CPU core uses a piecewise-linear scale + // from 0.0 (minimum clock speed) to 0.5 (base clock speed) to 1.0 (maximum + // clock-speed). + double cpu_speed; +}; + +// Specifies a quantization scheme for the data in a ComputePressureState. +// +// Each array of thresholds subdivides the interval [0.0, 1.0]. The array must +// not contain the 0.0 and 1.0 values, as they are implied. For example, the +// array {0.2, 0.5, 0.8} specifies the sub-intervals [0.0, 0.2], [0.2, 0.5], +// [0.5, 0.8], and [0.8, 1.0]. The thresholds in an array must be sorted. +// +// A value is quantized by replacing it with the center of the interval that it +// falls in. For example, a CPU utilization quantizing scheme that matches the +// example above would report a CPU utilization value of 0.51 as 0.65. This is +// because 0.51 falls in the sub-interval [0.5, 0.8], and the center of that +// interval is 0.65, the average of 0.5 and 0.8. +struct ComputePressureQuantization { + array<double> cpu_utilization_thresholds; + array<double> cpu_speed_thresholds; +}; + +// The maximum size of ComputePressureQuantization.cpu_utilization_thresholds. +const int32 kMaxComputePressureCpuUtilizationThresholds = 3; + +// The maximum size of ComputePressureQuantization.cpu_speed_thresholds. +const int32 kMaxComputePressureCpuSpeedThresholds = 1; + +// Implemented by renderers to receive compute pressure info from the browser. +// +// The values in the ComputePressureState reported to the renderer are always +// quantized according to a ComputePressureQuantization scheme. +interface ComputePressureObserver { + // Called in the following circumstances. + // + // 1. Once after an observer is created. + // 2. When the (quantized) compute pressure state differs from the previously + // reported state. + // + // Updates to an observer are rate-limited. Observers that belong to visible + // pages receive updates at most once a second, while other observers are + // limited to at most one update in 10 seconds. + OnUpdate(ComputePressureState state); +}; + +// Result of ComputePressureManager.AddObserver(). +enum ComputePressureStatus { + kOk, + + // The underlying platform does not report compute pressure information. + // + // For example, this is reported on Linux if Chrome cannot access /proc. + kNotSupported, + + // The renderer is not allowed access to the feature. + // + // This is only reported in conditions that the renderer process cannot check. + // Renderers that attempt to access the feature when they know they shouldn't + // will be terminated. + kSecurityError, +}; + +// Origin-scoped access to the browser-side Compute Pressure API implementation. +// +// The interface is implemented in the browser and consumed by renderers. The +// interface is only accessible to frames (and not workers). Each frame that +// accesses the API creates a separate connection. +interface ComputePressureHost { + // Subscribes to updates on the device's compute pressure state. + // + // The reported state will be quantized according to the `quantization` + // scheme. `quantization` must be a valid quantization scheme. + // + // `observer` is active (eligible for notifications) as soon as AddObserver() + // completes. Observation is stopped by disconnecting the mojo pipe. + // + // All active observers belonging to an origin use the same `quantization` + // scheme. If `quantization` differs from the scheme used by active observers + // belonging to the same origin, the conflict is resolved by stopping all the + // origin's pre-existing active observers. In other words, after AddObserver() + // completes, the newly created observer will be the only active observer. + // + // This method is only accessible to frames served from the same + // origin as the top-level frame, in secure contexts. The same-origin frame + // requirement is stricter than the usual first-party, and is necessary so + // sites can't use iframes and postMessage() to use observers with different + // quantization schemes. + AddObserver(pending_remote<ComputePressureObserver> observer, + ComputePressureQuantization quantization) + => (ComputePressureStatus status); +};
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 336b1a12..50f61f3 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -3211,6 +3211,9 @@ kWebBluetoothManufacturerDataFilter = 3896, kSanitizerAPIGetConfig = 3897, kSanitizerAPIGetDefaultConfig = 3898, + kComputePressureObserver_Constructor = 3899, + kComputePressureObserver_Observe = 3900, + kComputePressureObserver_Stop = 3901, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/renderer/bindings/generated_in_modules.gni b/third_party/blink/renderer/bindings/generated_in_modules.gni index ce85dab..34f5d89 100644 --- a/third_party/blink/renderer/bindings/generated_in_modules.gni +++ b/third_party/blink/renderer/bindings/generated_in_modules.gni
@@ -217,6 +217,10 @@ "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_collected_client_data.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_color_select_event_init.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_color_select_event_init.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_observer_options.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_observer_options.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_observer_update.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_observer_update.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_constant_source_options.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_constant_source_options.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_constrain_boolean_parameters.cc", @@ -1450,6 +1454,10 @@ "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_color_select_event.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compression_stream.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compression_stream.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_observer.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_observer.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_update_callback.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_update_callback.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_constant_source_node.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_constant_source_node.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_contact_address.cc",
diff --git a/third_party/blink/renderer/bindings/idl_in_modules.gni b/third_party/blink/renderer/bindings/idl_in_modules.gni index 0acd6f72..bd1048d 100644 --- a/third_party/blink/renderer/bindings/idl_in_modules.gni +++ b/third_party/blink/renderer/bindings/idl_in_modules.gni
@@ -111,6 +111,10 @@ "//third_party/blink/renderer/modules/clipboard/navigator_clipboard.idl", "//third_party/blink/renderer/modules/compression/compression_stream.idl", "//third_party/blink/renderer/modules/compression/decompression_stream.idl", + "//third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.idl", + "//third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_options.idl", + "//third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_update.idl", + "//third_party/blink/renderer/modules/compute_pressure/compute_pressure_update_callback.idl", "//third_party/blink/renderer/modules/contacts_picker/contact_address.idl", "//third_party/blink/renderer/modules/contacts_picker/contact_info.idl", "//third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl",
diff --git a/third_party/blink/renderer/core/css/css_properties.json5 b/third_party/blink/renderer/core/css/css_properties.json5 index 7ed8fa1..a6c0edd 100644 --- a/third_party/blink/renderer/core/css/css_properties.json5 +++ b/third_party/blink/renderer/core/css/css_properties.json5
@@ -5586,19 +5586,16 @@ name: "syntax", is_descriptor: true, is_property: false, - runtime_flag: "CSSVariables2AtProperty", }, { name: "initial-value", is_descriptor: true, is_property: false, - runtime_flag: "CSSVariables2AtProperty", }, { name: "inherits", is_descriptor: true, is_property: false, - runtime_flag: "CSSVariables2AtProperty", }, { name: "source",
diff --git a/third_party/blink/renderer/core/css/css_property_rule.idl b/third_party/blink/renderer/core/css/css_property_rule.idl index 90d05d5b..ff3ea9f 100644 --- a/third_party/blink/renderer/core/css/css_property_rule.idl +++ b/third_party/blink/renderer/core/css/css_property_rule.idl
@@ -3,8 +3,7 @@ // found in the LICENSE file. [ - Exposed=Window, - RuntimeEnabled=CSSVariables2AtProperty + Exposed=Window ] interface CSSPropertyRule : CSSRule { readonly attribute CSSOMString name; readonly attribute CSSOMString syntax;
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_impl.cc b/third_party/blink/renderer/core/css/parser/css_parser_impl.cc index 167f96e..0e9f3645 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_impl.cc +++ b/third_party/blink/renderer/core/css/parser/css_parser_impl.cc
@@ -913,9 +913,6 @@ return nullptr; CSSParserTokenStream::BlockGuard guard(stream); - if (!RuntimeEnabledFeatures::CSSVariables2AtPropertyEnabled()) - return nullptr; - const CSSParserToken& name_token = prelude.ConsumeIncludingWhitespace(); if (!prelude.AtEnd()) return nullptr;
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_impl_test.cc b/third_party/blink/renderer/core/css/parser/css_parser_impl_test.cc index 682bfe9..7352967 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_impl_test.cc +++ b/third_party/blink/renderer/core/css/parser/css_parser_impl_test.cc
@@ -158,8 +158,6 @@ } TEST(CSSParserImplTest, AtPropertyOffsets) { - ScopedCSSVariables2AtPropertyForTest scoped_feature(true); - String sheet_text = "@property --test { }"; auto* context = MakeGarbageCollected<CSSParserContext>( kHTMLStandardMode, SecureContextMode::kInsecureContext);
diff --git a/third_party/blink/renderer/core/css/property_registry.cc b/third_party/blink/renderer/core/css/property_registry.cc index 397f895cf..226faaf 100644 --- a/third_party/blink/renderer/core/css/property_registry.cc +++ b/third_party/blink/renderer/core/css/property_registry.cc
@@ -15,7 +15,6 @@ void PropertyRegistry::DeclareProperty(const AtomicString& name, PropertyRegistration& registration) { - DCHECK(RuntimeEnabledFeatures::CSSVariables2AtPropertyEnabled()); declared_properties_.Set(name, ®istration); version_++; }
diff --git a/third_party/blink/renderer/core/css/property_registry_test.cc b/third_party/blink/renderer/core/css/property_registry_test.cc index 8b4be0b8..98b80bde 100644 --- a/third_party/blink/renderer/core/css/property_registry_test.cc +++ b/third_party/blink/renderer/core/css/property_registry_test.cc
@@ -5,16 +5,12 @@ #include "third_party/blink/renderer/core/css/property_registry.h" #include "third_party/blink/renderer/core/css/css_test_helpers.h" #include "third_party/blink/renderer/core/testing/page_test_base.h" -#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { -class PropertyRegistryTest : public PageTestBase, - private ScopedCSSVariables2AtPropertyForTest { +class PropertyRegistryTest : public PageTestBase { public: - PropertyRegistryTest() : ScopedCSSVariables2AtPropertyForTest(true) {} - PropertyRegistry& Registry() { return GetDocument().EnsurePropertyRegistry(); }
diff --git a/third_party/blink/renderer/core/css/style_engine_test.cc b/third_party/blink/renderer/core/css/style_engine_test.cc index 6ec2e25d..077436a 100644 --- a/third_party/blink/renderer/core/css/style_engine_test.cc +++ b/third_party/blink/renderer/core/css/style_engine_test.cc
@@ -3024,8 +3024,6 @@ } TEST_F(StyleEngineTest, AtPropertyUseCount) { - ScopedCSSVariables2AtPropertyForTest scoped_feature(true); - GetDocument().body()->setInnerHTML(R"HTML( <style> body { --x: No @property rule here; } @@ -3071,8 +3069,6 @@ } TEST_F(StyleEngineTest, RemoveDeclaredPropertiesEmptyRegistry) { - ScopedCSSVariables2AtPropertyForTest scoped_feature(true); - EXPECT_FALSE(GetDocument().GetPropertyRegistry()); PropertyRegistration::RemoveDeclaredProperties(GetDocument()); EXPECT_FALSE(GetDocument().GetPropertyRegistry());
diff --git a/third_party/blink/renderer/core/css/style_rule_test.cc b/third_party/blink/renderer/core/css/style_rule_test.cc index 11a6ca4a..05ecba16 100644 --- a/third_party/blink/renderer/core/css/style_rule_test.cc +++ b/third_party/blink/renderer/core/css/style_rule_test.cc
@@ -78,8 +78,6 @@ } TEST_F(StyleRuleTest, StyleRulePropertyCopy) { - ScopedCSSVariables2AtPropertyForTest scoped_feature(true); - auto* base_rule = css_test_helpers::ParseRule(GetDocument(), R"CSS( @property --foo { syntax: "<length>";
diff --git a/third_party/blink/renderer/core/html/html_attribute_names.json5 b/third_party/blink/renderer/core/html/html_attribute_names.json5 index 1cfa59d..dbbe0a57 100644 --- a/third_party/blink/renderer/core/html/html_attribute_names.json5 +++ b/third_party/blink/renderer/core/html/html_attribute_names.json5
@@ -68,6 +68,7 @@ "decoding", "default", "defer", + "delegatesfocus", "dir", "direction", "dirname",
diff --git a/third_party/blink/renderer/core/html/html_element.cc b/third_party/blink/renderer/core/html/html_element.cc index 1477332..1f175733 100644 --- a/third_party/blink/renderer/core/html/html_element.cc +++ b/third_party/blink/renderer/core/html/html_element.cc
@@ -906,9 +906,12 @@ new_child = Text::Create(GetDocument(), text); // textToFragment might cause mutation events. - if (!parentNode()) + if (!parentNode()) { + // TODO(crbug.com/1206014) We can likely remove this entire if() block. + NOTREACHED(); exception_state.ThrowDOMException(DOMExceptionCode::kHierarchyRequestError, "The element has no parent."); + } if (exception_state.HadException()) return;
diff --git a/third_party/blink/renderer/core/html/html_element.h b/third_party/blink/renderer/core/html/html_element.h index 3b903ec..e89fe4e 100644 --- a/third_party/blink/renderer/core/html/html_element.h +++ b/third_party/blink/renderer/core/html/html_element.h
@@ -108,6 +108,9 @@ bool HasDirectionAuto() const; virtual bool IsHTMLBodyElement() const { return false; } + // TODO(crbug.com/1123606): Remove this virtual method once the fenced frame + // origin trial is over. + virtual bool IsHTMLFencedFrameElement() const { return false; } virtual bool IsHTMLFrameSetElement() const { return false; } virtual bool IsHTMLPortalElement() const { return false; } virtual bool IsHTMLUnknownElement() const { return false; }
diff --git a/third_party/blink/renderer/core/html/html_fenced_frame_element.h b/third_party/blink/renderer/core/html/html_fenced_frame_element.h index c8731b7..494c744 100644 --- a/third_party/blink/renderer/core/html/html_fenced_frame_element.h +++ b/third_party/blink/renderer/core/html/html_fenced_frame_element.h
@@ -24,6 +24,28 @@ public: explicit HTMLFencedFrameElement(Document& document); ~HTMLFencedFrameElement() override; + + // HTMLElement overrides. + bool IsHTMLFencedFrameElement() const final { return true; } +}; + +// Type casting. Custom since adoption could lead to an HTMLFencedFrameElement +// ending up in a document that doesn't have the Fenced Frame origin trial +// enabled, which would result in creation of an HTMLUnknownElement with the +// "fencedframe" tag name. We can't support casting those elements to +// HTMLFencedFrameElements because they are not fenced frame elements. +// TODO(crbug.com/1123606): Remove these custom helpers when the origin trial is +// over. +template <> +struct DowncastTraits<HTMLFencedFrameElement> { + static bool AllowFrom(const HTMLElement& element) { + return element.IsHTMLFencedFrameElement(); + } + static bool AllowFrom(const Node& node) { + if (const HTMLElement* html_element = DynamicTo<HTMLElement>(node)) + return html_element->IsHTMLFencedFrameElement(); + return false; + } }; } // namespace blink
diff --git a/third_party/blink/renderer/core/html/html_popup_element.cc b/third_party/blink/renderer/core/html/html_popup_element.cc index 9c47070..964422b 100644 --- a/third_party/blink/renderer/core/html/html_popup_element.cc +++ b/third_party/blink/renderer/core/html/html_popup_element.cc
@@ -6,6 +6,7 @@ #include "third_party/blink/renderer/core/css/style_change_reason.h" #include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h" #include "third_party/blink/renderer/core/events/keyboard_event.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/web_feature.h" @@ -76,6 +77,89 @@ PseudoStateChanged(CSSSelector::kPseudoPopupOpen); PushNewPopupElement(this); MarkStyleDirty(); + SetFocus(); +} + +bool HTMLPopupElement::IsKeyboardFocusable() const { + // Popup is not keyboard focusable. + return false; +} +bool HTMLPopupElement::IsMouseFocusable() const { + // Popup *is* mouse focusable. + return true; +} + +// TODO(masonf) This should really live in either Element or FocusController. +// The spec for +// https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area +// does not include dialogs or popups yet. +Element* HTMLPopupElement::GetFocusableArea(bool autofocus_only) const { + Node* next = nullptr; + for (Node* node = FlatTreeTraversal::FirstChild(*this); node; node = next) { + if (IsA<HTMLPopupElement>(*node) || IsA<HTMLDialogElement>(*node)) { + next = FlatTreeTraversal::NextSkippingChildren(*node, this); + continue; + } + next = FlatTreeTraversal::Next(*node, this); + auto* element = DynamicTo<Element>(node); + if (element && element->IsFocusable() && + (!autofocus_only || element->IsAutofocusable())) { + return element; + } + } + return nullptr; +} + +void HTMLPopupElement::focus(const FocusParams& params) { + if (hasAttribute(html_names::kDelegatesfocusAttr)) { + if (auto* node_to_focus = GetFocusableArea(/*autofocus_only=*/false)) { + node_to_focus->focus(params); + } + } else { + HTMLElement::focus(params); + } +} + +void HTMLPopupElement::SetFocus() { + // The layout must be updated here because we call Element::isFocusable, + // which requires an up-to-date layout. + GetDocument().UpdateStyleAndLayoutTreeForNode(this); + + Element* control = nullptr; + if (IsAutofocusable() || hasAttribute(html_names::kDelegatesfocusAttr)) { + // If the <popup> has the autofocus or delegatesfocus, focus it. + control = this; + } else { + // Otherwise, look for a child control that has the autofocus attribute. + control = GetFocusableArea(/*autofocus_only=*/true); + } + + // If the popup does not use autofocus or delegatesfocus, then the focus + // should remain on the currently active element. + // https://open-ui.org/components/popup.research.explainer#autofocus-logic + if (!control) + return; + + // 3. Run the focusing steps for control. + DCHECK(control->IsFocusable()); + control->focus(); + + // 4. Let topDocument be the active document of control's node document's + // browsing context's top-level browsing context. + // 5. If control's node document's origin is not the same as the origin of + // topDocument, then return. + Document& doc = control->GetDocument(); + if (!doc.IsActive()) + return; + if (!doc.IsInMainFrame() && + !doc.TopFrameOrigin()->CanAccess( + doc.GetExecutionContext()->GetSecurityOrigin())) { + return; + } + + // 6. Empty topDocument's autofocus candidates. + // 7. Set topDocument's autofocus processed flag to true. + doc.TopDocument().FinalizeAutofocus(); } Node::InsertionNotificationRequest HTMLPopupElement::InsertedInto(
diff --git a/third_party/blink/renderer/core/html/html_popup_element.h b/third_party/blink/renderer/core/html/html_popup_element.h index 5f30e68c..7731cd3 100644 --- a/third_party/blink/renderer/core/html/html_popup_element.h +++ b/third_party/blink/renderer/core/html/html_popup_element.h
@@ -50,6 +50,11 @@ private: void ScheduleHideEvent(); void MarkStyleDirty(); + void focus(const FocusParams& params) override; + Element* GetFocusableArea(bool autofocus_only) const; + void SetFocus(); + bool IsKeyboardFocusable() const override; + bool IsMouseFocusable() const override; Node::InsertionNotificationRequest InsertedInto( ContainerNode& insertion_point) override;
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.cc index 50f1b71..30efd9c8d 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.cc
@@ -1353,10 +1353,15 @@ (track_direction == kForColumns) ? grid_style.GridAutoColumns().NGTrackList() : grid_style.GridAutoRows().NGTrackList(); + const wtf_size_t named_grid_area_track_count = + (track_direction == kForColumns) + ? grid_style.NamedGridAreaColumnCount() + : grid_style.NamedGridAreaRowCount(); track_collection->SetSpecifiedTracks( &template_track_list, &auto_track_list, start_offset, - grid_placement->AutoRepetitions(track_collection->Direction())); + grid_placement->AutoRepetitions(track_direction), + named_grid_area_track_count); EnsureTrackCoverageForGridItems(*grid_items, track_collection); track_collection->FinalizeRanges(start_offset); }; @@ -1517,8 +1522,11 @@ // Indefinite lengths cannot occur, as they must be normalized to 'auto'. DCHECK(!track_size.FitContentTrackBreadth().HasPercentage() || available_size != kIndefiniteSize); - current_set.SetFitContentLimit(MinimumValueForLength( - track_size.FitContentTrackBreadth().length(), available_size)); + + LayoutUnit fit_content_argument = MinimumValueForLength( + track_size.FitContentTrackBreadth().length(), available_size); + current_set.SetFitContentLimit(fit_content_argument * + current_set.TrackCount()); } if (track_size.HasFixedMinTrackBreadth()) { @@ -1739,8 +1747,13 @@ case GridItemContributionType::kForContentBasedMinimums: case GridItemContributionType::kForMaxContentMinimums: { LayoutUnit growth_limit = set.GrowthLimit(); - return (growth_limit == kIndefiniteSize) ? kIndefiniteSize - : growth_limit - set.BaseSize(); + if (growth_limit == kIndefiniteSize) + return kIndefiniteSize; + + LayoutUnit increased_base_size = + set.BaseSize() + set.ItemIncurredIncrease(); + DCHECK_LE(increased_base_size, growth_limit); + return growth_limit - increased_base_size; } case GridItemContributionType::kForIntrinsicMaximums: case GridItemContributionType::kForMaxContentMaximums: { @@ -1760,8 +1773,9 @@ // argument, after which it is treated as having a fixed sizing function // of that argument (with a growth potential of zero). if (fit_content_limit != kIndefiniteSize) { - LayoutUnit growth_potential = - fit_content_limit - DefiniteGrowthLimit(set); + LayoutUnit growth_potential = fit_content_limit - + DefiniteGrowthLimit(set) - + set.ItemIncurredIncrease(); return growth_potential.ClampNegativeToZero(); } // Otherwise, this set has infinite growth potential. @@ -3291,4 +3305,5 @@ } return set_data; } + } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.cc b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.cc index 5eb1f41..9137a76 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.cc +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.cc
@@ -157,10 +157,11 @@ void NGGridBlockTrackCollection::SetSpecifiedTracks( const NGGridTrackList* explicit_tracks, const NGGridTrackList* implicit_tracks, - wtf_size_t start_offset, - wtf_size_t auto_repetitions) { - DCHECK_NE(nullptr, explicit_tracks); - DCHECK_NE(nullptr, implicit_tracks); + const wtf_size_t start_offset, + const wtf_size_t auto_repetitions, + const wtf_size_t named_grid_area_track_count) { + DCHECK(explicit_tracks && implicit_tracks); + // The implicit track list should have only one repeater, if any. DCHECK_LE(implicit_tracks->RepeaterCount(), 1u); DCHECK_NE(kInvalidRangeIndex, auto_repetitions); @@ -182,6 +183,21 @@ current_repeater_start_line += repeater_track_count; end_lines_.push_back(current_repeater_start_line); } + + // There is a special scenario where named grid areas can be specified through + // the "grid-template" property with no specified explicit grid; such case is + // tricky because the computed value of "grid-template-columns" is expected to + // return the computed size of columns from the named grid areas. + // + // In order to guarantee that such columns are included, if the last repeater + // from the explicit grid ended before the end of the named grid area, add an + // extra repeater to fulfill the named grid area's span. + const wtf_size_t named_grid_area_end_line = + start_offset + named_grid_area_track_count; + if (current_repeater_start_line < named_grid_area_end_line) { + start_lines_.push_back(current_repeater_start_line); + end_lines_.push_back(named_grid_area_end_line); + } } void NGGridBlockTrackCollection::EnsureTrackCoverage(wtf_size_t track_number,
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h index 3f8e60b..7b9ce3d9 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h
@@ -107,8 +107,9 @@ // Sets the specified, implicit tracks, along with a given auto repeat value. void SetSpecifiedTracks(const NGGridTrackList* explicit_tracks, const NGGridTrackList* implicit_tracks, - wtf_size_t start_offset, - wtf_size_t auto_repetitions); + const wtf_size_t start_offset, + const wtf_size_t auto_repetitions, + const wtf_size_t named_grid_area_track_count); // Ensures that after FinalizeRanges is called, a range will start at the // |track_number|, and a range will end at |track_number| + |span_length| void EnsureTrackCoverage(wtf_size_t track_number, wtf_size_t span_length);
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection_test.cc b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection_test.cc index 58555b5..757f379c 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection_test.cc +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection_test.cc
@@ -194,7 +194,8 @@ NGGridBlockTrackCollection block_collection; block_collection.SetSpecifiedTracks(&explicit_tracks, &implicit_tracks, /* start_offset */ 0, - /* auto_repeat_count */ 3); + /* auto_repeat_count */ 3, + /* named_grid_area_track_count */ 0); block_collection.FinalizeRanges(/* start_offset */ 0); NGGridTrackCollectionBase::RangeRepeatIterator iterator(&block_collection, @@ -217,7 +218,8 @@ NGGridBlockTrackCollection block_collection; block_collection.SetSpecifiedTracks(&explicit_tracks, &implicit_tracks, /* start_offset */ 0, - /* auto_repeat_count */ 3); + /* auto_repeat_count */ 3, + /* named_grid_area_track_count */ 0); block_collection.FinalizeRanges(/* start_offset */ 0); NGGridTrackCollectionBase::RangeRepeatIterator iterator(&block_collection, @@ -246,7 +248,8 @@ NGGridBlockTrackCollection block_collection; block_collection.SetSpecifiedTracks(&explicit_tracks, &implicit_tracks, /* start_offset */ 0, - /* auto_repeat_count */ 3); + /* auto_repeat_count */ 3, + /* named_grid_area_track_count */ 0); block_collection.EnsureTrackCoverage(3, 40); block_collection.EnsureTrackCoverage(3, 40); block_collection.FinalizeRanges(/* start_offset */ 0); @@ -342,7 +345,8 @@ NGGridBlockTrackCollection block_collection; block_collection.SetSpecifiedTracks(&explicit_tracks, &implicit_tracks, /* start_offset */ 0, - /* auto_repeat_count */ 0); + /* auto_repeat_count */ 0, + /* named_grid_area_track_count */ 0); block_collection.FinalizeRanges(/* start_offset */ 0); NGGridLayoutAlgorithmTrackCollection algorithm_collection( block_collection, /* is_content_box_size_defined */ false); @@ -397,7 +401,8 @@ NGGridBlockTrackCollection block_collection; block_collection.SetSpecifiedTracks(&explicit_tracks, &implicit_tracks, /* start_offset */ 0, - /* auto_repeat_count */ 5); + /* auto_repeat_count */ 5, + /* named_grid_area_track_count */ 0); block_collection.EnsureTrackCoverage(2, 4); block_collection.EnsureTrackCoverage(12, 4); block_collection.EnsureTrackCoverage(17, 3); @@ -514,7 +519,8 @@ NGGridBlockTrackCollection block_collection; block_collection.SetSpecifiedTracks(&explicit_tracks, &implicit_tracks, /* start_offset */ 0, - /* auto_repeat_count */ 0); + /* auto_repeat_count */ 0, + /* named_grid_area_track_count */ 0); block_collection.EnsureTrackCoverage(2, 13); block_collection.EnsureTrackCoverage(23, 2); block_collection.FinalizeRanges(/* start_offset */ 0); @@ -590,7 +596,8 @@ NGGridBlockTrackCollection block_collection; block_collection.SetSpecifiedTracks(&explicit_tracks, &implicit_tracks, /* start_offset */ 0, - /* auto_repeat_count */ 0); + /* auto_repeat_count */ 0, + /* named_grid_area_track_count */ 0); block_collection.EnsureTrackCoverage(1, 2); block_collection.EnsureTrackCoverage(7, 4); block_collection.FinalizeRanges(/* start_offset */ 0);
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index e7b5063..1b9f3c72 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -94,6 +94,7 @@ "//third_party/blink/renderer/modules/cache_storage", "//third_party/blink/renderer/modules/canvas", "//third_party/blink/renderer/modules/clipboard", + "//third_party/blink/renderer/modules/compute_pressure", "//third_party/blink/renderer/modules/contacts_picker", "//third_party/blink/renderer/modules/content_index", "//third_party/blink/renderer/modules/cookie_store",
diff --git a/third_party/blink/renderer/modules/compute_pressure/BUILD.gn b/third_party/blink/renderer/modules/compute_pressure/BUILD.gn new file mode 100644 index 0000000..ae60791 --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/BUILD.gn
@@ -0,0 +1,14 @@ +# Copyright 2021 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("//third_party/blink/renderer/modules/modules.gni") + +blink_modules_sources("compute_pressure") { + sources = [ + "compute_pressure_observer.cc", + "compute_pressure_observer.h", + ] + + deps = [ "//third_party/blink/renderer/platform" ] +}
diff --git a/third_party/blink/renderer/modules/compute_pressure/DEPS b/third_party/blink/renderer/modules/compute_pressure/DEPS new file mode 100644 index 0000000..924647dfb --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/DEPS
@@ -0,0 +1,5 @@ +include_rules = [ + "-third_party/blink/renderer/modules", + "+third_party/blink/renderer/modules/modules_export.h", + "+third_party/blink/renderer/modules/compute_pressure", +]
diff --git a/third_party/blink/renderer/modules/compute_pressure/DIR_METADATA b/third_party/blink/renderer/modules/compute_pressure/DIR_METADATA new file mode 100644 index 0000000..40a233c --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/DIR_METADATA
@@ -0,0 +1,5 @@ +monorail { + component: "Blink>PerformanceAPIs>ComputePressure" +} + +team_email: "storage-dev@chromium.org"
diff --git a/third_party/blink/renderer/modules/compute_pressure/OWNERS b/third_party/blink/renderer/modules/compute_pressure/OWNERS new file mode 100644 index 0000000..32024c4 --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/OWNERS
@@ -0,0 +1,4 @@ +file://content/browser/compute_pressure/OWNERS + +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.cc b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.cc new file mode 100644 index 0000000..e9feea6 --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.cc
@@ -0,0 +1,221 @@ +// Copyright 2021 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/compute_pressure/compute_pressure_observer.h" + +#include "third_party/blink/public/common/browser_interface_broker_proxy.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom-blink.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.h" +#include "third_party/blink/renderer/core/dom/dom_exception.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_options.h" +#include "third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_update.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/heap/heap.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" +#include "third_party/blink/renderer/platform/wtf/wtf_size_t.h" + +namespace blink { + +ComputePressureObserver::ComputePressureObserver( + ExecutionContext* execution_context, + V8ComputePressureUpdateCallback* observer_callback, + ComputePressureObserverOptions* normalized_options) + : ExecutionContextLifecycleStateObserver(execution_context), + observer_callback_(observer_callback), + normalized_options_(normalized_options), + compute_pressure_host_(execution_context), + receiver_(this, execution_context) { + execution_context->GetBrowserInterfaceBroker().GetInterface( + compute_pressure_host_.BindNewPipeAndPassReceiver( + execution_context->GetTaskRunner(TaskType::kUserInteraction))); + // ExecutionContextLifecycleStateObserver. + UpdateStateIfNeeded(); +} + +ComputePressureObserver::~ComputePressureObserver() = default; + +namespace { + +// Validates a sorted array that specifies a quantization scheme. +// +// Returns false if the array is not a valid quantization scheme. +// `exception_state` is populated in this case. +bool ValidateThresholds(const Vector<double>& thresholds, + ExceptionState& exception_state) { + double previous_threshold = 0.0; + + for (double threshold : thresholds) { + if (threshold <= 0.0) { + exception_state.ThrowTypeError("Thresholds must be greater than 0.0"); + return false; + } + + if (threshold >= 1.0) { + exception_state.ThrowTypeError("Thresholds must be less than 1.0"); + return false; + } + + DCHECK_GE(threshold, previous_threshold) << "the thresholds are not sorted"; + if (threshold == previous_threshold) { + exception_state.ThrowTypeError("Thresholds must be different"); + return false; + } + previous_threshold = threshold; + } + return true; +} + +bool NormalizeObserverOptions(ComputePressureObserverOptions& options, + ExceptionState& exception_state) { + Vector<double> cpu_utilization_thresholds = + options.cpuUtilizationThresholds(); + if (cpu_utilization_thresholds.size() > + mojom::blink::kMaxComputePressureCpuUtilizationThresholds) { + cpu_utilization_thresholds.resize( + mojom::blink::kMaxComputePressureCpuUtilizationThresholds); + } + std::sort(cpu_utilization_thresholds.begin(), + cpu_utilization_thresholds.end()); + if (!ValidateThresholds(cpu_utilization_thresholds, exception_state)) { + DCHECK(exception_state.HadException()); + return false; + } + options.setCpuUtilizationThresholds(cpu_utilization_thresholds); + + Vector<double> cpu_speed_thresholds = options.cpuSpeedThresholds(); + if (cpu_speed_thresholds.size() > + mojom::blink::kMaxComputePressureCpuSpeedThresholds) { + cpu_speed_thresholds.resize( + mojom::blink::kMaxComputePressureCpuSpeedThresholds); + } + std::sort(cpu_speed_thresholds.begin(), cpu_speed_thresholds.end()); + if (!ValidateThresholds(cpu_speed_thresholds, exception_state)) { + DCHECK(exception_state.HadException()); + return false; + } + options.setCpuSpeedThresholds(cpu_speed_thresholds); + + return true; +} + +} // namespace + +// static +ComputePressureObserver* ComputePressureObserver::Create( + ScriptState* script_state, + V8ComputePressureUpdateCallback* callback, + ComputePressureObserverOptions* options, + ExceptionState& exception_state) { + if (!NormalizeObserverOptions(*options, exception_state)) { + DCHECK(exception_state.HadException()); + return nullptr; + } + + ExecutionContext* execution_context = ExecutionContext::From(script_state); + return MakeGarbageCollected<ComputePressureObserver>(execution_context, + callback, options); +} + +ScriptPromise ComputePressureObserver::observe( + ScriptState* script_state, + ExceptionState& exception_state) { + if (!compute_pressure_host_.is_bound()) { + exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, + "ComputePressureHost backend went away"); + return ScriptPromise(); + } + + if (receiver_.is_bound()) + return ScriptPromise::CastUndefined(script_state); + + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + + scoped_refptr<base::SingleThreadTaskRunner> task_runner = + ExecutionContext::From(script_state) + ->GetTaskRunner(TaskType::kMiscPlatformAPI); + + auto mojo_options = mojom::blink::ComputePressureQuantization::New( + normalized_options_->cpuUtilizationThresholds(), + normalized_options_->cpuSpeedThresholds()); + + compute_pressure_host_->AddObserver( + receiver_.BindNewPipeAndPassRemote(std::move(task_runner)), + std::move(mojo_options), + WTF::Bind(&ComputePressureObserver::DidAddObserver, + WrapWeakPersistent(this), WrapPersistent(resolver))); + receiver_.set_disconnect_handler( + WTF::Bind(&ComputePressureObserver::OnReceiverDisconnect, + WrapWeakPersistent(this))); + return resolver->Promise(); +} + +void ComputePressureObserver::stop(ScriptState* script_state) { + receiver_.reset(); + return; +} + +void ComputePressureObserver::Trace(blink::Visitor* visitor) const { + ScriptWrappable::Trace(visitor); + ContextLifecycleObserver::Trace(visitor); + visitor->Trace(observer_callback_); + visitor->Trace(normalized_options_); + visitor->Trace(compute_pressure_host_); + visitor->Trace(receiver_); +} + +void ComputePressureObserver::OnUpdate( + mojom::blink::ComputePressureStatePtr state) { + auto* update = ComputePressureObserverUpdate::Create(); + update->setCpuUtilization(state->cpu_utilization); + update->setCpuSpeed(state->cpu_speed); + update->setOptions(normalized_options_); + + observer_callback_->InvokeAndReportException(this, update); +} + +void ComputePressureObserver::ContextDestroyed() { + receiver_.reset(); +} + +void ComputePressureObserver::ContextLifecycleStateChanged( + mojom::blink::FrameLifecycleState state) { + // TODO(https://crbug.com/1186433): Disconnect and re-establish a connection + // when frozen or send a disconnect event. +} + +void ComputePressureObserver::OnReceiverDisconnect() { + receiver_.reset(); +} + +void ComputePressureObserver::DidAddObserver( + ScriptPromiseResolver* resolver, + mojom::blink::ComputePressureStatus status) { + ScriptState* script_state = resolver->GetScriptState(); + if (!script_state->ContextIsValid()) + return; + ScriptState::Scope scope(script_state); + + switch (status) { + case mojom::blink::ComputePressureStatus::kOk: + break; + case mojom::blink::ComputePressureStatus::kNotSupported: + resolver->Reject(V8ThrowDOMException::CreateOrEmpty( + script_state->GetIsolate(), DOMExceptionCode::kNotSupportedError, + "Not available on this platform.")); + return; + case mojom::blink::ComputePressureStatus::kSecurityError: + resolver->Reject(V8ThrowDOMException::CreateOrEmpty( + script_state->GetIsolate(), DOMExceptionCode::kSecurityError, + "Security error. Make sure the page is visible.")); + return; + } + + resolver->Resolve(); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.h b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.h new file mode 100644 index 0000000..5242a9ba --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.h
@@ -0,0 +1,88 @@ +// Copyright 2021 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_COMPUTE_PRESSURE_COMPUTE_PRESSURE_OBSERVER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_COMPUTE_PRESSURE_COMPUTE_PRESSURE_OBSERVER_H_ + +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom-blink.h" +#include "third_party/blink/public/mojom/frame/lifecycle.mojom-blink.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_compute_pressure_update_callback.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_state_observer.h" +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/heap/heap.h" +#include "third_party/blink/renderer/platform/mojo/heap_mojo_receiver.h" +#include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" + +namespace blink { + +class ExceptionState; +class ScriptState; +class ScriptPromise; +class ScriptPromiseResolver; +class ComputePressureObserverOptions; + +class ComputePressureObserver final + : public ScriptWrappable, + public ExecutionContextLifecycleStateObserver, + public mojom::blink::ComputePressureObserver { + DEFINE_WRAPPERTYPEINFO(); + + public: + ComputePressureObserver(ExecutionContext* execution_context, + V8ComputePressureUpdateCallback* observer_callback, + ComputePressureObserverOptions* normalized_options); + ~ComputePressureObserver() override; + + static ComputePressureObserver* Create(ScriptState*, + V8ComputePressureUpdateCallback*, + ComputePressureObserverOptions*, + ExceptionState&); + + // ComputePressureObserver IDL implementation. + ScriptPromise observe(ScriptState*, ExceptionState&); + void stop(ScriptState*); + + ComputePressureObserver(const ComputePressureObserver&) = delete; + ComputePressureObserver operator=(const ComputePressureObserver&) = delete; + + // GarbageCollected implementation. + void Trace(blink::Visitor*) const override; + + // mojom::blink::ComputePressureObserver implementation. + void OnUpdate(mojom::blink::ComputePressureStatePtr state) override; + + // ExecutionContextLifecycleObserver implementation. + void ContextDestroyed() override; + + // ExecutionContextLifecycleStateObserver implementation. + void ContextLifecycleStateChanged( + mojom::blink::FrameLifecycleState state) override; + + private: + // Called when `receiver_` is disconnected. + void OnReceiverDisconnect(); + + void DidAddObserver(ScriptPromiseResolver* resolver, + mojom::blink::ComputePressureStatus status); + + // The callback that receives compute pressure state updates. + Member<V8ComputePressureUpdateCallback> observer_callback_; + + // The quantization scheme sent to the browser-side implementation. + Member<ComputePressureObserverOptions> normalized_options_; + + // Connection to the browser-side implementation. + HeapMojoRemote<mojom::blink::ComputePressureHost> compute_pressure_host_; + + // Routes ComputePressureObserver mojo messages to this instance. + HeapMojoReceiver<mojom::blink::ComputePressureObserver, + ComputePressureObserver> + receiver_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_COMPUTE_PRESSURE_COMPUTE_PRESSURE_OBSERVER_H_
diff --git a/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.idl b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.idl new file mode 100644 index 0000000..cd3cda57 --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer.idl
@@ -0,0 +1,24 @@ +// Copyright 2021 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://github.com/oyiptong/compute-pressure/ +[ + Exposed=Window, + RuntimeEnabled=ComputePressure, + SecureContext +] interface ComputePressureObserver { + [ + CallWith=ScriptState, RaisesException, + MeasureAs=ComputePressureObserver_Constructor + ] constructor(ComputePressureUpdateCallback callback, + optional ComputePressureObserverOptions options = {}); + + [ + CallWith=ScriptState, + MeasureAs=ComputePressureObserver_Observe, + RaisesException + ] Promise<void> observe(); + + [CallWith=ScriptState, MeasureAs=ComputePressureObserver_Stop] void stop(); +};
diff --git a/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_options.idl b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_options.idl new file mode 100644 index 0000000..42e1bf5c4 --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_options.idl
@@ -0,0 +1,12 @@ +// Copyright 2021 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://github.com/oyiptong/compute-pressure/ +[ + Exposed=Window, + SecureContext +] dictionary ComputePressureObserverOptions { + sequence<double> cpuUtilizationThresholds = []; + sequence<double> cpuSpeedThresholds = []; +};
diff --git a/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_update.idl b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_update.idl new file mode 100644 index 0000000..61071f3 --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_observer_update.idl
@@ -0,0 +1,14 @@ +// Copyright 2021 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://github.com/oyiptong/compute-pressure/ + +[ + Exposed=Window, + SecureContext +] dictionary ComputePressureObserverUpdate { + double cpuUtilization; + double cpuSpeed; + ComputePressureObserverOptions options; +};
diff --git a/third_party/blink/renderer/modules/compute_pressure/compute_pressure_update_callback.idl b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_update_callback.idl new file mode 100644 index 0000000..e2473fc --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/compute_pressure_update_callback.idl
@@ -0,0 +1,10 @@ +// Copyright 2021 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://github.com/oyiptong/compute-pressure/ +[ + Exposed=Window, + RuntimeEnabled=ComputePressure, + SecureContext +] callback ComputePressureUpdateCallback = void (ComputePressureObserverUpdate update);
diff --git a/third_party/blink/renderer/modules/compute_pressure/idls.gni b/third_party/blink/renderer/modules/compute_pressure/idls.gni new file mode 100644 index 0000000..c5401c5 --- /dev/null +++ b/third_party/blink/renderer/modules/compute_pressure/idls.gni
@@ -0,0 +1,12 @@ +# Copyright 2021 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. + +modules_idl_files = [ "compute_pressure_observer.idl" ] + +modules_callback_function_idl_files = [ "compute_pressure_update_callback.idl" ] + +modules_dictionary_idl_files = [ + "compute_pressure_observer_update.idl", + "compute_pressure_observer_options.idl", +]
diff --git a/third_party/blink/renderer/modules/modules_idl_files.gni b/third_party/blink/renderer/modules/modules_idl_files.gni index a10dc76..5d9ce54 100644 --- a/third_party/blink/renderer/modules/modules_idl_files.gni +++ b/third_party/blink/renderer/modules/modules_idl_files.gni
@@ -64,6 +64,7 @@ "//third_party/blink/renderer/modules/canvas/idls.gni", "//third_party/blink/renderer/modules/clipboard/idls.gni", "//third_party/blink/renderer/modules/compression/idls.gni", + "//third_party/blink/renderer/modules/compute_pressure/idls.gni", "//third_party/blink/renderer/modules/contacts_picker/idls.gni", "//third_party/blink/renderer/modules/content_index/idls.gni", "//third_party/blink/renderer/modules/cookie_store/idls.gni",
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 84fe3f7..936ad073 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -692,11 +692,6 @@ name: "CSSTargetTextPseudoElement", status: "stable", }, - // Support for @property rules. - { - name: "CSSVariables2AtProperty", - status: "stable", - }, // Support for registered custom properties with <image> syntax. { name: "CSSVariables2ImageValues",
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests index a2a009c..b941a960 100644 --- a/third_party/blink/web_tests/NeverFixTests +++ b/third_party/blink/web_tests/NeverFixTests
@@ -2100,6 +2100,32 @@ virtual/font-access-persistent/external/wpt/font-access/font_access-enumeration.tentative.https.window.html [ Pass ] virtual/font-access-persistent/external/wpt/font-access/font_metadata.tentative.https.window.html [ Pass ] +# Remove from virtual tests when ComputePressure is turned on by default. +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_detached_iframe.tenative.https.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_different_quantizations.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_stop.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_stop_idempotent.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_stop_immediately.tentative.https.window.html [ Skip ] +crbug.com/1196419 external/wpt/compute-pressure/compute_pressure_values.tenative.https.window.html [ Skip ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_detached_iframe.tenative.https.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_different_quantizations.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_stop.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_stop_idempotent.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_stop_immediately.tentative.https.window.html [ Pass ] +crbug.com/1196419 virtual/compute-pressure/external/wpt/compute-pressure/compute_pressure_values.tenative.https.window.html [ Pass ] + # text-orientation:upright crbug.com/1005518 external/wpt/css/css-writing-modes/table-progression-vlr-003.html [ Skip ] crbug.com/1005518 external/wpt/css/css-writing-modes/table-progression-vlr-004.html [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 8cd595ad..5b78208 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -4256,9 +4256,7 @@ crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-column-axis-self-baseline-synthesized-001.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-column-axis-self-baseline-synthesized-003.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-column-axis-self-baseline-synthesized-005.html [ Failure ] -crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-content-alignment-auto-sized-tracks-001.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-content-alignment-overflow-001.html [ Failure ] -crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-fit-content-tracks-dont-stretch-001.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-item-no-aspect-ratio-stretch-4.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-item-no-aspect-ratio-stretch-5.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-item-no-aspect-ratio-stretch-6.html [ Failure ] @@ -4272,18 +4270,13 @@ crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-self-baseline-not-applied-if-sizing-cyclic-dependency-001.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-self-baseline-not-applied-if-sizing-cyclic-dependency-002.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/alignment/grid-self-baseline-not-applied-if-sizing-cyclic-dependency-003.html [ Failure ] -crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/grid-definition/grid-change-fit-content-argument-001.html [ Failure ] -crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/grid-definition/grid-template-columns-fit-content-001.html [ Failure ] -crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/grid-definition/grid-template-rows-fit-content-001.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/layout-algorithm/grid-as-flex-item-should-not-shrink-to-fit-007.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/layout-algorithm/grid-flex-track-intrinsic-sizes-001.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/layout-algorithm/grid-flex-track-intrinsic-sizes-003.html [ Failure ] -crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/layout-algorithm/grid-fit-content-percentage.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/layout-algorithm/grid-intrinsic-size-with-orthogonal-items.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/layout-algorithm/grid-minimum-contribution-baseline-shim-vertical-lr.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/layout-algorithm/grid-minimum-contribution-baseline-shim-vertical-rl.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/external/wpt/css/css-grid/layout-algorithm/grid-minimum-contribution-baseline-shim.html [ Failure ] -crbug.com/1045599 virtual/layout-ng-grid/fast/css-grid-layout/grid-template-shorthand-get-set.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/fast/css-grid-layout/implicit-tracks-before-explicit.html [ Failure ] crbug.com/1045599 virtual/layout-ng-grid/fast/css-grid-layout/percent-padding-margin-resolution-grid-item-update.html [ Failure ] @@ -7112,3 +7105,4 @@ crbug.com/1205780 [ Mac10.15 ] external/wpt/css/mediaqueries/test_media_queries.html [ Failure Pass ] crbug.com/1205796 [ Mac10.12 ] external/wpt/html/dom/idlharness.https.html?include=HTML.* [ Failure ] crbug.com/1205796 [ Mac10.14 ] external/wpt/html/dom/idlharness.https.html?include=HTML.* [ Failure ] +crbug.com/1206019 [ Linux ] http/tests/devtools/sources/snippet-module.js [ Failure ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index cba1937a1..544df26 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -242,6 +242,11 @@ "args": ["--enable-features=FontAccess,FontAccessPersistent"] }, { + "prefix": "compute-pressure", + "bases": ["external/wpt/compute-pressure"], + "args": ["--enable-features=ComputePressure"] + }, + { "prefix": "highdpi-threaded", "bases": ["external/wpt/css/css-paint-api/hidpi"], "args": ["--force-device-scale-factor=2",
diff --git a/third_party/blink/web_tests/android/WebLayerWPTOverrideExpectations b/third_party/blink/web_tests/android/WebLayerWPTOverrideExpectations index 370d9c8..0e57f7f 100644 --- a/third_party/blink/web_tests/android/WebLayerWPTOverrideExpectations +++ b/third_party/blink/web_tests/android/WebLayerWPTOverrideExpectations
@@ -180,7 +180,7 @@ # Failing WebAppApi tests on Clank and WebLayer on Android crbug.com/1198573 external/wpt/html/webappapis/dynamic-markup-insertion/document-write/047.html [ Crash Pass ] crbug.com/1198573 external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/history.window.html [ Crash Pass ] -crbug.com/1198573 external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/reload.window.html [ Crash Pass ] +crbug.com/1198573 external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/reload.window.html [ Crash Pass Timeout ] crbug.com/1198573 external/wpt/html/webappapis/scripting/processing-model-2/integration-with-the-javascript-agent-formalism/requires-success.any.worker.html [ Failure Pass ] crbug.com/1198573 external/wpt/html/webappapis/scripting/processing-model-2/integration-with-the-javascript-job-queue/promise-job-entry-different-function-realm.html [ Crash Pass ] crbug.com/1198573 external/wpt/html/webappapis/scripting/processing-model-2/integration-with-the-javascript-job-queue/promise-job-entry.html [ Crash Pass ] @@ -418,12 +418,17 @@ crbug.com/1050754 external/wpt/bluetooth/requestDevice/acceptAllDevices/optional-services-present.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/blocklisted-service-in-filter.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/blocklisted-service-in-optionalServices.https.html [ Failure ] +crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/data-prefix-and-mask-size.https.window.html [ Failure ] +crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/dataPrefix-buffer-is-detached.https.window.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/device-name-longer-than-29-bytes.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/empty-filter.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/empty-filters-member.https.html [ Failure ] +crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/empty-manufacturerData-member.https.window.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/empty-namePrefix.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/empty-services-member.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/filters-xor-acceptAllDevices.https.html [ Failure ] +crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/invalid-companyIdentifier.https.window.html [ Failure ] +crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/mask-buffer-is-detached.https.window.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/max-length-exceeded-name-unicode.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/max-length-exceeded-name.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/max-length-exceeded-namePrefix-unicode.https.html [ Failure ] @@ -433,6 +438,7 @@ crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/max-length-namePrefix-unicode.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/max-length-namePrefix.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/no-arguments.https.html [ Pass ] +crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/same-company-identifier.https.window.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/unicode-valid-length-name-name.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/unicode-valid-length-name-namePrefix.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/canonicalizeFilter/wrong-service-in-optionalServices-member.https.html [ Failure ] @@ -442,6 +448,7 @@ crbug.com/1050754 external/wpt/bluetooth/requestDevice/doesnt-consume-user-gesture.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/filter-matches.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/le-not-supported.https.html [ Failure ] +crbug.com/1050754 external/wpt/bluetooth/requestDevice/manufacturer-data-filter-matches.https.window.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/name-empty-device-from-name-empty-filter.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/not-processing-user-gesture.https.html [ Failure ] crbug.com/1050754 external/wpt/bluetooth/requestDevice/radio-not-present.https.html [ Failure ] @@ -664,7 +671,7 @@ crbug.com/1050754 external/wpt/css/css-text/white-space/white-space-collapse-002.html [ Failure ] crbug.com/1050754 external/wpt/css/css-transforms/transform-scale-hittest.html [ Failure ] crbug.com/1050754 external/wpt/css/css-transitions/CSSTransition-effect.tentative.html [ Failure Pass ] -crbug.com/1050754 external/wpt/css/css-transitions/properties-value-inherit-003.html [ Failure ] +crbug.com/1050754 external/wpt/css/css-transitions/properties-value-inherit-003.html [ Failure Pass ] crbug.com/1050754 external/wpt/css/css-ui/animation/outline-width-interpolation.html [ Failure ] crbug.com/1050754 external/wpt/css/css-ui/text-overflow-023.html [ Pass ] crbug.com/1050754 external/wpt/css/css-values/lh-rlh-on-root-001.html [ Failure ] @@ -927,6 +934,7 @@ crbug.com/1050754 external/wpt/html/canvas/element/manual/wide-gamut-canvas/canvas-draw-high-bit-depth-images.html [ Failure ] crbug.com/1050754 external/wpt/html/canvas/element/scroll/2d.scrollPathIntoView.verticalRL.html [ Failure ] crbug.com/1050754 external/wpt/html/canvas/offscreen/drawing-images-to-the-canvas/2d.drawImage.animated.poster.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.pattern.paint.repeat.basic.html [ Failure ] crbug.com/1050754 external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.pattern.paint.repeat.outside.html [ Failure Pass ] crbug.com/1050754 external/wpt/html/canvas/offscreen/manual/the-offscreen-canvas/offscreencanvas.getcontext.html [ Failure ] crbug.com/1050754 external/wpt/html/canvas/offscreen/manual/the-offscreen-canvas/offscreencanvas.getcontext.worker.html [ Failure ] @@ -940,7 +948,7 @@ crbug.com/1050754 external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.worker.html [ Pass ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/cross-origin-isolated.html [ Pass Timeout ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/fetch.tentative.https.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe.tentative.html [ Timeout ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe.tentative.html [ Pass Timeout ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/image.tentative.https.html [ Failure Pass ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/link.tentative.https.html [ Failure Pass ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/redirect.tentative.html [ Failure Pass Timeout ] @@ -981,7 +989,7 @@ crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-blur.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-close.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-closed.https.html [ Crash Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-focus.https.html [ Crash ] +crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-focus.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-frames.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-length.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-location-get.https.html [ Crash Pass ] @@ -990,7 +998,7 @@ crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-postmessage-2.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-self.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-top.https.html [ Crash Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-window.https.html [ Crash ] +crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/property-window.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/report-to-both_coop-ro.https.html [ Crash Pass ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/access-reporting/reporting-observer.html [ Crash Pass Timeout ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/reporting/navigation-reporting/reporting-redirect-with-same-origin-allow-popups.https.html [ Crash Pass ] @@ -1059,6 +1067,7 @@ crbug.com/1050754 external/wpt/html/user-activation/consumption-sameorigin.tentative.html [ Failure ] crbug.com/1050754 external/wpt/html/user-activation/propagation-crossorigin.sub.tentative.html [ Failure ] crbug.com/1050754 external/wpt/html/user-activation/propagation-sameorigin.tentative.html [ Failure ] +crbug.com/1050754 external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/tasks.window.html [ Pass ] crbug.com/1050754 external/wpt/idle-detection/idle-detection-allowed-by-feature-policy-attribute-redirect-on-load.https.sub.html [ Failure ] crbug.com/1050754 external/wpt/idle-detection/idle-detection-allowed-by-feature-policy-attribute.https.sub.html [ Failure ] crbug.com/1050754 external/wpt/idle-detection/idle-detection-allowed-by-feature-policy.https.sub.html [ Failure ] @@ -1158,7 +1167,7 @@ crbug.com/1050754 external/wpt/mathml/relations/html5-tree/tabindex-002.html [ Timeout ] crbug.com/1050754 external/wpt/media-source/dedicated-worker/mediasource-worker-play-terminate-worker.html [ Failure Pass Timeout ] crbug.com/1050754 external/wpt/media-source/mediasource-changetype-play-negative.html [ Timeout ] -crbug.com/1050754 external/wpt/media-source/mediasource-detach.html [ Failure ] +crbug.com/1050754 external/wpt/media-source/mediasource-detach.html [ Failure Pass ] crbug.com/1050754 external/wpt/media-source/mediasource-getvideoplaybackquality.html [ Pass ] crbug.com/1050754 external/wpt/mediacapture-record/passthrough/MediaRecorder-passthrough.https.html [ Failure Pass Timeout ] crbug.com/1050754 external/wpt/mediacapture-streams/MediaStream-MediaElement-firstframe.https.html [ Failure ] @@ -1681,6 +1690,7 @@ crbug.com/1050754 external/wpt/uievents/order-of-events/mouse-events/click-on-body.html [ Failure Pass ] crbug.com/1050754 external/wpt/uievents/order-of-events/mouse-events/wheel-basic.html [ Pass ] crbug.com/1050754 external/wpt/uievents/order-of-events/mouse-events/wheel-scrolling.html [ Pass ] +crbug.com/1050754 external/wpt/upgrade-insecure-requests/gen/iframe-blank-inherit.meta/unset/sharedworker-import-data.https.html [ Failure ] crbug.com/1050754 external/wpt/upgrade-insecure-requests/gen/iframe-blank-inherit.meta/upgrade/sharedworker-import-data.https.html [ Failure ] crbug.com/1050754 external/wpt/upgrade-insecure-requests/gen/iframe-blank-inherit.meta/upgrade/sharedworker-import.https.html [ Failure ] crbug.com/1050754 external/wpt/upgrade-insecure-requests/gen/sharedworker-classic-data.http-rp/upgrade/fetch.https.html [ Failure ]
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/DIR_METADATA b/third_party/blink/web_tests/external/wpt/compute-pressure/DIR_METADATA new file mode 100644 index 0000000..866fe18 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/DIR_METADATA
@@ -0,0 +1,8 @@ +monorail { + component: "Blink>PerformanceAPIs>ComputePressure" +} +team_email: "storage-dev@chromium.org" +wpt { + notify: YES +} +
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/OWNERS b/third_party/blink/web_tests/external/wpt/compute-pressure/OWNERS new file mode 100644 index 0000000..40ec9fc --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/OWNERS
@@ -0,0 +1,2 @@ +oyiptong@chromium.org +pwnall@chromium.org
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/README.md b/third_party/blink/web_tests/external/wpt/compute-pressure/README.md new file mode 100644 index 0000000..9766bb0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/README.md
@@ -0,0 +1,2 @@ +This directory contains (tentative) tests for the +[Compute Pressure](https://oyiptong.github.io/compute-pressure/) specification.
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.js new file mode 100644 index 0000000..515c9d7 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_arguments.tentative.https.window.js
@@ -0,0 +1,73 @@ +'use strict'; + +for (const property of ['cpuUtilizationThresholds', 'cpuSpeedThresholds']) { + for (const out_of_range_value of [-1.0, 0.0, 1.0, 2.0]) { + test(t => { + const callback = () => {}; + + const options = { + cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5] }; + options[property] = [out_of_range_value]; + + assert_throws_js(TypeError, () => { + new ComputePressureObserver(callback, options); + }); + }, `ComputePressureObserver constructor throws when ${property} ` + + `is [${out_of_range_value}]`); + } + + for (const valid_value of [0.05, 0.1, 0.2, 0.5, 0.9, 0.95]) { + test(t => { + const callback = () => {}; + + const options = { + cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5] }; + options[property] = [valid_value]; + + const observer = new ComputePressureObserver(callback, options); + assert_true(observer instanceof ComputePressureObserver); + }, `ComputePressureObserver constructor accepts ${property} value ` + + `[${valid_value}]`); + } + + promise_test(async t => { + const many_thresholds = [0.5]; + for (let i = 0.01; i < 0.5; i += 0.0001) { + many_thresholds.push(0.5 + i); + many_thresholds.push(0.5 - i); + } + + const options = { + cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5] }; + options[property] = many_thresholds; + + const update = await new Promise((resolve, reject) => { + const observer = new ComputePressureObserver(resolve, options); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + const effective_thresholds = update.options[property]; + assert_less_than(effective_thresholds.length, many_thresholds.length, + 'only a small number of thresholds are selected'); + + const expected_thresholds = + many_thresholds.slice(0, effective_thresholds.length); + expected_thresholds.sort(); + assert_array_equals( + effective_thresholds, expected_thresholds, + 'thresholds are selected in the given order, before sorting'); + }, `ComputePressureObserver filters thresholds in ${property}`); +} + +test(t => { + const callback = () => {}; + + + assert_throws_js(TypeError, () => { + new ComputePressureObserver( + callback, + { cpuUtilizationThresholds: [0.5, 0.5], cpuSpeedThresholds: [0.5] }); + }); +}, 'ComputePressureObserver constructor throws when cpuUtilizationThresholds ' + + 'has duplicates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.js new file mode 100644 index 0000000..dac1dab --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_basic.tentative.https.window.js
@@ -0,0 +1,24 @@ +'use strict'; + +promise_test(async t => { + // The quantization thresholds and the quantized values that they lead to can + // be represented exactly in floating-point, so === comparison works. + + const update = await new Promise((resolve, reject) => { + const observer = new ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + assert_equals(typeof update.cpuUtilization, 'number'); + assert_greater_than_equal(update.cpuUtilization, 0.0, 'cpuUtilization range'); + assert_less_than_equal(update.cpuUtilization, 1.0, 'cpuUtilization range'); + assert_in_array(update.cpuUtilization, [0.25, 0.75], + 'cpuUtilization quantization'); + + assert_equals(typeof update.cpuSpeed, 'number'); + assert_greater_than_equal(update.cpuSpeed, 0.0, 'cpuSpeed range'); + assert_less_than_equal(update.cpuSpeed, 1.0, 'cpuUSpeed range'); + assert_in_array(update.cpuSpeed, [0.25, 0.75], 'cpuSpeed quantization'); +}, 'An active ComputePressureObserver calls its callback at least once');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_detached_iframe.tenative.https.html b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_detached_iframe.tenative.https.html new file mode 100644 index 0000000..be0b938 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_detached_iframe.tenative.https.html
@@ -0,0 +1,83 @@ +<!doctype html> +<meta charset="utf-8"> +<title>ComputePressureObserver on DOMWindow of detached iframe</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<body> +<script> +'use strict'; + +test(() => { + const iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + const frame_window = iframe.contentWindow; + + iframe.remove(); + assert_equals(undefined, frame_window.ComputePressureObserver); +}, 'ComputePressureObserver constructor does not exist in detached iframes'); + +promise_test(async t => { + const iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + const frame_window = iframe.contentWindow; + + const observer = new frame_window.ComputePressureObserver( + () => {}, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + const iframe_DOMException = frame_window.DOMException; + + iframe.remove(); + + // Calling observe() from a detached iframe should fail but not crash. + await promise_rejects_dom(t, 'InvalidStateError', iframe_DOMException, + observer.observe()); +}, 'ComputePressureObserver.observe() on detached frame rejects'); + +promise_test(async t => { + const iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + const frame_window = iframe.contentWindow; + + const observer = new frame_window.ComputePressureObserver( + () => {}, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + + await observer.observe(); + + iframe.remove(); + + // Calling stop() from a detached iframe should not crash. + observer.stop(); +}, 'ComputePressureObserver.stop() on detached frame returns'); + +promise_test(async t => { + const iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + const frame_window = iframe.contentWindow; + + const observer = new frame_window.ComputePressureObserver( + () => {}, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + const iframe_DOMException = frame_window.DOMException; + + // await is intentionally not used here. We want to remove the iframe while + // the returned Promise settles. + const observe_promise = observer.observe(); + iframe.remove(); + + // Establish an observer and wait for an update in the main frame. This should + // keep the test running long enough to catch any crash from the observe() + // call in the removed iframe's ComputePressureObserver. + const update = await new Promise((resolve, reject) => { + const observer = new ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + assert_in_array(update.cpuUtilization, [0.25, 0.75], + 'cpuUtilization quantization'); + assert_in_array(update.cpuSpeed, [0.25, 0.75], 'cpuSpeed quantization') +}, 'Detaching frame while ComputePressureObserver.observe() settles'); + +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations.tentative.https.window.js new file mode 100644 index 0000000..6f1d6d8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations.tentative.https.window.js
@@ -0,0 +1,79 @@ +'use strict'; + +promise_test(async t => { + const observer1_updates = []; + const observer1 = new ComputePressureObserver( + update => { observer1_updates.push(update); }, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer1.stop()); + // Ensure that observer1's quantization scheme gets registered as the origin's + // scheme before observer2 starts. + await observer1.observe(); + + const observer2_updates = []; + await new Promise((resolve, reject) => { + const observer2 = new ComputePressureObserver( + update => { + observer2_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.25], cpuSpeedThresholds: [0.75]}); + t.add_cleanup(() => observer2.stop()); + observer2.observe().catch(reject); + }); + + // observer2 uses a different quantization scheme than observer1. After + // observer2.observe() completes, observer1 should no longer be active. + // + // The check below assumes that observer2.observe() completes before the + // browser dispatches any update for observer1. This assumption is highly + // likely to be true, because there shold be a 1-second delay between + // observer1.observe() and the first update that observer1 would receive. + assert_equals( + observer1_updates.length, 0, + 'observer2.observe() should have stopped observer1; the two observers ' + + 'have different quantization schemes'); + + assert_equals(observer2_updates.length, 1); + assert_in_array(observer2_updates[0].cpuUtilization, [0.125, 0.625], + 'cpuUtilization quantization'); + assert_in_array(observer2_updates[0].cpuSpeed, [0.375, 0.875], + 'cpuSpeed quantization'); + + // Go through one more update cycle so any (incorrect) update for observer1 + // makes it through the IPC queues. + observer1_updates.length = 0; + observer2_updates.length = 0; + + const observer3_updates = []; + await new Promise((resolve, reject) => { + const observer3 = new ComputePressureObserver( + update => { + observer3_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.75], cpuSpeedThresholds: [0.25]}); + t.add_cleanup(() => observer3.stop()); + observer3.observe().catch(reject); + }); + + assert_equals( + observer1_updates.length, 0, + 'observer2.observe() should have stopped observer1; the two observers ' + + 'have different quantization schemes'); + + // observer3 uses a different quantization scheme than observer2. So, + // observer3.observe() should stop observer2. + assert_equals( + observer2_updates.length, 0, + 'observer3.observe() should have stopped observer2; the two observers ' + + 'have different quantization schemes'); + + assert_equals(observer3_updates.length, 1); + assert_in_array(observer3_updates[0].cpuUtilization, [0.375, 0.875], + 'cpuUtilization quantization'); + assert_in_array(observer3_updates[0].cpuSpeed, [0.125, 0.625], + 'cpuSpeed quantization'); + +}, 'ComputePressureObserver with a new quantization schema stops all ' + + 'other active observers');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.js new file mode 100644 index 0000000..e0429b2 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_different_quantizations_across_iframes.tentative.https.window.js
@@ -0,0 +1,87 @@ +'use strict'; + +promise_test(async t => { + const observer1_updates = []; + const observer1 = new ComputePressureObserver( + update => { observer1_updates.push(update); }, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer1.stop()); + // Ensure that observer1's quantization scheme gets registered as the origin's + // scheme before observer2 starts. + await observer1.observe(); + + // iframe numbers are aligned with observer numbers. The first observer is in + // the main frame, so there is no iframe1. + const iframe2 = document.createElement('iframe'); + document.body.appendChild(iframe2); + + const observer2_updates = []; + await new Promise((resolve, reject) => { + const observer2 = new iframe2.contentWindow.ComputePressureObserver( + update => { + observer2_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.25], cpuSpeedThresholds: [0.75]}); + t.add_cleanup(() => observer2.stop()); + observer2.observe().catch(reject); + }); + + // observer2 uses a different quantization scheme than observer1. After + // observer2.observe() completes, observer1 should no longer be active. + // + // The check below assumes that observer2.observe() completes before the + // browser dispatches any update for observer1. This assumption is highly + // likely to be true, because there shold be a 1-second delay between + // observer1.observe() and the first update that observer1 would receive. + assert_equals( + observer1_updates.length, 0, + 'observer2.observe() should have stopped observer1; the two observers ' + + 'have different quantization schemes'); + + assert_equals(observer2_updates.length, 1); + assert_in_array(observer2_updates[0].cpuUtilization, [0.125, 0.625], + 'cpuUtilization quantization'); + assert_in_array(observer2_updates[0].cpuSpeed, [0.375, 0.875], + 'cpuSpeed quantization'); + + // Go through one more update cycle so any (incorrect) update for observer1 + // makes it through the IPC queues. + observer1_updates.length = 0; + observer2_updates.length = 0; + + const iframe3 = document.createElement('iframe'); + document.body.appendChild(iframe3); + + const observer3_updates = []; + await new Promise((resolve, reject) => { + const observer3 = new iframe3.contentWindow.ComputePressureObserver( + update => { + observer3_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.75], cpuSpeedThresholds: [0.25]}); + t.add_cleanup(() => observer3.stop()); + observer3.observe().catch(reject); + }); + + assert_equals( + observer1_updates.length, 0, + 'observer2.observe() should have stopped observer1; the two observers ' + + 'have different quantization schemes'); + + // observer3 uses a different quantization scheme than observer2. So, + // observer3.observe() should stop observer2. + assert_equals( + observer2_updates.length, 0, + 'observer3.observe() should have stopped observer2; the two observers ' + + 'have different quantization schemes'); + + assert_equals(observer3_updates.length, 1); + assert_in_array(observer3_updates[0].cpuUtilization, [0.375, 0.875], + 'cpuUtilization quantization'); + assert_in_array(observer3_updates[0].cpuSpeed, [0.125, 0.625], + 'cpuSpeed quantization'); + +}, 'ComputePressureObserver with a new quantization schema stops all ' + + 'other active observers');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.js new file mode 100644 index 0000000..d1650cb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple.tentative.https.window.js
@@ -0,0 +1,34 @@ +'use strict'; + +promise_test(async t => { + const update1_promise = new Promise((resolve, reject) => { + const observer = new ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + const update2_promise = new Promise((resolve, reject) => { + const observer = new ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + const update3_promise = new Promise((resolve, reject) => { + const observer = new ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + const [update1, update2, update3] = + await Promise.all([update1_promise, update2_promise, update3_promise]); + + for (const update of [update1, update2, update3]) { + assert_in_array(update.cpuUtilization, [0.25, 0.75], + 'cpuUtilization quantization'); + assert_in_array(update.cpuSpeed, [0.25, 0.75], 'cpuSpeed quantization'); + } +}, 'Three ComputePressureObserver instances with the same quantization ' + + 'schema receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.js new file mode 100644 index 0000000..5a020ad --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_multiple_across_iframes.tentative.https.window.js
@@ -0,0 +1,42 @@ +'use strict'; + +promise_test(async t => { + const update1_promise = new Promise((resolve, reject) => { + const observer = new ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + // iframe numbers are aligned with observer numbers. The first observer is in + // the main frame, so there is no iframe1. + const iframe2 = document.createElement('iframe'); + document.body.appendChild(iframe2); + + const update2_promise = new Promise((resolve, reject) => { + const observer = new iframe2.contentWindow.ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + const iframe3 = document.createElement('iframe'); + document.body.appendChild(iframe3); + + const update3_promise = new Promise((resolve, reject) => { + const observer = new iframe3.contentWindow.ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + const [update1, update2, update3] = + await Promise.all([update1_promise, update2_promise, update3_promise]); + + for (const update of [update1, update2, update3]) { + assert_in_array(update.cpuUtilization, [0.25, 0.75], + 'cpuUtilization quantization'); + assert_in_array(update.cpuSpeed, [0.25, 0.75], 'cpuSpeed quantization'); + } +}, 'Three ComputePressureObserver instances in different iframes, but with ' + + 'the same quantization schema, receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.js new file mode 100644 index 0000000..773512f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_observe_idempotent.tentative.https.window.js
@@ -0,0 +1,27 @@ +'use strict'; + +promise_test(async t => { + // The quantization thresholds and the quantized values that they lead to can + // be represented exactly in floating-point, so === comparison works. + + const update = await new Promise((resolve, reject) => { + const observer = new ComputePressureObserver( + resolve, {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + observer.observe().catch(reject); + observer.observe().catch(reject); + }); + + assert_equals(typeof update.cpuUtilization, 'number'); + assert_greater_than_equal(update.cpuUtilization, 0.0, 'cpuUtilization range'); + assert_less_than_equal(update.cpuUtilization, 1.0, 'cpuUtilization range'); + assert_in_array(update.cpuUtilization, [0.25, 0.75], + 'cpuUtilization quantization'); + + assert_equals(typeof update.cpuSpeed, 'number'); + assert_greater_than_equal(update.cpuSpeed, 0.0, 'cpuSpeed range'); + assert_less_than_equal(update.cpuSpeed, 1.0, 'cpuUSpeed range'); + assert_in_array(update.cpuSpeed, [0.25, 0.75], 'cpuSpeed quantization'); +}, 'ComputePressureObserver.observe() is idempotent'); +
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop.tentative.https.window.js new file mode 100644 index 0000000..5dbd505 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop.tentative.https.window.js
@@ -0,0 +1,58 @@ +'use strict'; + +promise_test(async t => { + const observer1_updates = []; + const observer1 = new ComputePressureObserver( + update => { observer1_updates.push(update); }, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer1.stop()); + // Ensure that observer1's schema gets registered before observer2 starts. + await observer1.observe(); + observer1.stop(); + + const observer2_updates = []; + await new Promise((resolve, reject) => { + const observer2 = new ComputePressureObserver( + update => { + observer2_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer2.stop()); + observer2.observe().catch(reject); + }); + + assert_equals(observer1_updates.length, 0, + 'stopped observers should not receive callbacks'); + + assert_equals(observer2_updates.length, 1); + assert_in_array(observer2_updates[0].cpuUtilization, [0.25, 0.75], + 'cpuUtilization quantization'); + assert_in_array(observer2_updates[0].cpuSpeed, [0.25, 0.75], + 'cpuSpeed quantization'); + + // Go through one more update cycle so any (incorrect) update for observer1 + // makes it through the IPC queues. + + const observer3_updates = []; + await new Promise((resolve, reject) => { + const observer3 = new ComputePressureObserver( + update => { + observer3_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.75], cpuSpeedThresholds: [0.25]}); + t.add_cleanup(() => observer3.stop()); + observer3.observe().catch(reject); + }); + + assert_equals(observer1_updates.length, 0, + 'stopped observers should not receive callbacks'); + + assert_equals(observer3_updates.length, 1); + assert_in_array(observer3_updates[0].cpuUtilization, [0.375, 0.875], + 'cpuUtilization quantization'); + assert_in_array(observer3_updates[0].cpuSpeed, [0.125, 0.625], + 'cpuSpeed quantization'); + +}, 'Stopped ComputePressureObservers do not receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop_idempotent.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop_idempotent.tentative.https.window.js new file mode 100644 index 0000000..785c55b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop_idempotent.tentative.https.window.js
@@ -0,0 +1,59 @@ +'use strict'; + +promise_test(async t => { + const observer1_updates = []; + const observer1 = new ComputePressureObserver( + update => { observer1_updates.push(update); }, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer1.stop()); + // Ensure that observer1's schema gets registered before observer2 starts. + observer1.observe(); + observer1.stop(); + observer1.stop(); + + const observer2_updates = []; + await new Promise((resolve, reject) => { + const observer2 = new ComputePressureObserver( + update => { + observer2_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer2.stop()); + observer2.observe().catch(reject); + }); + + assert_equals(observer1_updates.length, 0, + 'stopped observers should not receive callbacks'); + + assert_equals(observer2_updates.length, 1); + assert_in_array(observer2_updates[0].cpuUtilization, [0.25, 0.75], + 'cpuUtilization quantization'); + assert_in_array(observer2_updates[0].cpuSpeed, [0.25, 0.75], + 'cpuSpeed quantization'); + + // Go through one more update cycle so any (incorrect) update for observer1 + // makes it through the IPC queues. + + const observer3_updates = []; + await new Promise((resolve, reject) => { + const observer3 = new ComputePressureObserver( + update => { + observer3_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.75], cpuSpeedThresholds: [0.25]}); + t.add_cleanup(() => observer3.stop()); + observer3.observe().catch(reject); + }); + + assert_equals(observer1_updates.length, 0, + 'stopped observers should not receive callbacks'); + + assert_equals(observer3_updates.length, 1); + assert_in_array(observer3_updates[0].cpuUtilization, [0.375, 0.875], + 'cpuUtilization quantization'); + assert_in_array(observer3_updates[0].cpuSpeed, [0.125, 0.625], + 'cpuSpeed quantization'); + +}, 'Stopped ComputePressureObservers do not receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop_immediately.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop_immediately.tentative.https.window.js new file mode 100644 index 0000000..0d9929c4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_stop_immediately.tentative.https.window.js
@@ -0,0 +1,58 @@ +'use strict'; + +promise_test(async t => { + const observer1_updates = []; + const observer1 = new ComputePressureObserver( + update => { observer1_updates.push(update); }, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer1.stop()); + // Ensure that observer1's schema gets registered before observer2 starts. + observer1.observe(); + observer1.stop(); + + const observer2_updates = []; + await new Promise((resolve, reject) => { + const observer2 = new ComputePressureObserver( + update => { + observer2_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.5], cpuSpeedThresholds: [0.5]}); + t.add_cleanup(() => observer2.stop()); + observer2.observe().catch(reject); + }); + + assert_equals(observer1_updates.length, 0, + 'stopped observers should not receive callbacks'); + + assert_equals(observer2_updates.length, 1); + assert_in_array(observer2_updates[0].cpuUtilization, [0.25, 0.75], + 'cpuUtilization quantization'); + assert_in_array(observer2_updates[0].cpuSpeed, [0.25, 0.75], + 'cpuSpeed quantization'); + + // Go through one more update cycle so any (incorrect) update for observer1 + // makes it through the IPC queues. + + const observer3_updates = []; + await new Promise((resolve, reject) => { + const observer3 = new ComputePressureObserver( + update => { + observer3_updates.push(update); + resolve(); + }, + {cpuUtilizationThresholds: [0.75], cpuSpeedThresholds: [0.25]}); + t.add_cleanup(() => observer3.stop()); + observer3.observe().catch(reject); + }); + + assert_equals(observer1_updates.length, 0, + 'stopped observers should not receive callbacks'); + + assert_equals(observer3_updates.length, 1); + assert_in_array(observer3_updates[0].cpuUtilization, [0.375, 0.875], + 'cpuUtilization quantization'); + assert_in_array(observer3_updates[0].cpuSpeed, [0.125, 0.625], + 'cpuSpeed quantization'); + +}, 'Stopped ComputePressureObservers do not receive updates');
diff --git a/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_values.tenative.https.window.js b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_values.tenative.https.window.js new file mode 100644 index 0000000..837fa9d6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compute-pressure/compute_pressure_values.tenative.https.window.js
@@ -0,0 +1,18 @@ +'use strict'; + +promise_test(async t => { + // The quantization thresholds and the quantized values that they lead to can + // be represented exactly in floating-point, so === comparison works. + + const update = await new Promise((resolve, reject) => { + const observer = new ComputePressureObserver( + resolve, + {cpuUtilizationThresholds: [0.25], cpuSpeedThresholds: [0.75]}); + t.add_cleanup(() => observer.stop()); + observer.observe().catch(reject); + }); + + assert_in_array(update.cpuUtilization, [0.125, 0.625], + 'cpuUtilization quantization'); + assert_in_array(update.cpuSpeed, [0.375, 0.875], 'cpuSpeed quantization'); +}, 'ComputePressureObserver quantizes utilization and speed separately');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/rotate_x_45deg.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/rotate_x_45deg.html index 654659c..90ea4cd 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/rotate_x_45deg.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/rotate_x_45deg.html
@@ -5,7 +5,7 @@ <link rel="author" title="Ebay Inc." href="mailto:xiatian@ebay.com"/> <link rel="help" href="http://www.w3.org/TR/css-transforms-2/#3d-transform-rendering"/> <link rel="match" href="rotate_x_45deg-ref.html"/> - <meta name=fuzzy content="159;200"> + <meta name=fuzzy content="159-200;200"> <meta name="flags" content="" /> <meta name="assert" content="Rotate 45 degree in y axis"/> <style type="text/css">
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/rotate_y_45deg.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/rotate_y_45deg.html index 2569cc7..714246b 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/rotate_y_45deg.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/rotate_y_45deg.html
@@ -5,7 +5,7 @@ <link rel="author" title="Ebay Inc." href="mailto:xiatian@ebay.com"/> <link rel="help" href="http://www.w3.org/TR/css-transforms-2/#3d-transform-rendering"/> <link rel="match" href="rotate_y_45deg-ref.html"/> - <meta name=fuzzy content="159;200"> + <meta name=fuzzy content="159-200;200"> <meta name="flags" content="" /> <meta name="assert" content="Rotate 45 degree in y axis"/> <style type="text/css">
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-matrix3d-001.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-matrix3d-001.html index e513eeb50..2f4a98b1 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-matrix3d-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-matrix3d-001.html
@@ -10,7 +10,7 @@ various matrix3d()s are equivalent to other transform functions.'> <link rel="match" href="transform3d-matrix3d-001-ref.html"> <link rel="mismatch" href="transform-lime-square-ref.html"> - <meta name=fuzzy content="transform3d-matrix3d-001-ref.html:0-100;950-980"> + <meta name=fuzzy content="transform3d-matrix3d-001-ref.html:0-100;0-980"> </head> <body> <div style="transform: matrix3d(1,2,0,0, 3,4,0,0, 0,0,1,0, 5,6,0,1);
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/interactive-elements/the-popup-element/popup-focus.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/interactive-elements/the-popup-element/popup-focus.tentative.html new file mode 100644 index 0000000..bb8d679 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/interactive-elements/the-popup-element/popup-focus.tentative.html
@@ -0,0 +1,145 @@ +<!DOCTYPE html> +<meta charset="utf-8" /> +<title>Popup focus behaviors</title> +<link rel="author" href="mailto:masonf@chromium.org"> +<link rel=help href="https://open-ui.org/components/popup.research.explainer"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<popup data-test='default behavior - popup is not focused' data-no-focus> + <p>This is a popup</p> + <button>first button</button> +</popup> + +<popup data-test='autofocus popup' autofocus class=should-be-focused> + <p>This is a popup</p> +</popup> + +<popup data-test='autofocus empty popup' autofocus class=should-be-focused></popup> + +<popup data-test='autofocus popup with button' autofocus class=should-be-focused> + <p>This is a popup</p> + <button>button</button> +</popup> + +<popup data-test='autofocus child'> + <p>This is a popup</p> + <button autofocus class=should-be-focused>autofocus button</button> +</popup> + +<popup data-test='autofocus on tabindex=0 element'> + <p autofocus tabindex=0 class=should-be-focused>This is a popup with autofocus on a tabindex=0 element</p> + <button>button</button> +</popup> + +<popup data-test='autofocus multiple children'> + <p>This is a popup</p> + <button autofocus class=should-be-focused>autofocus button</button> + <button autofocus>second autofocus button</button> +</popup> + +<popup autofocus data-test='autofocus popup and multiple autofocus children' class=should-be-focused> + <p>This is a popup</p> + <button autofocus>autofocus button</button> + <button autofocus>second autofocus button</button> +</popup> + +<popup delegatesfocus data-test='delegatesfocus popup'> + <p>This is a popup</p> + <button class=should-be-focused>first button should be focused</button> + <button>second button</button> +</popup> + +<popup delegatesfocus data-test='delegatesfocus takes precedence over autofocus'> + <p>This is a popup</p> + <button class=should-be-focused>first button</button> + <button autofocus>autofocus button should NOT be focused</button> +</popup> + +<popup delegatesfocus autofocus data-test='delegatesfocus takes precedence over autofocus 2'> + <p>This is a popup</p> + <button class=should-be-focused>first button</button> + <button>autofocus button should NOT be focused</button> +</popup> + +<popup delegatesfocus data-test='delegatesfocus on empty popup has no effect' data-no-focus></popup> + +<popup data-test='delegatesfocus on child has no effect' data-no-focus> + <p>This is a popup</p> + <button delegatesfocus>first button</button> +</popup> + +<popup delegatesfocus data-test='delegatesfocus skips contained popups'> + <p>This is a popup</p> + <popup> + <button>Contained popup button</button> + </popup> + <button class=should-be-focused>first button</button> + <button>autofocus button should NOT be focused</button> +</popup> + +<popup delegatesfocus data-test='delegatesfocus skips contained dialogs'> + <p>This is a popup</p> + <dialog> + <button>Contained dialog button</button> + </dialog> + <button class=should-be-focused>first button</button> + <button>autofocus button should NOT be focused</button> +</popup> + +<style> + popup { + border: 2px solid black; + top:150px; + left:150px; + } + :focus-within { border: 5px dashed red; } + :focus { border: 5px solid lime; } +</style> + +<script> + function activateAndVerify(popup) { + const testName = popup.getAttribute('data-test'); + const priorFocus = document.createElement('button'); + priorFocus.id = 'prior-focus'; + document.body.appendChild(priorFocus); + let expectedFocusedElement = popup.matches('.should-be-focused') ? popup : popup.querySelector('.should-be-focused'); + if (popup.hasAttribute('data-no-focus')) { + expectedFocusedElement = priorFocus; + } + test(t => { + t.add_cleanup(() => priorFocus.remove()); + assert_true(!!expectedFocusedElement); + assert_false(popup.open); + priorFocus.focus(); + assert_equals(document.activeElement,priorFocus); + + // Directly show the popup: + popup.show(); + assert_equals(document.activeElement, expectedFocusedElement, `${testName} activated by popup.show()`); + popup.hide(); + + // Use an activating element: + const button = document.createElement('button'); + const popupId = 'popup-id'; + assert_equals(document.querySelectorAll('#' + popupId).length,0); + document.body.appendChild(button); + t.add_cleanup(function() { + popup.removeAttribute('id'); + button.remove(); + }); + popup.id = popupId; + button.setAttribute('popup', popupId); + priorFocus.focus(); + button.click(); + assert_equals(document.activeElement, expectedFocusedElement, `${testName} activated by button.click()`); + + // Make sure we can directly focus the (already open) popup: + popup.focus(); + assert_equals(document.activeElement, popup.hasAttribute('delegatesfocus') ? expectedFocusedElement : popup, `${testName} directly focus with popup.focus()`); + popup.hide(); + }, "Popup focus test: " + testName); + } + + document.querySelectorAll('body > popup').forEach(popup => activateAndVerify(popup)); +</script>
diff --git a/third_party/blink/web_tests/virtual/compute-pressure/OWNERS b/third_party/blink/web_tests/virtual/compute-pressure/OWNERS new file mode 100644 index 0000000..973ac7d8 --- /dev/null +++ b/third_party/blink/web_tests/virtual/compute-pressure/OWNERS
@@ -0,0 +1 @@ +file://third_party/blink/renderer/modules/compute_pressure/OWNERS
diff --git a/third_party/blink/web_tests/virtual/compute-pressure/README.md b/third_party/blink/web_tests/virtual/compute-pressure/README.md new file mode 100644 index 0000000..552b0e8 --- /dev/null +++ b/third_party/blink/web_tests/virtual/compute-pressure/README.md
@@ -0,0 +1 @@ +# This suite runs tests with --enable-features=ComputePressure
diff --git a/third_party/metrics_proto/README.chromium b/third_party/metrics_proto/README.chromium index 5fcaa69..e975e7a 100644 --- a/third_party/metrics_proto/README.chromium +++ b/third_party/metrics_proto/README.chromium
@@ -1,8 +1,8 @@ Name: Metrics Protos Short Name: metrics_proto URL: This is the canonical public repository -Version: 371363092 -Date: 2021/04/30 UTC +Version: 371915777 +Date: 2021/05/04 UTC License: BSD Security Critical: Yes
diff --git a/third_party/metrics_proto/structured_data.proto b/third_party/metrics_proto/structured_data.proto index c5b9d59e..8ce594e 100644 --- a/third_party/metrics_proto/structured_data.proto +++ b/third_party/metrics_proto/structured_data.proto
@@ -14,8 +14,10 @@ // // Next tag: 4 message StructuredEventProto { - // A per-profile, per-client, per-event ID that is used only for structured - // metrics. + // A per-client, per-profile, per-project ID that is used only for structured + // metrics. For projects recorded from Chrome OS's platform2 repository, this + // ID is device-wide, not per-profile. The ID is rotated at least every 90 + // days. optional fixed64 profile_event_id = 1; // The first 8 bytes of the MD5 hash of the event's name as a string. Each @@ -40,9 +42,9 @@ // // HMAC_SHA256(concat(string, metric_name), event_key) // - // The event_key is a per-profile, per-client, per-event secret 32-byte + // The event_key is a per-profile, per-client, per-project secret 32-byte // key used only for signing hashed values for this event. Keys should - // never leave the device, and are rotated at most every 90 days. + // never leave the device, and are rotated at least every 90 days. message Metric { optional fixed64 name_hash = 1; oneof value {
diff --git a/third_party/metrics_proto/system_profile.proto b/third_party/metrics_proto/system_profile.proto index 9c8059e..7941bc02 100644 --- a/third_party/metrics_proto/system_profile.proto +++ b/third_party/metrics_proto/system_profile.proto
@@ -17,7 +17,7 @@ // Almost all the fields should be populated on every upload. (The only // exception is some fields in the stability section that are only uploaded // once per browsing session, usually shortly after startup.) -// Next tag: 38 +// Next tag: 39 message SystemProfileProto { // The time when the client was compiled/linked, in seconds since the epoch. optional int64 build_timestamp = 1; @@ -106,6 +106,13 @@ // e.g. "en-US". optional string application_locale = 4; + // Hashes of command line keys used in the browser session when the MetricsLog + // is created. This takes into account the command line switches that were + // used when launching the session, as well as any modifications made to them, + // for example via CommandLine::AppendSwitch and CommandLine::RemoveSwitch. + // Values are the lower 32-bit of SHA1 hash in little-endian. + repeated fixed32 command_line_key_hash = 38 [packed = true]; + // Information on the user's operating system. // Next tag: 8 message OS {
diff --git a/tools/ipc_fuzzer/fuzzer/DEPS b/tools/ipc_fuzzer/fuzzer/DEPS index 9fcae1cf..746c34c 100644 --- a/tools/ipc_fuzzer/fuzzer/DEPS +++ b/tools/ipc_fuzzer/fuzzer/DEPS
@@ -1,6 +1,9 @@ include_rules = [ + "+components/content_settings", + "+components/viz/common", "+printing/mojom", "+third_party/skia/include", + "+third_party/blink/public", "+ui/base/cursor", "+ui/base/mojom", "+ui/gfx/geometry",
diff --git a/tools/ipc_fuzzer/fuzzer/fuzzer.cc b/tools/ipc_fuzzer/fuzzer/fuzzer.cc index a2a75a6..7bdfc8b3 100644 --- a/tools/ipc_fuzzer/fuzzer/fuzzer.cc +++ b/tools/ipc_fuzzer/fuzzer/fuzzer.cc
@@ -18,11 +18,14 @@ #include "base/util/type_safety/id_type.h" #include "base/values.h" #include "build/build_config.h" +#include "components/content_settings/core/common/content_settings_pattern.h" +#include "components/viz/common/surfaces/frame_sink_id.h" #include "ipc/ipc_message.h" #include "ipc/ipc_message_utils.h" #include "ipc/ipc_sync_channel.h" #include "ipc/ipc_sync_message.h" #include "printing/mojom/print.mojom-shared.h" +#include "third_party/blink/public/common/page_state/page_state.h" #include "third_party/skia/include/core/SkBitmap.h" #include "tools/ipc_fuzzer/fuzzer/fuzzer.h" #include "tools/ipc_fuzzer/fuzzer/rand_util.h"
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index e7595c5..9efa240 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -296,6 +296,9 @@ 'Libfuzzer Upload Linux UBSan': 'libfuzzer_ubsan_release_bot', 'Libfuzzer Upload Mac ASan': 'libfuzzer_mac_asan_shared_release_bot', 'Libfuzzer Upload Windows ASan': 'libfuzzer_windows_asan_release_bot', + 'Linux Builder (core-32) (goma)': 'gpu_tests_release_bot', + 'Linux Builder (core-32) (reclient)': 'gpu_tests_release_bot_reclient', + 'Linux Builder (core-32) (runsc) (reclient)': 'gpu_tests_release_bot_reclient', 'Linux Builder (deps-cache) (reclient)': 'gpu_tests_release_bot_reclient', 'Linux Builder (j-500) (reclient)': 'gpu_tests_release_bot_reclient', 'Linux TSan Builder (goma cache silo)': 'tsan_disable_nacl_release_bot', @@ -311,7 +314,7 @@ 'Site Isolation Android': 'android_release_bot_minimal_symbols_arm64', 'TSAN Debug (reclient)': 'tsan_disable_nacl_debug_bot_reclient', - 'TSAN Release (core-32) (goma)': 'tsan_disable_nacl_release_bot_reclient', + 'TSAN Release (core-32) (goma)': 'tsan_disable_nacl_release_bot', 'TSAN Release (core-32) (reclient)': 'tsan_disable_nacl_release_bot_reclient', 'TSAN Release (deps-cache) (reclient)': 'tsan_disable_nacl_release_bot_reclient', 'TSAN Release (deps-cache-full-files) (reclient)': 'tsan_disable_nacl_release_bot_reclient', @@ -2822,7 +2825,7 @@ }, 'amd64-lacros': { - 'gn_args': 'use_ozone=true ozone_platform_wayland=true ozone_platform_x11=false target_os="chromeos" use_evdev_gestures=false use_vaapi=false use_gtk=false use_glib=false enable_linux_installer=false rtc_use_pipewire=false use_gio=false use_v8_context_snapshot=false use_custom_libcxx=false use_pulseaudio=false use_pangocairo=false chromeos_is_browser_only=true use_system_libsync=false cros_host_sysroot="//build/linux/debian_sid_amd64-sysroot" cros_v8_snapshot_sysroot="//build/linux/debian_sid_amd64-sysroot" use_custom_libcxx_for_host=true' + 'gn_args': 'use_ozone=true ozone_platform="wayland" ozone_platform_wayland=true ozone_platform_gbm=false ozone_platform_drm=false ozone_platform_x11=false target_os="chromeos" use_evdev_gestures=false use_vaapi=false use_gtk=false use_glib=false enable_linux_installer=false rtc_use_pipewire=false use_gio=false use_v8_context_snapshot=false use_custom_libcxx=false use_pulseaudio=false use_pangocairo=false chromeos_is_browser_only=true use_system_libsync=false cros_host_sysroot="//build/linux/debian_sid_amd64-sysroot" cros_v8_snapshot_sysroot="//build/linux/debian_sid_amd64-sysroot" use_custom_libcxx_for_host=true' }, # We build Android with codecs on most bots to ensure maximum test
diff --git a/tools/mb/mb_config_expectations/chrome.json b/tools/mb/mb_config_expectations/chrome.json index fc45870..adc85ee 100644 --- a/tools/mb/mb_config_expectations/chrome.json +++ b/tools/mb/mb_config_expectations/chrome.json
@@ -208,6 +208,9 @@ "is_chrome_branded": true, "is_chromeos_device": true, "is_official_build": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/chromium.chromiumos.json b/tools/mb/mb_config_expectations/chromium.chromiumos.json index 5d034864..c9833e0c 100644 --- a/tools/mb/mb_config_expectations/chromium.chromiumos.json +++ b/tools/mb/mb_config_expectations/chromium.chromiumos.json
@@ -47,6 +47,9 @@ "enable_linux_installer": false, "is_chromeos_device": true, "is_debug": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false, @@ -109,6 +112,9 @@ "cros_v8_snapshot_sysroot": "//build/linux/debian_sid_amd64-sysroot", "enable_linux_installer": false, "is_chromeos_device": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false, @@ -137,6 +143,9 @@ "cros_v8_snapshot_sysroot": "//build/linux/debian_sid_amd64-sysroot", "enable_linux_installer": false, "is_chromeos_device": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/chromium.fyi.json b/tools/mb/mb_config_expectations/chromium.fyi.json index ab0c491..a49a39c8 100644 --- a/tools/mb/mb_config_expectations/chromium.fyi.json +++ b/tools/mb/mb_config_expectations/chromium.fyi.json
@@ -146,6 +146,33 @@ "use_libfuzzer": true } }, + "Linux Builder (core-32) (goma)": { + "gn_args": { + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "use_goma": true + } + }, + "Linux Builder (core-32) (reclient)": { + "gn_args": { + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "use_rbe": true + } + }, + "Linux Builder (core-32) (runsc) (reclient)": { + "gn_args": { + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "use_rbe": true + } + }, "Linux Builder (deps-cache) (reclient)": { "gn_args": { "ffmpeg_branding": "Chrome", @@ -249,7 +276,7 @@ "is_component_build": false, "is_debug": false, "is_tsan": true, - "use_rbe": true + "use_goma": true } }, "TSAN Release (core-32) (reclient)": { @@ -642,6 +669,9 @@ "cros_v8_snapshot_sysroot": "//build/linux/debian_sid_amd64-sysroot", "enable_linux_installer": false, "is_chromeos_device": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/chromium.perf.json b/tools/mb/mb_config_expectations/chromium.perf.json index 9edfe140..1216bcf 100644 --- a/tools/mb/mb_config_expectations/chromium.perf.json +++ b/tools/mb/mb_config_expectations/chromium.perf.json
@@ -77,6 +77,9 @@ "is_chrome_branded": true, "is_chromeos_device": true, "is_official_build": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/internal.chrome.fyi.json b/tools/mb/mb_config_expectations/internal.chrome.fyi.json index fc5a748..0ade047 100644 --- a/tools/mb/mb_config_expectations/internal.chrome.fyi.json +++ b/tools/mb/mb_config_expectations/internal.chrome.fyi.json
@@ -7,6 +7,9 @@ "cros_v8_snapshot_sysroot": "//build/linux/debian_sid_amd64-sysroot", "enable_linux_installer": false, "is_chromeos_device": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/internal.chromeos.fyi.json b/tools/mb/mb_config_expectations/internal.chromeos.fyi.json index 44dcb30e..5ccd2114 100644 --- a/tools/mb/mb_config_expectations/internal.chromeos.fyi.json +++ b/tools/mb/mb_config_expectations/internal.chromeos.fyi.json
@@ -46,6 +46,9 @@ "is_chrome_branded": true, "is_chromeos_device": true, "is_official_build": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/official.chrome.continuous.json b/tools/mb/mb_config_expectations/official.chrome.continuous.json index 5e9ade0..5d060cc 100644 --- a/tools/mb/mb_config_expectations/official.chrome.continuous.json +++ b/tools/mb/mb_config_expectations/official.chrome.continuous.json
@@ -10,6 +10,9 @@ "is_chrome_branded": true, "is_chromeos_device": true, "is_official_build": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/official.chrome.json b/tools/mb/mb_config_expectations/official.chrome.json index 460d39f7..749e3c3 100644 --- a/tools/mb/mb_config_expectations/official.chrome.json +++ b/tools/mb/mb_config_expectations/official.chrome.json
@@ -28,6 +28,9 @@ "is_chrome_branded": true, "is_chromeos_device": true, "is_official_build": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/tryserver.chrome.json b/tools/mb/mb_config_expectations/tryserver.chrome.json index 13701124..912195e 100644 --- a/tools/mb/mb_config_expectations/tryserver.chrome.json +++ b/tools/mb/mb_config_expectations/tryserver.chrome.json
@@ -130,6 +130,9 @@ "is_chrome_branded": true, "is_chromeos_device": true, "is_official_build": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.chromiumos.json b/tools/mb/mb_config_expectations/tryserver.chromium.chromiumos.json index 577ff57..0c0dd95 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.chromiumos.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.chromiumos.json
@@ -117,6 +117,9 @@ "cros_v8_snapshot_sysroot": "//build/linux/debian_sid_amd64-sysroot", "enable_linux_installer": false, "is_chromeos_device": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.perf.json b/tools/mb/mb_config_expectations/tryserver.chromium.perf.json index 3afb836..6df9a543 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.perf.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.perf.json
@@ -39,6 +39,9 @@ "is_chrome_branded": true, "is_chromeos_device": true, "is_official_build": true, + "ozone_platform": "wayland", + "ozone_platform_drm": false, + "ozone_platform_gbm": false, "ozone_platform_headless": true, "ozone_platform_wayland": true, "ozone_platform_x11": false,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 9e9b6bc..202a595 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -6711,6 +6711,7 @@ <int value="196618" label="kEmbedder-kPermissionRequestManager"/> <int value="196619" label="kEmbedder-kModalDialog"/> <int value="196620" label="kEmbedder-kExtensions"/> + <int value="196621" label="kEmbedder-kExtensionMessaging"/> </enum> <enum name="BackForwardCacheDisabledForRenderFrameHostReasonShort"> @@ -14470,6 +14471,11 @@ <int value="3" label="Cache hit, but the entry was stale"/> </enum> +<enum name="CpuAffinityMode"> + <int value="0" label="kDefault"/> + <int value="1" label="kLittleCoresOnly"/> +</enum> + <enum name="CpuTimeMetricsThreadType"> <summary>Thread types used for CPU time metric breakdowns.</summary> <int value="0" label="UnattributedThread"> @@ -32385,6 +32391,9 @@ <int value="3896" label="WebBluetoothManufacturerDataFilter"/> <int value="3897" label="SanitizerAPIGetConfig"/> <int value="3898" label="SanitizerAPIGetDefaultConfig"/> + <int value="3899" label="ComputePressureObserver_Constructor"/> + <int value="3900" label="ComputePressureObserver_Observe"/> + <int value="3901" label="ComputePressureObserver_Stop"/> </enum> <enum name="FeaturePolicyAllowlistType"> @@ -44329,6 +44338,7 @@ <int value="-2097895488" label="NotificationScrollBar:enabled"/> <int value="-2097515669" label="disable-cast"/> <int value="-2095519429" label="FtpProtocol:enabled"/> + <int value="-2094897448" label="TranslateIntent:disabled"/> <int value="-2093047873" label="AbusiveOriginNotificationPermissionRevocation:enabled"/> <int value="-2092067251" label="NativeFilesystemAPI:disabled"/> @@ -44725,6 +44735,8 @@ <int value="-1772942854" label="LongPressBackForHistory:enabled"/> <int value="-1772905637" label="RunVideoCaptureServiceInBrowserProcess:enabled"/> + <int value="-1772476751" + label="ExperimentalAccessibilityDictationListening:enabled"/> <int value="-1772172557" label="enable-osk-overscroll"/> <int value="-1771552112" label="QueryTilesInOmnibox:disabled"/> <int value="-1768672408" label="ChromeDuplex:disabled"/> @@ -47469,6 +47481,8 @@ <int value="630308195" label="SignInProfileCreation:enabled"/> <int value="630776247" label="USBGuard:disabled"/> <int value="630947363" label="touch-events"/> + <int value="632324382" + label="ExperimentalAccessibilityDictationListening:disabled"/> <int value="632340413" label="network-settings-config"/> <int value="633442161" label="ExperimentalUi:disabled"/> <int value="634789085" label="LayeredAPI:disabled"/> @@ -48396,6 +48410,7 @@ <int value="1428004502" label="PaymentRequestOptionalTotal:enabled"/> <int value="1428221397" label="QueryTilesInNTP:enabled"/> <int value="1429923065" label="enable-media-internals:enabled"/> + <int value="1430924529" label="TranslateIntent:enabled"/> <int value="1431050645" label="PayWithGoogleV1:disabled"/> <int value="1431934725" label="OmniboxAutocompleteTitles:disabled"/> <int value="1434515920" label="ReaderModeInCCT:enabled"/> @@ -68991,10 +69006,10 @@ <enum name="SB2DownloadChecks"> <int value="0" label="URL_CHECKS_TOTAL"/> - <int value="1" label="URL_CHECKS_CANCELED"/> + <int value="1" label="DEPRECATED_URL_CHECKS_CANCELED"/> <int value="2" label="URL_CHECKS_MALWARE"/> - <int value="3" label="HASH_CHECKS_TOTAL"/> - <int value="4" label="HASH_CHECKS_MALWARE"/> + <int value="3" label="DEPRECATED_HASH_CHECKS_TOTAL"/> + <int value="4" label="DEPRECATED_HASH_CHECKS_MALWARE"/> </enum> <enum name="SB2FilterLoad"> @@ -82875,7 +82890,8 @@ <int value="52" label="WebOTPService"/> <int value="53" label="OutstandingNetworkRequestDirectSocket"/> <int value="54" label="IsolatedWorldScript"/> - <int value="55" label="ExtensionStyleSheet"/> + <int value="55" label="InjectedStyleSheet"/> + <int value="56" label="MediaSessionImplOnServiceCreated"/> </enum> <enum name="WebShareMethod">
diff --git a/tools/metrics/histograms/histograms_xml/METRIC_REVIEWER_OWNERS b/tools/metrics/histograms/histograms_xml/METRIC_REVIEWER_OWNERS index 09c0efe..6363cda 100644 --- a/tools/metrics/histograms/histograms_xml/METRIC_REVIEWER_OWNERS +++ b/tools/metrics/histograms/histograms_xml/METRIC_REVIEWER_OWNERS
@@ -6,6 +6,7 @@ csharrison@chromium.org cthomp@chromium.org curranmax@chromium.org +dewittj@chromium.org dschinazi@chromium.org eirage@chromium.org ender@chromium.org
diff --git a/tools/metrics/histograms/histograms_xml/content/OWNERS b/tools/metrics/histograms/histograms_xml/content/OWNERS index 3249a7e3..d450084 100644 --- a/tools/metrics/histograms/histograms_xml/content/OWNERS +++ b/tools/metrics/histograms/histograms_xml/content/OWNERS
@@ -3,3 +3,4 @@ # Prefer sending CLs to the owners listed below. # Use chromium-metrics-reviews@google.com as a backup. rayankans@chromium.org +dewittj@chromium.org
diff --git a/tools/metrics/histograms/histograms_xml/image/histograms.xml b/tools/metrics/histograms/histograms_xml/image/histograms.xml index d0148ff5..6db9e83 100644 --- a/tools/metrics/histograms/histograms_xml/image/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/image/histograms.xml
@@ -222,7 +222,7 @@ </histogram> <histogram base="true" name="ImageFetcher.CacheMetadataCount" units="records" - expires_after="2021-05-01"> + expires_after="2022-06-01"> <!-- Name completed by histogram_suffixes name="ImageFetcherCacheStrategy" --> <owner>fgorski@chromium.org</owner>
diff --git a/tools/metrics/histograms/histograms_xml/others/histograms.xml b/tools/metrics/histograms/histograms_xml/others/histograms.xml index 79cce27f..2aaad328 100644 --- a/tools/metrics/histograms/histograms_xml/others/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/others/histograms.xml
@@ -13335,19 +13335,25 @@ </histogram> <histogram name="SB2.DownloadChecks" enum="SB2DownloadChecks" - expires_after="M77"> - <owner>vakh@chromium.org</owner> + expires_after="2022-05-02"> + <owner>xinghuilu@chromium.org</owner> <owner>chrome-safebrowsing-alerts@google.com</owner> <summary> - Records results of SafeBrowsing download check, including both url check and - downloaded file hash check. + Records results of SafeBrowsing download url check. Warning: this histogram + was expired from M78 to M91. Data may be missing. + + This metric is used to populate a dashboard on go/crsb-site. </summary> </histogram> -<histogram name="SB2.DownloadUrlCheckDuration" units="ms" expires_after="M77"> - <owner>vakh@chromium.org</owner> +<histogram name="SB2.DownloadUrlCheckDuration" units="ms" + expires_after="2022-05-02"> + <owner>xinghuilu@chromium.org</owner> <owner>chrome-safebrowsing-alerts@google.com</owner> - <summary>The time it takes for SafeBrowsing to check a download url.</summary> + <summary> + The time it takes for SafeBrowsing to check a download url. Warning: this + histogram was expired from M78 to M91. Data may be missing. + </summary> </histogram> <histogram name="SB2.GetHashResponseOrErrorCode" @@ -17203,6 +17209,16 @@ </summary> </histogram> +<histogram name="UserImage.Changed" enum="ChromeOSUserImageId" + expires_after="2022-03-30"> + <owner>jasontt@chromium.org</owner> + <owner>assistive-eng@google.com</owner> + <summary> + Distribution of the images that users changed (Chrome OS). One sample is + taken each time the user changes their image to a different one in Settings. + </summary> +</histogram> + <histogram name="UserImage.LoggedIn" enum="ChromeOSUserImageId" expires_after="M82"> <obsolete> @@ -18831,7 +18847,7 @@ </histogram> <histogram name="WebUITabStrip.CloseAction" enum="WebUITabStripCloseActions" - expires_after="2021-10-04"> + expires_after="2021-10-25"> <owner>collinbaker@chromium.org</owner> <owner>tluk@chromium.org</owner> <summary> @@ -18842,7 +18858,7 @@ </histogram> <histogram name="WebUITabStrip.CloseTabAction" - enum="WebUITabStripCloseTabActions" expires_after="2021-10-10"> + enum="WebUITabStripCloseTabActions" expires_after="2021-10-25"> <owner>johntlee@chromium.org</owner> <owner>dpapad@chromium.org</owner> <summary> @@ -18853,7 +18869,7 @@ </histogram> <histogram name="WebUITabStrip.OpenAction" enum="WebUITabStripOpenActions" - expires_after="2021-10-04"> + expires_after="2021-10-25"> <owner>collinbaker@chromium.org</owner> <owner>tluk@chromium.org</owner> <summary> @@ -18864,7 +18880,7 @@ </histogram> <histogram name="WebUITabStrip.OpenDuration" units="ms" - expires_after="2021-10-10"> + expires_after="2021-10-25"> <owner>collinbaker@chromium.org</owner> <owner>tluk@chromium.org</owner> <summary> @@ -18874,7 +18890,8 @@ </summary> </histogram> -<histogram name="WebUITabStrip.TabActivation" units="ms" expires_after="M90"> +<histogram name="WebUITabStrip.TabActivation" units="ms" + expires_after="2021-10-25"> <owner>robliao@chromium.org</owner> <owner>johntlee@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/histograms_xml/power/histograms.xml b/tools/metrics/histograms/histograms_xml/power/histograms.xml index 2dcf6e20..43e5b2d 100644 --- a/tools/metrics/histograms/histograms_xml/power/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/power/histograms.xml
@@ -250,6 +250,17 @@ </summary> </histogram> +<histogram name="Power.CpuAffinityExperiments.ProcessAffinityMode" + enum="CpuAffinityMode" expires_after="2021-10-04"> + <owner>eseckler@chromium.org</owner> + <owner>skyostil@chromium.org</owner> + <summary> + For clients enrolled in CPU affinity restriction experiments (e.g. + restricting execution to little cores only), records the new CPU affinity + for a process every time it is changed, provided it was succcessfully set. + </summary> +</histogram> + <histogram name="Power.CpuAffinityExperiments.ProcessAffinityUpdateSuccess" enum="BooleanSuccess" expires_after="2021-10-04"> <owner>eseckler@chromium.org</owner>
diff --git a/tools/metrics/histograms/histograms_xml/sb_client/histograms.xml b/tools/metrics/histograms/histograms_xml/sb_client/histograms.xml index 14ed676..3fb6dedd 100644 --- a/tools/metrics/histograms/histograms_xml/sb_client/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/sb_client/histograms.xml
@@ -280,6 +280,18 @@ <summary>The counts for malware verdicts given by server side model.</summary> </histogram> +<histogram name="SBClientPhishing.BrowserReadyOnClassifierNotReady" + enum="BooleanReady" expires_after="2022-03-08"> + <owner>drubery@chromium.org</owner> + <owner>chrome-safebrowsing-alerts@google.com</owner> + <summary> + When a renderer-side classification returns the error + "CLASSIFIER_NOT_READY", this histogram is logged with whether or + not the browser process had a valid model. This can help to identify + problems distributing the model from browser process to the renderers. + </summary> +</histogram> + <histogram name="SBClientPhishing.CacheDetectsPhishing" enum="BooleanIsPhishing" expires_after="2021-09-17"> <owner>drubery@chromium.org</owner> @@ -326,7 +338,11 @@ </histogram> <histogram name="SBClientPhishing.ClassifierNotReadyReason" - enum="SBClientPhishingClientModelStatus" expires_after="2021-10-31"> + enum="SBClientPhishingClientModelStatus" expires_after="2021-08-29"> + <obsolete> + Removed in 05-2021 and replaced with + SBClientPhishing.BrowserReadyOnClassifierNotReady. + </obsolete> <owner>drubery@chromium.org</owner> <owner>chrome-safebrowsing-alerts@google.com</owner> <summary> @@ -453,6 +469,26 @@ </summary> </histogram> +<histogram name="SBClientPhishing.ModelDynamicUpdateSuccess" + enum="BooleanSuccess" expires_after="2022-03-08"> + <owner>drubery@chromium.org</owner> + <owner>chrome-safebrowsing-alerts@google.com</owner> + <summary> + Records whether a dynamic update is successful or not. This is logged when a + new model is pushed (rare), or on each startup. + </summary> +</histogram> + +<histogram name="SBClientPhishing.ModelDynamicUpdateVersion" + units="client phishing model version" expires_after="2022-03-08"> + <owner>drubery@chromium.org</owner> + <owner>chrome-safebrowsing-alerts@google.com</owner> + <summary> + Records the model version on a successful dynamic update. This is logged + when a new model is pushed (rare), or on each startup. + </summary> +</histogram> + <histogram name="SBClientPhishing.PageCapturedMatchesBrowserURL" enum="BooleanMatched" expires_after="2021-01-27"> <obsolete>
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index e1b86a9..dd5c16c 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -7410,6 +7410,26 @@ </metric> </event> +<event name="IOS.IsDefaultBrowser"> + <owner>javierrobles@chromium.org</owner> + <owner>rkgibson@chromium.org</owner> + <summary> + As of iOS14, users will be able to set a default browser other than Safari. + When Chrome is the default browser, it will open all URL links, which is + likely to change certain stability metrics. Thus, it will be good to filter + those metrics by default browser status. This metrics records whether the + user was deemed to have set Chrome as the device's default browser. This + metric will be logged once per metrics log upload, and if the metric changes + mid-report, this just records the state at the very end of the report. Note: + this is tied to a source_id that is not going to be emitted. + </summary> + <metric name="IsDefaultBrowser" enum="Boolean"> + <summary> + True if Chrome is set as default browser. + </summary> + </metric> +</event> + <event name="IOS.PageAddedToReadingList"> <owner>thegreenfrog@chromium.org</owner> <summary>
diff --git a/ui/accessibility/accessibility_features.cc b/ui/accessibility/accessibility_features.cc index e4061e54..c7e3879 100644 --- a/ui/accessibility/accessibility_features.cc +++ b/ui/accessibility/accessibility_features.cc
@@ -118,6 +118,15 @@ return base::FeatureList::IsEnabled( ::features::kEnableSwitchAccessPointScanning); } + +const base::Feature kExperimentalAccessibilityDictationListening{ + "ExperimentalAccessibilityDictationListening", + base::FEATURE_DISABLED_BY_DEFAULT}; + +bool IsExperimentalAccessibilityDictationListeningEnabled() { + return base::FeatureList::IsEnabled( + ::features::kExperimentalAccessibilityDictationListening); +} #endif // BUILDFLAG(IS_CHROMEOS_ASH) const base::Feature kAugmentExistingImageLabels{
diff --git a/ui/accessibility/accessibility_features.h b/ui/accessibility/accessibility_features.h index cbc368b6..a303ecf 100644 --- a/ui/accessibility/accessibility_features.h +++ b/ui/accessibility/accessibility_features.h
@@ -100,6 +100,16 @@ // Returns true if the feature to allow point scanning in switch access is // enabled. AX_BASE_EXPORT bool IsSwitchAccessPointScanningEnabled(); + +// Enables dictation using web speech to listen for a longer duration and +// allow profanity, and for dictation with web speech or on-device speech +// to continue listening after speech is finalized. +AX_BASE_EXPORT extern const base::Feature + kExperimentalAccessibilityDictationListening; + +// Returns true if the feature to allow experimental listening features for +// Dictation is enabled. +AX_BASE_EXPORT bool IsExperimentalAccessibilityDictationListeningEnabled(); #endif // BUILDFLAG(IS_CHROMEOS_ASH) // Enables Get Image Descriptions to augment existing images labels,
diff --git a/ui/accessibility/accessibility_switches.cc b/ui/accessibility/accessibility_switches.cc index 3bd0148..b4ffa8e 100644 --- a/ui/accessibility/accessibility_switches.cc +++ b/ui/accessibility/accessibility_switches.cc
@@ -22,12 +22,6 @@ const char kEnableExperimentalAccessibilityDictationOffline[] = "enable-experimental-accessibility-dictation-offline"; -// Enables dictation using web speech to listen for a longer duration, -// and for dictation with web speech or on-device speech to continue listening -// after speech is finalized. -const char kEnableExperimentalAccessibilityDictationListening[] = - "enable-experimental-accessibility-dictation-listening"; - // Enables support for visually debugging the accessibility labels // feature, which provides images descriptions for screen reader users. const char kEnableExperimentalAccessibilityLabelsDebugging[] = @@ -65,11 +59,6 @@ ::switches::kEnableExperimentalAccessibilityDictationOffline); } -bool IsExperimentalAccessibilityDictationListeningEnabled() { - return base::CommandLine::ForCurrentProcess()->HasSwitch( - ::switches::kEnableExperimentalAccessibilityDictationListening); -} - bool IsExperimentalAccessibilityLanguageDetectionEnabled() { return base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kEnableExperimentalAccessibilityLanguageDetection);
diff --git a/ui/accessibility/accessibility_switches.h b/ui/accessibility/accessibility_switches.h index 5dfeba8..634b780 100644 --- a/ui/accessibility/accessibility_switches.h +++ b/ui/accessibility/accessibility_switches.h
@@ -35,10 +35,6 @@ // Returns true if experimental accessibility offline dictation is enabled. AX_BASE_EXPORT bool IsExperimentalAccessibilityDictationOfflineEnabled(); -// Returns true if experimental accessibility dictation listening features are -// enabled. -AX_BASE_EXPORT bool IsExperimentalAccessibilityDictationListeningEnabled(); - // Returns true if experimental accessibility language detection is enabled. AX_BASE_EXPORT bool IsExperimentalAccessibilityLanguageDetectionEnabled();
diff --git a/ui/android/java/src/org/chromium/ui/base/EventForwarder.java b/ui/android/java/src/org/chromium/ui/base/EventForwarder.java index aab96322..f9629ba3 100644 --- a/ui/android/java/src/org/chromium/ui/base/EventForwarder.java +++ b/ui/android/java/src/org/chromium/ui/base/EventForwarder.java
@@ -274,14 +274,6 @@ int eventAction = event.getActionMasked(); - // Ignore ACTION_HOVER_ENTER & ACTION_HOVER_EXIT because every mouse-down on Android - // follows a hover-exit and is followed by a hover-enter. https://crbug.com/715114 - // filed on distinguishing actual hover enter/exit from these bogus ones. - if (eventAction == MotionEvent.ACTION_HOVER_ENTER - || eventAction == MotionEvent.ACTION_HOVER_EXIT) { - return false; - } - // For mousedown and mouseup events, we use ACTION_BUTTON_PRESS // and ACTION_BUTTON_RELEASE respectively because they provide // info about the changed-button.
diff --git a/ui/file_manager/file_manager/background/js/background.js b/ui/file_manager/file_manager/background/js/background.js index f41d802..ddbd283 100644 --- a/ui/file_manager/file_manager/background/js/background.js +++ b/ui/file_manager/file_manager/background/js/background.js
@@ -144,9 +144,6 @@ this.onContextMenuClicked_.bind(this)); } - chrome.contextMenus.onClicked.addListener( - this.onContextMenuClicked_.bind(this)); - // Initialize string and volume manager related stuffs. this.initializationPromise_.then(strings => { this.stringData = strings;
diff --git a/ui/gfx/color_utils.cc b/ui/gfx/color_utils.cc index c4e4165..f703a0f 100644 --- a/ui/gfx/color_utils.cc +++ b/ui/gfx/color_utils.cc
@@ -234,28 +234,6 @@ base::ClampRound<U8CPU>(g), base::ClampRound<U8CPU>(b)); } -void BuildLumaHistogram(const SkBitmap& bitmap, int histogram[256]) { - DCHECK_EQ(kN32_SkColorType, bitmap.colorType()); - - int pixel_width = bitmap.width(); - int pixel_height = bitmap.height(); - for (int y = 0; y < pixel_height; ++y) { - for (int x = 0; x < pixel_width; ++x) - ++histogram[GetLuma(bitmap.getColor(x, y))]; - } -} - -double CalculateBoringScore(const SkBitmap& bitmap) { - if (bitmap.isNull() || bitmap.empty()) - return 1.0; - int histogram[256] = {0}; - BuildLumaHistogram(bitmap, histogram); - - int color_count = *std::max_element(histogram, histogram + 256); - int pixel_count = bitmap.width() * bitmap.height(); - return static_cast<double>(color_count) / pixel_count; -} - SkColor AlphaBlend(SkColor foreground, SkColor background, SkAlpha alpha) { return AlphaBlend(foreground, background, alpha / 255.0f); }
diff --git a/ui/gfx/color_utils.h b/ui/gfx/color_utils.h index 94ab366..93d13819 100644 --- a/ui/gfx/color_utils.h +++ b/ui/gfx/color_utils.h
@@ -12,8 +12,6 @@ #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/gfx_export.h" -class SkBitmap; - namespace color_utils { // Represents an HSL color. @@ -98,15 +96,6 @@ // 1 = full lightness (make all pixels white). GFX_EXPORT SkColor HSLShift(SkColor color, const HSL& shift); -// Builds a histogram based on the Y' of the Y'UV representation of this image. -GFX_EXPORT void BuildLumaHistogram(const SkBitmap& bitmap, int histogram[256]); - -// Calculates how "boring" an image is. The boring score is the -// 0,1 ranged percentage of pixels that are the most common -// luma. Higher boring scores indicate that a higher percentage of a -// bitmap are all the same brightness. -GFX_EXPORT double CalculateBoringScore(const SkBitmap& bitmap); - // Returns a blend of the supplied colors, ranging from |background| (for // |alpha| == 0) to |foreground| (for |alpha| == 255). The alpha channels of // the supplied colors are also taken into account, so the returned color may
diff --git a/ui/gfx/color_utils_unittest.cc b/ui/gfx/color_utils_unittest.cc index 8159ab3..446a772 100644 --- a/ui/gfx/color_utils_unittest.cc +++ b/ui/gfx/color_utils_unittest.cc
@@ -144,39 +144,6 @@ EXPECT_EQ(SkColorGetB(input), SkColorGetB(result)); } -TEST(ColorUtils, CalculateBoringScore_Empty) { - SkBitmap bitmap; - EXPECT_DOUBLE_EQ(1.0, CalculateBoringScore(bitmap)); -} - -TEST(ColorUtils, CalculateBoringScore_SingleColor) { - const gfx::Size kSize(20, 10); - gfx::Canvas canvas(kSize, 1.0f, true); - // Fill all pixels in black. - canvas.FillRect(gfx::Rect(kSize), SK_ColorBLACK); - - SkBitmap bitmap = canvas.GetBitmap(); - // The thumbnail should deserve the highest boring score. - EXPECT_DOUBLE_EQ(1.0, CalculateBoringScore(bitmap)); -} - -TEST(ColorUtils, CalculateBoringScore_TwoColors) { - const gfx::Size kSize(20, 10); - - gfx::Canvas canvas(kSize, 1.0f, true); - // Fill all pixels in black. - canvas.FillRect(gfx::Rect(kSize), SK_ColorBLACK); - // Fill the left half pixels in white. - canvas.FillRect(gfx::Rect(0, 0, kSize.width() / 2, kSize.height()), - SK_ColorWHITE); - - SkBitmap bitmap = canvas.GetBitmap(); - ASSERT_EQ(kSize.width(), bitmap.width()); - ASSERT_EQ(kSize.height(), bitmap.height()); - // The thumbnail should be less boring because two colors are used. - EXPECT_DOUBLE_EQ(0.5, CalculateBoringScore(bitmap)); -} - TEST(ColorUtils, AlphaBlend) { SkColor fore = SkColorSetARGB(255, 200, 200, 200); SkColor back = SkColorSetARGB(255, 100, 100, 100);
diff --git a/ui/gfx/gpu_memory_buffer.cc b/ui/gfx/gpu_memory_buffer.cc index 44b2667..6eb3674 100644 --- a/ui/gfx/gpu_memory_buffer.cc +++ b/ui/gfx/gpu_memory_buffer.cc
@@ -65,6 +65,18 @@ return handle; } +Size GpuMemoryBuffer::GetSizeOfPlane(gfx::BufferPlane plane) const { + switch (plane) { + case gfx::BufferPlane::DEFAULT: + case gfx::BufferPlane::Y: + return GetSize(); + case gfx::BufferPlane::UV: + case gfx::BufferPlane::U: + case gfx::BufferPlane::V: + return ScaleToFlooredSize(GetSize(), 0.5); + } +} + void GpuMemoryBuffer::SetColorSpace(const ColorSpace& color_space) {} void GpuMemoryBuffer::SetHDRMetadata(const HDRMetadata& hdr_metadata) {}
diff --git a/ui/gfx/gpu_memory_buffer.h b/ui/gfx/gpu_memory_buffer.h index c3a1f81..9cf5f37e 100644 --- a/ui/gfx/gpu_memory_buffer.h +++ b/ui/gfx/gpu_memory_buffer.h
@@ -102,12 +102,15 @@ // after this has been called. virtual void Unmap() = 0; - // Returns the size for the buffer. + // Returns the size in pixels of the first plane of the buffer. virtual Size GetSize() const = 0; // Returns the format for the buffer. virtual BufferFormat GetFormat() const = 0; + // Returns the size in pixels of the specified plane. + Size GetSizeOfPlane(gfx::BufferPlane plane) const; + // Fills the stride in bytes for each plane of the buffer. The stride of // plane K is stored at index K-1 of the |stride| array. virtual int stride(size_t plane) const = 0;
diff --git a/ui/gl/delegated_ink_point_renderer_gpu.h b/ui/gl/delegated_ink_point_renderer_gpu.h index 136c9189..653ccdd 100644 --- a/ui/gl/delegated_ink_point_renderer_gpu.h +++ b/ui/gl/delegated_ink_point_renderer_gpu.h
@@ -329,14 +329,20 @@ if (metadata_ && metadata_->presentation_area() == new_presentation_area) return true; + // If (0,0) of a visual is clipped out, it can result in delegated ink not + // being drawn at all. This is more common when DComp Surfaces are enabled, + // but doesn't negatively impact things when the swapchain is used, so just + // offset the visual instead of clipping the top left corner in all cases. + ink_visual_->SetOffsetX(new_presentation_area.x()); + ink_visual_->SetOffsetY(new_presentation_area.y()); + D2D_RECT_F clip_rect; clip_rect.bottom = new_presentation_area.bottom(); - clip_rect.left = new_presentation_area.x(); clip_rect.right = new_presentation_area.right(); - clip_rect.top = new_presentation_area.y(); - // If setting the clip failed, we want to bail early so that a trail can't - // incorrectly appear over things on the user's screen. - return SUCCEEDED(ink_visual_->SetClip(clip_rect)); + // If setting the clip or committing failed, we want to bail early so that a + // trail can't incorrectly appear over things on the user's screen. + return SUCCEEDED(ink_visual_->SetClip(clip_rect)) && + SUCCEEDED(dcomp_device_->Commit()); } void RemoveSavedPointsOlderThanMetadata() { @@ -362,17 +368,20 @@ DCHECK(delegated_ink_trail_); + InkTrailPoint ink_point; + ink_point.radius = metadata_->diameter() / 2.f; + // In order to account for the visual offset, the point must be offset in + // the opposite direction. + ink_point.x = point.point().x() - metadata_->presentation_area().x(); + ink_point.y = point.point().y() - metadata_->presentation_area().y(); + unsigned int token; + // AddTrailPoints() can accept and draw more than one InkTrailPoint per // call. However, all the points get lumped together in the one token then, // which means that they can only be removed all together. This may be fine // in some scenarios, but in the vast majority of cases we will need to // remove one point at a time, so we choose to only add one InkTrailPoint at // a time. - InkTrailPoint ink_point; - ink_point.radius = metadata_->diameter() / 2.f; - ink_point.x = point.point().x(); - ink_point.y = point.point().y(); - unsigned int token; if (TraceEventOnFailure( delegated_ink_trail_->AddTrailPoints(&ink_point, /*inkPointsCount*/ 1, &token),
diff --git a/ui/gl/gl_surface_egl_surface_control.cc b/ui/gl/gl_surface_egl_surface_control.cc index 9116d5a9..47c28b5 100644 --- a/ui/gl/gl_surface_egl_surface_control.cc +++ b/ui/gl/gl_surface_egl_surface_control.cc
@@ -396,8 +396,33 @@ gfx::RectF scaled_rect = gfx::ScaleRect(crop_rect, buffer_size.width(), buffer_size.height()); - gfx::Rect src = gfx::ToEnclosedRect(scaled_rect); gfx::Rect dst = bounds_rect; + gfx::Rect src = gfx::ToEnclosedRect(scaled_rect); + + // When the video is being scrolled offscreen DisplayCompositor will crop it + // to only visible portion and adjust crop_rect accordingly. When the video + // is smaller than the surface is can lead to the crop rect being less than + // a pixel in size. This adjusts the crop rect size to at least 1 pixel as + // we want to stretch last visible pixel line/column in this case. + // Note: We will do it even if crop_rect width/height is exact 0.0f. In + // reality this should never happen and there is no way to display video + // with empty crop rect, so display compositor should not request this. + + if (src.width() == 0) { + src.set_width(1); + if (src.right() > buffer_size.width()) + src.set_x(buffer_size.width() - 1); + } + if (src.height() == 0) { + src.set_height(1); + if (src.bottom() > buffer_size.height()) + src.set_y(buffer_size.height() - 1); + } + + // When display compositor rounds up destination rect to integer coordinates + // it becomes slightly bigger. After we adjust source rect accordingly, it + // can become larger then a buffer so we clip it here. See crbug.com/1083412 + src.Intersect(gfx::Rect(buffer_size)); if (uninitialized || surface_state.src != src || surface_state.dst != dst || surface_state.transform != transform) {
diff --git a/ui/ozone/platform/drm/gpu/drm_window.cc b/ui/ozone/platform/drm/gpu/drm_window.cc index f514a35..0f6ed73 100644 --- a/ui/ozone/platform/drm/gpu/drm_window.cc +++ b/ui/ozone/platform/drm/gpu/drm_window.cc
@@ -132,10 +132,6 @@ last_submitted_planes_); } -const DrmOverlayPlane* DrmWindow::GetLastModesetBuffer() const { - return DrmOverlayPlane::GetPrimaryPlane(last_submitted_planes_); -} - void DrmWindow::UpdateCursorImage() { if (!controller_) return;
diff --git a/ui/ozone/platform/drm/gpu/drm_window.h b/ui/ozone/platform/drm/gpu/drm_window.h index 8860f6d0..13b346bf 100644 --- a/ui/ozone/platform/drm/gpu/drm_window.h +++ b/ui/ozone/platform/drm/gpu/drm_window.h
@@ -88,8 +88,9 @@ OverlayStatusList TestPageFlip( const OverlaySurfaceCandidateList& overlay_params); - // Returns the last buffer associated with this window. - const DrmOverlayPlane* GetLastModesetBuffer() const; + const DrmOverlayPlaneList& last_submitted_planes() const { + return last_submitted_planes_; + } private: // Draw next frame in an animated cursor.
diff --git a/ui/ozone/platform/drm/gpu/screen_manager.cc b/ui/ozone/platform/drm/gpu/screen_manager.cc index fe1cb65..c28ce60 100644 --- a/ui/ozone/platform/drm/gpu/screen_manager.cc +++ b/ui/ozone/platform/drm/gpu/screen_manager.cc
@@ -405,10 +405,10 @@ controller->GetDisableProps(&commit_request); } } - // If we have no overlays, there is nothing new to test after the previous - // modifiers tests and Modeset can take all available planes. + // If we have no overlays, report not modesetting with overlays as we haven't + // tested with overlays. if (!does_an_overlay_exist) - return true; + return false; return drm->plane_manager()->Commit( std::move(commit_request), @@ -707,18 +707,23 @@ } // If the current primary plane matches what we need for the next page flip, - // we can clone it. + // clone all last_submitted_planes (matching primary + overlays). DrmWindow* window = FindWindowAt(bounds); if (window) { - const DrmOverlayPlane* primary = window->GetLastModesetBuffer(); + const DrmOverlayPlaneList& last_submitted_planes = + window->last_submitted_planes(); + const DrmOverlayPlane* primary = + DrmOverlayPlane::GetPrimaryPlane(last_submitted_planes); if (primary && primary->buffer->size() == bounds.size() && primary->buffer->drm_device() == controller->GetDrmDevice().get() && primary->buffer->format_modifier() == buffer->GetFormatModifier()) { - // TODO(markyacoub): use |include_overlays| to return all planes not just - // Primary. - DrmOverlayPlaneList modeset_planes; - modeset_planes.push_back(primary->Clone()); - return modeset_planes; + if (include_overlays) { + return DrmOverlayPlane::Clone(last_submitted_planes); + } else { + DrmOverlayPlaneList modeset_plane; + modeset_plane.push_back(primary->Clone()); + return modeset_plane; + } } }
diff --git a/ui/ozone/platform/drm/gpu/screen_manager_unittest.cc b/ui/ozone/platform/drm/gpu/screen_manager_unittest.cc index 2413cb7..a98d358 100644 --- a/ui/ozone/platform/drm/gpu/screen_manager_unittest.cc +++ b/ui/ozone/platform/drm/gpu/screen_manager_unittest.cc
@@ -1467,8 +1467,6 @@ CHECK_EQ(pre_modeset_buffer->modeset_sequence_id_at_allocation(), 0); } -// TODO(markyacoub): Create another one testing cloning overlays for modeset -// when supported. TEST_F(ScreenManagerTest, CloningPlanesOnModeset) { InitializeDrmStateWithDefault(drm_.get(), /*is_atomic=*/true); @@ -1502,6 +1500,53 @@ window->Shutdown(); } +TEST_F(ScreenManagerTest, CloningMultiplePlanesOnModeset) { + std::vector<CrtcState> crtc_states = {{ + /* .planes = */ + { + {/* .formats = */ {DRM_FORMAT_XRGB8888}}, + {/* .formats = */ {DRM_FORMAT_XRGB8888}}, + }, + }}; + InitializeDrmState(drm_.get(), crtc_states, /*is_atomic=*/true); + + std::unique_ptr<ui::DrmWindow> window( + new ui::DrmWindow(1, device_manager_.get(), screen_manager_.get())); + window->Initialize(); + window->SetBounds(GetPrimaryBounds()); + scoped_refptr<DrmFramebuffer> primary = + CreateBuffer(DRM_FORMAT_XRGB8888, GetPrimaryBounds().size()); + scoped_refptr<DrmFramebuffer> overlay = + CreateBuffer(DRM_FORMAT_XRGB8888, GetPrimaryBounds().size()); + ui::DrmOverlayPlaneList planes; + planes.push_back(ui::DrmOverlayPlane(primary, nullptr)); + planes.push_back(ui::DrmOverlayPlane(overlay, nullptr)); + window->SchedulePageFlip(std::move(planes), base::DoNothing(), + base::DoNothing()); + screen_manager_->AddWindow(1, std::move(window)); + + screen_manager_->AddDisplayController(drm_, kPrimaryCrtc, kPrimaryConnector); + ScreenManager::ControllerConfigsList controllers_to_enable; + controllers_to_enable.emplace_back( + kPrimaryDisplayId, drm_, kPrimaryCrtc, kPrimaryConnector, + GetPrimaryBounds().origin(), + std::make_unique<drmModeModeInfo>(kDefaultMode)); + ASSERT_TRUE( + screen_manager_->ConfigureDisplayControllers(controllers_to_enable)); + + EXPECT_TRUE(base::Contains(drm_->plane_manager() + ->GetCrtcStateForCrtcId(kPrimaryCrtc) + .modeset_framebuffers, + primary)); + EXPECT_TRUE(base::Contains(drm_->plane_manager() + ->GetCrtcStateForCrtcId(kPrimaryCrtc) + .modeset_framebuffers, + overlay)); + + window = screen_manager_->RemoveWindow(1); + window->Shutdown(); +} + TEST_F(ScreenManagerTest, ModesetWithClonedPlanesNoOverlays) { InitializeDrmStateWithDefault(drm_.get(), /*is_atomic=*/true); @@ -1551,13 +1596,13 @@ new ui::DrmWindow(1, device_manager_.get(), screen_manager_.get())); window->Initialize(); window->SetBounds(GetPrimaryBounds()); - scoped_refptr<DrmFramebuffer> buffer1 = + scoped_refptr<DrmFramebuffer> primary = CreateBuffer(DRM_FORMAT_XRGB8888, GetPrimaryBounds().size()); - scoped_refptr<DrmFramebuffer> buffer2 = + scoped_refptr<DrmFramebuffer> overlay = CreateBuffer(DRM_FORMAT_XRGB8888, GetPrimaryBounds().size()); ui::DrmOverlayPlaneList planes; - planes.push_back(ui::DrmOverlayPlane(buffer1, nullptr)); - planes.push_back(ui::DrmOverlayPlane(buffer2, nullptr)); + planes.push_back(ui::DrmOverlayPlane(primary, nullptr)); + planes.push_back(ui::DrmOverlayPlane(overlay, nullptr)); window->SchedulePageFlip(std::move(planes), base::DoNothing(), base::DoNothing()); screen_manager_->AddWindow(1, std::move(window)); @@ -1571,17 +1616,17 @@ ASSERT_TRUE( screen_manager_->ConfigureDisplayControllers(controllers_to_enable)); - // TODO(markyacoub): Add another one to check if buffer2 is contained in - // modeset_framebuffers. EXPECT_TRUE(base::Contains(drm_->plane_manager() ->GetCrtcStateForCrtcId(kPrimaryCrtc) .modeset_framebuffers, - buffer1)); + primary)); + EXPECT_TRUE(base::Contains(drm_->plane_manager() + ->GetCrtcStateForCrtcId(kPrimaryCrtc) + .modeset_framebuffers, + overlay)); - // TODO(markyacoub): Increment both counts to 2 once we clone overlays as - // well for modeset. - EXPECT_EQ(drm_->get_test_modeset_count(), 1); - EXPECT_EQ(drm_->last_planes_committed_count(), 1); + EXPECT_EQ(drm_->get_test_modeset_count(), 2); + EXPECT_EQ(drm_->last_planes_committed_count(), 2); window = screen_manager_->RemoveWindow(1); window->Shutdown(); @@ -1601,13 +1646,13 @@ new ui::DrmWindow(1, device_manager_.get(), screen_manager_.get())); window->Initialize(); window->SetBounds(GetPrimaryBounds()); - scoped_refptr<DrmFramebuffer> primary_buffer = + scoped_refptr<DrmFramebuffer> primary = CreateBuffer(DRM_FORMAT_XRGB8888, GetPrimaryBounds().size()); - scoped_refptr<DrmFramebuffer> overlay_buffer = + scoped_refptr<DrmFramebuffer> overlay = CreateBuffer(DRM_FORMAT_XRGB8888, GetPrimaryBounds().size()); ui::DrmOverlayPlaneList planes; - planes.push_back(ui::DrmOverlayPlane(primary_buffer, nullptr)); - planes.push_back(ui::DrmOverlayPlane(overlay_buffer, nullptr)); + planes.push_back(ui::DrmOverlayPlane(primary, nullptr)); + planes.push_back(ui::DrmOverlayPlane(overlay, nullptr)); window->SchedulePageFlip(std::move(planes), base::DoNothing(), base::DoNothing()); screen_manager_->AddWindow(1, std::move(window)); @@ -1619,20 +1664,70 @@ kPrimaryDisplayId, drm_, kPrimaryCrtc, kPrimaryConnector, GetPrimaryBounds().origin(), std::make_unique<drmModeModeInfo>(kDefaultMode)); - ASSERT_TRUE( + EXPECT_TRUE( screen_manager_->ConfigureDisplayControllers(controllers_to_enable)); EXPECT_TRUE(base::Contains(drm_->plane_manager() ->GetCrtcStateForCrtcId(kPrimaryCrtc) .modeset_framebuffers, - primary_buffer)); + primary)); EXPECT_FALSE(base::Contains(drm_->plane_manager() ->GetCrtcStateForCrtcId(kPrimaryCrtc) .modeset_framebuffers, - overlay_buffer)); + overlay)); - // TODO(markyacoub): Increment get_test_modeset_count once we clone overlays - // for modesetting test. + EXPECT_EQ(drm_->get_test_modeset_count(), 2); + EXPECT_EQ(drm_->last_planes_committed_count(), 1); + + window = screen_manager_->RemoveWindow(1); + window->Shutdown(); +} + +TEST_F(ScreenManagerTest, ModesetWithNewBuffersOnModifiersChange) { + std::vector<CrtcState> crtc_states = {{ + /* .planes = */ + { + {/* .formats = */ {DRM_FORMAT_XRGB8888}}, + {/* .formats = */ {DRM_FORMAT_XRGB8888}}, + }, + }}; + InitializeDrmState(drm_.get(), crtc_states, /*is_atomic=*/true, + /*use_modifiers_list=*/true); + std::unique_ptr<ui::DrmWindow> window( + new ui::DrmWindow(1, device_manager_.get(), screen_manager_.get())); + window->Initialize(); + window->SetBounds(GetPrimaryBounds()); + + scoped_refptr<DrmFramebuffer> primary = + CreateBuffer(DRM_FORMAT_XRGB8888, GetPrimaryBounds().size()); + scoped_refptr<DrmFramebuffer> overlay = + CreateBuffer(DRM_FORMAT_XRGB8888, GetPrimaryBounds().size()); + ui::DrmOverlayPlaneList planes; + planes.push_back(ui::DrmOverlayPlane(primary, nullptr)); + planes.push_back(ui::DrmOverlayPlane(overlay, nullptr)); + window->SchedulePageFlip(std::move(planes), base::DoNothing(), + base::DoNothing()); + screen_manager_->AddWindow(1, std::move(window)); + + screen_manager_->AddDisplayController(drm_, kPrimaryCrtc, kPrimaryConnector); + ScreenManager::ControllerConfigsList controllers_to_enable; + controllers_to_enable.emplace_back( + kPrimaryDisplayId, drm_, kPrimaryCrtc, kPrimaryConnector, + GetPrimaryBounds().origin(), + std::make_unique<drmModeModeInfo>(kDefaultMode)); + ASSERT_TRUE( + screen_manager_->ConfigureDisplayControllers(controllers_to_enable)); + + EXPECT_FALSE(base::Contains(drm_->plane_manager() + ->GetCrtcStateForCrtcId(kPrimaryCrtc) + .modeset_framebuffers, + primary)); + EXPECT_FALSE(base::Contains(drm_->plane_manager() + ->GetCrtcStateForCrtcId(kPrimaryCrtc) + .modeset_framebuffers, + overlay)); + + // Testing test modifiers only, no linear or overlays test. EXPECT_EQ(drm_->get_test_modeset_count(), 1); EXPECT_EQ(drm_->last_planes_committed_count(), 1);
diff --git a/ui/resources/default_100_percent/common/pointers/sb_h_double_arrow.png b/ui/resources/default_100_percent/common/pointers/sb_horizontal_double_arrow.png similarity index 100% rename from ui/resources/default_100_percent/common/pointers/sb_h_double_arrow.png rename to ui/resources/default_100_percent/common/pointers/sb_horizontal_double_arrow.png Binary files differ
diff --git a/ui/resources/default_100_percent/common/pointers/sb_h_double_arrow_big.png b/ui/resources/default_100_percent/common/pointers/sb_horizontal_double_arrow_big.png similarity index 100% rename from ui/resources/default_100_percent/common/pointers/sb_h_double_arrow_big.png rename to ui/resources/default_100_percent/common/pointers/sb_horizontal_double_arrow_big.png Binary files differ
diff --git a/ui/resources/default_100_percent/common/pointers/sb_v_double_arrow.png b/ui/resources/default_100_percent/common/pointers/sb_vertical_double_arrow.png similarity index 100% rename from ui/resources/default_100_percent/common/pointers/sb_v_double_arrow.png rename to ui/resources/default_100_percent/common/pointers/sb_vertical_double_arrow.png Binary files differ
diff --git a/ui/resources/default_100_percent/common/pointers/sb_v_double_arrow_big.png b/ui/resources/default_100_percent/common/pointers/sb_vertical_double_arrow_big.png similarity index 100% rename from ui/resources/default_100_percent/common/pointers/sb_v_double_arrow_big.png rename to ui/resources/default_100_percent/common/pointers/sb_vertical_double_arrow_big.png Binary files differ
diff --git a/ui/resources/default_200_percent/common/pointers/sb_h_double_arrow.png b/ui/resources/default_200_percent/common/pointers/sb_horizontal_double_arrow.png similarity index 100% rename from ui/resources/default_200_percent/common/pointers/sb_h_double_arrow.png rename to ui/resources/default_200_percent/common/pointers/sb_horizontal_double_arrow.png Binary files differ
diff --git a/ui/resources/default_200_percent/common/pointers/sb_v_double_arrow.png b/ui/resources/default_200_percent/common/pointers/sb_vertical_double_arrow.png similarity index 100% rename from ui/resources/default_200_percent/common/pointers/sb_v_double_arrow.png rename to ui/resources/default_200_percent/common/pointers/sb_vertical_double_arrow.png Binary files differ
diff --git a/ui/resources/ui_resources.grd b/ui/resources/ui_resources.grd index 38731743..deda554 100644 --- a/ui/resources/ui_resources.grd +++ b/ui/resources/ui_resources.grd
@@ -19,13 +19,13 @@ <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_ALIAS" file="common/pointers/alias.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_ALIAS" file="common/pointers/alias_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_CELL" file="common/pointers/cell_big.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_COL_RESIZE" file="common/pointers/sb_h_double_arrow_big.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_COL_RESIZE" file="common/pointers/sb_horizontal_double_arrow_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_CONTEXT_MENU" file="common/pointers/context_menu_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_COPY" file="common/pointers/copy_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_CROSSHAIR" file="common/pointers/crosshair_big.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_EAST_RESIZE" file="common/pointers/sb_h_double_arrow_big.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_EAST_RESIZE" file="common/pointers/sb_horizontal_double_arrow_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_EAST_WEST_NO_RESIZE" file="common/pointers/sb_horizontal_double_arrow_block_big.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_EAST_WEST_RESIZE" file="common/pointers/sb_h_double_arrow_big.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_EAST_WEST_RESIZE" file="common/pointers/sb_horizontal_double_arrow_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_GRAB" file="common/pointers/fleur_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_GRABBING" file="common/pointers/hand3_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_HAND" file="common/pointers/hand2_big.png" /> @@ -35,30 +35,30 @@ <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_EAST_RESIZE" file="common/pointers/top_right_corner_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_EAST_SOUTH_WEST_NO_RESIZE" file="common/pointers/top_right_corner_block_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_EAST_SOUTH_WEST_RESIZE" file="common/pointers/top_right_corner_big.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_RESIZE" file="common/pointers/sb_v_double_arrow_big.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_RESIZE" file="common/pointers/sb_vertical_double_arrow_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_SOUTH_NO_RESIZE" file="common/pointers/sb_vertical_double_arrow_block_big.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_SOUTH_RESIZE" file="common/pointers/sb_v_double_arrow_big.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_SOUTH_RESIZE" file="common/pointers/sb_vertical_double_arrow_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_WEST_RESIZE" file="common/pointers/top_left_corner_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_WEST_SOUTH_EAST_NO_RESIZE" file="common/pointers/top_left_corner_block_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NORTH_WEST_SOUTH_EAST_RESIZE" file="common/pointers/top_left_corner_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_NO_DROP" file="common/pointers/nodrop_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_PTR" file="common/pointers/left_ptr_big.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_ROW_RESIZE" file="common/pointers/sb_v_double_arrow_big.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_ROW_RESIZE" file="common/pointers/sb_vertical_double_arrow_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_SOUTH_EAST_RESIZE" file="common/pointers/top_left_corner_big.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_SOUTH_RESIZE" file="common/pointers/sb_v_double_arrow_big.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_SOUTH_RESIZE" file="common/pointers/sb_vertical_double_arrow_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_SOUTH_WEST_RESIZE" file="common/pointers/top_right_corner_big.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_WEST_RESIZE" file="common/pointers/sb_h_double_arrow_big.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_WEST_RESIZE" file="common/pointers/sb_horizontal_double_arrow_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_XTERM_HORIZ" file="common/pointers/xterm_horiz_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_ZOOM_IN" file="common/pointers/zoom_in_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_BIG_ZOOM_OUT" file="common/pointers/zoom_out_big.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_CELL" file="common/pointers/cell.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_COL_RESIZE" file="common/pointers/sb_h_double_arrow.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_COL_RESIZE" file="common/pointers/sb_horizontal_double_arrow.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_CONTEXT_MENU" file="common/pointers/context_menu.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_COPY" file="common/pointers/copy.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_CROSSHAIR" file="common/pointers/crosshair.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_EAST_RESIZE" file="common/pointers/sb_h_double_arrow.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_EAST_RESIZE" file="common/pointers/sb_horizontal_double_arrow.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_EAST_WEST_NO_RESIZE" file="common/pointers/sb_horizontal_double_arrow_block.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_EAST_WEST_RESIZE" file="common/pointers/sb_h_double_arrow.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_EAST_WEST_RESIZE" file="common/pointers/sb_horizontal_double_arrow.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_GRAB" file="common/pointers/fleur.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_GRABBING" file="common/pointers/hand3.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_HAND" file="common/pointers/hand2.png" /> @@ -68,20 +68,20 @@ <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_EAST_RESIZE" file="common/pointers/top_right_corner.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_EAST_SOUTH_WEST_NO_RESIZE" file="common/pointers/top_right_corner_block.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_EAST_SOUTH_WEST_RESIZE" file="common/pointers/top_right_corner.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_RESIZE" file="common/pointers/sb_v_double_arrow.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_RESIZE" file="common/pointers/sb_vertical_double_arrow.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_SOUTH_NO_RESIZE" file="common/pointers/sb_vertical_double_arrow_block.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_SOUTH_RESIZE" file="common/pointers/sb_v_double_arrow.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_SOUTH_RESIZE" file="common/pointers/sb_vertical_double_arrow.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_WEST_RESIZE" file="common/pointers/top_left_corner.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_WEST_SOUTH_EAST_NO_RESIZE" file="common/pointers/top_left_corner_block.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NORTH_WEST_SOUTH_EAST_RESIZE" file="common/pointers/top_left_corner.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_NO_DROP" file="common/pointers/nodrop.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_PTR" file="common/pointers/left_ptr.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_ROW_RESIZE" file="common/pointers/sb_v_double_arrow.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_ROW_RESIZE" file="common/pointers/sb_vertical_double_arrow.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_SOUTH_EAST_RESIZE" file="common/pointers/top_left_corner.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_SOUTH_RESIZE" file="common/pointers/sb_v_double_arrow.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_SOUTH_RESIZE" file="common/pointers/sb_vertical_double_arrow.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_SOUTH_WEST_RESIZE" file="common/pointers/top_right_corner.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_THROBBER" file="common/pointers/throbber.png" /> - <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_WEST_RESIZE" file="common/pointers/sb_h_double_arrow.png" /> + <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_WEST_RESIZE" file="common/pointers/sb_horizontal_double_arrow.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_XTERM_HORIZ" file="common/pointers/xterm_horiz.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_ZOOM_IN" file="common/pointers/zoom_in.png" /> <structure type="chrome_scaled_image" name="IDR_AURA_CURSOR_ZOOM_OUT" file="common/pointers/zoom_out.png" />
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn index 6a80a1e..0a5bb26f 100644 --- a/ui/views/BUILD.gn +++ b/ui/views/BUILD.gn
@@ -159,10 +159,10 @@ "controls/resize_area.h", "controls/resize_area_delegate.h", "controls/scroll_view.h", - "controls/scrollbar/base_scroll_bar_button.h", "controls/scrollbar/base_scroll_bar_thumb.h", "controls/scrollbar/overlay_scroll_bar.h", "controls/scrollbar/scroll_bar.h", + "controls/scrollbar/scroll_bar_button.h", "controls/scrollbar/scroll_bar_views.h", "controls/separator.h", "controls/slider.h", @@ -369,10 +369,10 @@ "controls/progress_bar.cc", "controls/resize_area.cc", "controls/scroll_view.cc", - "controls/scrollbar/base_scroll_bar_button.cc", "controls/scrollbar/base_scroll_bar_thumb.cc", "controls/scrollbar/overlay_scroll_bar.cc", "controls/scrollbar/scroll_bar.cc", + "controls/scrollbar/scroll_bar_button.cc", "controls/scrollbar/scroll_bar_views.cc", "controls/separator.cc", "controls/slider.cc", @@ -1139,7 +1139,7 @@ "controls/progress_bar_unittest.cc", "controls/resize_area_unittest.cc", "controls/scroll_view_unittest.cc", - "controls/scrollbar/base_scroll_bar_button_unittest.cc", + "controls/scrollbar/scroll_bar_button_unittest.cc", "controls/scrollbar/scrollbar_unittest.cc", "controls/separator_unittest.cc", "controls/slider_unittest.cc",
diff --git a/ui/views/controls/scrollbar/base_scroll_bar_button.cc b/ui/views/controls/scrollbar/base_scroll_bar_button.cc deleted file mode 100644 index 7f9fbd0..0000000 --- a/ui/views/controls/scrollbar/base_scroll_bar_button.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/base_scroll_bar_button.h" - -#include <utility> - -#include "base/bind.h" -#include "base/callback_helpers.h" -#include "ui/base/metadata/metadata_impl_macros.h" -#include "ui/display/screen.h" -#include "ui/events/event_utils.h" - -namespace views { - -BaseScrollBarButton::BaseScrollBarButton(PressedCallback callback, - const base::TickClock* tick_clock) - : Button(std::move(callback)), - repeater_(base::BindRepeating(&BaseScrollBarButton::RepeaterNotifyClick, - base::Unretained(this)), - tick_clock) { - // Not focusable by default. - SetFocusBehavior(FocusBehavior::NEVER); -} - -BaseScrollBarButton::~BaseScrollBarButton() = default; - -bool BaseScrollBarButton::OnMousePressed(const ui::MouseEvent& event) { - Button::NotifyClick(event); - repeater_.Start(); - return true; -} - -void BaseScrollBarButton::OnMouseReleased(const ui::MouseEvent& event) { - OnMouseCaptureLost(); -} - -void BaseScrollBarButton::OnMouseCaptureLost() { - repeater_.Stop(); -} - -void BaseScrollBarButton::RepeaterNotifyClick() { - // TODO(sky): See if we can convert to using |Screen| everywhere. - gfx::Point cursor_point = - display::Screen::GetScreen()->GetCursorScreenPoint(); - ui::MouseEvent event(ui::ET_MOUSE_RELEASED, cursor_point, cursor_point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - Button::NotifyClick(event); -} - -BEGIN_METADATA(BaseScrollBarButton, Button) -END_METADATA - -} // namespace views
diff --git a/ui/views/controls/scrollbar/base_scroll_bar_button.h b/ui/views/controls/scrollbar/base_scroll_bar_button.h deleted file mode 100644 index 09635d6..0000000 --- a/ui/views/controls/scrollbar/base_scroll_bar_button.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_BUTTON_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_BUTTON_H_ - -#include "ui/views/controls/button/button.h" - -#include "base/macros.h" -#include "build/build_config.h" -#include "ui/views/repeat_controller.h" - -namespace base { -class TickClock; -} - -namespace views { - -/////////////////////////////////////////////////////////////////////////////// -// -// ScrollBarButton -// -// A button that activates on mouse pressed rather than released, and that -// continues to fire the clicked action as the mouse button remains pressed -// down on the button. -// -/////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT BaseScrollBarButton : public Button { - public: - METADATA_HEADER(BaseScrollBarButton); - - explicit BaseScrollBarButton(PressedCallback callback, - const base::TickClock* tick_clock = nullptr); - ~BaseScrollBarButton() override; - - protected: - bool OnMousePressed(const ui::MouseEvent& event) override; - void OnMouseReleased(const ui::MouseEvent& event) override; - void OnMouseCaptureLost() override; - - private: - void RepeaterNotifyClick(); - - // The repeat controller that we use to repeatedly click the button when the - // mouse button is down. - RepeatController repeater_; - - DISALLOW_COPY_AND_ASSIGN(BaseScrollBarButton); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_BUTTON_H_
diff --git a/ui/views/controls/scrollbar/scroll_bar_button.cc b/ui/views/controls/scrollbar/scroll_bar_button.cc new file mode 100644 index 0000000..decf5a3 --- /dev/null +++ b/ui/views/controls/scrollbar/scroll_bar_button.cc
@@ -0,0 +1,113 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/views/controls/scrollbar/scroll_bar_button.h" + +#include <utility> + +#include "base/bind.h" +#include "base/time/tick_clock.h" +#include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/display/screen.h" +#include "ui/events/base_event_utils.h" +#include "ui/events/event_constants.h" +#include "ui/gfx/canvas.h" +#include "ui/gfx/geometry/rect.h" + +namespace views { + +ScrollBarButton::ScrollBarButton(PressedCallback callback, + Type type, + const base::TickClock* tick_clock) + : Button(std::move(callback)), + type_(type), + repeater_(base::BindRepeating(&ScrollBarButton::RepeaterNotifyClick, + base::Unretained(this)), + tick_clock) { + SetFlipCanvasOnPaintForRTLUI(true); + // Not focusable by default. + SetFocusBehavior(FocusBehavior::NEVER); +} + +ScrollBarButton::~ScrollBarButton() = default; + +gfx::Size ScrollBarButton::CalculatePreferredSize() const { + return GetNativeTheme()->GetPartSize( + GetNativeThemePart(), GetNativeThemeState(), GetNativeThemeParams()); +} + +bool ScrollBarButton::OnMousePressed(const ui::MouseEvent& event) { + Button::NotifyClick(event); + repeater_.Start(); + return true; +} + +void ScrollBarButton::OnMouseReleased(const ui::MouseEvent& event) { + OnMouseCaptureLost(); +} + +void ScrollBarButton::OnMouseCaptureLost() { + repeater_.Stop(); +} + +void ScrollBarButton::PaintButtonContents(gfx::Canvas* canvas) { + gfx::Rect bounds(GetPreferredSize()); + GetNativeTheme()->Paint(canvas->sk_canvas(), GetNativeThemePart(), + GetNativeThemeState(), bounds, + GetNativeThemeParams()); +} + +ui::NativeTheme::ExtraParams ScrollBarButton::GetNativeThemeParams() const { + ui::NativeTheme::ExtraParams params; + params.scrollbar_arrow.is_hovering = GetState() == Button::STATE_HOVERED; + return params; +} + +ui::NativeTheme::Part ScrollBarButton::GetNativeThemePart() const { + switch (type_) { + case Type::kUp: + return ui::NativeTheme::kScrollbarUpArrow; + case Type::kDown: + return ui::NativeTheme::kScrollbarDownArrow; + case Type::kLeft: + return ui::NativeTheme::kScrollbarLeftArrow; + case Type::kRight: + return ui::NativeTheme::kScrollbarRightArrow; + } + + NOTREACHED(); + return ui::NativeTheme::kScrollbarUpArrow; +} + +ui::NativeTheme::State ScrollBarButton::GetNativeThemeState() const { + switch (GetState()) { + case Button::STATE_HOVERED: + return ui::NativeTheme::kHovered; + case Button::STATE_PRESSED: + return ui::NativeTheme::kPressed; + case Button::STATE_DISABLED: + return ui::NativeTheme::kDisabled; + case Button::STATE_NORMAL: + return ui::NativeTheme::kNormal; + case Button::STATE_COUNT: + break; + } + + NOTREACHED(); + return ui::NativeTheme::kNormal; +} + +void ScrollBarButton::RepeaterNotifyClick() { + gfx::Point cursor_point = + display::Screen::GetScreen()->GetCursorScreenPoint(); + ui::MouseEvent event(ui::ET_MOUSE_RELEASED, cursor_point, cursor_point, + ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, + ui::EF_LEFT_MOUSE_BUTTON); + Button::NotifyClick(event); +} + +BEGIN_METADATA(ScrollBarButton, Button) +END_METADATA + +} // namespace views
diff --git a/ui/views/controls/scrollbar/scroll_bar_button.h b/ui/views/controls/scrollbar/scroll_bar_button.h new file mode 100644 index 0000000..1b3851d --- /dev/null +++ b/ui/views/controls/scrollbar/scroll_bar_button.h
@@ -0,0 +1,71 @@ +// Copyright 2021 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_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_BUTTON_H_ +#define UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_BUTTON_H_ + +#include "ui/base/metadata/metadata_header_macros.h" +#include "ui/events/event.h" +#include "ui/gfx/geometry/size.h" +#include "ui/native_theme/native_theme.h" +#include "ui/views/controls/button/button.h" +#include "ui/views/repeat_controller.h" +#include "ui/views/views_export.h" + +namespace base { +class TickClock; +} + +namespace gfx { +class Canvas; +} + +namespace views { + +// A button that activates on mouse pressed rather than released, and that +// continues to fire the clicked action as the mouse button remains pressed +// down on the button. +class VIEWS_EXPORT ScrollBarButton : public Button { + public: + METADATA_HEADER(ScrollBarButton); + + enum class Type { + kUp, + kDown, + kLeft, + kRight, + }; + + ScrollBarButton(PressedCallback callback, + Type type, + const base::TickClock* tick_clock = nullptr); + ScrollBarButton(const ScrollBarButton&) = delete; + ScrollBarButton& operator=(const ScrollBarButton&) = delete; + ~ScrollBarButton() override; + + gfx::Size CalculatePreferredSize() const override; + + protected: + // Button + bool OnMousePressed(const ui::MouseEvent& event) override; + void OnMouseReleased(const ui::MouseEvent& event) override; + void OnMouseCaptureLost() override; + void PaintButtonContents(gfx::Canvas* canvas) override; + + private: + ui::NativeTheme::ExtraParams GetNativeThemeParams() const; + ui::NativeTheme::Part GetNativeThemePart() const; + ui::NativeTheme::State GetNativeThemeState() const; + void RepeaterNotifyClick(); + + Type type_; + + // The repeat controller that we use to repeatedly click the button when the + // mouse button is down. + RepeatController repeater_; +}; + +} // namespace views + +#endif // UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_BUTTON_H_
diff --git a/ui/views/controls/scrollbar/base_scroll_bar_button_unittest.cc b/ui/views/controls/scrollbar/scroll_bar_button_unittest.cc similarity index 83% rename from ui/views/controls/scrollbar/base_scroll_bar_button_unittest.cc rename to ui/views/controls/scrollbar/scroll_bar_button_unittest.cc index 8672169..42b23df58 100644 --- a/ui/views/controls/scrollbar/base_scroll_bar_button_unittest.cc +++ b/ui/views/controls/scrollbar/scroll_bar_button_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ui/views/controls/scrollbar/base_scroll_bar_button.h" +#include "ui/views/controls/scrollbar/scroll_bar_button.h" #include <memory> @@ -34,15 +34,18 @@ MOCK_METHOD(void, ButtonPressed, ()); }; -class BaseScrollBarButtonTest : public testing::Test { +class ScrollBarButtonTest : public testing::Test { public: - BaseScrollBarButtonTest() - : button_(std::make_unique<BaseScrollBarButton>( + ScrollBarButtonTest() + : button_(std::make_unique<ScrollBarButton>( base::BindRepeating(&MockButtonCallback::ButtonPressed, base::Unretained(&callback_)), + ScrollBarButton::Type::kLeft, task_environment_.GetMockTickClock())) {} - ~BaseScrollBarButtonTest() override = default; + ScrollBarButtonTest(const ScrollBarButtonTest&) = delete; + ScrollBarButtonTest& operator=(const ScrollBarButtonTest&) = delete; + ~ScrollBarButtonTest() override = default; protected: testing::StrictMock<MockButtonCallback>& callback() { return callback_; } @@ -64,15 +67,15 @@ } // namespace -TEST_F(BaseScrollBarButtonTest, Metadata) { +TEST_F(ScrollBarButtonTest, Metadata) { test::TestViewMetadata(button()); } -TEST_F(BaseScrollBarButtonTest, FocusBehavior) { +TEST_F(ScrollBarButtonTest, FocusBehavior) { EXPECT_EQ(View::FocusBehavior::NEVER, button()->GetFocusBehavior()); } -TEST_F(BaseScrollBarButtonTest, CallbackFiresOnMouseDown) { +TEST_F(ScrollBarButtonTest, CallbackFiresOnMouseDown) { EXPECT_CALL(callback(), ButtonPressed()); // By default the button should notify its callback on mouse release. @@ -81,7 +84,7 @@ ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); } -TEST_F(BaseScrollBarButtonTest, CallbackFiresMultipleTimesMouseHeldDown) { +TEST_F(ScrollBarButtonTest, CallbackFiresMultipleTimesMouseHeldDown) { EXPECT_CALL(callback(), ButtonPressed()).Times(AtLeast(2)); // By default the button should notify its callback on mouse release. @@ -92,7 +95,7 @@ AdvanceTime(RepeatController::GetInitialWaitForTesting() * 10); } -TEST_F(BaseScrollBarButtonTest, CallbackStopsFiringAfterMouseReleased) { +TEST_F(ScrollBarButtonTest, CallbackStopsFiringAfterMouseReleased) { EXPECT_CALL(callback(), ButtonPressed()).Times(AtLeast(2)); // By default the button should notify its callback on mouse release. @@ -113,7 +116,7 @@ EXPECT_CALL(callback(), ButtonPressed()).Times(AtMost(0)); } -TEST_F(BaseScrollBarButtonTest, CallbackStopsFiringAfterMouseCaptureReleased) { +TEST_F(ScrollBarButtonTest, CallbackStopsFiringAfterMouseCaptureReleased) { EXPECT_CALL(callback(), ButtonPressed()).Times(AtLeast(2)); // By default the button should notify its callback on mouse release.
diff --git a/ui/views/controls/scrollbar/scroll_bar_views.cc b/ui/views/controls/scrollbar/scroll_bar_views.cc index 3674a64..cc635689 100644 --- a/ui/views/controls/scrollbar/scroll_bar_views.cc +++ b/ui/views/controls/scrollbar/scroll_bar_views.cc
@@ -15,9 +15,9 @@ #include "ui/gfx/canvas.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/focusable_border.h" -#include "ui/views/controls/scrollbar/base_scroll_bar_button.h" #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" #include "ui/views/controls/scrollbar/scroll_bar.h" +#include "ui/views/controls/scrollbar/scroll_bar_button.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/view_class_properties.h" @@ -25,32 +25,6 @@ namespace { -// Wrapper for the scroll buttons. -class ScrollBarButton : public BaseScrollBarButton { - public: - enum class Type { - kUp, - kDown, - kLeft, - kRight, - }; - - ScrollBarButton(PressedCallback callback, Type type); - ~ScrollBarButton() override; - - gfx::Size CalculatePreferredSize() const override; - - protected: - void PaintButtonContents(gfx::Canvas* canvas) override; - - private: - ui::NativeTheme::ExtraParams GetNativeThemeParams() const; - ui::NativeTheme::Part GetNativeThemePart() const; - ui::NativeTheme::State GetNativeThemeState() const; - - Type type_; -}; - // Wrapper for the scroll thumb class ScrollBarThumb : public BaseScrollBarThumb { public: @@ -70,75 +44,6 @@ ScrollBar* scroll_bar_; }; -ScrollBarButton::ScrollBarButton(PressedCallback callback, Type type) - : BaseScrollBarButton(std::move(callback)), type_(type) { - SetFlipCanvasOnPaintForRTLUI(true); - DCHECK_EQ(FocusBehavior::NEVER, GetFocusBehavior()); -} - -ScrollBarButton::~ScrollBarButton() = default; - -gfx::Size ScrollBarButton::CalculatePreferredSize() const { - return GetNativeTheme()->GetPartSize( - GetNativeThemePart(), GetNativeThemeState(), GetNativeThemeParams()); -} - -void ScrollBarButton::PaintButtonContents(gfx::Canvas* canvas) { - gfx::Rect bounds(GetPreferredSize()); - GetNativeTheme()->Paint(canvas->sk_canvas(), GetNativeThemePart(), - GetNativeThemeState(), bounds, - GetNativeThemeParams()); -} - -ui::NativeTheme::ExtraParams ScrollBarButton::GetNativeThemeParams() const { - ui::NativeTheme::ExtraParams params; - - switch (GetState()) { - case Button::STATE_HOVERED: - params.scrollbar_arrow.is_hovering = true; - break; - default: - params.scrollbar_arrow.is_hovering = false; - break; - } - - return params; -} - -ui::NativeTheme::Part ScrollBarButton::GetNativeThemePart() const { - switch (type_) { - case Type::kUp: - return ui::NativeTheme::kScrollbarUpArrow; - case Type::kDown: - return ui::NativeTheme::kScrollbarDownArrow; - case Type::kLeft: - return ui::NativeTheme::kScrollbarLeftArrow; - case Type::kRight: - return ui::NativeTheme::kScrollbarRightArrow; - } - - NOTREACHED(); - return ui::NativeTheme::kScrollbarUpArrow; -} - -ui::NativeTheme::State ScrollBarButton::GetNativeThemeState() const { - switch (GetState()) { - case Button::STATE_HOVERED: - return ui::NativeTheme::kHovered; - case Button::STATE_PRESSED: - return ui::NativeTheme::kPressed; - case Button::STATE_DISABLED: - return ui::NativeTheme::kDisabled; - case Button::STATE_NORMAL: - return ui::NativeTheme::kNormal; - case Button::STATE_COUNT: - break; - } - - NOTREACHED(); - return ui::NativeTheme::kNormal; -} - ScrollBarThumb::ScrollBarThumb(ScrollBar* scroll_bar) : BaseScrollBarThumb(scroll_bar), scroll_bar_(scroll_bar) {}
diff --git a/ui/views/controls/scrollbar/scroll_bar_views.h b/ui/views/controls/scrollbar/scroll_bar_views.h index a08f89b..448353e 100644 --- a/ui/views/controls/scrollbar/scroll_bar_views.h +++ b/ui/views/controls/scrollbar/scroll_bar_views.h
@@ -7,7 +7,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" -#include "ui/gfx/geometry/point.h" +#include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/scrollbar/scroll_bar.h" #include "ui/views/view.h"