diff --git a/DEPS b/DEPS index 0998f50..f5fbf56 100644 --- a/DEPS +++ b/DEPS
@@ -129,11 +129,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '99d792276740293109edb22a26fea50490e7eeaf', + 'skia_revision': '76e626d9bb555d2a831b1f91b37e93649bfbd71d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '0ec288d449bc14033c44dd5d0bbcd3f6d64ec9f1', + 'v8_revision': '43d68733271e51914feafc8fe1e0216435d471cb', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -145,7 +145,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '3635a1295b1212fb17cba920b080b381acf6ea4e', + 'swiftshader_revision': '5d64ec4c2dcd5dbeac89a1f5e50bb3d6619081cd', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -196,7 +196,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': 'dc0c991440dbeb33c04e4ad9f52e22c173817abd', + 'catapult_revision': 'd27288f5266a4ebf69de7cc91dc865707425736b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -268,7 +268,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': 'f4c3f4562eeeaeab99a19d4a293d062936c5a2ee', + 'dawn_revision': '51fd66e3dd35d4ed80dc64244a6dd132e2321fa7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -820,7 +820,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': { - 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + '4ebef283ecc4b2a94d68f4b4e1584cdb288a38db', + 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + 'cbd8851734d891ca863b2effef55f43f5ff95d59', 'condition': 'checkout_linux', }, @@ -1172,7 +1172,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '911b1a37708e3ded201d9664602f9670a0acb572', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'de4e8874ae8261e916af8c5e1926149f8b8540d9', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78', @@ -1343,7 +1343,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '688fbfe33779392aa210d67d4aa12cb012f112c2', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '408a3c63d37bdb7e4f3d53a9891dc69c4765e11d', + Var('webrtc_git') + '/src.git' + '@' + '7ddef1af885921e74076b1c2f6695231b48e5ace', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1384,7 +1384,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@21a8eca7b39fba5fd05a3a6be30d061ede7da334', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@3ec1a396fb7932f2fa19253833dd2229394056b4', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/browser/gfx/scoped_app_gl_state_restore.cc b/android_webview/browser/gfx/scoped_app_gl_state_restore.cc index 5025c40..358eaad 100644 --- a/android_webview/browser/gfx/scoped_app_gl_state_restore.cc +++ b/android_webview/browser/gfx/scoped_app_gl_state_restore.cc
@@ -199,8 +199,11 @@ SaveHWUIState(); } - if (mode_ == ScopedAppGLStateRestore::MODE_RESOURCE_MANAGEMENT) { + if (mode_ == ScopedAppGLStateRestore::MODE_RESOURCE_MANAGEMENT && + ::gl::g_current_gl_driver->fn.glBindRenderbufferEXTFn != nullptr) { // Android 5.0.0 specific qualcomm workaround. See crbug.com/434570. + // Null check the binding since checking the proper condition is hard. See + // crbug.com/950472. glBindRenderbufferEXT(GL_RENDERBUFFER, 0); }
diff --git a/ash/system/ime_menu/ime_menu_tray.cc b/ash/system/ime_menu/ime_menu_tray.cc index f94fca0..5ccc86c 100644 --- a/ash/system/ime_menu/ime_menu_tray.cc +++ b/ash/system/ime_menu/ime_menu_tray.cc
@@ -352,7 +352,7 @@ init_params.delegate = this; init_params.parent_window = GetBubbleWindowContainer(); init_params.anchor_view = GetBubbleAnchor(); - init_params.anchor_alignment = GetAnchorAlignment(); + init_params.shelf_alignment = shelf()->alignment(); init_params.min_width = kTrayMenuWidth; init_params.max_width = kTrayMenuWidth; init_params.close_on_deactivate = true;
diff --git a/ash/system/palette/palette_tray.cc b/ash/system/palette/palette_tray.cc index cfe8d531..07bfe15a 100644 --- a/ash/system/palette/palette_tray.cc +++ b/ash/system/palette/palette_tray.cc
@@ -482,7 +482,7 @@ init_params.delegate = this; init_params.parent_window = GetBubbleWindowContainer(); init_params.anchor_view = GetBubbleAnchor(); - init_params.anchor_alignment = GetAnchorAlignment(); + init_params.shelf_alignment = shelf()->alignment(); init_params.min_width = kPaletteWidth; init_params.max_width = kPaletteWidth; init_params.close_on_deactivate = true;
diff --git a/ash/system/tray/tray_background_view.cc b/ash/system/tray/tray_background_view.cc index ae121e9..988af7ff 100644 --- a/ash/system/tray/tray_background_view.cc +++ b/ash/system/tray/tray_background_view.cc
@@ -415,14 +415,6 @@ layer()->SetTransform(transform); } -TrayBubbleView::AnchorAlignment TrayBackgroundView::GetAnchorAlignment() const { - if (shelf_->alignment() == SHELF_ALIGNMENT_LEFT) - return TrayBubbleView::ANCHOR_ALIGNMENT_LEFT; - if (shelf_->alignment() == SHELF_ALIGNMENT_RIGHT) - return TrayBubbleView::ANCHOR_ALIGNMENT_RIGHT; - return TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM; -} - void TrayBackgroundView::SetIsActive(bool is_active) { if (is_active_ == is_active) return; @@ -443,7 +435,8 @@ gfx::Insets TrayBackgroundView::GetBubbleAnchorInsets() const { gfx::Insets anchor_insets = GetBubbleAnchor()->GetInsets(); gfx::Insets tray_bg_insets = GetInsets(); - if (GetAnchorAlignment() == TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM) { + if (shelf_->alignment() == SHELF_ALIGNMENT_BOTTOM || + shelf_->alignment() == SHELF_ALIGNMENT_BOTTOM_LOCKED) { return gfx::Insets(-tray_bg_insets.top(), anchor_insets.left(), -tray_bg_insets.bottom(), anchor_insets.right()); } else {
diff --git a/ash/system/tray/tray_background_view.h b/ash/system/tray/tray_background_view.h index a84344b..8121940 100644 --- a/ash/system/tray/tray_background_view.h +++ b/ash/system/tray/tray_background_view.h
@@ -94,9 +94,6 @@ // May close the bubble. virtual void ClickedOutsideBubble() = 0; - // Returns the bubble anchor alignment based on |shelf_alignment_|. - TrayBubbleView::AnchorAlignment GetAnchorAlignment() const; - void SetIsActive(bool is_active); bool is_active() const { return is_active_; }
diff --git a/ash/system/tray/tray_bubble_view.cc b/ash/system/tray/tray_bubble_view.cc index 1917b07..29ff641 100644 --- a/ash/system/tray/tray_bubble_view.cc +++ b/ash/system/tray/tray_bubble_view.cc
@@ -42,15 +42,19 @@ namespace { -BubbleBorder::Arrow GetArrowAlignment( - TrayBubbleView::AnchorAlignment alignment) { - if (alignment == TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM) { - return base::i18n::IsRTL() ? BubbleBorder::BOTTOM_LEFT - : BubbleBorder::BOTTOM_RIGHT; +BubbleBorder::Arrow GetArrowAlignment(ash::ShelfAlignment alignment) { + // The tray bubble is in a corner. In this case, we want the arrow to be + // flush with one side instead of centered on the bubble. + switch (alignment) { + case ash::SHELF_ALIGNMENT_BOTTOM: + case ash::SHELF_ALIGNMENT_BOTTOM_LOCKED: + return base::i18n::IsRTL() ? BubbleBorder::BOTTOM_LEFT + : BubbleBorder::BOTTOM_RIGHT; + case ash::SHELF_ALIGNMENT_LEFT: + return BubbleBorder::LEFT_BOTTOM; + case ash::SHELF_ALIGNMENT_RIGHT: + return BubbleBorder::RIGHT_BOTTOM; } - if (alignment == TrayBubbleView::ANCHOR_ALIGNMENT_LEFT) - return BubbleBorder::LEFT_BOTTOM; - return BubbleBorder::RIGHT_BOTTOM; } // Only one TrayBubbleView is visible at a time, but there are cases where the @@ -197,7 +201,7 @@ TrayBubbleView::TrayBubbleView(const InitParams& init_params) : BubbleDialogDelegateView(init_params.anchor_view, - GetArrowAlignment(init_params.anchor_alignment)), + GetArrowAlignment(init_params.shelf_alignment)), params_(init_params), layout_(nullptr), delegate_(init_params.delegate), @@ -334,8 +338,7 @@ BubbleDialogDelegateView::SetAnchorRect(rect); } -void TrayBubbleView::ChangeAnchorAlignment( - TrayBubbleView::AnchorAlignment alignment) { +void TrayBubbleView::ChangeAnchorAlignment(ShelfAlignment alignment) { SetArrow(GetArrowAlignment(alignment)); }
diff --git a/ash/system/tray/tray_bubble_view.h b/ash/system/tray/tray_bubble_view.h index 9bc03a9..6ce0ea05 100644 --- a/ash/system/tray/tray_bubble_view.h +++ b/ash/system/tray/tray_bubble_view.h
@@ -8,6 +8,7 @@ #include <memory> #include "ash/ash_export.h" +#include "ash/public/cpp/shelf_types.h" #include "base/macros.h" #include "base/optional.h" #include "ui/accessibility/ax_enums.mojom.h" @@ -41,18 +42,8 @@ class ASH_EXPORT TrayBubbleView : public views::BubbleDialogDelegateView, public views::MouseWatcherListener { public: - // AnchorAlignment determines to which side of the anchor the bubble will - // align itself. - enum AnchorAlignment { - ANCHOR_ALIGNMENT_BOTTOM, - ANCHOR_ALIGNMENT_LEFT, - ANCHOR_ALIGNMENT_RIGHT, - }; - class ASH_EXPORT Delegate { public: - typedef TrayBubbleView::AnchorAlignment AnchorAlignment; - Delegate() {} virtual ~Delegate(); @@ -100,7 +91,7 @@ AnchorMode anchor_mode = AnchorMode::kView; // Only used if anchor_mode == AnchorMode::kRect. gfx::Rect anchor_rect; - AnchorAlignment anchor_alignment = ANCHOR_ALIGNMENT_BOTTOM; + ShelfAlignment shelf_alignment = SHELF_ALIGNMENT_BOTTOM; int min_width = 0; int max_width = 0; int max_height = 0; @@ -153,7 +144,7 @@ void ChangeAnchorRect(const gfx::Rect& anchor_rect); // Change anchor alignment mode when anchoring either the rect or view. - void ChangeAnchorAlignment(AnchorAlignment alignment); + void ChangeAnchorAlignment(ShelfAlignment alignment); // Returns true if the bubble is an anchored status area bubble. Override // this function for a bubble which is not anchored directly to the status
diff --git a/ash/system/tray/tray_popup_utils.cc b/ash/system/tray/tray_popup_utils.cc index ea26228..f15559cb 100644 --- a/ash/system/tray/tray_popup_utils.cc +++ b/ash/system/tray/tray_popup_utils.cc
@@ -203,7 +203,7 @@ } void TrayPopupUtils::ConfigureTrayPopupButton(views::Button* button) { - button->SetFocusPainter(TrayPopupUtils::CreateFocusPainter()); + button->SetInstallFocusRingOnFocus(true); button->SetFocusForPlatform(); button->SetInkDropMode(views::InkDropHostView::InkDropMode::ON);
diff --git a/ash/system/unified/collapse_button.cc b/ash/system/unified/collapse_button.cc index 3bae80f..31ac219 100644 --- a/ash/system/unified/collapse_button.cc +++ b/ash/system/unified/collapse_button.cc
@@ -20,6 +20,7 @@ #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_mask.h" #include "ui/views/border.h" +#include "ui/views/view_class_properties.h" namespace ash { @@ -104,6 +105,9 @@ CollapseButton::CollapseButton(views::ButtonListener* listener) : CustomShapeButton(listener) { OnEnabledChanged(); + auto path = std::make_unique<SkPath>( + CreateCustomShapePath(gfx::Rect(CalculatePreferredSize()))); + SetProperty(views::kHighlightPathKey, path.release()); } CollapseButton::~CollapseButton() = default;
diff --git a/ash/system/unified/sign_out_button.cc b/ash/system/unified/sign_out_button.cc index d061b87..19faf685 100644 --- a/ash/system/unified/sign_out_button.cc +++ b/ash/system/unified/sign_out_button.cc
@@ -16,6 +16,7 @@ #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_mask.h" #include "ui/views/border.h" +#include "ui/views/view_class_properties.h" namespace ash { @@ -29,6 +30,11 @@ label()->SetFontList(views::Label::GetDefaultFontList().Derive( 1, gfx::Font::NORMAL, gfx::Font::Weight::MEDIUM)); TrayPopupUtils::ConfigureTrayPopupButton(this); + + auto path = std::make_unique<SkPath>(); + path->addRoundRect(gfx::RectToSkRect(gfx::Rect(CalculatePreferredSize())), + kTrayItemSize / 2, kTrayItemSize / 2); + SetProperty(views::kHighlightPathKey, path.release()); } RoundedLabelButton::~RoundedLabelButton() = default;
diff --git a/ash/system/unified/unified_slider_bubble_controller.cc b/ash/system/unified/unified_slider_bubble_controller.cc index f88ce28..7b6d90c 100644 --- a/ash/system/unified/unified_slider_bubble_controller.cc +++ b/ash/system/unified/unified_slider_bubble_controller.cc
@@ -157,7 +157,7 @@ TrayBubbleView::InitParams init_params; - init_params.anchor_alignment = tray_->GetAnchorAlignment(); + init_params.shelf_alignment = tray_->shelf()->alignment(); init_params.min_width = kTrayMenuWidth; init_params.max_width = kTrayMenuWidth; init_params.delegate = this;
diff --git a/ash/system/unified/unified_system_tray_bubble.cc b/ash/system/unified/unified_system_tray_bubble.cc index e7096a8..e73c7e6 100644 --- a/ash/system/unified/unified_system_tray_bubble.cc +++ b/ash/system/unified/unified_system_tray_bubble.cc
@@ -75,7 +75,7 @@ time_shown_by_click_ = base::TimeTicks::Now(); TrayBubbleView::InitParams init_params; - init_params.anchor_alignment = tray_->GetAnchorAlignment(); + init_params.shelf_alignment = tray_->shelf()->alignment(); init_params.min_width = kTrayMenuWidth; init_params.max_width = kTrayMenuWidth; init_params.delegate = tray; @@ -303,7 +303,7 @@ int max_height = CalculateMaxHeight(); unified_view_->SetMaxHeight(max_height); bubble_view_->SetMaxHeight(max_height); - bubble_view_->ChangeAnchorAlignment(tray_->GetAnchorAlignment()); + bubble_view_->ChangeAnchorAlignment(tray_->shelf()->alignment()); bubble_view_->ChangeAnchorRect(tray_->shelf()->GetSystemTrayAnchorRect()); }
diff --git a/ash/system/unified/unified_system_tray_view.cc b/ash/system/unified/unified_system_tray_view.cc index 579fa02..2267dc48 100644 --- a/ash/system/unified/unified_system_tray_view.cc +++ b/ash/system/unified/unified_system_tray_view.cc
@@ -27,7 +27,6 @@ #include "ui/views/focus/focus_search.h" #include "ui/views/layout/box_layout.h" #include "ui/views/painter.h" -#include "ui/views/widget/widget.h" namespace ash {
diff --git a/base/json/json_parser_unittest.cc b/base/json/json_parser_unittest.cc index 2c738000..2b792df 100644 --- a/base/json/json_parser_unittest.cc +++ b/base/json/json_parser_unittest.cc
@@ -87,9 +87,8 @@ TestLastThree(parser.get()); ASSERT_TRUE(value); - base::ListValue* list; - EXPECT_TRUE(value->GetAsList(&list)); - EXPECT_EQ(2u, list->GetSize()); + ASSERT_TRUE(value->is_list()); + EXPECT_EQ(2u, value->GetList().size()); } TEST_F(JSONParserTest, ConsumeDictionary) { @@ -101,11 +100,10 @@ TestLastThree(parser.get()); ASSERT_TRUE(value); - base::DictionaryValue* dict; - EXPECT_TRUE(value->GetAsDictionary(&dict)); - std::string str; - EXPECT_TRUE(dict->GetString("abc", &str)); - EXPECT_EQ("def", str); + ASSERT_TRUE(value->is_dict()); + const std::string* str = value->FindStringKey("abc"); + ASSERT_TRUE(str); + EXPECT_EQ("def", *str); } TEST_F(JSONParserTest, ConsumeLiterals) {
diff --git a/base/json/json_perftest.cc b/base/json/json_perftest.cc index d58f034..1e0ea33d 100644 --- a/base/json/json_perftest.cc +++ b/base/json/json_perftest.cc
@@ -5,6 +5,7 @@ #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/memory/ptr_util.h" +#include "base/strings/string_number_conversions.h" #include "base/time/time.h" #include "base/values.h" #include "build/build_config.h" @@ -16,33 +17,33 @@ namespace { // Generates a simple dictionary value with simple data types, a string and a // list. -std::unique_ptr<DictionaryValue> GenerateDict() { - auto root = std::make_unique<DictionaryValue>(); - root->SetDoubleKey("Double", 3.141); - root->SetBoolKey("Bool", true); - root->SetIntKey("Int", 42); - root->SetStringKey("String", "Foo"); +DictionaryValue GenerateDict() { + DictionaryValue root; + root.SetDoubleKey("Double", 3.141); + root.SetBoolKey("Bool", true); + root.SetIntKey("Int", 42); + root.SetStringKey("String", "Foo"); - auto list = std::make_unique<ListValue>(); - list->Set(0, std::make_unique<Value>(2.718)); - list->Set(1, std::make_unique<Value>(false)); - list->Set(2, std::make_unique<Value>(123)); - list->Set(3, std::make_unique<Value>("Bar")); - root->Set("List", std::move(list)); + ListValue list; + list.GetList().emplace_back(2.718); + list.GetList().emplace_back(false); + list.GetList().emplace_back(123); + list.GetList().emplace_back("Bar"); + root.SetKey("List", std::move(list)); return root; } // Generates a tree-like dictionary value with a size of O(breadth ** depth). -std::unique_ptr<DictionaryValue> GenerateLayeredDict(int breadth, int depth) { +DictionaryValue GenerateLayeredDict(int breadth, int depth) { if (depth == 1) return GenerateDict(); - auto root = GenerateDict(); - auto next = GenerateLayeredDict(breadth, depth - 1); + DictionaryValue root = GenerateDict(); + DictionaryValue next = GenerateLayeredDict(breadth, depth - 1); for (int i = 0; i < breadth; ++i) { - root->Set("Dict" + std::to_string(i), next->CreateDeepCopy()); + root.SetKey("Dict" + base::NumberToString(i), next.Clone()); } return root; @@ -53,13 +54,13 @@ class JSONPerfTest : public testing::Test { public: void TestWriteAndRead(int breadth, int depth) { - std::string description = "Breadth: " + std::to_string(breadth) + - ", Depth: " + std::to_string(depth); - auto dict = GenerateLayeredDict(breadth, depth); + std::string description = "Breadth: " + base::NumberToString(breadth) + + ", Depth: " + base::NumberToString(depth); + DictionaryValue dict = GenerateLayeredDict(breadth, depth); std::string json; TimeTicks start_write = TimeTicks::Now(); - JSONWriter::Write(*dict, &json); + JSONWriter::Write(dict, &json); TimeTicks end_write = TimeTicks::Now(); perf_test::PrintResult("Write", "", description, (end_write - start_write).InMillisecondsF(), "ms",
diff --git a/base/json/json_value_converter.cc b/base/json/json_value_converter.cc index 6f772f3..1f83efe 100644 --- a/base/json/json_value_converter.cc +++ b/base/json/json_value_converter.cc
@@ -4,32 +4,54 @@ #include "base/json/json_value_converter.h" +#include "base/strings/utf_string_conversions.h" + namespace base { namespace internal { bool BasicValueConverter<int>::Convert( const base::Value& value, int* field) const { - return value.GetAsInteger(field); + if (!value.is_int()) + return false; + if (field) + *field = value.GetInt(); + return true; } bool BasicValueConverter<std::string>::Convert( const base::Value& value, std::string* field) const { - return value.GetAsString(field); + if (!value.is_string()) + return false; + if (field) + *field = value.GetString(); + return true; } bool BasicValueConverter<string16>::Convert( const base::Value& value, string16* field) const { - return value.GetAsString(field); + if (!value.is_string()) + return false; + if (field) + *field = base::UTF8ToUTF16(value.GetString()); + return true; } bool BasicValueConverter<double>::Convert( const base::Value& value, double* field) const { - return value.GetAsDouble(field); + if (!value.is_double() && !value.is_int()) + return false; + if (field) + *field = value.GetDouble(); + return true; } bool BasicValueConverter<bool>::Convert( const base::Value& value, bool* field) const { - return value.GetAsBoolean(field); + if (!value.is_bool()) + return false; + if (field) + *field = value.GetBool(); + return true; } } // namespace internal
diff --git a/base/json/json_value_converter.h b/base/json/json_value_converter.h index ef081150..4e5d7f2 100644 --- a/base/json/json_value_converter.h +++ b/base/json/json_value_converter.h
@@ -254,25 +254,22 @@ bool Convert(const base::Value& value, std::vector<std::unique_ptr<Element>>* field) const override { - const base::ListValue* list = NULL; - if (!value.GetAsList(&list)) { + if (!value.is_list()) { // The field is not a list. return false; } - field->reserve(list->GetSize()); - for (size_t i = 0; i < list->GetSize(); ++i) { - const base::Value* element = NULL; - if (!list->Get(i, &element)) - continue; - - std::unique_ptr<Element> e(new Element); - if (basic_converter_.Convert(*element, e.get())) { + field->reserve(value.GetList().size()); + size_t i = 0; + for (const Value& element : value.GetList()) { + auto e = std::make_unique<Element>(); + if (basic_converter_.Convert(element, e.get())) { field->push_back(std::move(e)); } else { DVLOG(1) << "failure at " << i << "-th element"; return false; } + i++; } return true; } @@ -290,23 +287,20 @@ bool Convert(const base::Value& value, std::vector<std::unique_ptr<NestedType>>* field) const override { - const base::ListValue* list = NULL; - if (!value.GetAsList(&list)) + if (!value.is_list()) return false; - field->reserve(list->GetSize()); - for (size_t i = 0; i < list->GetSize(); ++i) { - const base::Value* element = NULL; - if (!list->Get(i, &element)) - continue; - - std::unique_ptr<NestedType> nested(new NestedType); - if (converter_.Convert(*element, nested.get())) { + field->reserve(value.GetList().size()); + size_t i = 0; + for (const Value& element : value.GetList()) { + auto nested = std::make_unique<NestedType>(); + if (converter_.Convert(element, nested.get())) { field->push_back(std::move(nested)); } else { DVLOG(1) << "failure at " << i << "-th element"; return false; } + i++; } return true; } @@ -327,23 +321,20 @@ bool Convert(const base::Value& value, std::vector<std::unique_ptr<NestedType>>* field) const override { - const base::ListValue* list = NULL; - if (!value.GetAsList(&list)) + if (!value.is_list()) return false; - field->reserve(list->GetSize()); - for (size_t i = 0; i < list->GetSize(); ++i) { - const base::Value* element = NULL; - if (!list->Get(i, &element)) - continue; - - std::unique_ptr<NestedType> nested(new NestedType); - if ((*convert_func_)(element, nested.get())) { + field->reserve(value.GetList().size()); + size_t i = 0; + for (const Value& element : value.GetList()) { + auto nested = std::make_unique<NestedType>(); + if ((*convert_func_)(&element, nested.get())) { field->push_back(std::move(nested)); } else { DVLOG(1) << "failure at " << i << "-th element"; return false; } + i++; } return true; } @@ -494,15 +485,14 @@ } bool Convert(const base::Value& value, StructType* output) const { - const DictionaryValue* dictionary_value = NULL; - if (!value.GetAsDictionary(&dictionary_value)) + if (!value.is_dict()) return false; for (size_t i = 0; i < fields_.size(); ++i) { const internal::FieldConverterBase<StructType>* field_converter = fields_[i].get(); - const base::Value* field = NULL; - if (dictionary_value->Get(field_converter->field_path(), &field)) { + const base::Value* field = value.FindPath(field_converter->field_path()); + if (field) { if (!field_converter->ConvertField(*field, output)) { DVLOG(1) << "failure at field " << field_converter->field_path(); return false;
diff --git a/base/json/json_value_converter_unittest.cc b/base/json/json_value_converter_unittest.cc index 72ed38ac..a18a31f 100644 --- a/base/json/json_value_converter_unittest.cc +++ b/base/json/json_value_converter_unittest.cc
@@ -48,13 +48,11 @@ } static bool GetValueString(const base::Value* value, std::string* result) { - const base::DictionaryValue* dict = nullptr; - if (!value->GetAsDictionary(&dict)) + const std::string* str = value->FindStringKey("val"); + if (!str) return false; - - if (!dict->GetString("val", result)) - return false; - + if (result) + *result = *str; return true; }
diff --git a/base/json/json_value_serializer_unittest.cc b/base/json/json_value_serializer_unittest.cc index 9c4e8bb9..443c7daa 100644 --- a/base/json/json_value_serializer_unittest.cc +++ b/base/json/json_value_serializer_unittest.cc
@@ -216,26 +216,17 @@ static const char kOriginalSerialization[] = "{\"bool\":true,\"double\":3.14,\"int\":42,\"list\":[1,2],\"null\":null}"; JSONStringValueDeserializer deserializer(kOriginalSerialization); - std::unique_ptr<DictionaryValue> root_dict = - DictionaryValue::From(deserializer.Deserialize(nullptr, nullptr)); + std::unique_ptr<Value> root_dict = deserializer.Deserialize(nullptr, nullptr); ASSERT_TRUE(root_dict); + ASSERT_TRUE(root_dict->is_dict()); - Value* null_value = nullptr; - ASSERT_TRUE(root_dict->Get("null", &null_value)); + Value* null_value = root_dict->FindKey("null"); ASSERT_TRUE(null_value); ASSERT_TRUE(null_value->is_none()); - bool bool_value = false; - ASSERT_TRUE(root_dict->GetBoolean("bool", &bool_value)); - ASSERT_TRUE(bool_value); - - int int_value = 0; - ASSERT_TRUE(root_dict->GetInteger("int", &int_value)); - ASSERT_EQ(42, int_value); - - double double_value = 0.0; - ASSERT_TRUE(root_dict->GetDouble("double", &double_value)); - ASSERT_DOUBLE_EQ(3.14, double_value); + ASSERT_TRUE(root_dict->FindBoolKey("bool").value()); + ASSERT_EQ(42, root_dict->FindIntKey("int").value()); + ASSERT_DOUBLE_EQ(3.14, root_dict->FindDoubleKey("double").value()); std::string test_serialization; JSONStringValueSerializer mutable_serializer(&test_serialization); @@ -298,8 +289,8 @@ "\"}"; // Test JSONWriter interface std::string output_js; - DictionaryValue valueRoot; - valueRoot.SetString("all_chars", all_chars); + Value valueRoot(Value::Type::DICTIONARY); + valueRoot.SetStringKey("all_chars", all_chars); JSONWriter::Write(valueRoot, &output_js); ASSERT_EQ(expected_output, output_js); @@ -311,9 +302,9 @@ TEST(JSONValueSerializerTest, UnicodeStrings) { // unicode string json -> escaped ascii text - DictionaryValue root; + Value root(Value::Type::DICTIONARY); string16 test(WideToUTF16(L"\x7F51\x9875")); - root.SetString("web", test); + root.SetStringKey("web", test); static const char kExpected[] = "{\"web\":\"\xE7\xBD\x91\xE9\xA1\xB5\"}"; @@ -327,18 +318,16 @@ std::unique_ptr<Value> deserial_root = deserializer.Deserialize(nullptr, nullptr); ASSERT_TRUE(deserial_root); - DictionaryValue* dict_root = - static_cast<DictionaryValue*>(deserial_root.get()); - string16 web_value; - ASSERT_TRUE(dict_root->GetString("web", &web_value)); - ASSERT_EQ(test, web_value); + const std::string* web_value = deserial_root->FindStringKey("web"); + ASSERT_TRUE(web_value); + ASSERT_EQ("\xE7\xBD\x91\xE9\xA1\xB5", *web_value); } TEST(JSONValueSerializerTest, HexStrings) { // hex string json -> escaped ascii text - DictionaryValue root; + Value root(Value::Type::DICTIONARY); string16 test(WideToUTF16(L"\x01\x02")); - root.SetString("test", test); + root.SetStringKey("test", test); static const char kExpected[] = "{\"test\":\"\\u0001\\u0002\"}"; @@ -352,20 +341,18 @@ std::unique_ptr<Value> deserial_root = deserializer.Deserialize(nullptr, nullptr); ASSERT_TRUE(deserial_root); - DictionaryValue* dict_root = - static_cast<DictionaryValue*>(deserial_root.get()); - string16 test_value; - ASSERT_TRUE(dict_root->GetString("test", &test_value)); - ASSERT_EQ(test, test_value); + const std::string* test_value = deserial_root->FindStringKey("test"); + ASSERT_TRUE(test_value); + ASSERT_EQ("\u0001\u0002", *test_value); // Test converting escaped regular chars static const char kEscapedChars[] = "{\"test\":\"\\u0067\\u006f\"}"; JSONStringValueDeserializer deserializer2(kEscapedChars); deserial_root = deserializer2.Deserialize(nullptr, nullptr); ASSERT_TRUE(deserial_root); - dict_root = static_cast<DictionaryValue*>(deserial_root.get()); - ASSERT_TRUE(dict_root->GetString("test", &test_value)); - ASSERT_EQ(ASCIIToUTF16("go"), test_value); + test_value = deserial_root->FindStringKey("test"); + ASSERT_TRUE(test_value); + ASSERT_EQ("go", *test_value); } TEST(JSONValueSerializerTest, JSONReaderComments) { @@ -407,26 +394,20 @@ ASSERT_TRUE(PathExists(original_file_path)); JSONFileValueDeserializer deserializer(original_file_path); - std::unique_ptr<DictionaryValue> root_dict = - DictionaryValue::From(deserializer.Deserialize(nullptr, nullptr)); + std::unique_ptr<Value> root_dict = deserializer.Deserialize(nullptr, nullptr); ASSERT_TRUE(root_dict); + ASSERT_TRUE(root_dict->is_dict()); - Value* null_value = nullptr; - ASSERT_TRUE(root_dict->Get("null", &null_value)); + Value* null_value = root_dict->FindKey("null"); ASSERT_TRUE(null_value); ASSERT_TRUE(null_value->is_none()); - bool bool_value = false; - ASSERT_TRUE(root_dict->GetBoolean("bool", &bool_value)); - ASSERT_TRUE(bool_value); + ASSERT_TRUE(root_dict->FindBoolKey("bool").value()); + ASSERT_EQ(42, root_dict->FindIntKey("int").value()); - int int_value = 0; - ASSERT_TRUE(root_dict->GetInteger("int", &int_value)); - ASSERT_EQ(42, int_value); - - std::string string_value; - ASSERT_TRUE(root_dict->GetString("string", &string_value)); - ASSERT_EQ("hello", string_value); + const std::string* string_value = root_dict->FindStringKey("string"); + ASSERT_TRUE(string_value); + ASSERT_EQ("hello", *string_value); // Now try writing. const FilePath written_file_path =
diff --git a/base/json/json_writer_unittest.cc b/base/json/json_writer_unittest.cc index cfe0f60..291a225 100644 --- a/base/json/json_writer_unittest.cc +++ b/base/json/json_writer_unittest.cc
@@ -4,6 +4,7 @@ #include "base/json/json_writer.h" +#include "base/containers/span.h" #include "base/memory/ptr_util.h" #include "base/values.h" #include "build/build_config.h" @@ -57,13 +58,13 @@ // Writer unittests like empty list/dict nesting, // list list nesting, etc. DictionaryValue root_dict; - std::unique_ptr<ListValue> list(new ListValue()); - std::unique_ptr<DictionaryValue> inner_dict(new DictionaryValue()); - inner_dict->SetIntKey("inner int", 10); - list->Append(std::move(inner_dict)); - list->Append(std::make_unique<ListValue>()); - list->AppendBoolean(true); - root_dict.Set("list", std::move(list)); + ListValue list; + DictionaryValue inner_dict; + inner_dict.SetIntKey("inner int", 10); + list.GetList().push_back(std::move(inner_dict)); + list.GetList().emplace_back(Value::Type::LIST); + list.GetList().emplace_back(true); + root_dict.SetKey("list", std::move(list)); // Test the pretty-printer. EXPECT_TRUE(JSONWriter::Write(root_dict, &output_js)); @@ -93,14 +94,14 @@ DictionaryValue period_dict; period_dict.SetIntKey("a.b", 3); period_dict.SetIntKey("c", 2); - std::unique_ptr<DictionaryValue> period_dict2(new DictionaryValue()); - period_dict2->SetIntKey("g.h.i.j", 1); - period_dict.SetWithoutPathExpansion("d.e.f", std::move(period_dict2)); + DictionaryValue period_dict2; + period_dict2.SetIntKey("g.h.i.j", 1); + period_dict.SetKey("d.e.f", std::move(period_dict2)); EXPECT_TRUE(JSONWriter::Write(period_dict, &output_js)); EXPECT_EQ("{\"a.b\":3,\"c\":2,\"d.e.f\":{\"g.h.i.j\":1}}", output_js); DictionaryValue period_dict3; - period_dict3.SetInteger("a.b", 2); + period_dict3.SetIntPath("a.b", 2); period_dict3.SetIntKey("a.b", 1); EXPECT_TRUE(JSONWriter::Write(period_dict3, &output_js)); EXPECT_EQ("{\"a\":{\"b\":2},\"a.b\":1}", output_js); @@ -111,29 +112,31 @@ // Binary values should return errors unless suppressed via the // OPTIONS_OMIT_BINARY_VALUES flag. - std::unique_ptr<Value> root(Value::CreateWithCopiedBuffer("asdf", 4)); - EXPECT_FALSE(JSONWriter::Write(*root, &output_js)); + const auto kBufferSpan = + base::make_span(reinterpret_cast<const uint8_t*>("asdf"), 4); + Value root(kBufferSpan); + EXPECT_FALSE(JSONWriter::Write(root, &output_js)); EXPECT_TRUE(JSONWriter::WriteWithOptions( - *root, JSONWriter::OPTIONS_OMIT_BINARY_VALUES, &output_js)); + root, JSONWriter::OPTIONS_OMIT_BINARY_VALUES, &output_js)); EXPECT_TRUE(output_js.empty()); ListValue binary_list; - binary_list.Append(Value::CreateWithCopiedBuffer("asdf", 4)); - binary_list.Append(std::make_unique<Value>(5)); - binary_list.Append(Value::CreateWithCopiedBuffer("asdf", 4)); - binary_list.Append(std::make_unique<Value>(2)); - binary_list.Append(Value::CreateWithCopiedBuffer("asdf", 4)); + binary_list.GetList().emplace_back(kBufferSpan); + binary_list.GetList().emplace_back(5); + binary_list.GetList().emplace_back(kBufferSpan); + binary_list.GetList().emplace_back(2); + binary_list.GetList().emplace_back(kBufferSpan); EXPECT_FALSE(JSONWriter::Write(binary_list, &output_js)); EXPECT_TRUE(JSONWriter::WriteWithOptions( binary_list, JSONWriter::OPTIONS_OMIT_BINARY_VALUES, &output_js)); EXPECT_EQ("[5,2]", output_js); DictionaryValue binary_dict; - binary_dict.Set("a", Value::CreateWithCopiedBuffer("asdf", 4)); + binary_dict.SetKey("a", Value(kBufferSpan)); binary_dict.SetIntKey("b", 5); - binary_dict.Set("c", Value::CreateWithCopiedBuffer("asdf", 4)); + binary_dict.SetKey("c", Value(kBufferSpan)); binary_dict.SetIntKey("d", 2); - binary_dict.Set("e", Value::CreateWithCopiedBuffer("asdf", 4)); + binary_dict.SetKey("e", Value(kBufferSpan)); EXPECT_FALSE(JSONWriter::Write(binary_dict, &output_js)); EXPECT_TRUE(JSONWriter::WriteWithOptions( binary_dict, JSONWriter::OPTIONS_OMIT_BINARY_VALUES, &output_js));
diff --git a/base/win/embedded_i18n/create_string_rc.py b/base/win/embedded_i18n/create_string_rc.py index e65a8c26..e046b6f 100755 --- a/base/win/embedded_i18n/create_string_rc.py +++ b/base/win/embedded_i18n/create_string_rc.py
@@ -61,7 +61,6 @@ from __future__ import print_function import argparse -import exceptions import glob import io import os @@ -273,20 +272,20 @@ self.language = language self.translation = translation - def __cmp__(self, other): + def __lt__(self, other): """Allow __TranslationDatas to be sorted by id then by language.""" - id_result = cmp(self.resource_id_str, other.resource_id_str) - return cmp(self.language, other.language) if id_result == 0 else id_result + return (self.resource_id_str, self.language) < (other.resource_id_str, + other.language) def __AddModeSpecificStringIds(self): """Adds the mode-specific strings for all of the current brand's install modes to self.string_id_set.""" - for string_id, brands in self.mode_specific_strings.iteritems(): + for string_id, brands in self.mode_specific_strings.items(): brand_strings = brands.get(self.brand) if not brand_strings: - raise exceptions.RuntimeError( - 'No strings declared for brand \'%s\' in MODE_SPECIFIC_STRINGS for ' - 'message %s' % (self.brand, string_id)) + raise RuntimeError( + 'No strings declared for brand \'%s\' in MODE_SPECIFIC_STRINGS for ' + 'message %s' % (self.brand, string_id)) self.string_id_set.update(brand_strings) def __ReadSourceAndTranslatedStrings(self): @@ -359,7 +358,7 @@ # Manually put the source strings as en-US in the list of translated # strings. translated_strings = [] - for string_id, message_text in source_strings.iteritems(): + for string_id, message_text in source_strings.items(): translated_strings.append(self.__TranslationData(string_id, 'EN_US', message_text)) @@ -369,7 +368,7 @@ # message text; hence the message id is mapped to a list of string ids # instead of a single value. translation_ids = {} - for (string_id, message_text) in source_strings.iteritems(): + for (string_id, message_text) in source_strings.items(): message_id = tclib.GenerateMessageId(message_text) translation_ids.setdefault(message_id, []).append(string_id); @@ -384,7 +383,7 @@ if not xtb_filename in source_xtb_files: extra_xtb_files.append(xtb_filename) sax_parser.parse(xtb_filename) - for string_id, message_text in source_strings.iteritems(): + for string_id, message_text in source_strings.items(): translated_string = xtb_handler.translations.get(string_id, message_text) translated_strings.append(self.__TranslationData(string_id, @@ -464,13 +463,13 @@ resource_id += 1 # Handle mode-specific strings. - for string_id, brands in self.mode_specific_strings.iteritems(): + for string_id, brands in self.mode_specific_strings.items(): # Populate the DO_MODE_STRINGS macro. brand_strings = brands.get(self.brand) if not brand_strings: - raise exceptions.RuntimeError( - 'No strings declared for brand \'%s\' in MODE_SPECIFIC_STRINGS for ' - 'message %s' % (self.brand, string_id)) + raise RuntimeError( + 'No strings declared for brand \'%s\' in MODE_SPECIFIC_STRINGS for ' + 'message %s' % (self.brand, string_id)) do_mode_strings_lines.append( ' HANDLE_MODE_STRING(%s_BASE, %s)' % (string_id, ', '.join([ ('%s_BASE' % s) for s in brand_strings]))) @@ -490,7 +489,7 @@ installer_string_mapping_lines.append(' HANDLE_STRING(%s_BASE, %s)' % (string_id, string_id)) - with open(self.header_file, 'wb') as outfile: + with open(self.header_file, 'w') as outfile: outfile.write('\n'.join(lines)) outfile.write('\n#ifndef RC_INVOKED') outfile.write(' \\\n'.join(do_languages_lines))
diff --git a/chrome/android/features/autofill_assistant/BUILD.gn b/chrome/android/features/autofill_assistant/BUILD.gn index 6977726..d6bf08c5 100644 --- a/chrome/android/features/autofill_assistant/BUILD.gn +++ b/chrome/android/features/autofill_assistant/BUILD.gn
@@ -61,6 +61,7 @@ "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java", "java/src/org/chromium/chrome/browser/autofill_assistant/EditDistance.java", "java/src/org/chromium/chrome/browser/autofill_assistant/FeedbackContext.java", + "java/src/org/chromium/chrome/browser/autofill_assistant/SizeListenableLinearLayout.java", "java/src/org/chromium/chrome/browser/autofill_assistant/carousel/AssistantCarouselCoordinator.java", "java/src/org/chromium/chrome/browser/autofill_assistant/carousel/AssistantCarouselModel.java", "java/src/org/chromium/chrome/browser/autofill_assistant/carousel/AssistantChip.java",
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_bottombar_bg.9.png b/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_bottombar_bg.9.png deleted file mode 100644 index 606060d7..0000000 --- a/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_bottombar_bg.9.png +++ /dev/null Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_onboarding_bg.png b/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_onboarding_bg.png new file mode 100644 index 0000000..ffc420d --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_onboarding_bg.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_onboarding_try.png b/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_onboarding_try.png new file mode 100644 index 0000000..48f3c9b0 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-hdpi/autofill_assistant_onboarding_try.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_bottombar_bg.9.png b/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_bottombar_bg.9.png deleted file mode 100644 index 6d12e19..0000000 --- a/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_bottombar_bg.9.png +++ /dev/null Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_onboarding_bg.png b/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_onboarding_bg.png new file mode 100644 index 0000000..2c905707 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_onboarding_bg.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_onboarding_try.png b/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_onboarding_try.png new file mode 100644 index 0000000..211160b --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/autofill_assistant_onboarding_try.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/onboarding_background.png b/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/onboarding_background.png deleted file mode 100644 index 9812e98..0000000 --- a/chrome/android/features/autofill_assistant/java/res/drawable-mdpi/onboarding_background.png +++ /dev/null Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_bottombar_bg.9.png b/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_bottombar_bg.9.png deleted file mode 100644 index cbba344..0000000 --- a/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_bottombar_bg.9.png +++ /dev/null Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_onboarding_bg.png b/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_onboarding_bg.png new file mode 100644 index 0000000..5cd3572 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_onboarding_bg.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_onboarding_try.png b/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_onboarding_try.png new file mode 100644 index 0000000..1fc9003 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-xhdpi/autofill_assistant_onboarding_try.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_bottombar_bg.9.png b/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_bottombar_bg.9.png deleted file mode 100644 index f0ccbfea..0000000 --- a/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_bottombar_bg.9.png +++ /dev/null Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_onboarding_bg.png b/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_onboarding_bg.png new file mode 100644 index 0000000..270e310 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_onboarding_bg.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_onboarding_try.png b/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_onboarding_try.png new file mode 100644 index 0000000..95a2cf71 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/autofill_assistant_onboarding_try.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/onboarding_background.png b/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/onboarding_background.png deleted file mode 100644 index d9fa3c3..0000000 --- a/chrome/android/features/autofill_assistant/java/res/drawable-xxhdpi/onboarding_background.png +++ /dev/null Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_bottombar_bg.9.png b/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_bottombar_bg.9.png deleted file mode 100644 index a286cb21..0000000 --- a/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_bottombar_bg.9.png +++ /dev/null Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_onboarding_bg.png b/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_onboarding_bg.png new file mode 100644 index 0000000..de9d859 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_onboarding_bg.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_onboarding_try.png b/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_onboarding_try.png new file mode 100644 index 0000000..11841dc --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/drawable-xxxhdpi/autofill_assistant_onboarding_try.png Binary files differ
diff --git a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_header.xml b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_bottom_sheet_content.xml similarity index 74% rename from chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_header.xml rename to chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_bottom_sheet_content.xml index 58de6501..c6eb441 100644 --- a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_header.xml +++ b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_bottom_sheet_content.xml
@@ -2,10 +2,21 @@ <!-- Copyright 2018 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. --> -<merge +<org.chromium.chrome.browser.autofill_assistant.SizeListenableLinearLayout + xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" > + android:id="@+id/autofill_assistant" + android:clickable="true" + android:layout_height="wrap_content" + android:layout_width="match_parent" + android:paddingTop="12dp" + android:paddingBottom="@dimen/autofill_assistant_bottombar_vertical_spacing" + android:animateLayoutChanges="true" + android:clipChildren="false" + android:clipToPadding="false" + android:orientation="vertical"> <LinearLayout + android:id="@+id/header" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="56dp" @@ -43,4 +54,4 @@ android:layout_marginEnd="@dimen/autofill_assistant_bottombar_horizontal_spacing" app:colorBackground="@color/modern_grey_100" app:colorProgress="@color/modern_blue_600"/> -</merge> +</org.chromium.chrome.browser.autofill_assistant.SizeListenableLinearLayout>
diff --git a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_bottom_sheet_toolbar.xml b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_bottom_sheet_toolbar.xml new file mode 100644 index 0000000..8c71681c --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_bottom_sheet_toolbar.xml
@@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2018 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> +<LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:layout_width="match_parent" + android:layout_height="20dp" + android:paddingTop="8dp" + android:paddingBottom="8dp" + android:orientation="horizontal" + android:gravity="center_horizontal"> + + <ImageView + android:id="@+id/swipe_indicator" + android:layout_width="36dp" + android:layout_height="4dp" + android:layout_gravity="center_horizontal" + android:src="@drawable/autofill_assistant_swipe_indicator" + tools:ignore="ContentDescription" /> + +</LinearLayout> \ No newline at end of file
diff --git a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_onboarding.xml b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_onboarding.xml index 86d9e46..91f71b4 100644 --- a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_onboarding.xml +++ b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_onboarding.xml
@@ -12,6 +12,7 @@ android:orientation="vertical"> <org.chromium.chrome.browser.widget.FadingEdgeScrollView + android:id="@+id/onboarding_scroll_view" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent"> @@ -24,45 +25,63 @@ android:paddingStart="24dp" android:paddingEnd="24dp"> + <Space android:layout_width="0dp" android:layout_height="12dp"/> + <!-- Image background --> <ImageView + android:id="@+id/onboarding_image" tools:ignore="contentDescription" android:layout_width="250dp" - android:layout_height="141dp" - android:scaleType="centerCrop" - android:src="@drawable/onboarding_background" - android:paddingBottom="15dp"/> - - <!-- Title (e.g., 'Fast Checkout')--> - <TextView android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:textAppearance="@style/TextAppearance.AssistantBlackTitle" - android:gravity="center_horizontal" - android:text="@string/autofill_assistant_onboarding_title" /> + android:scaleType="centerCrop" + android:src="@drawable/autofill_assistant_onboarding_bg" + android:layout_marginTop="12dp" /> + + <!-- "Try Google Assistant in Chrome" --> + <ImageView + android:id="@+id/onboarding_try_assistant" + tools:ignore="contentDescription" + android:layout_width="185dp" + android:layout_height="wrap_content" + android:layout_marginTop="16dp" + android:src="@drawable/autofill_assistant_onboarding_try" /> <!-- Subtitle (e.g., 'Google Assistant saves you time...')--> - <Space android:layout_width="0dp" android:layout_height="16dp"/> - <TextView - android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:textAppearance="@style/TextAppearance.AssistantBlackBody" - android:paddingStart="12dp" - android:paddingEnd="12dp" - android:gravity="center_horizontal" - android:text="@string/autofill_assistant_init_message" /> - - <!-- Separator --> - <Space android:layout_width="0dp" android:layout_height="24dp"/> <LinearLayout android:layout_width="match_parent" + android:layout_height="wrap_content"> + <Space + android:layout_width="0dp" + android:layout_height="1dp" + android:layout_weight="1"/> + <!-- The subtitle takes 4/6 of the screen width. --> + <TextView + android:id="@+id/onboarding_subtitle" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="4" + android:layout_marginTop="24dp" + android:textAppearance="@style/TextAppearance.AssistantBlackBody" + android:gravity="center_horizontal" + android:text="@string/autofill_assistant_init_message" /> + <Space + android:layout_width="0dp" + android:layout_height="1dp" + android:layout_weight="1"/> + </LinearLayout> + + <!-- Separator --> + <LinearLayout + android:id="@+id/onboarding_separator" + android:layout_width="match_parent" android:layout_height="wrap_content" + android:layout_marginTop="24dp" android:gravity="center_horizontal" android:orientation="horizontal" android:weightSum="1.0"> <View style="@style/HorizontalDivider" android:layout_width="0dp" - android:layout_height="2dp" + android:layout_height="1dp" android:layout_weight="0.33"/> </LinearLayout> <Space android:layout_width="0dp" android:layout_height="24dp"/> @@ -71,10 +90,7 @@ <LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" - android:paddingStart="12dp" - android:paddingEnd="12dp" android:paddingBottom="9dp"> - <TextView android:id="@+id/google_terms_message" android:layout_width="wrap_content"
diff --git a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_sheet.xml b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_sheet.xml deleted file mode 100644 index cab8ba0..0000000 --- a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_sheet.xml +++ /dev/null
@@ -1,56 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2018 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. --> -<FrameLayout - xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - xmlns:tools="http://schemas.android.com/tools" - android:id="@+id/autofill_assistant" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:gravity="bottom"> - - <android.support.design.widget.CoordinatorLayout - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_gravity="bottom"> - - <LinearLayout - android:id="@+id/autofill_assistant_bottombar" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_gravity="bottom" - android:clickable="true" - android:background="@drawable/autofill_assistant_bottombar_bg" - android:orientation="vertical" - app:behavior_peekHeight="34dp" - app:layout_behavior="@string/bottom_sheet_behavior"> - - <ImageView - android:id="@+id/swipe_indicator" - android:layout_width="36dp" - android:layout_height="wrap_content" - android:layout_marginTop="20dp" - android:layout_gravity="center_horizontal" - android:src="@drawable/autofill_assistant_swipe_indicator" - tools:ignore="ContentDescription" /> - - <include - layout="@layout/autofill_assistant_header"/> - - <LinearLayout - android:id="@+id/autofill_assistant_bottombar_container" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:clipChildren="false" - android:clipToPadding="false" - android:paddingBottom="@dimen/autofill_assistant_bottombar_vertical_spacing" - android:orientation="vertical" - android:gravity="center" - android:animateLayoutChanges="true" > - </LinearLayout> - - </LinearLayout> - </android.support.design.widget.CoordinatorLayout> -</FrameLayout>
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java index f386377..f3cf7a4 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java
@@ -5,42 +5,38 @@ package org.chromium.chrome.browser.autofill_assistant; import android.content.Context; -import android.support.design.widget.BottomSheetBehavior; -import android.support.design.widget.CoordinatorLayout; -import android.util.DisplayMetrics; -import android.util.TypedValue; +import android.graphics.Color; +import android.support.annotation.Nullable; +import android.view.LayoutInflater; import android.view.View; -import android.view.ViewGroup; import android.widget.LinearLayout; +import android.widget.ScrollView; +import org.chromium.base.ApiCompatibilityUtils; +import org.chromium.base.Callback; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.autofill_assistant.carousel.AssistantCarouselCoordinator; import org.chromium.chrome.browser.autofill_assistant.carousel.AssistantChip; import org.chromium.chrome.browser.autofill_assistant.details.AssistantDetailsCoordinator; import org.chromium.chrome.browser.autofill_assistant.header.AssistantHeaderCoordinator; +import org.chromium.chrome.browser.autofill_assistant.header.AssistantHeaderModel; import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBoxCoordinator; +import org.chromium.chrome.browser.autofill_assistant.overlay.AssistantOverlayModel; +import org.chromium.chrome.browser.autofill_assistant.overlay.AssistantOverlayState; import org.chromium.chrome.browser.autofill_assistant.payment.AssistantPaymentRequestCoordinator; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; +import org.chromium.chrome.browser.widget.bottomsheet.EmptyBottomSheetObserver; import org.chromium.ui.modelutil.ListModel; /** - * Coordinator responsible for the Autofill Assistant bottom bar. This coordinator allows to enable - * or disable the swipeable behavior of the bottom bar and ensures that the bottom bar height is - * constant during the script execution (if possible) by adapting the spacing between its child - * views (details, infobox, payment request and carousel). + * Coordinator responsible for the Autofill Assistant bottom bar. */ class AssistantBottomBarCoordinator { - // The top padding that should be applied to the bottom bar when the swiping indicator is - // hidden. - private static final int BOTTOM_BAR_WITHOUT_INDICATOR_PADDING_TOP_DP = 16; - - private final ViewGroup mBottomBarView; - private final ViewGroup mBottomBarContainerView; - private final View mSwipeIndicatorView; - private final BottomSheetBehavior mBottomBarBehavior; - - // Dimensions in device pixels. - private final int mBottomBarWithoutIndicatorPaddingTop; + private final AssistantModel mModel; + private final BottomSheetController mBottomSheetController; + private final AssistantBottomSheetContent mContent; // Child coordinators. private AssistantInfoBoxCoordinator mInfoBoxCoordinator; @@ -50,21 +46,18 @@ private final AssistantCarouselCoordinator mSuggestionsCoordinator; private final AssistantCarouselCoordinator mActionsCoordinator; - AssistantBottomBarCoordinator(Context context, View assistantView, AssistantModel model) { - mBottomBarView = assistantView.findViewById(R.id.autofill_assistant_bottombar); - mBottomBarContainerView = - mBottomBarView.findViewById(R.id.autofill_assistant_bottombar_container); - mSwipeIndicatorView = mBottomBarView.findViewById(R.id.swipe_indicator); - mBottomBarBehavior = BottomSheetBehavior.from(mBottomBarView); + @Nullable + private ScrollView mOnboardingScrollView; - DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); - mBottomBarWithoutIndicatorPaddingTop = - (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, - BOTTOM_BAR_WITHOUT_INDICATOR_PADDING_TOP_DP, displayMetrics); + AssistantBottomBarCoordinator( + Context context, AssistantModel model, BottomSheetController controller) { + mModel = model; + mBottomSheetController = controller; + mContent = new AssistantBottomSheetContent(context); // Instantiate child components. - mHeaderCoordinator = - new AssistantHeaderCoordinator(context, mBottomBarView, model.getHeaderModel()); + mHeaderCoordinator = new AssistantHeaderCoordinator( + context, mContent.mBottomBarView, model.getHeaderModel()); mInfoBoxCoordinator = new AssistantInfoBoxCoordinator(context, model.getInfoBoxModel()); mDetailsCoordinator = new AssistantDetailsCoordinator(context, model.getDetailsModel()); mPaymentRequestCoordinator = @@ -74,16 +67,16 @@ mActionsCoordinator = new AssistantCarouselCoordinator(context, model.getActionsModel()); // Add child views to bottom bar container. - mBottomBarContainerView.addView(mInfoBoxCoordinator.getView()); - mBottomBarContainerView.addView(mDetailsCoordinator.getView()); - mBottomBarContainerView.addView(mPaymentRequestCoordinator.getView()); - mBottomBarContainerView.addView(mSuggestionsCoordinator.getView()); - mBottomBarContainerView.addView(mActionsCoordinator.getView()); + mContent.mBottomBarView.addView(mInfoBoxCoordinator.getView()); + mContent.mBottomBarView.addView(mDetailsCoordinator.getView()); + mContent.mBottomBarView.addView(mPaymentRequestCoordinator.getView()); + mContent.mBottomBarView.addView(mSuggestionsCoordinator.getView()); + mContent.mBottomBarView.addView(mActionsCoordinator.getView()); // Set children top margins to have a spacing between them. For the carousels, we set their // margin only when they are not empty given that they are always shown, even if empty. We // do not hide them because there is an incompatibility bug between the animateLayoutChanges - // attribute set on mBottomBarContainerView and the animations ran by the carousels + // attribute set on mBottomBarView and the animations ran by the carousels // RecyclerView. int childSpacing = context.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_bottombar_vertical_spacing); @@ -100,6 +93,32 @@ setHorizontalMargins(mInfoBoxCoordinator.getView()); setHorizontalMargins(mDetailsCoordinator.getView()); setHorizontalMargins(mPaymentRequestCoordinator.getView()); + + // Set the toolbar background color to white only in the PEEK state, to make sure it does + // not hide parts of the content view (which it overlaps). + controller.getBottomSheet().addObserver(new EmptyBottomSheetObserver() { + @Override + public void onSheetOpened(int reason) { + mContent.mToolbarView.setBackgroundColor(Color.TRANSPARENT); + } + + @Override + public void onSheetClosed(int reason) { + mContent.mToolbarView.setBackgroundColor(ApiCompatibilityUtils.getColor( + context.getResources(), R.color.modern_primary_color)); + } + }); + + // Show or hide the bottom sheet content when the Autofill Assistant visibility is changed. + model.addObserver((source, propertyKey) -> { + if (AssistantModel.VISIBLE == propertyKey) { + if (model.get(AssistantModel.VISIBLE)) { + showAndExpand(); + } else { + hide(); + } + } + }); } /** @@ -111,44 +130,46 @@ } /** - * Return the container view representing the bottom bar. Adding child views to this view should - * add them below the header. + * Show the onboarding screen and call {@code callback} with {@code true} if the user agreed to + * proceed, false otherwise. */ - public ViewGroup getView() { - return mBottomBarView; + public void showOnboarding(Callback<Boolean> callback) { + mModel.getHeaderModel().set(AssistantHeaderModel.VISIBLE, false); + + // Show overlay to prevent user from interacting with the page during onboarding. + mModel.getOverlayModel().set(AssistantOverlayModel.STATE, AssistantOverlayState.FULL); + + View onboardingView = AssistantOnboardingCoordinator.show( + mContent.mBottomBarView.getContext(), mContent.mBottomBarView, accepted -> { + mOnboardingScrollView = null; + if (!accepted) { + callback.onResult(false); + return; + } + + mModel.getHeaderModel().set(AssistantHeaderModel.VISIBLE, true); + + // Hide overlay. + mModel.getOverlayModel().set( + AssistantOverlayModel.STATE, AssistantOverlayState.HIDDEN); + + callback.onResult(true); + }); + mOnboardingScrollView = onboardingView.findViewById(R.id.onboarding_scroll_view); } - /** - * Returns the view container inside the bottom bar view. - */ - public ViewGroup getContainerView() { - return mBottomBarContainerView; - } - - /** - * Make sure the bottom bar is expanded and text is visible. - */ - public void expand() { - mBottomBarBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); - } - - /** - * Enable or disable to swipeable behavior of the bottom bar. - */ - public void allowSwipingBottomSheet(boolean allowed) { - CoordinatorLayout.LayoutParams params = - (CoordinatorLayout.LayoutParams) mBottomBarView.getLayoutParams(); - if (allowed) { - params.setBehavior(mBottomBarBehavior); - mSwipeIndicatorView.setVisibility(View.VISIBLE); - setBottomBarPaddingTop(0); - } else { - params.setBehavior(null); - mSwipeIndicatorView.setVisibility(View.GONE); - setBottomBarPaddingTop(mBottomBarWithoutIndicatorPaddingTop); + /** Request showing the Assistant bottom bar view and expand the sheet. */ + public void showAndExpand() { + if (mBottomSheetController.requestShowContent(mContent, /* animate= */ true)) { + mBottomSheetController.expandSheet(); } } + /** Hide the Assistant bottom bar view. */ + public void hide() { + mBottomSheetController.hideContent(mContent, /* animate= */ true); + } + private void setChildMarginTop(View child, int marginTop) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) child.getLayoutParams(); params.topMargin = marginTop; @@ -179,10 +200,6 @@ return mActionsCoordinator; } - private void setBottomBarPaddingTop(int paddingPx) { - mBottomBarView.setPadding(0, paddingPx, 0, 0); - } - private void setHorizontalMargins(View view) { LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams(); int horizontalMargin = view.getContext().getResources().getDimensionPixelSize( @@ -191,4 +208,102 @@ layoutParams.setMarginEnd(horizontalMargin); view.setLayoutParams(layoutParams); } + + // TODO(crbug.com/806868): Move this class at the top of the file once it is a static class. + private class AssistantBottomSheetContent implements BottomSheet.BottomSheetContent { + private final View mToolbarView; + private final SizeListenableLinearLayout mBottomBarView; + + public AssistantBottomSheetContent(Context context) { + mToolbarView = LayoutInflater.from(context).inflate( + R.layout.autofill_assistant_bottom_sheet_toolbar, /* root= */ null); + mBottomBarView = (SizeListenableLinearLayout) LayoutInflater.from(context).inflate( + R.layout.autofill_assistant_bottom_sheet_content, /* root= */ null); + } + + @Override + public View getContentView() { + return mBottomBarView; + } + + @Nullable + @Override + public View getToolbarView() { + return mToolbarView; + } + + @Override + public int getVerticalScrollOffset() { + // TODO(crbug.com/806868): Have a single ScrollView container that contains all child + // views (except carousels) instead. + if (mOnboardingScrollView != null && mOnboardingScrollView.isShown()) { + return mOnboardingScrollView.getScrollY(); + } + + if (mPaymentRequestCoordinator.getView().isShown()) { + return mPaymentRequestCoordinator.getView().getScrollY(); + } + + return 0; + } + + @Override + public void destroy() {} + + @Override + public int getPriority() { + return BottomSheet.ContentPriority.HIGH; + } + + @Override + public boolean swipeToDismissEnabled() { + return false; + } + + @Override + public boolean isPeekStateEnabled() { + return true; + } + + @Override + public boolean wrapContentEnabled() { + return true; + } + + @Override + public boolean hasCustomLifecycle() { + return true; + } + + @Override + public boolean hasCustomScrimLifecycle() { + return true; + } + + @Override + public boolean setContentSizeListener(@Nullable BottomSheet.ContentSizeListener listener) { + mBottomBarView.setContentSizeListener(listener); + return true; + } + + @Override + public int getSheetContentDescriptionStringId() { + return R.string.autofill_assistant_sheet_content_description; + } + + @Override + public int getSheetHalfHeightAccessibilityStringId() { + return R.string.autofill_assistant_sheet_half_height; + } + + @Override + public int getSheetFullHeightAccessibilityStringId() { + return R.string.autofill_assistant_sheet_full_height; + } + + @Override + public int getSheetClosedAccessibilityStringId() { + return R.string.autofill_assistant_sheet_closed; + } + } }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantCoordinator.java index b9c90b6..c34edfa 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantCoordinator.java
@@ -4,18 +4,12 @@ package org.chromium.chrome.browser.autofill_assistant; -import android.view.View; -import android.view.ViewGroup; - -import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.ChromeActivity; -import org.chromium.chrome.browser.autofill_assistant.header.AssistantHeaderModel; import org.chromium.chrome.browser.autofill_assistant.metrics.DropOutReason; import org.chromium.chrome.browser.autofill_assistant.overlay.AssistantOverlayCoordinator; -import org.chromium.chrome.browser.autofill_assistant.overlay.AssistantOverlayModel; -import org.chromium.chrome.browser.autofill_assistant.overlay.AssistantOverlayState; import org.chromium.chrome.browser.help.HelpAndFeedback; import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; /** * The main coordinator for the Autofill Assistant, responsible for instantiating all other @@ -37,60 +31,27 @@ private final Delegate mDelegate; private final AssistantModel mModel; - private final View mAssistantView; - private AssistantBottomBarCoordinator mBottomBarCoordinator; private final AssistantKeyboardCoordinator mKeyboardCoordinator; private final AssistantOverlayCoordinator mOverlayCoordinator; - /** - * Returns {@code true} if an AA UI is active on the given activity. - * - * <p>Used to avoid creating duplicate coordinators views. - * - * <p>TODO(crbug.com/806868): Refactor to have AssistantCoordinator owned by the activity, so - * it's easy to guarantee that there will be at most one per activity. - */ - static boolean isActive(ChromeActivity activity) { - View found = activity.findViewById(R.id.autofill_assistant); - return found != null && found.getParent() != null; - } - - AssistantCoordinator(ChromeActivity activity, Delegate delegate) { + AssistantCoordinator( + ChromeActivity activity, Delegate delegate, BottomSheetController controller) { mActivity = activity; mDelegate = delegate; mModel = new AssistantModel(); - // Inflate autofill_assistant_sheet layout and add it to the main coordinator view. - ViewGroup coordinator = activity.findViewById(R.id.coordinator); - mAssistantView = activity.getLayoutInflater() - .inflate(R.layout.autofill_assistant_sheet, coordinator) - .findViewById(R.id.autofill_assistant); - // Instantiate child components. - mBottomBarCoordinator = new AssistantBottomBarCoordinator(activity, mAssistantView, mModel); - mKeyboardCoordinator = new AssistantKeyboardCoordinator(activity); + mBottomBarCoordinator = new AssistantBottomBarCoordinator(activity, mModel, controller); + mKeyboardCoordinator = new AssistantKeyboardCoordinator(activity, mModel); mOverlayCoordinator = new AssistantOverlayCoordinator(activity, mModel.getOverlayModel()); - // Listen when we should (dis)allow the soft keyboard or swiping the bottom sheet. - mModel.addObserver((source, propertyKey) -> { - if (AssistantModel.ALLOW_SOFT_KEYBOARD == propertyKey) { - mKeyboardCoordinator.allowShowingSoftKeyboard( - mModel.get(AssistantModel.ALLOW_SOFT_KEYBOARD)); - } else if (AssistantModel.ALLOW_SWIPING_SHEET == propertyKey) { - mBottomBarCoordinator.allowSwipingBottomSheet( - mModel.get(AssistantModel.ALLOW_SWIPING_SHEET)); - } else if (AssistantModel.VISIBLE == propertyKey) { - setVisible(mModel.get(AssistantModel.VISIBLE)); - } - }); mModel.setVisible(true); } /** Detaches and destroys the view. */ public void destroy() { - setVisible(false); - detachAssistantView(); + mModel.setVisible(false); mOverlayCoordinator.destroy(); mBottomBarCoordinator.destroy(); mBottomBarCoordinator = null; @@ -101,30 +62,13 @@ * otherwise. */ public void showOnboarding(Runnable onAccept) { - mModel.getHeaderModel().set(AssistantHeaderModel.FEEDBACK_VISIBLE, false); - - // Show overlay to prevent user from interacting with the page during onboarding. - mModel.getOverlayModel().set(AssistantOverlayModel.STATE, AssistantOverlayState.FULL); - - // Disable swiping for the onboarding because it interferes with letting the user scroll - // the onboarding contents. - mBottomBarCoordinator.allowSwipingBottomSheet(false); - AssistantOnboardingCoordinator.show(mActivity, mBottomBarCoordinator.getContainerView()) - .then(accepted -> { - mBottomBarCoordinator.allowSwipingBottomSheet(true); - if (!accepted) { - mDelegate.stop(DropOutReason.DECLINED); - return; - } - - mModel.getHeaderModel().set(AssistantHeaderModel.FEEDBACK_VISIBLE, true); - - // Hide overlay. - mModel.getOverlayModel().set( - AssistantOverlayModel.STATE, AssistantOverlayState.HIDDEN); - - onAccept.run(); - }); + mBottomBarCoordinator.showOnboarding(accepted -> { + if (accepted) { + onAccept.run(); + } else { + mDelegate.stop(DropOutReason.DECLINED); + } + }); } /** @@ -149,25 +93,4 @@ mActivity.getActivityTab().getUrl(), FEEDBACK_CATEGORY_TAG, FeedbackContext.buildContextString(mActivity, debugContext, 4)); } - - // Private methods. - - private void setVisible(boolean visible) { - if (visible) { - mAssistantView.setVisibility(View.VISIBLE); - mKeyboardCoordinator.enableListenForKeyboardVisibility(true); - - mBottomBarCoordinator.expand(); - mBottomBarCoordinator.getView().announceForAccessibility( - mActivity.getString(R.string.autofill_assistant_available_accessibility)); - } else { - mAssistantView.setVisibility(View.GONE); - mKeyboardCoordinator.enableListenForKeyboardVisibility(false); - } - // TODO(crbug.com/806868): Control visibility of bottom bar and overlay separately. - } - - private void detachAssistantView() { - mActivity.<ViewGroup>findViewById(R.id.coordinator).removeView(mAssistantView); - } }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantKeyboardCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantKeyboardCoordinator.java index d61f702..38b75ec 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantKeyboardCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantKeyboardCoordinator.java
@@ -18,15 +18,27 @@ this::onKeyboardVisibilityChanged; private boolean mAllowShowingSoftKeyboard = true; - AssistantKeyboardCoordinator(ChromeActivity activity) { + AssistantKeyboardCoordinator(ChromeActivity activity, AssistantModel model) { mActivity = activity; mKeyboardDelegate = activity.getWindowAndroid().getKeyboardDelegate(); + + model.addObserver((source, propertyKey) -> { + if (AssistantModel.VISIBLE == propertyKey) { + if (model.get(AssistantModel.VISIBLE)) { + enableListenForKeyboardVisibility(true); + } else { + enableListenForKeyboardVisibility(false); + } + } else if (AssistantModel.ALLOW_SOFT_KEYBOARD == propertyKey) { + allowShowingSoftKeyboard(model.get(AssistantModel.ALLOW_SOFT_KEYBOARD)); + } + }); } /** * Enable or disable the soft keyboard. */ - public void allowShowingSoftKeyboard(boolean allowed) { + private void allowShowingSoftKeyboard(boolean allowed) { mAllowShowingSoftKeyboard = allowed; if (!allowed) { mKeyboardDelegate.hideKeyboard(mActivity.getCompositorViewHolder()); @@ -36,7 +48,7 @@ /** * Start or stop listening for keyboard visibility changes. */ - public void enableListenForKeyboardVisibility(boolean enabled) { + private void enableListenForKeyboardVisibility(boolean enabled) { if (enabled) { mKeyboardDelegate.addKeyboardVisibilityListener(mKeyboardVisibilityListener); } else {
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantModel.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantModel.java index 18e498bc..edb190d2 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantModel.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantModel.java
@@ -20,7 +20,6 @@ @JNINamespace("autofill_assistant") class AssistantModel extends PropertyModel { static final WritableBooleanPropertyKey ALLOW_SOFT_KEYBOARD = new WritableBooleanPropertyKey(); - static final WritableBooleanPropertyKey ALLOW_SWIPING_SHEET = new WritableBooleanPropertyKey(); static final WritableBooleanPropertyKey VISIBLE = new WritableBooleanPropertyKey(); private final AssistantOverlayModel mOverlayModel = new AssistantOverlayModel(); @@ -33,7 +32,7 @@ private final AssistantCarouselModel mActionsModel = new AssistantCarouselModel(); AssistantModel() { - super(ALLOW_SOFT_KEYBOARD, ALLOW_SWIPING_SHEET, VISIBLE); + super(ALLOW_SOFT_KEYBOARD, VISIBLE); } @CalledByNative @@ -75,11 +74,6 @@ } @CalledByNative - private void setAllowSwipingSheet(boolean allowed) { - set(ALLOW_SWIPING_SHEET, allowed); - } - - @CalledByNative void setVisible(boolean visible) { set(VISIBLE, visible); }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantOnboardingCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantOnboardingCoordinator.java index 1142f1cb..ed6bcebe 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantOnboardingCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantOnboardingCoordinator.java
@@ -12,7 +12,7 @@ import android.view.ViewGroup; import android.widget.TextView; -import org.chromium.base.Promise; +import org.chromium.base.Callback; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.customtabs.CustomTabActivity; import org.chromium.ui.text.NoUnderlineClickableSpan; @@ -23,11 +23,13 @@ * Assistant for the first time. */ class AssistantOnboardingCoordinator { + // TODO(crbug.com/806868): Wire this with A/B experiment. + private static final boolean SHOW_SMALL_ONBOARDING = false; + /** * Shows the onboarding screen and returns whether we should proceed. */ - static Promise<Boolean> show(Context context, ViewGroup root) { - Promise<Boolean> promise = new Promise<>(); + static View show(Context context, ViewGroup root, Callback<Boolean> callback) { View initView = LayoutInflater.from(context) .inflate(R.layout.autofill_assistant_onboarding, root) .findViewById(R.id.assistant_onboarding); @@ -50,18 +52,30 @@ initView.setFocusable(true); initView.findViewById(R.id.button_init_ok) - .setOnClickListener(unusedView -> onClicked(true, root, initView, promise)); + .setOnClickListener(unusedView -> onClicked(true, root, initView, callback)); initView.findViewById(R.id.button_init_not_ok) - .setOnClickListener(unusedView -> onClicked(false, root, initView, promise)); + .setOnClickListener(unusedView -> onClicked(false, root, initView, callback)); initView.announceForAccessibility( context.getString(R.string.autofill_assistant_first_run_accessibility)); - return promise; + + // Hide views that should not be displayed when showing the small onboarding. + if (SHOW_SMALL_ONBOARDING) { + hide(initView, R.id.onboarding_image); + hide(initView, R.id.onboarding_subtitle); + hide(initView, R.id.onboarding_separator); + } + + return initView; + } + + private static void hide(View root, int resId) { + root.findViewById(resId).setVisibility(View.GONE); } private static void onClicked( - boolean accept, ViewGroup root, View initView, Promise<Boolean> promise) { + boolean accept, ViewGroup root, View initView, Callback<Boolean> callback) { AutofillAssistantPreferencesUtil.setInitialPreferences(accept); root.removeView(initView); - promise.fulfill(accept); + callback.onResult(accept); } }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java index bbbd993..83eef5e 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java
@@ -21,11 +21,14 @@ import org.chromium.chrome.browser.customtabs.CustomTabActivity; import org.chromium.chrome.browser.snackbar.SnackbarManager.SnackbarController; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.content_public.browser.WebContents; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; /** * Bridge to native side autofill_assistant::UiControllerAndroid. It allows native side to control @@ -37,6 +40,7 @@ // TODO(crbug.com/806868): This class should be removed once all logic is in native side and the // model is directly modified by the native AssistantMediator. class AutofillAssistantUiController implements AssistantCoordinator.Delegate { + private static Set<ChromeActivity> sActiveChromeActivities; private long mNativeUiController; private final ChromeActivity mActivity; @@ -54,25 +58,49 @@ @Nullable private static ChromeActivity findAppropriateActivity(WebContents webContents) { ChromeActivity activity = ChromeActivity.fromWebContents(webContents); - if (activity != null && AssistantCoordinator.isActive(activity)) { + if (activity != null && isActive(activity)) { return null; } return activity; } + /** + * Returns {@code true} if an AA UI is active on the given activity. + * + * <p>Used to avoid creating duplicate coordinators views. + * + * <p>TODO(crbug.com/806868): Refactor to have AssistantCoordinator owned by the activity, so + * it's easy to guarantee that there will be at most one per activity. + */ + private static boolean isActive(ChromeActivity activity) { + if (sActiveChromeActivities == null) { + return false; + } + + return sActiveChromeActivities.contains(activity); + } + @CalledByNative private static AutofillAssistantUiController create( ChromeActivity activity, boolean allowTabSwitching, long nativeUiController) { assert activity != null; - return new AutofillAssistantUiController(activity, allowTabSwitching, nativeUiController); + assert activity.getBottomSheetController() != null; + + if (sActiveChromeActivities == null) { + sActiveChromeActivities = new HashSet<>(); + } + sActiveChromeActivities.add(activity); + + return new AutofillAssistantUiController(activity, activity.getBottomSheetController(), + allowTabSwitching, nativeUiController); } - private AutofillAssistantUiController( - ChromeActivity activity, boolean allowTabSwitching, long nativeUiController) { + private AutofillAssistantUiController(ChromeActivity activity, BottomSheetController controller, + boolean allowTabSwitching, long nativeUiController) { mNativeUiController = nativeUiController; mActivity = activity; - mCoordinator = new AssistantCoordinator(activity, this); + mCoordinator = new AssistantCoordinator(activity, this, controller); mActivityTabObserver = new ActivityTabProvider.ActivityTabTabObserver(activity.getActivityTabProvider()) { @Override @@ -154,6 +182,7 @@ mNativeUiController = 0; mActivityTabObserver.destroy(); mCoordinator.destroy(); + sActiveChromeActivities.remove(mActivity); } /** @@ -174,7 +203,7 @@ @CalledByNative private void expandBottomSheet() { - mCoordinator.getBottomBarCoordinator().expand(); + mCoordinator.getBottomBarCoordinator().showAndExpand(); } @CalledByNative
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/SizeListenableLinearLayout.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/SizeListenableLinearLayout.java new file mode 100644 index 0000000..747cdeb55 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/SizeListenableLinearLayout.java
@@ -0,0 +1,42 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill_assistant; + +import android.content.Context; +import android.support.annotation.Nullable; +import android.util.AttributeSet; +import android.widget.LinearLayout; + +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet; + +/** A LinearLayout that can notify when its size changes. */ +public class SizeListenableLinearLayout extends LinearLayout { + @Nullable + private BottomSheet.ContentSizeListener mListener; + + public SizeListenableLinearLayout(Context context) { + super(context); + } + + public SizeListenableLinearLayout(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public SizeListenableLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + if (mListener != null) { + mListener.onSizeChanged(w, h, oldw, oldh); + } + } + + void setContentSizeListener(@Nullable BottomSheet.ContentSizeListener listener) { + mListener = listener; + } +}
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderCoordinator.java index ab878a0..55588793 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderCoordinator.java
@@ -15,7 +15,8 @@ * Coordinator for the header of the Autofill Assistant. */ public class AssistantHeaderCoordinator { - public AssistantHeaderCoordinator(Context context, ViewGroup root, AssistantHeaderModel model) { + public AssistantHeaderCoordinator( + Context context, ViewGroup bottomBarView, AssistantHeaderModel model) { // Create the poodle and insert it before the status message. We have to create a view // bigger than the desired poodle size (24dp) because the actual downstream implementation // needs extra space for the animation. @@ -24,13 +25,16 @@ R.dimen.autofill_assistant_poodle_view_size), context.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_poodle_size)); - addPoodle(root, poodle.getView()); + addPoodle(bottomBarView, poodle.getView()); // Bind view and mediator through the model. AssistantHeaderViewBinder.ViewHolder viewHolder = - new AssistantHeaderViewBinder.ViewHolder(root, poodle); + new AssistantHeaderViewBinder.ViewHolder(bottomBarView, poodle); AssistantHeaderViewBinder viewBinder = new AssistantHeaderViewBinder(); PropertyModelChangeProcessor.create(model, viewHolder, viewBinder); + + model.set(AssistantHeaderModel.VISIBLE, true); + model.set(AssistantHeaderModel.PROGRESS_VISIBLE, true); } private void addPoodle(ViewGroup root, View poodleView) {
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderModel.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderModel.java index af378cf..f5771cf 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderModel.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderModel.java
@@ -14,15 +14,12 @@ */ @JNINamespace("autofill_assistant") public class AssistantHeaderModel extends PropertyModel { + public static final WritableBooleanPropertyKey VISIBLE = new WritableBooleanPropertyKey(); + @VisibleForTesting public static final WritableObjectPropertyKey<String> STATUS_MESSAGE = new WritableObjectPropertyKey<>(); - // TODO(crbug.com/806868): Change visibility to package-private once this is only set through - // native calls. - public static final WritableBooleanPropertyKey FEEDBACK_VISIBLE = - new WritableBooleanPropertyKey(); - static final WritableIntPropertyKey PROGRESS = new WritableIntPropertyKey(); @VisibleForTesting @@ -35,7 +32,7 @@ new WritableObjectPropertyKey<>(); public AssistantHeaderModel() { - super(STATUS_MESSAGE, FEEDBACK_VISIBLE, PROGRESS, PROGRESS_VISIBLE, SPIN_POODLE, + super(VISIBLE, STATUS_MESSAGE, PROGRESS, PROGRESS_VISIBLE, SPIN_POODLE, FEEDBACK_BUTTON_CALLBACK); }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderViewBinder.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderViewBinder.java index 1663e02..e3984ef 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderViewBinder.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AssistantHeaderViewBinder.java
@@ -24,35 +24,34 @@ */ static class ViewHolder { final AnimatedPoodle mPoodle; + final View mHeader; final TextView mStatusMessage; final AnimatedProgressBar mProgressBar; final View mFeedbackButton; - public ViewHolder(View headerView, AnimatedPoodle poodle) { + public ViewHolder(View bottomBarView, AnimatedPoodle poodle) { mPoodle = poodle; - mStatusMessage = headerView.findViewById(R.id.status_message); - mProgressBar = new AnimatedProgressBar(headerView.findViewById(R.id.progress_bar)); - mFeedbackButton = headerView.findViewById(R.id.feedback_button); + mHeader = bottomBarView.findViewById(R.id.header); + mStatusMessage = bottomBarView.findViewById(R.id.status_message); + mProgressBar = new AnimatedProgressBar(bottomBarView.findViewById(R.id.progress_bar)); + mFeedbackButton = bottomBarView.findViewById(R.id.feedback_button); } } @Override public void bind(AssistantHeaderModel model, ViewHolder view, PropertyKey propertyKey) { - if (AssistantHeaderModel.STATUS_MESSAGE == propertyKey) { + if (AssistantHeaderModel.VISIBLE == propertyKey) { + view.mHeader.setVisibility( + model.get(AssistantHeaderModel.VISIBLE) ? View.VISIBLE : View.GONE); + setProgressBarVisibility(view, model); + } else if (AssistantHeaderModel.STATUS_MESSAGE == propertyKey) { String message = model.get(AssistantHeaderModel.STATUS_MESSAGE); view.mStatusMessage.setText(message); view.mStatusMessage.announceForAccessibility(message); - } else if (AssistantHeaderModel.FEEDBACK_VISIBLE == propertyKey) { - view.mFeedbackButton.setVisibility( - model.get(AssistantHeaderModel.FEEDBACK_VISIBLE) ? View.VISIBLE : View.GONE); } else if (AssistantHeaderModel.PROGRESS == propertyKey) { view.mProgressBar.setProgress(model.get(AssistantHeaderModel.PROGRESS)); } else if (AssistantHeaderModel.PROGRESS_VISIBLE == propertyKey) { - if (model.get(AssistantHeaderModel.PROGRESS_VISIBLE)) { - view.mProgressBar.show(); - } else { - view.mProgressBar.hide(); - } + setProgressBarVisibility(view, model); } else if (AssistantHeaderModel.SPIN_POODLE == propertyKey) { view.mPoodle.setSpinEnabled(model.get(AssistantHeaderModel.SPIN_POODLE)); } else if (AssistantHeaderModel.FEEDBACK_BUTTON_CALLBACK == propertyKey) { @@ -62,4 +61,13 @@ assert false : "Unhandled property detected in AssistantHeaderViewBinder!"; } } + + private void setProgressBarVisibility(ViewHolder view, AssistantHeaderModel model) { + if (model.get(AssistantHeaderModel.VISIBLE) + && model.get(AssistantHeaderModel.PROGRESS_VISIBLE)) { + view.mProgressBar.show(); + } else { + view.mProgressBar.hide(); + } + } }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantChoiceList.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantChoiceList.java index c30f31c..a1e94cc3 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantChoiceList.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantChoiceList.java
@@ -294,15 +294,12 @@ } private void setCheckedItem(Item item) { - boolean changed = false; for (int i = 0; i < mItems.size(); i++) { RadioButton radioButton = mItems.get(i).mRadioButton; - boolean isItem = mItems.get(i) == item; - changed |= isItem && !radioButton.isChecked(); - radioButton.setChecked(isItem); + radioButton.setChecked(mItems.get(i) == item); } - if (changed && mItemSelectedListener != null) { + if (mItemSelectedListener != null) { mItemSelectedListener.onResult(item.mContent); } }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantPaymentRequestCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantPaymentRequestCoordinator.java index c6e22d2..46e306dd 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantPaymentRequestCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantPaymentRequestCoordinator.java
@@ -10,6 +10,7 @@ import android.support.v4.util.ArrayMap; import android.text.TextUtils; import android.view.View; +import android.widget.ScrollView; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.Callback; @@ -81,7 +82,7 @@ model.get(AssistantPaymentRequestModel.DELEGATE))); } - public View getView() { + public ScrollView getView() { return mPaymentRequestUI.getView(); }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantPaymentRequestUI.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantPaymentRequestUI.java index 3bcf8da6..256e925 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantPaymentRequestUI.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AssistantPaymentRequestUI.java
@@ -15,6 +15,7 @@ import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; +import android.widget.ScrollView; import android.widget.TextView; import org.chromium.chrome.autofill_assistant.R; @@ -164,7 +165,7 @@ /** * Gets the root view of AssistantPaymentRequestUI. */ - public View getView() { + public ScrollView getView() { return mRequestViewContainer; }
diff --git a/chrome/android/features/autofill_assistant/java/strings/android_chrome_autofill_assistant_strings.grd b/chrome/android/features/autofill_assistant/java/strings/android_chrome_autofill_assistant_strings.grd index 7373067..ebf9b03 100644 --- a/chrome/android/features/autofill_assistant/java/strings/android_chrome_autofill_assistant_strings.grd +++ b/chrome/android/features/autofill_assistant/java/strings/android_chrome_autofill_assistant_strings.grd
@@ -112,9 +112,6 @@ </translations> <release allow_pseudo="false" seq="1"> <messages fallback_to_english="true"> - <message name="IDS_AUTOFILL_ASSISTANT_ONBOARDING_TITLE" desc="Onboarding title for the autofill assistant."> - Google Assistant\nin Chrome - </message> <message name="IDS_INIT_OK" desc="Init screen confirmation text."> I accept </message> @@ -136,9 +133,6 @@ <message name="IDS_AUTOFILL_ASSISTANT_3RD_PARTY_PRIVACY_NOTICE" desc="Privacy notice telling users that autofill assistant will send personal data to a third party’s website."> Chrome will send personal data you selected to <ph name="BEGIN_BOLD"><b></ph><ph name="DOMAIN">%1$s<ex>google.com</ex></ph><ph name="END_BOLD"></b></ph> </message> - <message name="IDS_AUTOFILL_ASSISTANT_AVAILABLE_ACCESSIBILITY" desc="Accessibility description of Autofill Assistant is available."> - Google Assistant in Chrome is available near bottom of the screen - </message> <message name="IDS_AUTOFILL_ASSISTANT_FIRST_RUN_ACCESSIBILITY" desc="Accessibility description of Autofill Assistant first run screen is shown."> Google Assistant in Chrome first run screen is shown </message> @@ -156,6 +150,18 @@ <message name="IDS_AUTOFILL_ASSISTANT_VIEW_ORIGINAL_IMAGE_CANCEL" desc="Text on the button to dismiss view image dialog."> Cancel </message> + <message name="IDS_AUTOFILL_ASSISTANT_SHEET_CONTENT_DESCRIPTION" desc="Content description for the Autofill Assistant sheet."> + Google Assistant in Chrome. + </message> + <message name="IDS_AUTOFILL_ASSISTANT_SHEET_HALF_HEIGHT" desc="Text announced when the Autofill Assistant sheet is opened at half height."> + Google Assistant in Chrome opened at half height. + </message> + <message name="IDS_AUTOFILL_ASSISTANT_SHEET_FULL_HEIGHT" desc="Text announced when the Autofill Assistant sheet is opened at full height."> + Google Assistant in Chrome opened at full height. + </message> + <message name="IDS_AUTOFILL_ASSISTANT_SHEET_CLOSED" desc="Text announced when the Autofill Assistant sheet is closed."> + Google Assistant in Chrome closed. + </message> </messages> </release> </grit>
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java index 8544d09..99cb626 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java
@@ -10,6 +10,7 @@ import android.support.test.InstrumentationRegistry; import android.support.test.filters.MediumTest; import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; @@ -45,6 +46,9 @@ import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; import org.chromium.chrome.browser.customtabs.CustomTabsTestUtils; import org.chromium.chrome.browser.firstrun.FirstRunStatus; +import org.chromium.chrome.browser.snackbar.BottomContainer; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet; +import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.net.test.EmbeddedTestServer; @@ -98,14 +102,28 @@ InstrumentationRegistry.getTargetContext(), mTestPage); } - private View findViewByIdInMainCoordinator(int id) { - return getActivity().findViewById(R.id.coordinator).findViewById(id); - } - private CustomTabActivity getActivity() { return mCustomTabActivityTestRule.getActivity(); } + // Copied from {@link ChromeActivity#initializeBottomSheet}. + protected BottomSheetController initializeBottomSheet() { + CustomTabActivity activity = getActivity(); + ViewGroup coordinator = activity.findViewById(org.chromium.chrome.R.id.coordinator); + LayoutInflater.from(activity).inflate( + org.chromium.chrome.R.layout.bottom_sheet, coordinator); + BottomSheet bottomSheet = coordinator.findViewById(org.chromium.chrome.R.id.bottom_sheet); + bottomSheet.init(coordinator, activity); + + ((BottomContainer) activity.findViewById(org.chromium.chrome.R.id.bottom_container)) + .setBottomSheet(bottomSheet); + + return new BottomSheetController(activity, activity.getActivityTabProvider(), + activity.getScrim(), bottomSheet, + activity.getCompositorViewHolder().getLayoutManager().getOverlayPanelManager(), + /* suppressSheetForContextualSearch= */ false); + } + // TODO(crbug.com/806868): Add more UI details test and check, like payment request UI, // highlight chips and so on. @Test @@ -114,21 +132,24 @@ InOrder inOrder = inOrder(mRunnableMock); mCustomTabActivityTestRule.startCustomTabActivityWithIntent(createMinimalCustomTabIntent()); + BottomSheetController bottomSheetController = + ThreadUtils.runOnUiThreadBlocking(this::initializeBottomSheet); AssistantCoordinator assistantCoordinator = ThreadUtils.runOnUiThreadBlocking( - () -> new AssistantCoordinator(getActivity(), mCoordinatorDelegateMock)); + () + -> new AssistantCoordinator( + getActivity(), mCoordinatorDelegateMock, bottomSheetController)); - // Bottom sheet is shown when creating the AssistantCoordinator. - View bottomSheet = findViewByIdInMainCoordinator(R.id.autofill_assistant); - Assert.assertTrue(bottomSheet.isShown()); + // Bottom sheet is shown in the BottomSheet when creating the AssistantCoordinator. + ViewGroup bottomSheetContent = + bottomSheetController.getBottomSheet().findViewById(R.id.autofill_assistant); + Assert.assertNotNull(bottomSheetContent); - // Disable bottom sheet container animations. This is a workaround for http://crbug/943483. - ViewGroup bottomSheetContainer = - bottomSheet.findViewById(R.id.autofill_assistant_bottombar_container); - TestThreadUtils.runOnUiThreadBlocking(() -> bottomSheetContainer.setLayoutTransition(null)); + // Disable bottom sheet content animations. This is a workaround for http://crbug/943483. + TestThreadUtils.runOnUiThreadBlocking(() -> bottomSheetContent.setLayoutTransition(null)); // Show onboarding. ThreadUtils.runOnUiThreadBlocking(() -> assistantCoordinator.showOnboarding(mRunnableMock)); - View onboardingView = bottomSheet.findViewById(R.id.assistant_onboarding); + View onboardingView = bottomSheetContent.findViewById(R.id.assistant_onboarding); Assert.assertNotNull(onboardingView); View initOkButton = onboardingView.findViewById(R.id.button_init_ok); Assert.assertNotNull(initOkButton); @@ -141,7 +162,7 @@ () -> assistantCoordinator.getModel().getHeaderModel().set( AssistantHeaderModel.STATUS_MESSAGE, testStatusMessage)); - TextView statusMessageView = bottomSheet.findViewById(R.id.status_message); + TextView statusMessageView = bottomSheetContent.findViewById(R.id.status_message); Assert.assertEquals(statusMessageView.getText(), testStatusMessage); // Show scrim. @@ -179,24 +200,24 @@ false, /* highlightLine2 = */ false, /* highlightLine3 = */ false, /* animatePlaceholders= */ false))); - TextView detailsTitle = bottomSheet.findViewById(R.id.details_title); - TextView detailsLine1 = bottomSheet.findViewById(R.id.details_line1); - TextView detailsLine2 = bottomSheet.findViewById(R.id.details_line2); - TextView detailsLine3 = bottomSheet.findViewById(R.id.details_line3); + TextView detailsTitle = bottomSheetContent.findViewById(R.id.details_title); + TextView detailsLine1 = bottomSheetContent.findViewById(R.id.details_line1); + TextView detailsLine2 = bottomSheetContent.findViewById(R.id.details_line2); + TextView detailsLine3 = bottomSheetContent.findViewById(R.id.details_line3); Assert.assertEquals(detailsTitle.getText(), movieTitle); Assert.assertTrue(detailsLine1.getText().toString().contains(descriptionLine1)); Assert.assertTrue(detailsLine2.getText().toString().contains(descriptionLine2)); Assert.assertTrue(detailsLine3.getText().toString().contains(descriptionLine3)); // Progress bar must be shown. - Assert.assertTrue(bottomSheet.findViewById(R.id.progress_bar).isShown()); + Assert.assertTrue(bottomSheetContent.findViewById(R.id.progress_bar).isShown()); // Disable progress bar. ThreadUtils.runOnUiThreadBlocking( () -> assistantCoordinator.getModel().getHeaderModel().set( AssistantHeaderModel.PROGRESS_VISIBLE, false)); - Assert.assertFalse(bottomSheet.findViewById(R.id.progress_bar).isShown()); + Assert.assertFalse(bottomSheetContent.findViewById(R.id.progress_bar).isShown()); // Show info box content. String infoBoxExplanation = "InfoBox explanation."; @@ -206,7 +227,8 @@ AssistantInfoBoxModel.INFO_BOX, new AssistantInfoBox( /* imagePath = */ "", infoBoxExplanation))); - TextView infoBoxExplanationView = bottomSheet.findViewById(R.id.info_box_explanation); + TextView infoBoxExplanationView = + bottomSheetContent.findViewById(R.id.info_box_explanation); Assert.assertEquals(infoBoxExplanationView.getText(), infoBoxExplanation); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index 1636cdb..9d217d9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -417,17 +417,19 @@ mConnection.showSignInToastIfNecessary(mSession, getIntent()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ASSISTANT) - && AutofillAssistantFacade.isConfigured(getInitialIntent().getExtras())) { - AutofillAssistantFacade.start(this); - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && useSeparateTask()) { mTaskDescriptionHelper = new ActivityTabTaskDescriptionHelper(this, ApiCompatibilityUtils.getColor(getResources(), R.color.default_primary_color)); } super.finishNativeInitialization(); + + // We start the Autofill Assistant after the call to super.finishNativeInitialization() as + // this will initialize the BottomSheet that is used to embed the Autofill Assistant bottom + // bar. + if (isAutofillAssistantEnabled()) { + AutofillAssistantFacade.start(this); + } } @Override @@ -920,4 +922,14 @@ return component; } + + @Override + protected boolean shouldInitializeBottomSheet() { + return isAutofillAssistantEnabled(); + } + + private boolean isAutofillAssistantEnabled() { + return ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ASSISTANT) + && AutofillAssistantFacade.isConfigured(getInitialIntent().getExtras()); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tabgroup/TabGroupModelFilter.java b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tabgroup/TabGroupModelFilter.java index ef0b4ab..7d3def0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tabgroup/TabGroupModelFilter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tabgroup/TabGroupModelFilter.java
@@ -134,6 +134,7 @@ int groupId = tab.getRootId(); TabGroup group = mGroupIdToGroupMap.get(groupId); + if (group == null) return super.getRelatedTabList(TabModel.INVALID_TAB_INDEX); return getRelatedTabList(group.getTabIdList()); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java index 7d17bac0..dc54715 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java
@@ -329,6 +329,18 @@ } /** + * Set a {@link ContentSizeListener} that should be notified when the size of the content + * has changed. This will be called only if {@link #wrapContentEnabled()} returns {@code + * true}. Note that you need to implement this method only if the content view height + * changes are animated. + * + * @return Whether the listener was correctly set. + */ + default boolean setContentSizeListener(@Nullable ContentSizeListener listener) { + return false; + } + + /** * @return The resource id of the content description for the bottom sheet. This is * generally the name of the feature/content that is showing. 'Swipe down to close.' * will be automatically appended after the content description. @@ -354,6 +366,12 @@ int getSheetClosedAccessibilityStringId(); } + /** Interface to listen when the size of a BottomSheetContent changes. */ + public interface ContentSizeListener { + /** Called when the size of the view has changed. */ + void onSizeChanged(int width, int height, int oldWidth, int oldHeight); + } + /** * Returns whether the provided bottom sheet state is in one of the stable open or closed * states: {@link #SheetState.FULL}, {@link #SheetState.PEEK} or {@link #SheetState.HALF} @@ -517,7 +535,10 @@ int heightSize = MeasureSpec.getSize(heightMeasureSpec); assert heightSize != 0; int height = heightSize + mToolbarShadowHeight; - super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); + int mode = mSheetContent != null && mSheetContent.wrapContentEnabled() + ? MeasureSpec.AT_MOST + : MeasureSpec.EXACTLY; + super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, mode)); } /** @@ -768,7 +789,13 @@ @Override public float getMaxOffsetPx() { - return getFullRatio() * mContainerHeight; + float maxOffset = getFullRatio() * mContainerHeight; + if (mSheetContent != null && mSheetContent.wrapContentEnabled()) { + ensureContentDesiredHeightIsComputed(); + return Math.min(maxOffset, mContentDesiredHeight + mToolbarShadowHeight); + } + + return maxOffset; } /** @@ -782,8 +809,9 @@ // If the desired content is already showing, do nothing. if (mSheetContent == content) return; - // Remove this as listener from previous content layout changes. + // Remove this as listener from previous content layout and size changes. if (mSheetContent != null) { + mSheetContent.setContentSizeListener(null); mSheetContent.getContentView().removeOnLayoutChangeListener(this); } @@ -1374,19 +1402,24 @@ public float getSheetHeightForState(@SheetState int state) { if (mSheetContent != null && mSheetContent.wrapContentEnabled() && state == SheetState.FULL) { - if (mContentDesiredHeight == HEIGHT_UNSPECIFIED) { - mSheetContent.getContentView().measure( - MeasureSpec.makeMeasureSpec((int) mContainerWidth, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec((int) mContainerHeight, MeasureSpec.AT_MOST)); - mContentDesiredHeight = - mSheetContent.getContentView().getMeasuredHeight() + mToolbarShadowHeight; - } - return mContentDesiredHeight; + ensureContentDesiredHeightIsComputed(); + return mContentDesiredHeight + mToolbarShadowHeight; } return getRatioForState(state) * mContainerHeight; } + private void ensureContentDesiredHeightIsComputed() { + if (mContentDesiredHeight != HEIGHT_UNSPECIFIED) { + return; + } + + mSheetContent.getContentView().measure( + MeasureSpec.makeMeasureSpec((int) mContainerWidth, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec((int) mContainerHeight, MeasureSpec.AT_MOST)); + mContentDesiredHeight = mSheetContent.getContentView().getMeasuredHeight(); + } + private float getRatioForState(int state) { switch (state) { case SheetState.HIDDEN: @@ -1530,8 +1563,13 @@ mSheetContent = content; if (content != null && content.wrapContentEnabled()) { - content.getContentView().addOnLayoutChangeListener(this); - ensureContentIsWrapped(); + // Listen for layout/size changes. + if (!content.setContentSizeListener(this::onContentSizeChanged)) { + content.getContentView().addOnLayoutChangeListener(this); + } + + invalidateContentDesiredHeight(); + ensureContentIsWrapped(/* animate= */ true); // HALF state is forbidden when wrapping the content. if (mCurrentState == SheetState.HALF) { @@ -1551,12 +1589,19 @@ @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { - ensureContentIsWrapped(); + invalidateContentDesiredHeight(); + ensureContentIsWrapped(/* animate= */ true); } - private void ensureContentIsWrapped() { - invalidateContentDesiredHeight(); + /** + * Called when the sheet content size changed. + */ + private void onContentSizeChanged(int width, int height, int oldWidth, int oldHeight) { + mContentDesiredHeight = height; + ensureContentIsWrapped(/* animate= */ false); + } + private void ensureContentIsWrapped(boolean animate) { if (mCurrentState == SheetState.HIDDEN || mCurrentState == SheetState.PEEK) return; // The SCROLLING state is used when animating the sheet height or when the user is swiping @@ -1564,7 +1609,7 @@ cancelAnimation(); if (mCurrentState == SheetState.SCROLLING) return; - createSettleAnimation(mCurrentState, StateChangeReason.NONE); + setSheetState(mCurrentState, animate); } private void invalidateContentDesiredHeight() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserNativeUiTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserNativeUiTest.java index a93f031..3b15770 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserNativeUiTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserNativeUiTest.java
@@ -22,6 +22,7 @@ import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.ChromeSwitches; @@ -241,6 +242,7 @@ */ @Test @MediumTest + @DisabledTest(message = "crbug.com/951375") public void testOmniboxAutocompletion() throws InterruptedException { // At least with chrome:// URLs, autocompletion only kicks in when there's one valid option // left. So, test that:
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/widget/bottomsheet/TestBottomSheetContent.java b/chrome/android/javatests/src/org/chromium/chrome/browser/widget/bottomsheet/TestBottomSheetContent.java index 4e86ab8..5f1080f8 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/widget/bottomsheet/TestBottomSheetContent.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/widget/bottomsheet/TestBottomSheetContent.java
@@ -94,6 +94,11 @@ } @Override + public boolean setContentSizeListener(@Nullable BottomSheet.ContentSizeListener listener) { + return false; + } + + @Override public int getSheetContentDescriptionStringId() { return R.string.contextual_suggestions_button_description; }
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index 7f4fd3f5..818af247 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -3578,6 +3578,9 @@ <message name="IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_FAILED" desc="Message displayed in the notification when export (backup) of the Linux container fails."> Backup couldn't be completed due to an error </message> + <message name="IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_FAILED_IN_PROGRESS" desc="Message displayed in the notification when export (backup) of the Linux container fails due to another being in progress."> + Backup currently in progress for <ph name="CONTAINER_ID">$1<ex>(termina, penguin)</ex></ph> + </message> <message name="IDS_CROSTINI_IMPORT_NOTIFICATION_TITLE_RUNNING" desc="Title displayed in the notification while import (restore) of the Linux container is in progress."> Restoring Linux apps & files </message> @@ -3593,6 +3596,12 @@ <message name="IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED" desc="Message displayed in the notification when import (restore) of the Linux container fails."> Restoring couldn't be completed due to an error </message> + <message name="IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_IN_PROGRESS" desc="Message displayed in the notification when import (restore) of the Linux container fails due to another being in progress."> + Restore currently in progress for <ph name="CONTAINER_ID">$1<ex>(termina, penguin)</ex></ph> + </message> + <message name="IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_ARCHITECTURE" desc="Message displayed in the notification when import (restore) of the Linux container fails due to architecture mismatch."> + Cannot import container architecture type <ph name="ARCHITECTURE_CONTAINER">$1<ex>arm64</ex></ph> with this device which is <ph name="ARCHITECTURE_DEVICE">$2<ex>x86_64</ex></ph>. You can try restoring this container into a different device, or you can access the files inside this container image by opening in Files app. + </message> <!-- Time limit notification --> <message name="IDS_SCREEN_TIME_NOTIFICATION_TITLE" desc="The title of the notification when screen usage limit reaches before locking the device."> @@ -3601,6 +3610,21 @@ <message name="IDS_BED_TIME_NOTIFICATION_TITLE" desc="The title of the notification when bedtime reaches before locking the device."> Lights out soon </message> + <message name="IDS_TIME_LIMIT_UPDATED_NOTIFICATION_TITLE" desc="The title of the notification displayed when parent updates bedtime or usage limit for kids device."> + Update from your parent + </message> + <message name="IDS_BEDTIME_UPDATED_NOTIFICATION_MESSAGE" desc="The message of the notification when parent updates bedtime limit for kids device."> + New bedtime set + </message> + <message name="IDS_SCREEN_TIME_UPDATED_NOTIFICATION_MESSAGE" desc="The message of the notification when parent updates usage limit for kids device."> + New screen time limit + </message> + <message name="IDS_OVERRIDE_WITH_DURATION_UPDATED_NOTIFICATION_TITLE" desc="The title of the notification when parent granted the child more time on this device."> + Bonus! You got more screen time + </message> + <message name="IDS_OVERRIDE_WITH_DURATION_UPDATED_NOTIFICATION_MESSAGE" desc="The message of the notification when parent granted the child more time on this device. Informs the child of the device's new lock time."> + Your device now locks at <ph name="UNLOCK_TIME">$1<ex>9:30 PM</ex></ph>. + </message> <message name="IDS_TIME_LIMIT_NOTIFICATION_DISPLAY_SOURCE" desc="The string shown as the display source of the bedtime or screen time notifications."> Family Link </message>
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_FAILED_IN_PROGRESS.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_FAILED_IN_PROGRESS.png.sha1 new file mode 100644 index 0000000..2268b15 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_FAILED_IN_PROGRESS.png.sha1
@@ -0,0 +1 @@ +3519b1b96658bf54a93cb2df6d8b5d711522c9f7 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_ARCHITECTURE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_ARCHITECTURE.png.sha1 new file mode 100644 index 0000000..c41ee67 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_ARCHITECTURE.png.sha1
@@ -0,0 +1 @@ +0f025026240011c46a51b6d6752ae86df3d38930 \ No newline at end of file
diff --git a/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_IN_PROGRESS.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_IN_PROGRESS.png.sha1 new file mode 100644 index 0000000..2268b15 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_IN_PROGRESS.png.sha1
@@ -0,0 +1 @@ +3519b1b96658bf54a93cb2df6d8b5d711522c9f7 \ No newline at end of file
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 8130da4..085dee6 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -2051,6 +2051,27 @@ Open as window </message> + <!-- Finish policy app installation dialog --> + <message name="IDS_FINISH_POLICY_WEB_APP_INSTALLATION" desc="Main text for the Finish Policy Web App Installation dialog. This is a dialog message that appears on the first launch of an app after it was remotely installed by an enterprise administrator. The app has some cosmetic factors (like the app icon) that can only be fixed if the user launches and then restarts the app. After the initial launch, this dialog encourages users to restart the app to complete the installation."> + This app was added by your organization. Restart the app to finish installing it. + </message> + <if expr="not use_titlecase"> + <message name="IDS_FINISH_POLICY_WEB_APP_INSTALATION_RESTART" desc="The button in the Finish Policy Web App Installation dialog which closes the app and relaunches it."> + Restart + </message> + <message name="IDS_FINISH_POLICY_WEB_APP_INSTALLATION_NOT_NOW" desc="The button in the Finish Policy Web App Installation dialog which dismisses the dialog."> + Not now + </message> + </if> + <if expr="use_titlecase"> + <message name="IDS_FINISH_POLICY_WEB_APP_INSTALATION_RESTART" desc="The button in the Finish Policy Web App Installation dialog which closes the app and relaunches it."> + Restart + </message> + <message name="IDS_FINISH_POLICY_WEB_APP_INSTALLATION_NOT_NOW" desc="The button in the Finish Policy Web App Installation dialog which dismisses the dialog."> + Not Now + </message> + </if> + <!-- Quit all apps confirmation dialog --> <if expr="is_macosx"> <message name="IDS_QUIT_WITH_APPS_NOTIFICATION_DISPLAY_SOURCE" desc="Display source for the notification when quitting with apps open."> @@ -8967,7 +8988,7 @@ USB device detected </message> <message name="IDS_CROSUSB_NOTIFICATION_BUTTON_CONNECT_TO_LINUX" desc="Label for notification button shown to the user when a USB device gets plugged in to allowed Linux to use the device"> - Connect + Connect to Linux </message> <message name="IDS_CROSUSB_UNKNOWN_DEVICE_FROM_MANUFACTURER" desc="String describing an unknown device in notification shown when a USB device gets plugged in."> USB device from <ph name="MANUFACTURER_NAME">$1<ex>Google</ex></ph>
diff --git a/chrome/app/printing_strings.grdp b/chrome/app/printing_strings.grdp index a752a3f3..cb7aa4a 100644 --- a/chrome/app/printing_strings.grdp +++ b/chrome/app/printing_strings.grdp
@@ -307,6 +307,15 @@ These settings are enforced by your administrator </message> <if expr="chromeos"> + <message name="IDS_PRINT_PREVIEW_OPTION_PIN" desc="Option to print with pin."> + Enable user pin + </message> + <message name="IDS_PRINT_PREVIEW_PIN_ERROR_MESSAGE" desc="Message shown to the user when they attempt to print with pin, but don't enter pin in correct form."> + Enter a pin to print + </message> + <message name="IDS_PRINT_PREVIEW_PIN_PLACEHOLDER" desc="Text to put in a pin textfield when user has not entered any pin value."> + Enter 4 digit pin (0000-9999) + </message> <message name="IDS_PRINT_CONFIGURING_IN_PROGRESS_TEXT" desc="Message shown to user while their printer is being setup in Chrome OS."> Setting up </message>
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.cc b/chrome/browser/android/autofill_assistant/ui_controller_android.cc index c402df4..8eb0704 100644 --- a/chrome/browser/android/autofill_assistant/ui_controller_android.cc +++ b/chrome/browser/android/autofill_assistant/ui_controller_android.cc
@@ -173,14 +173,12 @@ SetOverlayState(OverlayState::FULL); AllowShowingSoftKeyboard(false); SetSpinPoodle(true); - SetAllowSwipingSheet(true); return; case AutofillAssistantState::RUNNING: SetOverlayState(OverlayState::FULL); AllowShowingSoftKeyboard(false); SetSpinPoodle(true); - SetAllowSwipingSheet(true); return; case AutofillAssistantState::AUTOSTART_FALLBACK_PROMPT: @@ -197,7 +195,6 @@ AllowShowingSoftKeyboard(true); SetSpinPoodle(false); - SetAllowSwipingSheet(ui_delegate_->GetPaymentRequestOptions() == nullptr); // user interaction is needed. ExpandBottomSheet(); return; @@ -206,14 +203,12 @@ SetOverlayState(OverlayState::FULL); AllowShowingSoftKeyboard(true); SetSpinPoodle(true); - SetAllowSwipingSheet(true); return; case AutofillAssistantState::STOPPED: SetOverlayState(OverlayState::HIDDEN); AllowShowingSoftKeyboard(true); SetSpinPoodle(false); - SetAllowSwipingSheet(true); // make sure user sees the error message. ExpandBottomSheet(); @@ -261,11 +256,6 @@ GetHeaderModel(), enabled); } -void UiControllerAndroid::SetAllowSwipingSheet(bool allow) { - Java_AssistantModel_setAllowSwipingSheet(AttachCurrentThread(), GetModel(), - allow); -} - void UiControllerAndroid::OnFeedbackButtonClicked() { JNIEnv* env = AttachCurrentThread(); Java_AutofillAssistantUiController_showFeedback(
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.h b/chrome/browser/android/autofill_assistant/ui_controller_android.h index 59acea37..c27bedf 100644 --- a/chrome/browser/android/autofill_assistant/ui_controller_android.h +++ b/chrome/browser/android/autofill_assistant/ui_controller_android.h
@@ -143,7 +143,6 @@ void AllowShowingSoftKeyboard(bool enabled); void ExpandBottomSheet(); void SetSpinPoodle(bool enabled); - void SetAllowSwipingSheet(bool allow); std::string GetDebugContext(); void DestroySelf(); void Shutdown(Metrics::DropOutReason reason);
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index c0ac270..dafc7ae 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -255,7 +255,7 @@ "AndroidSearchEngineChoiceNotification", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kAndroidSiteSettingsUIRefresh{ - "AndroidSiteSettingsUIRefresh", base::FEATURE_ENABLED_BY_DEFAULT}; + "AndroidSiteSettingsUIRefresh", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kAndroidWebContentsDarkMode{ "AndroidWebContentsDarkMode", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chrome/browser/apps/app_service/arc_apps.cc b/chrome/browser/apps/app_service/arc_apps.cc index 0899b24..9f1ccf92 100644 --- a/chrome/browser/apps/app_service/arc_apps.cc +++ b/chrome/browser/apps/app_service/arc_apps.cc
@@ -259,6 +259,9 @@ case apps::mojom::LaunchSource::kFromAppListRecommendation: uit = arc::UserInteractionType::APP_STARTED_FROM_LAUNCHER_SUGGESTED_APP; break; + case apps::mojom::LaunchSource::kFromKioskNextHome: + uit = arc::UserInteractionType::APP_STARTED_FROM_KIOSK_NEXT_HOME; + break; } arc::LaunchApp(profile_, app_id, event_flags, uit, display_id);
diff --git a/chrome/browser/apps/app_service/built_in_chromeos_apps.cc b/chrome/browser/apps/app_service/built_in_chromeos_apps.cc index 100ae71..fc08383 100644 --- a/chrome/browser/apps/app_service/built_in_chromeos_apps.cc +++ b/chrome/browser/apps/app_service/built_in_chromeos_apps.cc
@@ -136,6 +136,7 @@ int64_t display_id) { switch (launch_source) { case apps::mojom::LaunchSource::kUnknown: + case apps::mojom::LaunchSource::kFromKioskNextHome: break; case apps::mojom::LaunchSource::kFromAppListGrid: case apps::mojom::LaunchSource::kFromAppListGridContextMenu:
diff --git a/chrome/browser/apps/app_service/extension_apps.cc b/chrome/browser/apps/app_service/extension_apps.cc index 2d84d7c..310537ae 100644 --- a/chrome/browser/apps/app_service/extension_apps.cc +++ b/chrome/browser/apps/app_service/extension_apps.cc
@@ -161,6 +161,7 @@ switch (launch_source) { case apps::mojom::LaunchSource::kUnknown: + case apps::mojom::LaunchSource::kFromKioskNextHome: break; case apps::mojom::LaunchSource::kFromAppListGrid: case apps::mojom::LaunchSource::kFromAppListGridContextMenu:
diff --git a/chrome/browser/apps/app_service/launch_util.cc b/chrome/browser/apps/app_service/launch_util.cc index 6ccd1b0e..7f92ffe 100644 --- a/chrome/browser/apps/app_service/launch_util.cc +++ b/chrome/browser/apps/app_service/launch_util.cc
@@ -13,6 +13,7 @@ apps::mojom::LaunchSource launch_source) { switch (launch_source) { case apps::mojom::LaunchSource::kUnknown: + case apps::mojom::LaunchSource::kFromKioskNextHome: return ash::LAUNCH_FROM_UNKNOWN; case apps::mojom::LaunchSource::kFromAppListGrid: case apps::mojom::LaunchSource::kFromAppListGridContextMenu:
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index 675d8fa4..dfed891 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -102,6 +102,7 @@ "//chromeos/dbus/cryptohome:cryptohome_proto", "//chromeos/dbus/cryptohome:cryptohome_signkey_proto", "//chromeos/dbus/kerberos", + "//chromeos/dbus/kerberos:kerberos_proto", "//chromeos/dbus/machine_learning", "//chromeos/dbus/media_analytics", "//chromeos/dbus/media_analytics:media_perception_proto", @@ -620,6 +621,8 @@ "authpolicy/auth_policy_credentials_manager.h", "authpolicy/authpolicy_helper.cc", "authpolicy/authpolicy_helper.h", + "authpolicy/data_pipe_utils.cc", + "authpolicy/data_pipe_utils.h", "authpolicy/kerberos_files_handler.cc", "authpolicy/kerberos_files_handler.h", "base/file_flusher.cc", @@ -1063,6 +1066,8 @@ "input_method/input_method_persistence.h", "input_method/input_method_syncer.cc", "input_method/input_method_syncer.h", + "kerberos/kerberos_credentials_manager.cc", + "kerberos/kerberos_credentials_manager.h", "kiosk_next_home/app_controller_service.cc", "kiosk_next_home/app_controller_service.h", "kiosk_next_home/app_controller_service_factory.cc",
diff --git a/chrome/browser/chromeos/assistant/assistant_util.cc b/chrome/browser/chromeos/assistant/assistant_util.cc index 2b5934d6..08444a5 100644 --- a/chrome/browser/chromeos/assistant/assistant_util.cc +++ b/chrome/browser/chromeos/assistant/assistant_util.cc
@@ -46,10 +46,15 @@ // third_party/icu/source/common/unicode/uloc.h const std::string kAllowedLocales[] = {ULOC_CANADA, ULOC_CANADA_FRENCH, + ULOC_FRANCE, ULOC_FRENCH, ULOC_UK, ULOC_US, "da_DK", + "en_AU", + "en_IE", + "en_NZ", + "en_SE", "nl_NL", "no_NO", "sv_SE"};
diff --git a/chrome/browser/chromeos/authpolicy/authpolicy_helper.cc b/chrome/browser/chromeos/authpolicy/authpolicy_helper.cc index 8f73f4ea..608eff21 100644 --- a/chrome/browser/chromeos/authpolicy/authpolicy_helper.cc +++ b/chrome/browser/chromeos/authpolicy/authpolicy_helper.cc
@@ -6,10 +6,10 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/files/file_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/task/post_task.h" +#include "chrome/browser/chromeos/authpolicy/data_pipe_utils.h" #include "chromeos/dbus/auth_policy/auth_policy_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/upstart/upstart_client.h" @@ -25,23 +25,6 @@ constexpr char kDCPrefix[] = "DC="; constexpr char kOUPrefix[] = "OU="; -base::ScopedFD GetDataReadPipe(const std::string& data) { - int pipe_fds[2]; - if (!base::CreateLocalNonBlockingPipe(pipe_fds)) { - DLOG(ERROR) << "Failed to create pipe"; - return base::ScopedFD(); - } - base::ScopedFD pipe_read_end(pipe_fds[0]); - base::ScopedFD pipe_write_end(pipe_fds[1]); - - if (!base::WriteFileDescriptor(pipe_write_end.get(), data.c_str(), - data.size())) { - DLOG(ERROR) << "Failed to write to pipe"; - return base::ScopedFD(); - } - return pipe_read_end; -} - bool ParseDomainAndOU(const std::string& distinguished_name, authpolicy::JoinDomainRequest* request) { std::string machine_domain; @@ -147,7 +130,8 @@ request.set_user_principal_name(username); request.set_account_id(object_guid); AuthPolicyClient::Get()->AuthenticateUser( - request, GetDataReadPipe(password).get(), base::DoNothing()); + request, data_pipe_utils::GetDataReadPipe(password).get(), + base::DoNothing()); } // static @@ -189,7 +173,7 @@ request.set_dm_token(dm_token_); AuthPolicyClient::Get()->JoinAdDomain( - request, GetDataReadPipe(password).get(), + request, data_pipe_utils::GetDataReadPipe(password).get(), base::BindOnce(&AuthPolicyHelper::OnJoinCallback, weak_factory_.GetWeakPtr(), std::move(callback))); } @@ -203,7 +187,7 @@ request.set_user_principal_name(username); request.set_account_id(object_guid); AuthPolicyClient::Get()->AuthenticateUser( - request, GetDataReadPipe(password).get(), + request, data_pipe_utils::GetDataReadPipe(password).get(), base::BindOnce(&AuthPolicyHelper::OnAuthCallback, weak_factory_.GetWeakPtr(), std::move(callback))); }
diff --git a/chrome/browser/chromeos/authpolicy/data_pipe_utils.cc b/chrome/browser/chromeos/authpolicy/data_pipe_utils.cc new file mode 100644 index 0000000..76a1797f --- /dev/null +++ b/chrome/browser/chromeos/authpolicy/data_pipe_utils.cc
@@ -0,0 +1,30 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/authpolicy/data_pipe_utils.h" + +#include "base/files/file_util.h" + +namespace chromeos { +namespace data_pipe_utils { + +base::ScopedFD GetDataReadPipe(const std::string& data) { + int pipe_fds[2]; + if (!base::CreateLocalNonBlockingPipe(pipe_fds)) { + DLOG(ERROR) << "Failed to create pipe"; + return base::ScopedFD(); + } + base::ScopedFD pipe_read_end(pipe_fds[0]); + base::ScopedFD pipe_write_end(pipe_fds[1]); + + if (!base::WriteFileDescriptor(pipe_write_end.get(), data.c_str(), + data.size())) { + DLOG(ERROR) << "Failed to write to pipe"; + return base::ScopedFD(); + } + return pipe_read_end; +} + +} // namespace data_pipe_utils +} // namespace chromeos
diff --git a/chrome/browser/chromeos/authpolicy/data_pipe_utils.h b/chrome/browser/chromeos/authpolicy/data_pipe_utils.h new file mode 100644 index 0000000..124e1fe7 --- /dev/null +++ b/chrome/browser/chromeos/authpolicy/data_pipe_utils.h
@@ -0,0 +1,21 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_AUTHPOLICY_DATA_PIPE_UTILS_H_ +#define CHROME_BROWSER_CHROMEOS_AUTHPOLICY_DATA_PIPE_UTILS_H_ + +#include <string> + +#include "base/files/scoped_file.h" + +namespace chromeos { +namespace data_pipe_utils { + +// Writes |data| to the writing end of a pipe and returns the reading end. +base::ScopedFD GetDataReadPipe(const std::string& data); + +} // namespace data_pipe_utils +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_AUTHPOLICY_DATA_PIPE_UTILS_H_
diff --git a/chrome/browser/chromeos/authpolicy/kerberos_files_handler.cc b/chrome/browser/chromeos/authpolicy/kerberos_files_handler.cc index 96da832..6da7624 100644 --- a/chrome/browser/chromeos/authpolicy/kerberos_files_handler.cc +++ b/chrome/browser/chromeos/authpolicy/kerberos_files_handler.cc
@@ -26,8 +26,14 @@ namespace { +base::FilePath GetKerberosDir() { + base::FilePath dir; + base::PathService::Get(base::DIR_HOME, &dir); + return dir.Append(kKrb5Directory); +} + // Writes |blob| into file <UserPath>/kerberos/|file_name|. First writes into -// temporary file and then replaces existing one. +// temporary file and then replaces existing one. Prints an error or failure. void WriteFile(const base::FilePath& path, base::Optional<std::string> blob) { if (!blob.has_value()) return; @@ -35,13 +41,17 @@ LOG(ERROR) << "Failed to write file " << path.value(); } +// Deletes file at |path|. Prints an error or failure. +void RemoveFile(const base::FilePath& path) { + if (!base::DeleteFile(path, false /* recursive */)) + LOG(ERROR) << "Failed to delete file " << path.value(); +} + // Writes |krb5cc| to <DIR_HOME>/kerberos/krb5cc and |krb5config| to // <DIR_HOME>/kerberos/krb5.conf if set. Creates directories if necessary. void WriteFiles(base::Optional<std::string> krb5cc, base::Optional<std::string> krb5config) { - base::FilePath dir; - base::PathService::Get(base::DIR_HOME, &dir); - dir = dir.Append(kKrb5Directory); + base::FilePath dir = GetKerberosDir(); base::File::Error error; if (!base::CreateDirectoryAndGetError(dir, &error)) { LOG(ERROR) << "Failed to create '" << dir.value() @@ -53,6 +63,13 @@ WriteFile(dir.Append(kKrb5ConfFile), std::move(krb5config)); } +// Deletes <DIR_HOME>/kerberos/krb5cc and <DIR_HOME>/kerberos/krb5.conf. +void RemoveFiles() { + base::FilePath dir = GetKerberosDir(); + RemoveFile(dir.Append(kKrb5CCFile)); + RemoveFile(dir.Append(kKrb5ConfFile)); +} + // If |config| has a value, puts canonicalization settings first depending on // user policy. Whatever setting comes first wins, so even if krb5.conf sets // rdns or dns_canonicalize_hostname below, it would get overridden. @@ -129,11 +146,22 @@ weak_factory_.GetWeakPtr())); } +void KerberosFilesHandler::DeleteFiles() { + // These files contain user credentials, so use BLOCK_SHUTDOWN here to make + // sure they do get deleted. + base::PostTaskWithTraitsAndReply( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(&RemoveFiles), + base::BindOnce(&KerberosFilesHandler::OnFilesChanged, + weak_factory_.GetWeakPtr())); +} + void KerberosFilesHandler::SetFilesChangedForTesting( base::OnceClosure callback) { files_changed_for_testing_ = std::move(callback); } - void KerberosFilesHandler::OnDisabledAuthNegotiateCnameLookupChanged() { // Refresh kerberos files to adjust config for changed pref. get_kerberos_files_.Run();
diff --git a/chrome/browser/chromeos/authpolicy/kerberos_files_handler.h b/chrome/browser/chromeos/authpolicy/kerberos_files_handler.h index 8ca4e98..ee0ca75 100644 --- a/chrome/browser/chromeos/authpolicy/kerberos_files_handler.h +++ b/chrome/browser/chromeos/authpolicy/kerberos_files_handler.h
@@ -40,9 +40,13 @@ explicit KerberosFilesHandler(base::RepeatingClosure get_kerberos_files); ~KerberosFilesHandler(); + // Writes the Kerberos credentials to disk asynchronously. void SetFiles(base::Optional<std::string> krb5cc, base::Optional<std::string> krb5conf); + // Deletes the Kerberos credentials from disk asynchronously. + void DeleteFiles(); + // Sets a callback for when disk IO task posted by SetFiles has finished. void SetFilesChangedForTesting(base::OnceClosure callback);
diff --git a/chrome/browser/chromeos/crostini/crostini_export_import.cc b/chrome/browser/chromeos/crostini/crostini_export_import.cc index af0d4a8..b557a9f 100644 --- a/chrome/browser/chromeos/crostini/crostini_export_import.cc +++ b/chrome/browser/chromeos/crostini/crostini_export_import.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/metrics/histogram_macros.h" #include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chrome/browser/chromeos/crostini/crostini_manager_factory.h" #include "chrome/browser/chromeos/crostini/crostini_share_path.h" @@ -319,6 +320,10 @@ case crostini::CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STARTED: enum_hist_result = ImportContainerResult::kFailedVmStarted; break; + case crostini::CrostiniResult:: + CONTAINER_EXPORT_IMPORT_FAILED_ARCHITECTURE: + enum_hist_result = ImportContainerResult::kFailedArchitecture; + break; default: enum_hist_result = ImportContainerResult::kFailed; } @@ -338,7 +343,9 @@ const std::string& container_name, ImportContainerProgressStatus status, int progress_percent, - uint64_t progress_speed) { + uint64_t progress_speed, + const std::string& architecture_device, + const std::string& architecture_container) { ContainerId container_id(vm_name, container_name); auto it = notifications_.find(container_id); DCHECK(it != notifications_.end()) @@ -357,6 +364,13 @@ CrostiniExportImportNotification::Status::RUNNING, 50 + progress_percent / 2); break; + // Failure, set error message. + case ImportContainerProgressStatus::FAILURE_ARCHITECTURE: + it->second->set_message_failed(l10n_util::GetStringFUTF16( + IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED_ARCHITECTURE, + base::ASCIIToUTF16(architecture_container), + base::ASCIIToUTF16(architecture_device))); + break; default: LOG(WARNING) << "Unknown Export progress status " << int(status); }
diff --git a/chrome/browser/chromeos/crostini/crostini_export_import.h b/chrome/browser/chromeos/crostini/crostini_export_import.h index a3685856..84188388 100644 --- a/chrome/browser/chromeos/crostini/crostini_export_import.h +++ b/chrome/browser/chromeos/crostini/crostini_export_import.h
@@ -10,6 +10,7 @@ #include <string> #include "base/memory/weak_ptr.h" +#include "base/strings/string16.h" #include "base/time/time.h" #include "chrome/browser/chromeos/crostini/crostini_export_import_notification.h" #include "chrome/browser/chromeos/crostini/crostini_manager.h" @@ -43,7 +44,8 @@ kFailed = 1, kFailedVmStopped = 2, kFailedVmStarted = 3, - kMaxValue = kFailedVmStarted, + kFailedArchitecture = 4, + kMaxValue = kFailedArchitecture, }; // CrostiniExportImport is a keyed profile service to manage exporting and @@ -109,11 +111,14 @@ uint64_t progress_speed) override; // crostini::ImportContainerProgressObserver implementation. - void OnImportContainerProgress(const std::string& vm_name, - const std::string& container_name, - crostini::ImportContainerProgressStatus status, - int progress_percent, - uint64_t progress_speed) override; + void OnImportContainerProgress( + const std::string& vm_name, + const std::string& container_name, + crostini::ImportContainerProgressStatus status, + int progress_percent, + uint64_t progress_speed, + const std::string& architecture_device, + const std::string& architecture_container) override; void ExportAfterSharing(const ContainerId& container_id, const base::FilePath& filename,
diff --git a/chrome/browser/chromeos/crostini/crostini_export_import_notification.cc b/chrome/browser/chromeos/crostini/crostini_export_import_notification.cc index 480a54e..d39ae8c4 100644 --- a/chrome/browser/chromeos/crostini/crostini_export_import_notification.cc +++ b/chrome/browser/chromeos/crostini/crostini_export_import_notification.cc
@@ -6,6 +6,7 @@ #include "ash/public/cpp/notification_utils.h" #include "ash/public/cpp/vector_icons/vector_icons.h" +#include "base/strings/utf_string_conversions.h" #include "chrome/browser/chromeos/crostini/crostini_export_import.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/platform_util.h" @@ -39,18 +40,28 @@ // Messages. switch (type) { case ExportImportType::EXPORT: - title_running_ = IDS_CROSTINI_EXPORT_NOTIFICATION_TITLE_RUNNING; - title_done_ = IDS_CROSTINI_EXPORT_NOTIFICATION_TITLE_DONE; - message_done_ = IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_DONE; - title_failed_ = IDS_CROSTINI_EXPORT_NOTIFICATION_TITLE_FAILED; - message_failed_ = IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_FAILED; + title_running_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_EXPORT_NOTIFICATION_TITLE_RUNNING); + title_done_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_EXPORT_NOTIFICATION_TITLE_DONE); + message_done_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_DONE); + title_failed_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_EXPORT_NOTIFICATION_TITLE_FAILED); + message_failed_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_EXPORT_NOTIFICATION_MESSAGE_FAILED); break; case ExportImportType::IMPORT: - title_running_ = IDS_CROSTINI_IMPORT_NOTIFICATION_TITLE_RUNNING; - title_done_ = IDS_CROSTINI_IMPORT_NOTIFICATION_TITLE_DONE; - message_done_ = IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_DONE; - title_failed_ = IDS_CROSTINI_IMPORT_NOTIFICATION_TITLE_FAILED; - message_failed_ = IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED; + title_running_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_IMPORT_NOTIFICATION_TITLE_RUNNING); + title_done_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_IMPORT_NOTIFICATION_TITLE_DONE); + message_done_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_DONE); + title_failed_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_IMPORT_NOTIFICATION_TITLE_FAILED); + message_failed_ = l10n_util::GetStringUTF16( + IDS_CROSTINI_IMPORT_NOTIFICATION_MESSAGE_FAILED); break; default: NOTREACHED(); @@ -88,7 +99,7 @@ } notification_->set_type(message_center::NOTIFICATION_TYPE_PROGRESS); notification_->set_progress(progress_percent); - notification_->set_title(l10n_util::GetStringUTF16(title_running_)); + notification_->set_title(title_running_); notification_->set_message( GetTimeRemainingMessage(started_, progress_percent)); notification_->set_never_timeout(true); @@ -99,16 +110,16 @@ notification_->set_buttons({message_center::ButtonInfo( l10n_util::GetStringUTF16(IDS_DOWNLOAD_LINK_SHOW))}); } - notification_->set_title(l10n_util::GetStringUTF16(title_done_)); - notification_->set_message(l10n_util::GetStringUTF16(message_done_)); + notification_->set_title(title_done_); + notification_->set_message(message_done_); notification_->set_never_timeout(false); break; case Status::FAILED: notification_->set_type(message_center::NOTIFICATION_TYPE_SIMPLE); notification_->set_accent_color( ash::kSystemNotificationColorCriticalWarning); - notification_->set_title(l10n_util::GetStringUTF16(title_failed_)); - notification_->set_message(l10n_util::GetStringUTF16(message_failed_)); + notification_->set_title(title_failed_); + notification_->set_message(message_failed_); notification_->set_never_timeout(false); break; default:
diff --git a/chrome/browser/chromeos/crostini/crostini_export_import_notification.h b/chrome/browser/chromeos/crostini/crostini_export_import_notification.h index cc85bf35b..c4cdc5ff 100644 --- a/chrome/browser/chromeos/crostini/crostini_export_import_notification.h +++ b/chrome/browser/chromeos/crostini/crostini_export_import_notification.h
@@ -39,6 +39,9 @@ virtual ~CrostiniExportImportNotification(); void UpdateStatus(Status status, int progress_percent); + void set_message_failed(const base::string16& message) { + message_failed_ = message; + } // Getters for testing. Status get_status() { return status_; } @@ -60,11 +63,11 @@ Status status_ = Status::RUNNING; // Time when the operation started. Used for estimating time remaining. base::Time started_ = base::Time::Now(); - int title_running_; - int title_done_; - int message_done_; - int title_failed_; - int message_failed_; + base::string16 title_running_; + base::string16 title_done_; + base::string16 message_done_; + base::string16 title_failed_; + base::string16 message_failed_; std::unique_ptr<message_center::Notification> notification_; bool closed_ = false; base::WeakPtrFactory<CrostiniExportImportNotification> weak_ptr_factory_;
diff --git a/chrome/browser/chromeos/crostini/crostini_manager.cc b/chrome/browser/chromeos/crostini/crostini_manager.cc index b981be25..b78f6ad5 100644 --- a/chrome/browser/chromeos/crostini/crostini_manager.cc +++ b/chrome/browser/chromeos/crostini/crostini_manager.cc
@@ -2587,47 +2587,59 @@ if (signal.owner_id() != owner_id_) return; - bool importing = false; + bool call_observers = false; + bool call_original_callback = false; ImportContainerProgressStatus status; CrostiniResult result; switch (signal.status()) { case vm_tools::cicerone::ImportLxdContainerProgressSignal::IMPORTING_UPLOAD: - importing = true; + call_observers = true; status = ImportContainerProgressStatus::UPLOAD; break; case vm_tools::cicerone::ImportLxdContainerProgressSignal::IMPORTING_UNPACK: - importing = true; + call_observers = true; status = ImportContainerProgressStatus::UNPACK; break; case vm_tools::cicerone::ImportLxdContainerProgressSignal::DONE: + call_original_callback = true; result = CrostiniResult::SUCCESS; break; + case vm_tools::cicerone::ImportLxdContainerProgressSignal:: + FAILED_ARCHITECTURE: + call_observers = true; + status = ImportContainerProgressStatus::FAILURE_ARCHITECTURE; + call_original_callback = true; + result = CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_ARCHITECTURE; + break; default: + call_original_callback = true; result = CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED; LOG(ERROR) << "Failed during import container: " << signal.status() << ", " << signal.failure_reason(); } - // If we are still importing, call progress observers. - if (importing) { + // Call progress observers. + if (call_observers) { for (auto& observer : import_container_progress_observers_) { observer.OnImportContainerProgress( signal.vm_name(), signal.container_name(), status, - signal.progress_percent(), signal.progress_speed()); + signal.progress_percent(), signal.progress_speed(), + signal.architecture_device(), signal.architecture_container()); } - return; } // Invoke original callback with either success or failure. - auto key = std::make_pair(signal.vm_name(), signal.container_name()); - auto it = import_lxd_container_callbacks_.find(key); - if (it == import_lxd_container_callbacks_.end()) { - LOG(ERROR) << "No import callback for " << signal.vm_name() << ", " - << signal.container_name(); - return; + if (call_original_callback) { + auto key = std::make_pair(signal.vm_name(), signal.container_name()); + auto it = import_lxd_container_callbacks_.find(key); + if (it == import_lxd_container_callbacks_.end()) { + LOG(ERROR) << "No import callback for " << signal.vm_name() << ", " + << signal.container_name(); + return; + } + std::move(it->second).Run(result); + import_lxd_container_callbacks_.erase(it); } - std::move(it->second).Run(result); - import_lxd_container_callbacks_.erase(it); } } // namespace crostini
diff --git a/chrome/browser/chromeos/crostini/crostini_manager.h b/chrome/browser/chromeos/crostini/crostini_manager.h index 8ef3453..25e17b1 100644 --- a/chrome/browser/chromeos/crostini/crostini_manager.h +++ b/chrome/browser/chromeos/crostini/crostini_manager.h
@@ -70,6 +70,7 @@ CONTAINER_EXPORT_IMPORT_FAILED, CONTAINER_EXPORT_IMPORT_FAILED_VM_STOPPED, CONTAINER_EXPORT_IMPORT_FAILED_VM_STARTED, + CONTAINER_EXPORT_IMPORT_FAILED_ARCHITECTURE, NOT_ALLOWED, }; @@ -100,6 +101,7 @@ enum class ImportContainerProgressStatus { UPLOAD, UNPACK, + FAILURE_ARCHITECTURE, }; struct VmInfo { @@ -181,12 +183,15 @@ public: // A successfully started container import will continually fire progress // events until the original callback from ImportLxdContainer is invoked with - // a status of SUCCESS or CONTAINER_IMPORT_FAILED. - virtual void OnImportContainerProgress(const std::string& vm_name, - const std::string& container_name, - ImportContainerProgressStatus status, - int progress_percent, - uint64_t progress_speed) = 0; + // a status of SUCCESS or CONTAINER_IMPORT_FAILED[_*]. + virtual void OnImportContainerProgress( + const std::string& vm_name, + const std::string& container_name, + ImportContainerProgressStatus status, + int progress_percent, + uint64_t progress_speed, + const std::string& architecture_device, + const std::string& architecture_container) = 0; }; class InstallerViewStatusObserver : public base::CheckedObserver {
diff --git a/chrome/browser/chromeos/crostini/crostini_manager_unittest.cc b/chrome/browser/chromeos/crostini/crostini_manager_unittest.cc index 5cede0b..efbbc59 100644 --- a/chrome/browser/chromeos/crostini/crostini_manager_unittest.cc +++ b/chrome/browser/chromeos/crostini/crostini_manager_unittest.cc
@@ -1227,6 +1227,29 @@ run_loop()->Run(); } +TEST_F(CrostiniManagerTest, ImportContainerFailArchitecture) { + crostini_manager()->ImportLxdContainer( + kVmName, kContainerName, base::FilePath("import_path"), + base::BindOnce( + &CrostiniManagerTest::CrostiniResultCallback, base::Unretained(this), + run_loop()->QuitClosure(), + CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_ARCHITECTURE)); + + // Send signal with FAILED_ARCHITECTURE. + vm_tools::cicerone::ImportLxdContainerProgressSignal signal; + signal.set_owner_id(CryptohomeIdForProfile(profile())); + signal.set_vm_name(kVmName); + signal.set_container_name(kContainerName); + signal.set_status( + vm_tools::cicerone:: + ImportLxdContainerProgressSignal_Status_FAILED_ARCHITECTURE); + signal.set_architecture_device("archdev"); + signal.set_architecture_container("archcont"); + fake_cicerone_client_->NotifyImportLxdContainerProgress(signal); + + run_loop()->Run(); +} + TEST_F(CrostiniManagerTest, ImportContainerFailFromSignal) { crostini_manager()->ImportLxdContainer( kVmName, kContainerName, base::FilePath("import_path"),
diff --git a/chrome/browser/chromeos/kerberos/OWNERS b/chrome/browser/chromeos/kerberos/OWNERS new file mode 100644 index 0000000..65a577e7 --- /dev/null +++ b/chrome/browser/chromeos/kerberos/OWNERS
@@ -0,0 +1,7 @@ +# This is for the common case of adding or renaming files. If you're doing +# structural changes, use usual OWNERS rules. +per-file BUILD.gn=* + +ljusten@chromium.org + +# COMPONENT: Enterprise>ActiveDirectory
diff --git a/chrome/browser/chromeos/kerberos/kerberos_credentials_manager.cc b/chrome/browser/chromeos/kerberos/kerberos_credentials_manager.cc new file mode 100644 index 0000000..b2655dfd --- /dev/null +++ b/chrome/browser/chromeos/kerberos/kerberos_credentials_manager.cc
@@ -0,0 +1,442 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/kerberos/kerberos_credentials_manager.h" + +#include "base/bind.h" +#include "base/strings/string_split.h" +#include "base/strings/stringprintf.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/browser_process_platform_part_chromeos.h" +#include "chrome/browser/chromeos/authpolicy/data_pipe_utils.h" +#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" +#include "chrome/browser/profiles/profile.h" +#include "chromeos/components/account_manager/account_manager.h" +#include "chromeos/components/account_manager/account_manager_factory.h" +#include "chromeos/dbus/kerberos/kerberos_client.h" +#include "chromeos/dbus/kerberos/kerberos_service.pb.h" +#include "chromeos/dbus/upstart/upstart_client.h" +#include "dbus/message.h" +#include "third_party/cros_system_api/dbus/kerberos/dbus-constants.h" + +namespace chromeos { + +namespace { + +// Default encryption with strong encryption. +constexpr char kDefaultKerberosConfigFmt[] = R"( +[libdefaults] + default_tgs_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 + default_tkt_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 + permitted_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 + default_realm = %s +)"; + +AccountManager* GetAccountManager(Profile* profile) { + DCHECK(profile); + AccountManagerFactory* factory = + g_browser_process->platform_part()->GetAccountManagerFactory(); + return factory->GetAccountManager(profile->GetPath().value()); +} + +AccountManager::AccountKey GetAccountKey(const std::string& principal_name) { + return AccountManager::AccountKey{ + principal_name, + account_manager::AccountType::ACCOUNT_TYPE_ACTIVE_DIRECTORY}; +} + +// If |principal_name| is "UsEr@realm.com", sets |principal_name| to +// "user@REALM.COM". Returns false if the given name has no @ or one of the +// parts is empty. +bool NormalizePrincipal(std::string* principal_name) { + std::vector<std::string> parts = base::SplitString( + *principal_name, "@", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); + if (parts.size() != 2 || parts.at(0).empty() || parts.at(1).empty()) + return false; + *principal_name = + base::ToLowerASCII(parts[0]) + "@" + base::ToUpperASCII(parts[1]); + return true; +} + +// Tries to normalize |principal_name|. Runs |callback| with +// |ERROR_PARSE_PRINCIPAL_FAILED| if not possible. +bool NormalizePrincipalOrPostCallback( + std::string* principal_name, + KerberosCredentialsManager::ResultCallback* callback) { + if (NormalizePrincipal(principal_name)) + return true; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(*callback), + kerberos::ERROR_PARSE_PRINCIPAL_FAILED)); + return false; +} + +// If |normalized_principal| is "user@REALM.COM", returns "REALM.COM". +// DCHECKs valid format. +std::string GetRealm(const std::string& normalized_principal) { + std::vector<std::string> parts = base::SplitString( + normalized_principal, "@", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); + DCHECK(parts.size() == 2); + DCHECK(!parts[1].empty()); + return parts[1]; +} + +// Logs an error if |error| is not |ERROR_NONE|. +void LogError(const char* function_name, kerberos::ErrorType error) { + LOG_IF(ERROR, error != kerberos::ERROR_NONE) + << function_name << " failed with error code " << error; +} + +// Returns true if |error| is |ERROR_NONE|. +bool Succeeded(kerberos::ErrorType error) { + return error == kerberos::ERROR_NONE; +} + +} // namespace + +// Encapsulates the steps to add a Kerberos account. Overview of the flow: +// - Start up the daemon. +// - Call daemon's AddAccount. Handle errors duplicate errors transparently, +// it's OK if the account is already present. +// - If the account is new, call daemon's SetConfig with a default config. +// - Call daemon's AcquireKerberosTgt. +// - Call manager's OnAddAccountRunnerDone. +// If an error happens on any step, removes account if it was added and calls +// OnAddAccountRunnerDone with the error. +class KerberosAddAccountRunner { + public: + // Kicks off the flow to add (or re-authenticate) a Kerberos account. + // |manager| is a non-owned pointer to the owning manager. + // |normalized_principal| is the normalized user principal name, e.g. + // user@REALM.COM. |password| is the password of the account. |callback| is + // called by OnAddAccountRunnerDone() at the end of the flow, see class + // description. + KerberosAddAccountRunner(KerberosCredentialsManager* manager, + const std::string& normalized_principal, + const std::string& password, + KerberosCredentialsManager::ResultCallback callback) + : manager_(manager), + normalized_principal_(normalized_principal), + password_(password), + callback_(std::move(callback)) { + StartKerberosDaemon(); + } + + private: + // Make sure the Kerberos daemon is running. + void StartKerberosDaemon() { + UpstartClient::Get()->StartKerberosService( + base::BindOnce(&KerberosAddAccountRunner::OnStartKerberosService, + weak_factory_.GetWeakPtr())); + } + + // Gets called when the daemon has been started or failed to start. + void OnStartKerberosService(bool success) { + if (success) + AddAccount(); + else + Done(kerberos::ERROR_DBUS_FAILURE); + } + + // Adds the |normalized_principal_| account to the Kerberos daemon. + void AddAccount() { + kerberos::AddAccountRequest request; + request.set_principal_name(normalized_principal_); + KerberosClient::Get()->AddAccount( + request, base::BindOnce(&KerberosAddAccountRunner::OnAddAccount, + weak_factory_.GetWeakPtr())); + } + + // If the account was added (new account), calls SetDefaultConfig(). + // Otherwise, continues with AcquireKerberosTgt(). + void OnAddAccount(const kerberos::AddAccountResponse& response) { + // New account, set a default config. + if (response.error() == kerberos::ERROR_NONE) { + was_added_ = true; + SetDefaultConfig(); + return; + } + + if (response.error() == kerberos::ERROR_DUPLICATE_PRINCIPAL_NAME) { + AcquireKerberosTgt(); + return; + } + + // In all other cases, respond with error (shouldn't happen right now). + NOTREACHED(); + Done(response.error()); + } + + // Sets a default Kerberos configuration for |normalized_principal_|. + void SetDefaultConfig() { + const std::string realm = GetRealm(normalized_principal_); + const std::string krb5_conf = + base::StringPrintf(kDefaultKerberosConfigFmt, realm.c_str()); + + kerberos::SetConfigRequest request; + request.set_principal_name(normalized_principal_); + request.set_krb5conf(krb5_conf); + KerberosClient::Get()->SetConfig( + request, base::BindOnce(&KerberosAddAccountRunner::OnSetConfig, + weak_factory_.GetWeakPtr())); + } + + // Calls AcquireKerberosTgt() if no error occurred or Done() otherwise. + void OnSetConfig(const kerberos::SetConfigResponse& response) { + if (response.error() == kerberos::ERROR_NONE) { + AcquireKerberosTgt(); + return; + } + + Done(response.error()); + } + + // Authenticates |normalized_principal_| using |password_|. + void AcquireKerberosTgt() { + kerberos::AcquireKerberosTgtRequest request; + request.set_principal_name(normalized_principal_); + KerberosClient::Get()->AcquireKerberosTgt( + request, data_pipe_utils::GetDataReadPipe(password_).get(), + base::BindOnce(&KerberosAddAccountRunner::OnAcquireKerberosTgt, + weak_factory_.GetWeakPtr())); + } + + // Forwards to Done(). + void OnAcquireKerberosTgt( + const kerberos::AcquireKerberosTgtResponse& response) { + // We're ready. + Done(response.error()); + } + + // Calls back into |manager_|'s OnAddAccountRunnerDone(). + void Done(kerberos::ErrorType error) { + if (was_added_ && error != kerberos::ERROR_NONE) { + // Do a best effort cleaning up the account we added before. + kerberos::RemoveAccountRequest request; + request.set_principal_name(normalized_principal_); + KerberosClient::Get()->RemoveAccount( + request, base::BindOnce(&KerberosAddAccountRunner::OnRemoveAccount, + weak_factory_.GetWeakPtr(), error)); + } else { + // We're done. This call will delete us! + manager_->OnAddAccountRunnerDone(this, std::move(normalized_principal_), + std::move(callback_), error); + } + } + + // Prints out a warning if |removal_error| is an error case and forwards + // |original_error| to Done(). + void OnRemoveAccount(kerberos::ErrorType original_error, + const kerberos::RemoveAccountResponse& response) { + if (response.error() != kerberos::ERROR_NONE) { + LOG(WARNING) << "Failed to remove Kerberos account for " + << normalized_principal_; + } + + // We're done. This call will delete us! Note that we're passing the + // |original_error| here, not the |response.error()|. + manager_->OnAddAccountRunnerDone(this, std::move(normalized_principal_), + std::move(callback_), original_error); + } + + // Pointer to the owning manager, not owned. + KerberosCredentialsManager* const manager_; + std::string normalized_principal_; + std::string password_; + KerberosCredentialsManager::ResultCallback callback_; + + // Whether the account was newly added. + bool was_added_ = false; + + base::WeakPtrFactory<KerberosAddAccountRunner> weak_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(KerberosAddAccountRunner); +}; + +KerberosCredentialsManager::KerberosCredentialsManager(Profile* profile) + : profile_(profile), + kerberos_files_handler_( + base::BindRepeating(&KerberosCredentialsManager::GetKerberosFiles, + base::Unretained(this))) { + // Connect to a signal that indicates when Kerberos files change. + KerberosClient::Get()->ConnectToKerberosFileChangedSignal( + base::BindRepeating(&KerberosCredentialsManager::OnKerberosFilesChanged, + weak_factory_.GetWeakPtr())); +} + +KerberosCredentialsManager::~KerberosCredentialsManager() = default; + +void KerberosCredentialsManager::AddAccountAndAuthenticate( + std::string principal_name, + const std::string& password, + ResultCallback callback) { + if (!NormalizePrincipalOrPostCallback(&principal_name, &callback)) + return; + + // If there's a call in progress, respond with ERROR_IN_PROGRESS. + if (add_account_runner_) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(std::move(callback), kerberos::ERROR_IN_PROGRESS)); + return; + } + + add_account_runner_ = std::make_unique<KerberosAddAccountRunner>( + this, principal_name, password, std::move(callback)); + // The runner starts automatically and calls OnAddAccountRunnerDone when it's + // done. +} + +void KerberosCredentialsManager::OnAddAccountRunnerDone( + KerberosAddAccountRunner* runner, + std::string normalized_principal, + ResultCallback callback, + kerberos::ErrorType error) { + // Reset the instance. + DCHECK(runner == add_account_runner_.get()); + add_account_runner_.reset(); + + LogError("AddAccountAndAuthenticate", error); + if (Succeeded(error)) { + // Add it to the account manager if it's not already there. + GetAccountManager(profile_)->UpsertAccount( + GetAccountKey(normalized_principal), normalized_principal, + AccountManager::kActiveDirectoryDummyToken); + + // Set active account. + // TODO(https://crbug.com/948121): Wait until the files have been saved. + // This is important when this code is triggered directly through a page + // that requires Kerberos auth. + active_principal_name_ = normalized_principal; + GetKerberosFiles(); + } + + std::move(callback).Run(error); +} + +void KerberosCredentialsManager::RemoveAccount(std::string principal_name, + ResultCallback callback) { + if (!NormalizePrincipalOrPostCallback(&principal_name, &callback)) + return; + + kerberos::RemoveAccountRequest request; + request.set_principal_name(principal_name); + KerberosClient::Get()->RemoveAccount( + request, base::BindOnce(&KerberosCredentialsManager::OnRemoveAccount, + weak_factory_.GetWeakPtr(), principal_name, + std::move(callback))); +} + +void KerberosCredentialsManager::OnRemoveAccount( + const std::string& principal_name, + ResultCallback callback, + const kerberos::RemoveAccountResponse& response) { + LogError("RemoveAccount", response.error()); + if (Succeeded(response.error())) { + // Clear out active credentials. + if (active_principal_name_ == principal_name) { + kerberos_files_handler_.DeleteFiles(); + active_principal_name_.clear(); + } + + // Remove from account manager. + GetAccountManager(profile_)->RemoveAccount(GetAccountKey(principal_name)); + } + + std::move(callback).Run(response.error()); +} + +kerberos::ErrorType KerberosCredentialsManager::SetActiveAccount( + std::string principal_name) { + if (!NormalizePrincipal(&principal_name)) + return kerberos::ERROR_PARSE_PRINCIPAL_FAILED; + + // Don't early out if names are equal, this might be required to bootstrap + // Kerberos credentials. + active_principal_name_ = principal_name; + GetKerberosFiles(); + return kerberos::ERROR_NONE; +} + +void KerberosCredentialsManager::SetConfig(std::string principal_name, + const std::string& krb5_conf, + ResultCallback callback) { + if (!NormalizePrincipalOrPostCallback(&principal_name, &callback)) + return; + + kerberos::SetConfigRequest request; + request.set_principal_name(principal_name); + request.set_krb5conf(krb5_conf); + KerberosClient::Get()->SetConfig( + request, base::BindOnce(&KerberosCredentialsManager::OnSetConfig, + weak_factory_.GetWeakPtr(), std::move(callback))); +} + +void KerberosCredentialsManager::OnSetConfig( + ResultCallback callback, + const kerberos::SetConfigResponse& response) { + LogError("SetConfig", response.error()); + std::move(callback).Run(response.error()); +} + +void KerberosCredentialsManager::AcquireKerberosTgt(std::string principal_name, + const std::string& password, + ResultCallback callback) { + if (!NormalizePrincipalOrPostCallback(&principal_name, &callback)) + return; + + kerberos::AcquireKerberosTgtRequest request; + request.set_principal_name(principal_name); + KerberosClient::Get()->AcquireKerberosTgt( + request, data_pipe_utils::GetDataReadPipe(password).get(), + base::BindOnce(&KerberosCredentialsManager::OnAcquireKerberosTgt, + weak_factory_.GetWeakPtr(), std::move(callback))); +} + +void KerberosCredentialsManager::OnAcquireKerberosTgt( + ResultCallback callback, + const kerberos::AcquireKerberosTgtResponse& response) { + LogError("AcquireKerberosTgt", response.error()); + std::move(callback).Run(response.error()); +} + +void KerberosCredentialsManager::GetKerberosFiles() { + if (active_principal_name_.empty()) + return; + + kerberos::GetKerberosFilesRequest request; + request.set_principal_name(active_principal_name_); + KerberosClient::Get()->GetKerberosFiles( + request, + base::BindOnce(&KerberosCredentialsManager::OnGetKerberosFiles, + weak_factory_.GetWeakPtr(), request.principal_name())); +} + +void KerberosCredentialsManager::OnGetKerberosFiles( + const std::string& principal_name, + const kerberos::GetKerberosFilesResponse& response) { + LogError("GetKerberosFiles", response.error()); + if (!Succeeded(response.error())) + return; + + // Ignore if the principal changed in the meantime. + if (active_principal_name_ != principal_name) { + VLOG(1) << "Ignoring Kerberos files. Active principal changed from " + << principal_name << " to " << active_principal_name_; + return; + } + + auto nullstr = base::Optional<std::string>(); + kerberos_files_handler_.SetFiles( + response.files().has_krb5cc() ? response.files().krb5cc() : nullstr, + response.files().has_krb5conf() ? response.files().krb5conf() : nullstr); +} + +void KerberosCredentialsManager::OnKerberosFilesChanged( + const std::string& principal_name) { + // Only listen to the active account. + if (principal_name == active_principal_name_) + GetKerberosFiles(); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/kerberos/kerberos_credentials_manager.h b/chrome/browser/chromeos/kerberos/kerberos_credentials_manager.h new file mode 100644 index 0000000..56f7cc4d --- /dev/null +++ b/chrome/browser/chromeos/kerberos/kerberos_credentials_manager.h
@@ -0,0 +1,107 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_KERBEROS_KERBEROS_CREDENTIALS_MANAGER_H_ +#define CHROME_BROWSER_CHROMEOS_KERBEROS_KERBEROS_CREDENTIALS_MANAGER_H_ + +#include <string> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/chromeos/authpolicy/kerberos_files_handler.h" +#include "chromeos/dbus/kerberos/kerberos_service.pb.h" + +class Profile; + +namespace chromeos { + +class KerberosAddAccountRunner; + +class KerberosCredentialsManager { + public: + using ResultCallback = base::OnceCallback<void(kerberos::ErrorType)>; + + explicit KerberosCredentialsManager(Profile* profile); + ~KerberosCredentialsManager(); + + // Adds an account for the given |principal_name| and authenticates it using + // the given |password|. Sets |principal_name| as active principal on success. + void AddAccountAndAuthenticate(std::string principal_name, + const std::string& password, + ResultCallback callback); + + // Removes the Kerberos account for the account with given |principal_name|. + void RemoveAccount(std::string principal_name, ResultCallback callback); + + // Sets the contents of the Kerberos configuration (krb5.conf) to |krb5_conf| + // for the account with given |principal_name|. + void SetConfig(std::string principal_name, + const std::string& krb5_conf, + ResultCallback callback); + + // Gets a Kerberos ticket-granting-ticket for the account with given + // |principal_name|. + void AcquireKerberosTgt(std::string principal_name, + const std::string& password, + ResultCallback callback); + + // Sets the currently active account. + kerberos::ErrorType SetActiveAccount(std::string principal_name); + + private: + friend class KerberosAddAccountRunner; + + // Callback on KerberosAddAccountRunner::Done. + void OnAddAccountRunnerDone(KerberosAddAccountRunner* runner, + std::string principal_name, + ResultCallback callback, + kerberos::ErrorType error); + + // Callback for RemoveAccount(). + void OnRemoveAccount(const std::string& principal_name, + ResultCallback callback, + const kerberos::RemoveAccountResponse& response); + + // Callback for SetConfig(). + void OnSetConfig(ResultCallback callback, + const kerberos::SetConfigResponse& response); + + // Callback for AcquireKerberosTgt(). + void OnAcquireKerberosTgt( + ResultCallback callback, + const kerberos::AcquireKerberosTgtResponse& response); + + // Calls KerberosClient::GetKerberosFiles(). + void GetKerberosFiles(); + + // Callback for GetKerberosFiles(). + void OnGetKerberosFiles(const std::string& principal_name, + const kerberos::GetKerberosFilesResponse& response); + + // Callback for 'KerberosFilesChanged' D-Bus signal sent by kerberosd. + void OnKerberosFilesChanged(const std::string& principal_name); + + // Called when connected to 'KerberosFilesChanged' signal. + void OnSignalConnected(const std::string& interface_name, + const std::string& signal_name, + bool success); + + Profile* const profile_ = nullptr; + + // Called by OnSignalConnected(), puts Kerberos files where GSSAPI finds them. + KerberosFilesHandler kerberos_files_handler_; + + // Handles the steps to add a Kerberos account. + std::unique_ptr<KerberosAddAccountRunner> add_account_runner_; + + // Currently active principal. + std::string active_principal_name_; + + base::WeakPtrFactory<KerberosCredentialsManager> weak_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(KerberosCredentialsManager); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_KERBEROS_KERBEROS_CREDENTIALS_MANAGER_H_
diff --git a/chrome/browser/chromeos/kiosk_next_home/app_controller_service.cc b/chrome/browser/chromeos/kiosk_next_home/app_controller_service.cc index f109680b..6b161b9 100644 --- a/chrome/browser/chromeos/kiosk_next_home/app_controller_service.cc +++ b/chrome/browser/chromeos/kiosk_next_home/app_controller_service.cc
@@ -70,9 +70,11 @@ // be consumed. Refer to AppRegistryCache::ForEachApp for more information. app_service_proxy_->AppRegistryCache().ForEachApp( [this, &app_list](const apps::AppUpdate& update) { - // Only include relevant apps. - if (AppIsRelevantForKioskNextHome(update)) + // Only include apps that are both relevant and installed. + if (AppIsRelevantForKioskNextHome(update) && + update.Readiness() != apps::mojom::Readiness::kUninstalledByUser) { app_list.push_back(CreateAppPtr(update)); + } }); std::move(callback).Run(std::move(app_list)); } @@ -82,10 +84,8 @@ } void AppControllerService::LaunchApp(const std::string& app_id) { - // TODO(ltenorio): Create a new launch source for Kiosk Next Home and use it - // here. app_service_proxy_->Launch(app_id, ui::EventFlags::EF_NONE, - apps::mojom::LaunchSource::kFromAppListGrid, + apps::mojom::LaunchSource::kFromKioskNextHome, display::kDefaultDisplayId); }
diff --git a/chrome/browser/chromeos/kiosk_next_home/app_controller_service_unittest.cc b/chrome/browser/chromeos/kiosk_next_home/app_controller_service_unittest.cc index 4c7e40e1..169c6881 100644 --- a/chrome/browser/chromeos/kiosk_next_home/app_controller_service_unittest.cc +++ b/chrome/browser/chromeos/kiosk_next_home/app_controller_service_unittest.cc
@@ -412,6 +412,27 @@ ExpectApps({first_expected_app, second_expected_app}); } +TEST_F(AppControllerServiceTest, UninstalledAppsAreFiltered) { + // First seed an installed app and expect it to be returned. + apps::mojom::App app_delta; + app_delta.app_id = "app_id"; + app_delta.app_type = AppType::kBuiltIn; + app_delta.show_in_launcher = OptionalBool::kTrue; + app_delta.readiness = Readiness::kReady; + AddAppDeltaToAppService(app_delta.Clone()); + + mojom::App app; + app.app_id = "app_id"; + app.type = AppType::kBuiltIn; + app.readiness = Readiness::kReady; + ExpectApps({app}); + + // Then change the app's readiness and expect it to be filtered. + app_delta.readiness = Readiness::kUninstalledByUser; + AddAppDeltaToAppService(app_delta.Clone()); + ExpectApps({}); +} + TEST_F(AppControllerServiceTest, AppsThatAreNotRelevantAreFiltered) { // Seed an app that's allowed to be returned by the AppControllerService. apps::mojom::App allowed_app_delta;
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index da7b75b..83195747 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -1903,13 +1903,13 @@ }, { "name": "enable-webrtc-hybrid-agc", - // "owners": [ "your-team" ], - "expiry_milestone": 76 + "owners": [ "aleloi" ], + "expiry_milestone": 83 }, { "name": "enable-webrtc-new-encode-cpu-load-estimator", - // "owners": [ "your-team" ], - "expiry_milestone": 76 + "owners": [ "nisse" ], + "expiry_milestone": 77 }, { "name": "enable-webrtc-pipewire-capturer",
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index 2b59b08..2052e76 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -781,6 +781,11 @@ popup_controller_->FrameWasScrolled(); } +void ChromePasswordManagerClient::GenerationElementLostFocus() { + if (popup_controller_) + popup_controller_->GenerationElementLostFocus(); +} + const GURL& ChromePasswordManagerClient::GetMainFrameURL() const { return web_contents()->GetVisibleURL(); }
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.h b/chrome/browser/password_manager/chrome_password_manager_client.h index 275220c..ed7f872 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.h +++ b/chrome/browser/password_manager/chrome_password_manager_client.h
@@ -142,6 +142,7 @@ void PasswordNoLongerGenerated( const autofill::PasswordForm& password_form) override; void FrameWasScrolled() override; + void GenerationElementLostFocus() override; #if defined(FULL_SAFE_BROWSING) void CheckSafeBrowsingReputation(const GURL& form_action,
diff --git a/chrome/browser/password_manager/password_generation_interactive_uitest.cc b/chrome/browser/password_manager/password_generation_interactive_uitest.cc index 1c105893..e166320 100644 --- a/chrome/browser/password_manager/password_generation_interactive_uitest.cc +++ b/chrome/browser/password_manager/password_generation_interactive_uitest.cc
@@ -163,6 +163,11 @@ WebContents(), "document.getElementById('password_field').focus()")); } + void FocusUsernameField() { + ASSERT_TRUE(content::ExecuteScript( + WebContents(), "document.getElementById('username_field').focus();")); + } + void SendKeyToPopup(ui::KeyboardCode key) { content::NativeWebKeyboardEvent event( blink::WebKeyboardEvent::kRawKeyDown, @@ -283,6 +288,16 @@ FocusPasswordField(); EXPECT_TRUE(GenerationPopupShowing()); + FocusUsernameField(); + + // Popup is dismissed. + EXPECT_FALSE(GenerationPopupShowing()); +} +IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest, + PopupShownAndDismissedByKeyPress) { + FocusPasswordField(); + EXPECT_TRUE(GenerationPopupShowing()); + SendKeyToPopup(ui::VKEY_ESCAPE); // Popup is dismissed. @@ -331,8 +346,7 @@ SendKeyToPopup(ui::VKEY_RETURN); // Change username. - std::string focus("document.getElementById('username_field').focus();"); - ASSERT_TRUE(content::ExecuteScript(WebContents(), focus)); + FocusUsernameField(); content::SimulateKeyPress(WebContents(), ui::DomKey::FromCharacter('U'), ui::DomCode::US_U, ui::VKEY_U, false, false, false, false);
diff --git a/chrome/browser/resources/print_preview/new/BUILD.gn b/chrome/browser/resources/print_preview/new/BUILD.gn index fc5186a..30678d2cc 100644 --- a/chrome/browser/resources/print_preview/new/BUILD.gn +++ b/chrome/browser/resources/print_preview/new/BUILD.gn
@@ -44,6 +44,10 @@ ":settings_select", ":state", ] + + if (is_chromeos) { + deps += [ ":pin_settings" ] + } } js_library("app") { @@ -98,6 +102,10 @@ "../data:destination", "//ui/webui/resources/js:cr", ] + + if (is_chromeos) { + deps += [ ":pin_settings" ] + } } js_library("header") { @@ -146,6 +154,15 @@ externs_list = [ "$externs_path/pending.js" ] } +if (is_chromeos) { + js_library("pin_settings") { + deps = [ + ":input_behavior", + ":settings_behavior", + ] + } +} + js_library("pages_settings") { deps = [ ":input_behavior",
diff --git a/chrome/browser/resources/print_preview/new/destination_settings.html b/chrome/browser/resources/print_preview/new/destination_settings.html index 8d66637..673475cd 100644 --- a/chrome/browser/resources/print_preview/new/destination_settings.html +++ b/chrome/browser/resources/print_preview/new/destination_settings.html
@@ -24,6 +24,12 @@ <dom-module id="print-preview-destination-settings"> <template> <style include="print-preview-shared throbber cr-hidden-style"> +<if expr="chromeos"> + :host([has-pin-setting_]) { + margin-bottom: 0 !important; + } +</if> + .throbber-container { align-items: center; display: flex;
diff --git a/chrome/browser/resources/print_preview/new/destination_settings.js b/chrome/browser/resources/print_preview/new/destination_settings.js index 196bdae..753d7623 100644 --- a/chrome/browser/resources/print_preview/new/destination_settings.js +++ b/chrome/browser/resources/print_preview/new/destination_settings.js
@@ -81,6 +81,14 @@ value: null, }, + // <if expr="chromeos"> + hasPinSetting_: { + type: Boolean, + computed: 'computeHasPinSetting_(settings.pin.available)', + reflectToAttribute: true, + }, + // </if> + /** @private {?print_preview.InvitationStore} */ invitationStore_: { type: Object, @@ -398,6 +406,16 @@ this.destination.connectionStatusText; }, + // <if expr="chromeos"> + /** + * @return {boolean} + * @private + */ + computeHasPinSetting_: function() { + return this.getSetting('pin').available; + }, + // </if> + /** * @param {!CustomEvent<string>} e Event containing the new selected value. * @private
diff --git a/chrome/browser/resources/print_preview/new/pin_settings.html b/chrome/browser/resources/print_preview/new/pin_settings.html new file mode 100644 index 0000000..0e70698 --- /dev/null +++ b/chrome/browser/resources/print_preview/new/pin_settings.html
@@ -0,0 +1,64 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html"> +<link rel="import" href="input_behavior.html"> +<link rel="import" href="print_preview_shared_css.html"> +<link rel="import" href="settings_behavior.html"> +<link rel="import" href="settings_section.html"> + +<dom-module id="print-preview-pin-settings"> + <template> + <style include="print-preview-shared"> + :host { + margin-top: 0 !important; + } + + :host([input-valid_]) #pinValue { + --cr-input-error-display: none; + } + + /* Margin = standard margin (16px) - error field margin (8px) */ + :host([!input-valid_]) #customInputWrapper { + margin-bottom: 8px; + } + + #pinValue { + --cr-form-field-label-height: 100%; + --cr-input-row-container: { + min-height: 38px; + } + cursor: default; + } + + :host #title { + align-self: baseline; + } + </style> + <print-preview-settings-section> + <div slot="title"></div> + <div slot="controls" class="checkbox"> + <cr-checkbox id="pin" on-change="onPinChange_" + disabled="[[checkboxDisabled_]]" aria-labelledby="pin-label"> + <span id="pin-label">$i18n{optionPin}</span> + </cr-checkbox> + </div> + </print-preview-settings-section> + <iron-collapse opened="[[pinEnabled_]]" + on-transitionend="onCollapseChanged_"> + <print-preview-settings-section id="customInputWrapper"> + <div slot="title"></div> + <div slot="controls"> + <cr-input id="pinValue" type="text" pattern="[0-9]{4}" minlength="4" + maxlength="4" data-timeout-delay="250" aria-labelledby="pin" + placeholder="$i18n{pinPlaceholder}" spellcheck="false" + disabled$="[[inputDisabled_(pinEnabled_, inputValid_, disabled)]]" + error-message="$i18n{pinErrorMessage}" auto-validate> + </cr-input> + </div> + </print-preview-settings-section> + </iron-collapse> + </template> + <script src="pin_settings.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/print_preview/new/pin_settings.js b/chrome/browser/resources/print_preview/new/pin_settings.js new file mode 100644 index 0000000..fc87cfc0 --- /dev/null +++ b/chrome/browser/resources/print_preview/new/pin_settings.js
@@ -0,0 +1,131 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +Polymer({ + is: 'print-preview-pin-settings', + + behaviors: [SettingsBehavior, print_preview_new.InputBehavior], + + properties: { + disabled: Boolean, + + /** @private {boolean} */ + checkboxDisabled_: { + type: Boolean, + computed: 'computeCheckboxDisabled_(inputValid_, disabled, ' + + 'settings.pin.setByPolicy)', + }, + + /** @private {boolean} */ + pinEnabled_: { + type: Boolean, + value: false, + }, + + /** @private {string} */ + inputString_: { + type: String, + value: '', + observer: 'onInputChanged_', + }, + + /** @private */ + inputValid_: { + type: Boolean, + value: true, + reflectToAttribute: true, + }, + }, + + observers: + ['onSettingsChanged_(settings.pin.value, settings.pinValue.value)'], + + listeners: { + 'input-change': 'onInputChange_', + }, + + /** @return {!CrInputElement} The cr-input field element for InputBehavior. */ + getInput: function() { + return this.$.pinValue; + }, + + /** + * @param {!CustomEvent<string>} e Contains the new input value. + * @private + */ + onInputChange_: function(e) { + this.inputString_ = e.detail; + }, + + /** @private */ + onCollapseChanged_: function() { + if (this.pinEnabled_) { + /** @type {!CrInputElement} */ (this.$.pinValue).inputElement.focus(); + } + }, + + /** + * @param {boolean} inputValid Whether pin value is valid. + * @param {boolean} disabled Whether pin setting is disabled. + * @param {boolean} managed Whether pin setting is managed. + * @return {boolean} Whether pin checkbox should be disabled. + * @private + */ + computeCheckboxDisabled_: function(inputValid, disabled, managed) { + return inputValid && (disabled || managed); + }, + + /** + * @return {boolean} Whether to disable the pin value input. + * @private + */ + inputDisabled_: function() { + return !this.pinEnabled_ || (this.inputValid_ && this.disabled); + }, + + /** + * Updates the checkbox state when the setting has been initialized. + * @private + */ + onSettingsChanged_: function() { + const pinEnabled = /** @type {boolean} */ (this.getSetting('pin').value); + this.$.pin.checked = pinEnabled; + this.pinEnabled_ = pinEnabled; + const pinValue = this.getSetting('pinValue'); + this.inputString_ = /** @type {string} */ (pinValue.value); + }, + + /** @private */ + onPinChange_: function() { + this.setSetting('pin', this.$.pin.checked); + }, + + /** + * Updates pin value setting based on the current value of the pin value + * input. + * @private + */ + onInputChanged_: function() { + if (this.settings === undefined) { + return; + } + this.inputValid_ = this.computeValid_(); + this.setSettingValid('pinValue', this.inputValid_); + + if (this.inputValid_) { + this.setSetting('pinValue', this.inputString_); + } + }, + + /** + * @return {boolean} Whether input value represented by inputString_ is + * valid, so that it can be used to update the setting. + * @private + */ + computeValid_: function() { + // Make sure value updates first, in case inputString_ was updated by JS. + this.$.pinValue.value = this.inputString_; + return !this.$.pinValue.invalid; + }, +});
diff --git a/chrome/browser/resources/print_preview/new/print_preview_sidebar.html b/chrome/browser/resources/print_preview/new/print_preview_sidebar.html index 17ab4dd..2d7b551 100644 --- a/chrome/browser/resources/print_preview/new/print_preview_sidebar.html +++ b/chrome/browser/resources/print_preview/new/print_preview_sidebar.html
@@ -23,6 +23,9 @@ <link rel="import" href="other_options_settings.html"> <link rel="import" href="pages_per_sheet_settings.html"> <link rel="import" href="pages_settings.html"> +<if expr="chromeos"> + <link rel="import" href="pin_settings.html"> +</if> <link rel="import" href="print_preview_shared_css.html"> <link rel="import" href="scaling_settings.html"> <link rel="import" href="settings_behavior.html"> @@ -102,6 +105,12 @@ disabled="[[controlsDisabled_]]" available class="settings-section"> </print-preview-destination-settings> +<if expr="chromeos"> + <print-preview-pin-settings settings="[[settings]]" + disabled="[[controlsDisabled_]]" + hidden$="[[!settings.pin.available]]" class="settings-section"> + </print-preview-pin-settings> +</if> <print-preview-pages-settings settings="[[settings]]" page-count="[[pageCount]]" disabled="[[controlsDisabled_]]" hidden$="[[!settings.pages.available]]" class="settings-section">
diff --git a/chrome/browser/resources/print_preview/print_preview_resources.grd b/chrome/browser/resources/print_preview/print_preview_resources.grd index c15bd69..2eabd7b 100644 --- a/chrome/browser/resources/print_preview/print_preview_resources.grd +++ b/chrome/browser/resources/print_preview/print_preview_resources.grd
@@ -258,6 +258,14 @@ file="new/destination_settings.js" type="chrome_html" preprocess="true" /> + <if expr="chromeos"> + <structure name="IDR_PRINT_PREVIEW_NEW_PIN_SETTINGS_HTML" + file="new/pin_settings.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_NEW_PIN_SETTINGS_JS" + file="new/pin_settings.js" + type="chrome_html" /> + </if> <structure name="IDR_PRINT_PREVIEW_NEW_PAGES_SETTINGS_HTML" file="new/pages_settings.html" type="chrome_html" />
diff --git a/chrome/browser/signin/chrome_signin_helper.cc b/chrome/browser/signin/chrome_signin_helper.cc index 70359b1..1e91394 100644 --- a/chrome/browser/signin/chrome_signin_helper.cc +++ b/chrome/browser/signin/chrome_signin_helper.cc
@@ -210,6 +210,12 @@ // // - Going Incognito (already handled in above switch-case). // - Displaying the Account Manager for managing accounts. + + // Do not display Account Manager if the navigation happened in the + // "background". + if (!chrome::FindBrowserWithWebContents(web_contents)) + return; + chrome::SettingsWindowManager::GetInstance()->ShowChromePageForProfile( profile, GURL("chrome://settings/accountManager")); return;
diff --git a/chrome/browser/supervised_user/supervised_user_service.cc b/chrome/browser/supervised_user/supervised_user_service.cc index 377215d..58d8a1cf 100644 --- a/chrome/browser/supervised_user/supervised_user_service.cc +++ b/chrome/browser/supervised_user/supervised_user_service.cc
@@ -979,6 +979,7 @@ result.Put(syncer::APPS); result.Put(syncer::APP_SETTINGS); result.Put(syncer::APP_LIST); + result.Put(syncer::ARC_PACKAGE); return result; }
diff --git a/chrome/browser/sync/send_tab_to_self_sync_service_factory.cc b/chrome/browser/sync/send_tab_to_self_sync_service_factory.cc index 49914b7..7d7ba77f 100644 --- a/chrome/browser/sync/send_tab_to_self_sync_service_factory.cc +++ b/chrome/browser/sync/send_tab_to_self_sync_service_factory.cc
@@ -8,15 +8,11 @@ #include "base/memory/singleton.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/chrome_device_id_helper.h" -#include "chrome/browser/sync/device_info_sync_service_factory.h" #include "chrome/browser/sync/model_type_store_service_factory.h" #include "chrome/common/channel_info.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/send_tab_to_self/send_tab_to_self_sync_service.h" -#include "components/sync/device_info/device_info_sync_service.h" #include "components/sync/model/model_type_store_service.h" -#include "ui/base/device_form_factor.h" // static send_tab_to_self::SendTabToSelfSyncService* @@ -35,7 +31,6 @@ : BrowserContextKeyedServiceFactory( "SendTabToSelfSyncService", BrowserContextDependencyManager::GetInstance()) { - DependsOn(DeviceInfoSyncServiceFactory::GetInstance()); DependsOn(ModelTypeStoreServiceFactory::GetInstance()); DependsOn(HistoryServiceFactory::GetInstance()); } @@ -46,10 +41,6 @@ content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - syncer::LocalDeviceInfoProvider* local_device_info_provider = - DeviceInfoSyncServiceFactory::GetForProfile(profile) - ->GetLocalDeviceInfoProvider(); - syncer::OnceModelTypeStoreFactory store_factory = ModelTypeStoreServiceFactory::GetForProfile(profile)->GetStoreFactory(); @@ -58,6 +49,5 @@ ServiceAccessType::EXPLICIT_ACCESS); return new send_tab_to_self::SendTabToSelfSyncService( - chrome::GetChannel(), local_device_info_provider, - std::move(store_factory), history_service); + chrome::GetChannel(), std::move(store_factory), history_service); }
diff --git a/chrome/browser/sync/test/integration/autofill_helper.cc b/chrome/browser/sync/test/integration/autofill_helper.cc index 796b95f..bbc73fe 100644 --- a/chrome/browser/sync/test/integration/autofill_helper.cc +++ b/chrome/browser/sync/test/integration/autofill_helper.cc
@@ -409,6 +409,7 @@ } bool AutofillProfileChecker::Wait() { + DLOG(WARNING) << "AutofillProfileChecker::Wait() started"; PersonalDataLoadedObserverMock personal_data_observer; base::RunLoop run_loop_a; base::RunLoop run_loop_b; @@ -439,7 +440,7 @@ pdm_a->RemoveObserver(&personal_data_observer); pdm_b->RemoveObserver(&personal_data_observer); - + DLOG(WARNING) << "AutofillProfileChecker::Wait() completed"; return StatusChangeChecker::Wait(); }
diff --git a/chrome/browser/sync/test/integration/wallet_helper.cc b/chrome/browser/sync/test/integration/wallet_helper.cc index c8fa1d0..6d074361 100644 --- a/chrome/browser/sync/test/integration/wallet_helper.cc +++ b/chrome/browser/sync/test/integration/wallet_helper.cc
@@ -140,10 +140,7 @@ } void WaitForCurrentTasksToComplete(base::SequencedTaskRunner* task_runner) { - // We need to allow nestable tasks because AutofillWalletMetadataSizeChecker - // may cause this function getting called again while |loop| here is running. - // Without allowing nestable tasks, the outer loop will block forever. - base::RunLoop loop(base::RunLoop::Type::kNestableTasksAllowed); + base::RunLoop loop; task_runner->PostTask( FROM_HERE, base::BindOnce(&base::RunLoop::Quit, base::Unretained(&loop))); loop.Run(); @@ -546,6 +543,40 @@ } bool AutofillWalletMetadataSizeChecker::IsExitConditionSatisfied() { + // Make sure we do not nest IsExitConditionSatisfiedImpl() (as it can happen + // that OnPersonalDataChanged() gets notified while we're inside + // IsExitConditionSatisfiedImpl(), waiting for the DB task that loads metadata + // to finish). + switch (state_) { + case IDLE: + do { + state_ = CHECKING; + if (IsExitConditionSatisfiedImpl()) { + return true; + } + } while (state_ == SHOULD_RECHECK); + state_ = IDLE; + return false; + case CHECKING: + // Make sure that each IsExitConditionSatisfied() call is followed by a + // IsExitConditionSatisfiedImpl() call so that we do not miss any updates + // to the DB. + state_ = SHOULD_RECHECK; + return false; + case SHOULD_RECHECK: + return false; + } +} + +std::string AutofillWalletMetadataSizeChecker::GetDebugMessage() const { + return "Waiting for matching autofill wallet metadata sizes"; +} + +void AutofillWalletMetadataSizeChecker::OnPersonalDataChanged() { + CheckExitCondition(); +} + +bool AutofillWalletMetadataSizeChecker::IsExitConditionSatisfiedImpl() { // There could be trailing metadata left on one of the clients. Check that // metadata.size() is the same on both clients. std::map<std::string, AutofillMetadata> addresses_metadata_a = @@ -571,14 +602,6 @@ return true; } -std::string AutofillWalletMetadataSizeChecker::GetDebugMessage() const { - return "Waiting for matching autofill wallet metadata sizes"; -} - -void AutofillWalletMetadataSizeChecker::OnPersonalDataChanged() { - CheckExitCondition(); -} - UssWalletSwitchToggler::UssWalletSwitchToggler() {} void UssWalletSwitchToggler::InitWithDefaultFeatures() {
diff --git a/chrome/browser/sync/test/integration/wallet_helper.h b/chrome/browser/sync/test/integration/wallet_helper.h index 7b7d8e6..5042dec5 100644 --- a/chrome/browser/sync/test/integration/wallet_helper.h +++ b/chrome/browser/sync/test/integration/wallet_helper.h
@@ -151,6 +151,12 @@ void OnPersonalDataChanged() override; private: + // A state machine that makes sure we do not nest checking exit conditions. + enum State { IDLE, CHECKING, SHOULD_RECHECK }; + + bool IsExitConditionSatisfiedImpl(); + + State state_ = IDLE; const int profile_a_; const int profile_b_; };
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index 60e89af..59a9392 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -748,6 +748,7 @@ // chrome://extensions is on the list because it redirects to // chrome://settings. return host != chrome::kChromeUIAppLauncherPageHost && + host != chrome::kChromeUIAppManagementHost && host != chrome::kChromeUISettingsHost && host != chrome::kChromeUIHelpHost && host != chrome::kChromeUIHistoryHost &&
diff --git a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc index a431c0bc..7c5e5cd 100644 --- a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc +++ b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc
@@ -219,6 +219,10 @@ Hide(); } +void PasswordGenerationPopupControllerImpl::GenerationElementLostFocus() { + Hide(); +} + void PasswordGenerationPopupControllerImpl::GeneratedPasswordRejected() { Hide(); }
diff --git a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.h b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.h index 711a6e2b..7044a6b 100644 --- a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.h +++ b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.h
@@ -93,6 +93,10 @@ // Hides the popup, since its position is no longer valid. void FrameWasScrolled(); + // Hides the popup, since the generation element for which it was shown + // is no longer focused. + void GenerationElementLostFocus(); + // The generated password counts as rejected either if the user ignores the // popup and types a password, or if the generated password is deleted. // In both cases the popups should be hidden. In the latter case, a new popup
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_browsertest.cc b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_browsertest.cc index c7964ef..b7a6570 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_browsertest.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_browsertest.cc
@@ -50,7 +50,10 @@ : https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} void SetUp() override { - scoped_feature_list_.InitAndEnableFeature(network::features::kSecMetadata); + scoped_feature_list_.InitWithFeatures( + {network::features::kFetchMetadata, + network::features::kFetchMetadataDestination}, + {}); InProcessBrowserTest::SetUp(); }
diff --git a/chrome/browser/ui/webui/app_management/app_management_ui.cc b/chrome/browser/ui/webui/app_management/app_management_ui.cc index 2c9df00..b435f1b4 100644 --- a/chrome/browser/ui/webui/app_management/app_management_ui.cc +++ b/chrome/browser/ui/webui/app_management/app_management_ui.cc
@@ -26,7 +26,7 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) { content::WebUIDataSource* source = - content::WebUIDataSource::Create(chrome::kChromeUIAppLauncherPageHost); + content::WebUIDataSource::Create(chrome::kChromeUIAppManagementHost); source->AddLocalizedString("appListTitle", IDS_APP_MANAGEMENT_APP_LIST_TITLE); source->AddLocalizedString("appNoPermission",
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 89c6ea0..72021cd 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -432,7 +432,7 @@ ***************************************************************************/ #if !defined(OS_ANDROID) if (AppManagementUI::IsEnabled() && - url.host_piece() == chrome::kChromeUIAppLauncherPageHost && profile && + url.host_piece() == chrome::kChromeUIAppManagementHost && profile && !profile->IsGuestSession()) { return &NewWebUI<AppManagementUI>; } @@ -453,6 +453,7 @@ } if (profile->IsGuestSession() && (url.host_piece() == chrome::kChromeUIAppLauncherPageHost || + url.host_piece() == chrome::kChromeUIAppManagementHost || url.host_piece() == chrome::kChromeUIBookmarksHost || url.host_piece() == chrome::kChromeUIHistoryHost || url.host_piece() == chrome::kChromeUIExtensionsHost)) {
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc index c1531bef..6523fdd3 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc
@@ -281,6 +281,9 @@ #if defined(OS_CHROMEOS) {"configuringFailedText", IDS_PRINT_CONFIGURING_FAILED_TEXT}, {"configuringInProgressText", IDS_PRINT_CONFIGURING_IN_PROGRESS_TEXT}, + {"optionPin", IDS_PRINT_PREVIEW_OPTION_PIN}, + {"pinErrorMessage", IDS_PRINT_PREVIEW_PIN_ERROR_MESSAGE}, + {"pinPlaceholder", IDS_PRINT_PREVIEW_PIN_PLACEHOLDER}, #endif #if defined(OS_MACOSX) {"openPdfInPreviewOption", IDS_PRINT_PREVIEW_OPEN_PDF_IN_PREVIEW_APP},
diff --git a/chrome/common/webui_url_constants.cc b/chrome/common/webui_url_constants.cc index 9c301c7..7aae7fac 100644 --- a/chrome/common/webui_url_constants.cc +++ b/chrome/common/webui_url_constants.cc
@@ -22,7 +22,7 @@ const char kChromeUIAppIconHost[] = "app-icon"; const char kChromeUIAppIconURL[] = "chrome://app-icon/"; const char kChromeUIAppLauncherPageHost[] = "apps"; -const char kChromeUIAppManagementHost[] = "apps"; +const char kChromeUIAppManagementHost[] = "app-management"; const char kChromeUIAppsURL[] = "chrome://apps/"; const char kChromeUIAutofillInternalsHost[] = "autofill-internals"; const char kChromeUIBluetoothInternalsHost[] = "bluetooth-internals";
diff --git a/chrome/renderer/autofill/fake_password_generation_driver.h b/chrome/renderer/autofill/fake_password_generation_driver.h index d7090eb..b926a56b 100644 --- a/chrome/renderer/autofill/fake_password_generation_driver.h +++ b/chrome/renderer/autofill/fake_password_generation_driver.h
@@ -45,6 +45,7 @@ MOCK_METHOD1(PasswordNoLongerGenerated, void(const autofill::PasswordForm& password_form)); MOCK_METHOD0(FrameWasScrolled, void()); + MOCK_METHOD0(GenerationElementLostFocus, void()); private: mojo::AssociatedBinding<autofill::mojom::PasswordGenerationDriver> binding_;
diff --git a/chrome/renderer/autofill/password_generation_agent_browsertest.cc b/chrome/renderer/autofill/password_generation_agent_browsertest.cc index 24155fdc..5ba90ea 100644 --- a/chrome/renderer/autofill/password_generation_agent_browsertest.cc +++ b/chrome/renderer/autofill/password_generation_agent_browsertest.cc
@@ -288,6 +288,7 @@ // Unloading the document may trigger the event. EXPECT_CALL(fake_pw_client_, AutomaticGenerationStatusChanged(false, _)) .Times(AtMost(1)); + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()).Times(AtMost(1)); ChromeRenderViewTest::TearDown(); } @@ -527,6 +528,7 @@ GenerationAvailableForFormStatus::kAvailable); ExpectAutomaticGenerationAvailable("first_password", kAvailable); + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); ExpectAutomaticGenerationAvailable("second_password", kUnavailable); } @@ -782,6 +784,7 @@ testing::Mock::VerifyAndClearExpectations(&fake_pw_client_); // Change focus. Bubble should be hidden. + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); EXPECT_CALL(fake_pw_client_, AutomaticGenerationStatusChanged(false, _)); ExecuteJavaScriptForTests("document.getElementById('username').focus();"); fake_pw_client_.Flush(); @@ -795,6 +798,7 @@ // Loading a different page triggers UMA stat upload. Verify that only one // display event is sent. + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); EXPECT_CALL(fake_pw_client_, AutomaticGenerationStatusChanged(false, _)); LoadHTMLWithUserGesture(kSigninFormHTML); @@ -917,6 +921,7 @@ SetNotBlacklistedMessage(password_generation_, kAccountCreationFormHTML); // Need to focus another field first for verification to work. + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); ExpectAutomaticGenerationAvailable("second_password", kUnavailable); ExpectAutomaticGenerationAvailable("first_password", kAvailable); } @@ -935,6 +940,7 @@ // Remove focus from everywhere by clicking an unfocusable element: password // generation popup should not show up. + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); EXPECT_CALL(fake_pw_client_, AutomaticGenerationStatusChanged(false, _)); EXPECT_TRUE(SimulateElementClick("disabled")); fake_pw_client_.Flush(); @@ -976,6 +982,7 @@ kCurrentAndNewPasswordAutocompleteAttributeFormHTML); ExpectAutomaticGenerationAvailable("old_password", kNotReported); ExpectAutomaticGenerationAvailable("new_password", kAvailable); + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); ExpectAutomaticGenerationAvailable("confirm_password", kUnavailable); } @@ -991,6 +998,7 @@ GenerationAvailableForFormStatus::kAvailable, 0, 2); ExpectAutomaticGenerationAvailable("password", kNotReported); ExpectAutomaticGenerationAvailable("newpassword", kAvailable); + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); ExpectAutomaticGenerationAvailable("confirmpassword", kUnavailable); } @@ -1020,6 +1028,7 @@ SelectGenerationFallbackAndExpect(true); // Move the focus away to somewhere. + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); ExpectAutomaticGenerationAvailable("address", kUnavailable); // Moving the focus back should trigger the automatic generation again. @@ -1091,6 +1100,7 @@ // The current implementation may notify about unavailable generation. EXPECT_CALL(fake_pw_client_, AutomaticGenerationStatusChanged(false, _)) .Times(AtMost(1)); + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); FocusField("username"); EXPECT_CALL(fake_pw_client_, PresaveGeneratedPassword(testing::_)); SimulateUserTypingASCIICharacter('X', true); @@ -1108,6 +1118,7 @@ EXPECT_CALL(fake_pw_client_, PresaveGeneratedPassword(testing::_)).Times(0); EXPECT_CALL(fake_pw_client_, AutomaticGenerationStatusChanged(false, _)) .Times(AtMost(1)); + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); FocusField("username"); SimulateUserTypingASCIICharacter('Y', true); base::RunLoop().RunUntilIdle(); @@ -1226,8 +1237,11 @@ // Click on another HTML element. const char* const click_target_name = clickOnInputField ? kTextFieldId : kSpanId; + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); EXPECT_TRUE(SimulateElementClick(click_target_name)); EXPECT_FALSE(input.ShouldRevealPassword()); + fake_pw_client_.Flush(); + testing::Mock::VerifyAndClearExpectations(&fake_pw_client_); } } @@ -1397,6 +1411,7 @@ EXPECT_TRUE(input.ShouldRevealPassword()); // Focus another element on the page. The password should be masked. + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); EXPECT_CALL(fake_pw_client_, AutomaticGenerationStatusChanged(false, _)); ASSERT_TRUE(SimulateElementClick("span")); EXPECT_FALSE(input.ShouldRevealPassword()); @@ -1430,6 +1445,7 @@ password_generation_->FoundFormEligibleForGeneration(generation_data); ExpectAutomaticGenerationAvailable(kPasswordElementsIds[0], kAvailable); + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); ExpectAutomaticGenerationAvailable(kPasswordElementsIds[1], kUnavailable); ExpectAutomaticGenerationAvailable(kPasswordElementsIds[2], kNotReported); @@ -1439,6 +1455,7 @@ password_elements[2].UniqueRendererFormControlId(); password_generation_->FoundFormEligibleForGeneration(generation_data); ExpectAutomaticGenerationAvailable(kPasswordElementsIds[0], kAvailable); + EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus()); ExpectAutomaticGenerationAvailable(kPasswordElementsIds[1], kUnavailable); ExpectAutomaticGenerationAvailable(kPasswordElementsIds[2], kAvailable); }
diff --git a/chrome/renderer/extensions/automation_internal_custom_bindings.cc b/chrome/renderer/extensions/automation_internal_custom_bindings.cc index 463a90e..9bcb730 100644 --- a/chrome/renderer/extensions/automation_internal_custom_bindings.cc +++ b/chrome/renderer/extensions/automation_internal_custom_bindings.cc
@@ -736,11 +736,14 @@ AutomationAXTreeWrapper* tree_wrapper, ui::AXNode* node) { const std::vector<int> line_starts = node->GetOrComputeLineStartOffsets(); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> array_result( v8::Array::New(isolate, line_starts.size())); for (size_t i = 0; i < line_starts.size(); ++i) { - array_result->Set(static_cast<uint32_t>(i), - v8::Integer::New(isolate, line_starts[i])); + array_result + ->CreateDataProperty(context, static_cast<uint32_t>(i), + v8::Integer::New(isolate, line_starts[i])) + .Check(); } result.Set(array_result); }); @@ -898,11 +901,14 @@ ui::ParseIntAttribute(attribute_name.c_str()); std::set<int32_t> ids = tree->GetReverseRelations(attribute, node->id()); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> array_result(v8::Array::New(isolate, ids.size())); size_t count = 0; for (int32_t id : ids) { - array_result->Set(static_cast<uint32_t>(count++), - v8::Integer::New(isolate, id)); + array_result + ->CreateDataProperty(context, static_cast<uint32_t>(count++), + v8::Integer::New(isolate, id)) + .Check(); } result.Set(array_result); }); @@ -936,11 +942,14 @@ const std::vector<int32_t>& attr_value = node->data().GetIntListAttribute(attribute); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> array_result( v8::Array::New(isolate, attr_value.size())); for (size_t i = 0; i < attr_value.size(); ++i) - array_result->Set(static_cast<uint32_t>(i), - v8::Integer::New(isolate, attr_value[i])); + array_result + ->CreateDataProperty(context, static_cast<uint32_t>(i), + v8::Integer::New(isolate, attr_value[i])) + .Check(); result.Set(array_result); }); RouteNodeIDPlusAttributeFunction( @@ -952,11 +961,14 @@ ui::ParseIntListAttribute(attribute_name.c_str()); std::set<int32_t> ids = tree->GetReverseRelations(attribute, node->id()); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> array_result(v8::Array::New(isolate, ids.size())); size_t count = 0; for (int32_t id : ids) { - array_result->Set(static_cast<uint32_t>(count++), - v8::Integer::New(isolate, id)); + array_result + ->CreateDataProperty(context, static_cast<uint32_t>(count++), + v8::Integer::New(isolate, id)) + .Check(); } result.Set(array_result); }); @@ -1088,13 +1100,17 @@ return; } + v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> custom_actions( v8::Array::New(isolate, custom_action_ids.size())); for (size_t i = 0; i < custom_action_ids.size(); i++) { gin::DataObjectBuilder custom_action(isolate); custom_action.Set("id", custom_action_ids[i]); custom_action.Set("description", custom_action_descriptions[i]); - custom_actions->Set(static_cast<uint32_t>(i), custom_action.Build()); + custom_actions + ->CreateDataProperty(context, static_cast<uint32_t>(i), + custom_action.Build()) + .Check(); } result.Set(custom_actions); }); @@ -1235,11 +1251,14 @@ AutomationAXTreeWrapper* tree_wrapper, ui::AXNode* node) { std::vector<int32_t> col_headers; node->GetTableCellColHeaderNodeIds(&col_headers); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> array_result( v8::Array::New(isolate, col_headers.size())); for (size_t i = 0; i < col_headers.size(); ++i) - array_result->Set(static_cast<uint32_t>(i), - v8::Integer::New(isolate, col_headers[i])); + array_result + ->CreateDataProperty(context, static_cast<uint32_t>(i), + v8::Integer::New(isolate, col_headers[i])) + .Check(); result.Set(array_result); }); RouteNodeIDFunction( @@ -1248,11 +1267,14 @@ AutomationAXTreeWrapper* tree_wrapper, ui::AXNode* node) { std::vector<int32_t> row_headers; node->GetTableCellRowHeaderNodeIds(&row_headers); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> array_result( v8::Array::New(isolate, row_headers.size())); for (size_t i = 0; i < row_headers.size(); ++i) - array_result->Set(static_cast<uint32_t>(i), - v8::Integer::New(isolate, row_headers[i])); + array_result + ->CreateDataProperty(context, static_cast<uint32_t>(i), + v8::Integer::New(isolate, row_headers[i])) + .Check(); result.Set(array_result); }); RouteNodeIDFunction(
diff --git a/chrome/renderer/extensions/cast_streaming_native_handler.cc b/chrome/renderer/extensions/cast_streaming_native_handler.cc index 03ab1ef..3a1c8bf3 100644 --- a/chrome/renderer/extensions/cast_streaming_native_handler.cc +++ b/chrome/renderer/extensions/cast_streaming_native_handler.cc
@@ -543,9 +543,11 @@ RtpParams params; FromFrameSenderConfig(configs[i], ¶ms.payload); std::unique_ptr<base::DictionaryValue> params_value = params.ToValue(); - result->Set( - static_cast<int>(i), - converter->ToV8Value(params_value.get(), context()->v8_context())); + result + ->CreateDataProperty( + context()->v8_context(), static_cast<int>(i), + converter->ToV8Value(params_value.get(), context()->v8_context())) + .Check(); } args.GetReturnValue().Set(result); }
diff --git a/chrome/services/app_service/README.md b/chrome/services/app_service/README.md index 7d4fdf9..41ae51c 100644 --- a/chrome/services/app_service/README.md +++ b/chrome/services/app_service/README.md
@@ -4,7 +4,7 @@ There are a number (lets call it `M`) of different places or app Consumers, usually UI (user interfaces) related, where users interact with their installed -apps: e.g. launcher, search bar, shelf, New Tab Page, the `chrome://apps` page, +apps: e.g. launcher, search bar, shelf, New Tab Page, the App Management page, permissions or settings pages, picking and running default handlers for URLs, MIME types or intents, etc.
diff --git a/chrome/services/app_service/public/mojom/types.mojom b/chrome/services/app_service/public/mojom/types.mojom index c0c1a2e..19289f8 100644 --- a/chrome/services/app_service/public/mojom/types.mojom +++ b/chrome/services/app_service/public/mojom/types.mojom
@@ -138,6 +138,7 @@ kFromAppListQuery, // Query-dependent results (larger icons). kFromAppListQueryContextMenu, // Query-dependent results; context menu. kFromAppListRecommendation, // Query-less recommendations (smaller icons). + kFromKioskNextHome, // Kiosk Next Home app. }; enum TriState {
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 6bf33111..ebdd8d55 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3131,6 +3131,7 @@ "//components/subresource_filter/core/browser:test_support", "//components/sync:test_support_driver", "//components/sync:test_support_model", + "//components/sync:test_support_user_events", "//components/sync_sessions:test_support", "//components/ukm/content", "//components/version_info:generate_version_info",
diff --git a/chrome/test/base/chrome_test_launcher.cc b/chrome/test/base/chrome_test_launcher.cc index 0b2d3685..59e95a9 100644 --- a/chrome/test/base/chrome_test_launcher.cc +++ b/chrome/test/base/chrome_test_launcher.cc
@@ -20,7 +20,6 @@ #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/test/test_file_util.h" -#include "build/build_config.h" #include "chrome/app/chrome_main_delegate.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" @@ -59,8 +58,10 @@ #if defined(OS_WIN) #include "base/win/registry.h" +#include "base/win/scoped_com_initializer.h" #include "chrome/app/chrome_crash_reporter_client_win.h" #include "chrome/install_static/install_util.h" +#include "chrome/installer/util/firewall_manager_win.h" #endif ChromeTestSuiteRunner::ChromeTestSuiteRunner() {} @@ -73,6 +74,37 @@ return test_suite.Run(); } +#if defined(OS_WIN) + +// A helper class that adds Windows firewall rules for the duration of the test. +class ChromeTestLauncherDelegate::ScopedFirewallRules { + public: + ScopedFirewallRules() { + CHECK(com_initializer_.Succeeded()); + base::FilePath exe_path; + CHECK(base::PathService::Get(base::FILE_EXE, &exe_path)); + firewall_manager_ = installer::FirewallManager::Create(exe_path); + CHECK(firewall_manager_); + rules_added_ = firewall_manager_->AddFirewallRules(); + LOG_IF(WARNING, !rules_added_) + << "Failed to add Windows firewall rules -- Windows firewall dialogs " + "may appear."; + } + + ~ScopedFirewallRules() { + if (rules_added_) + firewall_manager_->RemoveFirewallRules(); + } + + private: + base::win::ScopedCOMInitializer com_initializer_; + std::unique_ptr<installer::FirewallManager> firewall_manager_; + bool rules_added_ = false; + DISALLOW_COPY_AND_ASSIGN(ScopedFirewallRules); +}; + +#endif // defined(OS_WIN) + ChromeTestLauncherDelegate::ChromeTestLauncherDelegate( ChromeTestSuiteRunner* runner) : runner_(runner) {} @@ -127,6 +159,16 @@ result = distrubution_key.DeleteKey(L"PreferenceMACs"); LOG_IF(ERROR, result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) << "Failed to cleanup PreferenceMACs: " << result; + + // Add firewall rules for the test binary so that Windows doesn't show a + // firewall dialog during the test run. + firewall_rules_ = std::make_unique<ScopedFirewallRules>(); +#endif +} + +void ChromeTestLauncherDelegate::OnDoneRunningTests() { +#if defined(OS_WIN) + firewall_rules_.reset(); #endif }
diff --git a/chrome/test/base/chrome_test_launcher.h b/chrome/test/base/chrome_test_launcher.h index 6ad9d06..5e87127a 100644 --- a/chrome/test/base/chrome_test_launcher.h +++ b/chrome/test/base/chrome_test_launcher.h
@@ -8,6 +8,7 @@ #include <memory> #include "base/macros.h" +#include "build/build_config.h" #include "content/public/test/test_launcher.h" // Allows a test suite to override the TestSuite class used. By default it is an @@ -37,8 +38,15 @@ const base::FilePath& temp_data_dir) override; content::ContentMainDelegate* CreateContentMainDelegate() override; void PreSharding() override; + void OnDoneRunningTests() override; private: +#if defined(OS_WIN) + class ScopedFirewallRules; + + std::unique_ptr<ScopedFirewallRules> firewall_rules_; +#endif + ChromeTestSuiteRunner* runner_; DISALLOW_COPY_AND_ASSIGN(ChromeTestLauncherDelegate);
diff --git a/chrome/test/data/webui/app_management/app_management_browsertest.js b/chrome/test/data/webui/app_management/app_management_browsertest.js index aa7daa9d..df89e3cd 100644 --- a/chrome/test/data/webui/app_management/app_management_browsertest.js +++ b/chrome/test/data/webui/app_management/app_management_browsertest.js
@@ -16,7 +16,7 @@ AppManagementBrowserTest.prototype = { __proto__: PolymerTest.prototype, - browsePreload: 'chrome://apps', + browsePreload: 'chrome://app-management', extraLibraries: PolymerTest.getLibraries(ROOT_PATH).concat([ '../test_store.js',
diff --git a/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js b/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js index e0e841f..9d42b881 100644 --- a/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js +++ b/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js
@@ -1528,3 +1528,25 @@ TEST_F('PrintPreviewDuplexSettingsTest', 'All', function() { mocha.run(); }); + +GEN('#if defined(OS_CHROMEOS)'); +PrintPreviewPinSettingsTest = class extends NewPrintPreviewTest { + /** @override */ + get browsePreload() { + return 'chrome://print/new/pin_settings.html'; + } + + /** @override */ + get extraLibraries() { + return super.extraLibraries.concat([ + '../settings/test_util.js', + 'print_preview_test_utils.js', + 'pin_settings_test.js', + ]); + } +}; + +TEST_F('PrintPreviewPinSettingsTest', 'All', function() { + mocha.run(); +}); +GEN('#endif');
diff --git a/chrome/test/data/webui/print_preview/pin_settings_test.js b/chrome/test/data/webui/print_preview/pin_settings_test.js new file mode 100644 index 0000000..1743b07 --- /dev/null +++ b/chrome/test/data/webui/print_preview/pin_settings_test.js
@@ -0,0 +1,118 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +cr.define('pin_settings_test', function() { + suite('PinSettingsTest', function() { + /** @type {?PrintPreviewPinSettingsElement} */ + let pinSection = null; + + /** @type {?PrintPreviewModelElement} */ + let model = null; + + /** @override */ + setup(function() { + PolymerTest.clearBody(); + model = document.createElement('print-preview-model'); + document.body.appendChild(model); + model.set('settings.pin.available', true); + model.set('settings.pin.value', false); + model.set('settings.pinValue.available', true); + model.set('settings.pinValue.value', ''); + + pinSection = document.createElement('print-preview-pin-settings'); + pinSection.settings = model.settings; + pinSection.disabled = false; + test_util.fakeDataBind(model, pinSection, 'settings'); + document.body.appendChild(pinSection); + Polymer.dom.flush(); + }); + + // Tests that checking the box or entering the pin value updates the + // setting. + test('enter valid pin value', async () => { + const checkbox = pinSection.$$('cr-checkbox'); + const collapse = pinSection.$$('iron-collapse'); + assertFalse(checkbox.checked); + assertFalse(collapse.opened); + assertFalse(pinSection.getSettingValue('pin')); + assertEquals('', pinSection.getSettingValue('pinValue')); + + checkbox.checked = true; + checkbox.dispatchEvent(new CustomEvent('change')); + assertTrue(collapse.opened); + assertTrue(pinSection.getSettingValue('pin')); + assertEquals('', pinSection.getSettingValue('pinValue')); + + const input = pinSection.$$('cr-input'); + assertEquals('', input.value); + + // Verify that entering the pin value in the input sets the setting. + await print_preview_test_utils.triggerInputEvent( + input, '0000', pinSection); + assertTrue(pinSection.getSettingValue('pin')); + assertEquals('0000', pinSection.getSettingValue('pinValue')); + assertEquals(true, pinSection.getSetting('pinValue').valid); + }); + + // Tests that entering non-digit pin value updates the validity of the + // setting. + test('enter non-digit pin value', async () => { + const checkbox = pinSection.$$('cr-checkbox'); + checkbox.checked = true; + checkbox.dispatchEvent(new CustomEvent('change')); + const input = pinSection.$$('cr-input'); + + // Verify that entering the non-digit pin value in the input updates the + // setting validity and doesn't update its value. + await print_preview_test_utils.triggerInputEvent( + input, 'aaaa', pinSection); + assertTrue(pinSection.getSettingValue('pin')); + assertEquals('', pinSection.getSettingValue('pinValue')); + assertEquals(false, pinSection.getSetting('pinValue').valid); + + // Check that checkbox and input are still enabled so user can correct + // invalid input. + assertEquals(false, checkbox.disabled); + assertEquals(false, input.disabled); + }); + + + // Tests that entering too short pin value updates the validity of the + // setting. + test('enter too short pin value', async () => { + const checkbox = pinSection.$$('cr-checkbox'); + checkbox.checked = true; + checkbox.dispatchEvent(new CustomEvent('change')); + const input = pinSection.$$('cr-input'); + + // Verify that entering too short pin value in the input updates the + // setting validity and doesn't update its value. + await print_preview_test_utils.triggerInputEvent( + input, '000', pinSection); + assertTrue(pinSection.getSettingValue('pin')); + assertEquals('', pinSection.getSettingValue('pinValue')); + assertEquals(false, pinSection.getSetting('pinValue').valid); + + // Check that checkbox and input are still enabled so user can correct + // invalid input. + assertEquals(false, checkbox.disabled); + assertEquals(false, input.disabled); + }); + + // Tests that if settings are enforced by enterprise policy the + // appropriate UI is disabled. + test('disabled by policy', function() { + const checkbox = pinSection.$$('cr-checkbox'); + assertFalse(checkbox.disabled); + + pinSection.setSetting('pin', true); + const input = pinSection.$$('cr-input'); + assertFalse(input.disabled); + + model.set('settings.pin.setByPolicy', true); + assertTrue(checkbox.disabled); + assertFalse(input.disabled); + }); + }); +});
diff --git a/chrome/test/data/webui/print_preview/restore_state_test.js b/chrome/test/data/webui/print_preview/restore_state_test.js index 9edd3344..4f5d11e 100644 --- a/chrome/test/data/webui/print_preview/restore_state_test.js +++ b/chrome/test/data/webui/print_preview/restore_state_test.js
@@ -126,6 +126,10 @@ isLandscapeEnabled: true, isColorEnabled: true, }; + if (cr.isChromeOS) { + stickySettings.pin = true; + stickySettings.pinValue = '0000'; + } return testInitializeWithStickySettings(stickySettings); }); @@ -162,6 +166,10 @@ isLandscapeEnabled: false, isColorEnabled: false, }; + if (cr.isChromeOS) { + stickySettings.pin = false; + stickySettings.pinValue = ''; + } return testInitializeWithStickySettings(stickySettings); }); @@ -266,6 +274,21 @@ }, } ]; + if (cr.isChromeOS) { + testData.push( + { + section: 'print-preview-pin-settings', + settingName: 'pin', + key: 'isPinEnabled', + value: true, + }, + { + section: 'print-preview-pin-settings', + settingName: 'pinValue', + key: 'pinValue', + value: '0000', + }); + } // Setup nativeLayer.setInitialSettings(initialSettings);
diff --git a/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc b/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc index da953a74..d356025c 100644 --- a/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc +++ b/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc
@@ -6,6 +6,7 @@ #include "base/command_line.h" #include "base/stl_util.h" +#include "base/threading/platform_thread.h" #include "base/time/time.h" #include "chromecast/base/chromecast_switches.h" #include "chromecast/media/cma/backend/alsa/alsa_wrapper.h" @@ -104,6 +105,12 @@ // the direction explicitly. constexpr int* kAlsaDirDontCare = nullptr; +// The snd_pcm_resume function can return EAGAIN error code, so call should be +// retried. Below constants define retries params. +constexpr int kRestoreAfterSuspensionAttempts = 10; +constexpr base::TimeDelta kRestoreAfterSuspensionAttemptDelay = + base::TimeDelta::FromMilliseconds(20); + // These sample formats will be tried in order. 32 bit samples is ideal, but // some devices do not support 32 bit samples. constexpr snd_pcm_format_t kPreferredSampleFormats[] = { @@ -226,6 +233,11 @@ while ((frames_or_error = alsa_->PcmWritei(pcm_, output_data, frames_left)) < 0) { *out_playback_interrupted = true; + if (frames_or_error == -EBADFD && + MaybeRecoverDeviceFromSuspendedState()) { + // Write data again, if recovered. + continue; + } RETURN_FALSE_ON_ERROR(PcmRecover, pcm_, frames_or_error, kPcmRecoverIsSilent); } @@ -267,8 +279,8 @@ LOG(INFO) << "snd_pcm_close: handle=" << pcm_; int err = alsa_->PcmClose(pcm_); if (err < 0) { - LOG(ERROR) << "snd_pcm_close error, leaking handle: " - << alsa_->StrError(err); + LOG(ERROR) << "snd_pcm_close error, leaking handle: " + << alsa_->StrError(err); } pcm_ = nullptr; } @@ -493,5 +505,33 @@ sample_rate_; } +bool MixerOutputStreamAlsa::MaybeRecoverDeviceFromSuspendedState() { + if (alsa_->PcmState(pcm_) != SND_PCM_STATE_SUSPENDED) { + LOG(WARNING) << "Alsa output is not suspended"; + return false; + } + if (alsa_->PcmHwParamsCanResume(pcm_hw_params_)) { + LOG(INFO) << "Trying to resume output"; + for (int attempt = 0; attempt < kRestoreAfterSuspensionAttempts; + ++attempt) { + int err = alsa_->PcmResume(pcm_); + if (err == 0) { + LOG(INFO) << "ALSA output is resumed from suspended state"; + return true; + } + if (err != -EAGAIN) { + // If PcmResume failed or device doesn't support resume, try to use + // PcmPrepare. + err = alsa_->PcmPrepare(pcm_); + LOG_IF(INFO, err == 0) + << "ALSA output is recovered from suspended state"; + return err == 0; + } + base::PlatformThread::Sleep(kRestoreAfterSuspensionAttemptDelay); + } + } + return false; +} + } // namespace media } // namespace chromecast
diff --git a/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h b/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h index d53f5ae..964c7b87 100644 --- a/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h +++ b/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h
@@ -56,6 +56,11 @@ void UpdateRenderingDelay(); + // Checks ALSA output for current state and if it's suspended, tries to + // recover. + // Returns true if ALSA device is recovered successfully. + bool MaybeRecoverDeviceFromSuspendedState(); + std::unique_ptr<AlsaWrapper> alsa_; snd_pcm_t* pcm_ = nullptr;
diff --git a/chromeos/services/assistant/public/features.cc b/chromeos/services/assistant/public/features.cc index 2f840a8..e35283d 100644 --- a/chromeos/services/assistant/public/features.cc +++ b/chromeos/services/assistant/public/features.cc
@@ -63,8 +63,7 @@ base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kEnableMediaSessionIntegration{ - "AssistantEnableMediaSessionIntegration", - base::FEATURE_DISABLED_BY_DEFAULT}; + "AssistantEnableMediaSessionIntegration", base::FEATURE_ENABLED_BY_DEFAULT}; bool IsAppSupportEnabled() { return base::FeatureList::IsEnabled(
diff --git a/components/arc/metrics/arc_metrics_constants.h b/components/arc/metrics/arc_metrics_constants.h index 4e48ecdc..81a8dadd 100644 --- a/components/arc/metrics/arc_metrics_constants.h +++ b/components/arc/metrics/arc_metrics_constants.h
@@ -86,7 +86,10 @@ // User started an app from Smart Text Selection context menu. APP_STARTED_FROM_SMART_TEXT_SELECTION_CONTEXT_MENU = 17, - kMaxValue = APP_STARTED_FROM_SMART_TEXT_SELECTION_CONTEXT_MENU, + // User started an app from the Kiosk Next Home app. + APP_STARTED_FROM_KIOSK_NEXT_HOME = 18, + + kMaxValue = APP_STARTED_FROM_KIOSK_NEXT_HOME, }; } // namespace arc
diff --git a/components/autofill/content/common/autofill_driver.mojom b/components/autofill/content/common/autofill_driver.mojom index 433bd60..d17a921 100644 --- a/components/autofill/content/common/autofill_driver.mojom +++ b/components/autofill/content/common/autofill_driver.mojom
@@ -148,6 +148,9 @@ // Notifies the browser when automatic generation becomes available or // unavailable and provides data needed by the UI. + // TODO(crbug.com/951714): Replace this with AutomaticGenerationAvailable, + // since the available == false case now overlaps with + // GenerationElementLostFocus. AutomaticGenerationStatusChanged( bool available, PasswordGenerationUIData? password_generation_ui_data); @@ -171,4 +174,8 @@ // Communicates to the browser that a scroll event happened on the frame. This // event affects the password generation popup position. FrameWasScrolled(); + + // Informs the browser that the generation element lost focus, so the browser + // might hide the generation popup. + GenerationElementLostFocus(); };
diff --git a/components/autofill/content/renderer/password_generation_agent.cc b/components/autofill/content/renderer/password_generation_agent.cc index c0990850..d8117fe8 100644 --- a/components/autofill/content/renderer/password_generation_agent.cc +++ b/components/autofill/content/renderer/password_generation_agent.cc
@@ -754,6 +754,7 @@ const blink::WebInputElement& element) { if (!element.IsNull() && current_generation_item_ && element == current_generation_item_->generation_element_) { + GetPasswordGenerationDriver()->GenerationElementLostFocus(); if (!current_generation_item_->password_is_generated_) AutomaticGenerationStatusChanged(false); current_generation_item_->generation_element_.SetShouldRevealPassword(
diff --git a/components/autofill/core/browser/address_email_form_label_formatter.cc b/components/autofill/core/browser/address_email_form_label_formatter.cc index 486cf7e..dcc46e2 100644 --- a/components/autofill/core/browser/address_email_form_label_formatter.cc +++ b/components/autofill/core/browser/address_email_form_label_formatter.cc
@@ -17,12 +17,26 @@ AddressEmailFormLabelFormatter::~AddressEmailFormLabelFormatter() {} -// Note that the order--name, address, and email--in which parts of the label -// are added ensures that the label is formatted correctly for |focused_group| -// and for this kind of formatter. base::string16 AddressEmailFormLabelFormatter::GetLabelForProfile( const AutofillProfile& profile, FieldTypeGroup focused_group) const { + return focused_group == ADDRESS_HOME && + !IsStreetAddressPart(focused_field_type()) + ? GetLabelForProfileOnFocusedNonStreetAddress( + form_has_street_address_, profile, app_locale(), + field_types_for_labels(), + GetLabelEmail(profile, app_locale())) + : GetLabelForProfileOnFocusedNameEmailOrStreetAddress( + profile, focused_group); +} + +// Note that the order--name, address, and email--in which parts of the label +// are added ensures that the label is formatted correctly for |focused_group|, +// |focused_field_type_| and for this kind of formatter. +base::string16 AddressEmailFormLabelFormatter:: + GetLabelForProfileOnFocusedNameEmailOrStreetAddress( + const AutofillProfile& profile, + FieldTypeGroup focused_group) const { std::vector<base::string16> label_parts; if (focused_group != NAME) {
diff --git a/components/autofill/core/browser/address_email_form_label_formatter.h b/components/autofill/core/browser/address_email_form_label_formatter.h index e6b3a50..606bf0a 100644 --- a/components/autofill/core/browser/address_email_form_label_formatter.h +++ b/components/autofill/core/browser/address_email_form_label_formatter.h
@@ -31,6 +31,14 @@ FieldTypeGroup focused_group) const override; private: + // Returns a label to show the user when |focused_field_type_| is a type + // other than a non-street-address field type. For example, + // |focused_field_type_| could be last name, home street address, or email + // address. + base::string16 GetLabelForProfileOnFocusedNameEmailOrStreetAddress( + const AutofillProfile& profile, + FieldTypeGroup focused_group) const; + // True if this formatter's associated form has a street address field. A // form may have an address-related field, e.g. zip code, without having a // street address field. If a form does not include a street address field, @@ -40,4 +48,4 @@ } // namespace autofill -#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_ADDRESS_EMAIL_FORM_LABEL_FORMATTER_H_ \ No newline at end of file +#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_ADDRESS_EMAIL_FORM_LABEL_FORMATTER_H_
diff --git a/components/autofill/core/browser/address_email_form_label_formatter_unittest.cc b/components/autofill/core/browser/address_email_form_label_formatter_unittest.cc index 4f3cc21..0949e8a 100644 --- a/components/autofill/core/browser/address_email_form_label_formatter_unittest.cc +++ b/components/autofill/core/browser/address_email_form_label_formatter_unittest.cc
@@ -30,6 +30,7 @@ ADDRESS_BILLING_LINE2, ADDRESS_BILLING_CITY, ADDRESS_BILLING_STATE, + ADDRESS_BILLING_DEPENDENT_LOCALITY, ADDRESS_BILLING_ZIP, ADDRESS_BILLING_COUNTRY}; } @@ -75,7 +76,7 @@ } TEST(AddressEmailFormLabelFormatterTest, - GetLabelsForUSProfilesAndFocusedAddress) { + GetLabelsForUSProfilesAndFocusedStreetAddress) { AutofillProfile profile1 = AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); test::SetProfileInfo(&profile1, "John", "F", "Kennedy", "jfk@gmail.com", "", @@ -110,6 +111,41 @@ } TEST(AddressEmailFormLabelFormatterTest, + GetLabelsForUSProfilesAndFocusedNonStreetAddress) { + AutofillProfile profile1 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile1, "John", "F", "Kennedy", "jfk@gmail.com", "", + "333 Washington St", "", "Brookline", "MA", "02445", + "US", "16177302000"); + + AutofillProfile profile2 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile2, "Jackie", "", "Kennedy", "", "", + "151 Irving Ave", "", "Hyannis", "MA", "02601", "US", + ""); + + AutofillProfile profile3 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile3, "", "", "", "paul1775@gmail.com", "", "", "", + "", "", "", "US", ""); + + AutofillProfile profile4 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile4, "", "", "", "", "", "", "", "Quincy", "MA", + "02169", "US", ""); + + const std::unique_ptr<LabelFormatter> formatter = + LabelFormatter::Create("en-US", ADDRESS_BILLING_ZIP, GetFieldTypes()); + + EXPECT_THAT( + formatter->GetLabels(std::vector<AutofillProfile*>{&profile1, &profile2, + &profile3, &profile4}), + ElementsAre(FormatExpectedLabel("333 Washington St", "jfk@gmail.com"), + base::ASCIIToUTF16("151 Irving Ave"), + base::ASCIIToUTF16("paul1775@gmail.com"), base::string16())); +} + +TEST(AddressEmailFormLabelFormatterTest, GetLabelsForUSProfilesAndFocusedEmail) { AutofillProfile profile1 = AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); @@ -170,7 +206,7 @@ } TEST(AddressEmailFormLabelFormatterTest, - GetLabelsForBRProfilesAndFocusedAddress) { + GetLabelsForBRProfilesAndFocusedStreetAddress) { AutofillProfile profile1 = AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); test::SetProfileInfo(&profile1, "Tarsila", "do", "Amaral", "tarsila@aol.com", @@ -195,6 +231,33 @@ } TEST(AddressEmailFormLabelFormatterTest, + GetLabelsForBRProfilesAndFocusedNonStreetAddress) { + AutofillProfile profile1 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile1, "Tarsila", "do", "Amaral", "tarsila@aol.com", + "", "Av. Pedro Álvares Cabral, 1301", "", "Vila Mariana", + "São Paulo", "SP", "04094-050", "BR", + "+55 11 2648-0254"); + + AutofillProfile profile2 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile2, "Artur", "", "Avila", "aavila@uol.com.br", "", + "Estr. Dona Castorina, 110", "", "Jardim Botânico", + "Rio de Janeiro", "RJ", "22460-320", "BR", + "21987650000"); + + const std::unique_ptr<LabelFormatter> formatter = LabelFormatter::Create( + "pt-BR", ADDRESS_BILLING_DEPENDENT_LOCALITY, GetFieldTypes()); + + EXPECT_THAT( + formatter->GetLabels(std::vector<AutofillProfile*>{&profile1, &profile2}), + ElementsAre(FormatExpectedLabel("Av. Pedro Álvares Cabral, 1301", + "tarsila@aol.com"), + FormatExpectedLabel("Estr. Dona Castorina, 110", + "aavila@uol.com.br"))); +} + +TEST(AddressEmailFormLabelFormatterTest, GetLabelsForBRProfilesAndFocusedEmail) { AutofillProfile profile1 = AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin);
diff --git a/components/autofill/core/browser/address_phone_form_label_formatter.cc b/components/autofill/core/browser/address_phone_form_label_formatter.cc index 63b0d785..670f1e8 100644 --- a/components/autofill/core/browser/address_phone_form_label_formatter.cc +++ b/components/autofill/core/browser/address_phone_form_label_formatter.cc
@@ -17,12 +17,26 @@ AddressPhoneFormLabelFormatter::~AddressPhoneFormLabelFormatter() {} -// Note that the order--name, phone, and address--in which parts of the label -// are added ensures that the label is formatted correctly for |focused_group| -// and for this kind of formatter. base::string16 AddressPhoneFormLabelFormatter::GetLabelForProfile( const AutofillProfile& profile, FieldTypeGroup focused_group) const { + return focused_group == ADDRESS_HOME && + !IsStreetAddressPart(focused_field_type()) + ? GetLabelForProfileOnFocusedNonStreetAddress( + form_has_street_address_, profile, app_locale(), + field_types_for_labels(), + GetLabelPhone(profile, app_locale())) + : GetLabelForProfileOnFocusedNamePhoneOrStreetAddress( + profile, focused_group); +} + +// Note that the order--name, phone, and address--in which parts of the label +// are added ensures that the label is formatted correctly for |focused_group|, +// |focused_field_type_| and for this kind of formatter. +base::string16 AddressPhoneFormLabelFormatter:: + GetLabelForProfileOnFocusedNamePhoneOrStreetAddress( + const AutofillProfile& profile, + FieldTypeGroup focused_group) const { std::vector<base::string16> label_parts; if (focused_group != NAME) { AddLabelPartIfNotEmpty(GetLabelName(profile, app_locale()), &label_parts);
diff --git a/components/autofill/core/browser/address_phone_form_label_formatter.h b/components/autofill/core/browser/address_phone_form_label_formatter.h index 0917f584..32f162a8 100644 --- a/components/autofill/core/browser/address_phone_form_label_formatter.h +++ b/components/autofill/core/browser/address_phone_form_label_formatter.h
@@ -31,6 +31,13 @@ FieldTypeGroup focused_group) const override; private: + // Returns a label to show the user when |focused_field_type_| is a type + // other than a non-street-address field type. For example, + // |focused_field_type_| could be first name, address line 1, or phone number. + base::string16 GetLabelForProfileOnFocusedNamePhoneOrStreetAddress( + const AutofillProfile& profile, + FieldTypeGroup focused_group) const; + // True if this formatter's associated form has a street address field. A // form may have an address-related field, e.g. zip code, without having a // street address field. If a form does not include a street address field,
diff --git a/components/autofill/core/browser/address_phone_form_label_formatter_unittest.cc b/components/autofill/core/browser/address_phone_form_label_formatter_unittest.cc index e8bfaec..01b71f8f 100644 --- a/components/autofill/core/browser/address_phone_form_label_formatter_unittest.cc +++ b/components/autofill/core/browser/address_phone_form_label_formatter_unittest.cc
@@ -70,7 +70,7 @@ } TEST(AddressPhoneFormLabelFormatterTest, - GetLabelsForUSProfilesAndFocusedAddress) { + GetLabelsForUSProfilesAndFocusedStreetAddress) { AutofillProfile profile1 = AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); test::SetProfileInfo(&profile1, "John", "F", "Kennedy", "jfk@gmail.com", "", @@ -105,6 +105,41 @@ } TEST(AddressPhoneFormLabelFormatterTest, + GetLabelsForUSProfilesAndFocusedNonStreetAddress) { + AutofillProfile profile1 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile1, "John", "F", "Kennedy", "jfk@gmail.com", "", + "333 Washington St", "", "Brookline", "MA", "02445", + "US", "16177302000"); + + AutofillProfile profile2 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile2, "Jackie", "", "Kennedy", "", "", + "151 Irving Ave", "", "Hyannis", "MA", "02601", "US", + ""); + + AutofillProfile profile3 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile3, "", "", "", "", "", "", "", "", "", "", "US", + "6175232338"); + + AutofillProfile profile4 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile4, "", "", "", "", "", "", "", "Quincy", "MA", + "02169", "US", ""); + + const std::unique_ptr<LabelFormatter> formatter = + LabelFormatter::Create("en-US", ADDRESS_HOME_CITY, GetFieldTypes()); + + EXPECT_THAT( + formatter->GetLabels(std::vector<AutofillProfile*>{&profile1, &profile2, + &profile3, &profile4}), + ElementsAre(FormatExpectedLabel("333 Washington St", "(617) 730-2000"), + base::ASCIIToUTF16("151 Irving Ave"), + base::ASCIIToUTF16("(617) 523-2338"), base::string16())); +} + +TEST(AddressPhoneFormLabelFormatterTest, GetLabelsForUSProfilesAndFocusedPhone) { AutofillProfile profile1 = AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); @@ -167,7 +202,7 @@ } TEST(AddressPhoneFormLabelFormatterTest, - GetLabelsForBRProfilesAndFocusedAddress) { + GetLabelsForBRProfilesAndFocusedStreetAddress) { AutofillProfile profile1 = AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); test::SetProfileInfo(&profile1, "Tarsila", "do", "Amaral", "tarsila@aol.com", @@ -192,6 +227,33 @@ } TEST(AddressPhoneFormLabelFormatterTest, + GetLabelsForBRProfilesAndFocusedNonStreetAddress) { + AutofillProfile profile1 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile1, "Tarsila", "do", "Amaral", "tarsila@aol.com", + "", "Av. Pedro Álvares Cabral, 1301", "", "Vila Mariana", + "São Paulo", "SP", "04094-050", "BR", + "+55 11 2648-0254"); + + AutofillProfile profile2 = + AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin); + test::SetProfileInfo(&profile2, "Artur", "", "Avila", "aavila@uol.com.br", "", + "Estr. Dona Castorina, 110", "", "Jardim Botânico", + "Rio de Janeiro", "RJ", "22460-320", "BR", + "21987650000"); + + const std::unique_ptr<LabelFormatter> formatter = + LabelFormatter::Create("pt-BR", ADDRESS_HOME_ZIP, GetFieldTypes()); + + EXPECT_THAT( + formatter->GetLabels(std::vector<AutofillProfile*>{&profile1, &profile2}), + ElementsAre( + FormatExpectedLabel("Av. Pedro Álvares Cabral, 1301", + "(11) 2648-0254"), + FormatExpectedLabel("Estr. Dona Castorina, 110", "(21) 98765-0000"))); +} + +TEST(AddressPhoneFormLabelFormatterTest, GetLabelsForBRProfilesAndFocusedPhone) { AutofillProfile profile1 = AutofillProfile(base::GenerateGUID(), test::kEmptyOrigin);
diff --git a/components/autofill/core/browser/label_formatter_utils.cc b/components/autofill/core/browser/label_formatter_utils.cc index 233af12..b75ec06 100644 --- a/components/autofill/core/browser/label_formatter_utils.cc +++ b/components/autofill/core/browser/label_formatter_utils.cc
@@ -215,6 +215,20 @@ return base::UTF8ToUTF16(address_line); } +base::string16 GetLabelForProfileOnFocusedNonStreetAddress( + bool form_has_street_address, + const AutofillProfile& profile, + const std::string& app_locale, + const std::vector<ServerFieldType>& types, + const base::string16& contact_info) { + std::vector<base::string16> label_parts; + AddLabelPartIfNotEmpty( + GetLabelAddress(form_has_street_address, profile, app_locale, types), + &label_parts); + AddLabelPartIfNotEmpty(contact_info, &label_parts); + return ConstructLabelLine(label_parts); +} + base::string16 GetLabelEmail(const AutofillProfile& profile, const std::string& app_locale) { const base::string16 email =
diff --git a/components/autofill/core/browser/label_formatter_utils.h b/components/autofill/core/browser/label_formatter_utils.h index 64b282a..d12d6c9 100644 --- a/components/autofill/core/browser/label_formatter_utils.h +++ b/components/autofill/core/browser/label_formatter_utils.h
@@ -151,6 +151,16 @@ const std::string& app_locale, const std::vector<ServerFieldType>& types); +// Returns a label to show the user when |focused_field_type_| is not part of +// a street address. For example, city and postal code are non-street-address +// field types. +base::string16 GetLabelForProfileOnFocusedNonStreetAddress( + bool form_has_street_address, + const AutofillProfile& profile, + const std::string& app_locale, + const std::vector<ServerFieldType>& types, + const base::string16& contact_info); + // Returns the email address associated with |profile|, if any; otherwise, // returns an empty string. base::string16 GetLabelEmail(const AutofillProfile& profile,
diff --git a/components/browser_sync/profile_sync_components_factory_impl.cc b/components/browser_sync/profile_sync_components_factory_impl.cc index b30f371d..7d43ba6 100644 --- a/components/browser_sync/profile_sync_components_factory_impl.cc +++ b/components/browser_sync/profile_sync_components_factory_impl.cc
@@ -402,12 +402,10 @@ controllers.push_back( std::make_unique<syncer::UserEventModelTypeController>( sync_service, - std::make_unique<syncer::ProxyModelTypeControllerDelegate>( - ui_thread_, - base::BindRepeating(&browser_sync::BrowserSyncClient:: - GetControllerDelegateForModelType, - base::Unretained(sync_client_), - syncer::USER_EVENTS)))); + std::make_unique<syncer::ForwardingModelTypeControllerDelegate>( + sync_client_ + ->GetControllerDelegateForModelType(syncer::USER_EVENTS) + .get()))); } if (!disabled_types.Has(syncer::SEND_TAB_TO_SELF) &&
diff --git a/components/password_manager/core/browser/new_password_form_manager.cc b/components/password_manager/core/browser/new_password_form_manager.cc index 0399d06..abe79c5 100644 --- a/components/password_manager/core/browser/new_password_form_manager.cc +++ b/components/password_manager/core/browser/new_password_form_manager.cc
@@ -421,7 +421,9 @@ } void NewPasswordFormManager::PasswordNoLongerGenerated() { - DCHECK(HasGeneratedPassword()); + if (!HasGeneratedPassword()) + return; + form_saver_->RemovePresavedPassword(); generated_password_.clear(); votes_uploader_.set_has_generated_password(false);
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge.cc b/components/send_tab_to_self/send_tab_to_self_bridge.cc index 66ec449..e9dc7484 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge.cc +++ b/components/send_tab_to_self/send_tab_to_self_bridge.cc
@@ -14,8 +14,7 @@ #include "components/history/core/browser/history_service.h" #include "components/send_tab_to_self/features.h" #include "components/send_tab_to_self/proto/send_tab_to_self.pb.h" -#include "components/sync/device_info/device_info.h" -#include "components/sync/device_info/local_device_info_provider.h" +#include "components/sync/base/get_session_name.h" #include "components/sync/model/entity_change.h" #include "components/sync/model/metadata_batch.h" #include "components/sync/model/metadata_change_list.h" @@ -68,11 +67,15 @@ base::Optional<syncer::ModelError> ParseLocalEntriesOnBackendSequence( base::Time now, std::map<std::string, std::unique_ptr<SendTabToSelfEntry>>* entries, + std::string* local_session_name, std::unique_ptr<ModelTypeStore::RecordList> record_list) { DCHECK(entries); DCHECK(entries->empty()); + DCHECK(local_session_name); DCHECK(record_list); + *local_session_name = syncer::GetSessionNameBlocking(); + for (const syncer::ModelTypeStore::Record& r : *record_list) { auto specifics = std::make_unique<SendTabToSelfLocal>(); if (specifics->ParseFromString(r.value)) { @@ -90,17 +93,14 @@ SendTabToSelfBridge::SendTabToSelfBridge( std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor, - syncer::LocalDeviceInfoProvider* local_device_info_provider, base::Clock* clock, syncer::OnceModelTypeStoreFactory create_store_callback, history::HistoryService* history_service) : ModelTypeSyncBridge(std::move(change_processor)), clock_(clock), - local_device_info_provider_(local_device_info_provider), history_service_(history_service), mru_entry_(nullptr), weak_ptr_factory_(this) { - DCHECK(local_device_info_provider); DCHECK(clock_); if (history_service) { history_service->AddObserver(this); @@ -422,19 +422,25 @@ auto initial_entries = std::make_unique<SendTabToSelfEntries>(); SendTabToSelfEntries* initial_entries_copy = initial_entries.get(); + auto local_device_name = std::make_unique<std::string>(); + std::string* local_device_name_copy = local_device_name.get(); + store_ = std::move(store); store_->ReadAllDataAndPreprocess( base::BindOnce(&ParseLocalEntriesOnBackendSequence, clock_->Now(), - base::Unretained(initial_entries_copy)), + base::Unretained(initial_entries_copy), + base::Unretained(local_device_name_copy)), base::BindOnce(&SendTabToSelfBridge::OnReadAllData, - weak_ptr_factory_.GetWeakPtr(), - std::move(initial_entries))); + weak_ptr_factory_.GetWeakPtr(), std::move(initial_entries), + std::move(local_device_name))); } void SendTabToSelfBridge::OnReadAllData( std::unique_ptr<SendTabToSelfEntries> initial_entries, + std::unique_ptr<std::string> local_device_name, const base::Optional<syncer::ModelError>& error) { DCHECK(initial_entries); + DCHECK(local_device_name); if (error) { change_processor()->ReportError(*error); @@ -442,24 +448,8 @@ } entries_ = std::move(*initial_entries); + local_device_name_ = std::move(*local_device_name); - if (local_device_info_provider_->GetLocalDeviceInfo()) { - OnDeviceProviderInitialized(); - } else { - device_subscription_ = - local_device_info_provider_->RegisterOnInitializedCallback( - base::BindRepeating( - &SendTabToSelfBridge::OnDeviceProviderInitialized, - base::Unretained(this))); - } -} - -void SendTabToSelfBridge::OnDeviceProviderInitialized() { - device_subscription_.reset(); - local_device_name_ = - local_device_info_provider_->GetLocalDeviceInfo()->client_name(); - - // now that all of the providers are ready we can read the metadata. store_->ReadAllMetadata(base::BindOnce( &SendTabToSelfBridge::OnReadAllMetadata, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge.h b/components/send_tab_to_self/send_tab_to_self_bridge.h index 445e4b87..2ea7a6a 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge.h +++ b/components/send_tab_to_self/send_tab_to_self_bridge.h
@@ -18,7 +18,6 @@ #include "components/send_tab_to_self/send_tab_to_self_entry.h" #include "components/send_tab_to_self/send_tab_to_self_model.h" #include "components/sync/base/model_type.h" -#include "components/sync/device_info/local_device_info_provider.h" #include "components/sync/model/model_type_store.h" #include "components/sync/model/model_type_sync_bridge.h" @@ -42,11 +41,9 @@ public SendTabToSelfModel, public history::HistoryServiceObserver { public: - // |local_device_info_provider| must not be null and must outlive this object. // |clock| must not be null and must outlive this object. SendTabToSelfBridge( std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor, - syncer::LocalDeviceInfoProvider* local_device_info_provider, base::Clock* clock, syncer::OnceModelTypeStoreFactory create_store_callback, history::HistoryService* history_service); @@ -109,10 +106,8 @@ void OnStoreCreated(const base::Optional<syncer::ModelError>& error, std::unique_ptr<syncer::ModelTypeStore> store); void OnReadAllData(std::unique_ptr<SendTabToSelfEntries> initial_entries, + std::unique_ptr<std::string> local_device_name, const base::Optional<syncer::ModelError>& error); - // Used as callback given to LocalDeviceInfoProvider. - void OnDeviceProviderInitialized(); - void OnReadAllMetadata(const base::Optional<syncer::ModelError>& error, std::unique_ptr<syncer::MetadataBatch> metadata_batch); void OnCommit(const base::Optional<syncer::ModelError>& error); @@ -133,9 +128,6 @@ // |clock_| isn't owned. const base::Clock* const clock_; - // |local_device_info_provider_| isn't owned. - syncer::LocalDeviceInfoProvider* const local_device_info_provider_; - // |history_service_| isn't owned. history::HistoryService* const history_service_; @@ -144,11 +136,6 @@ // In charge of actually persisting changes to disk, or loading previous data. std::unique_ptr<syncer::ModelTypeStore> store_; - // Used to listen for provider initialization. If the provider is already - // initialized during our constructor then the subscription is never used. - std::unique_ptr<syncer::LocalDeviceInfoProvider::Subscription> - device_subscription_; - // A pointer to the most recently used entry used for deduplication. const SendTabToSelfEntry* mru_entry_; base::WeakPtrFactory<SendTabToSelfBridge> weak_ptr_factory_;
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc b/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc index 8357f5ec..d5e869e 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc +++ b/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc
@@ -17,7 +17,6 @@ #include "components/history/core/browser/history_service.h" #include "components/send_tab_to_self/features.h" #include "components/send_tab_to_self/proto/send_tab_to_self.pb.h" -#include "components/sync/device_info/local_device_info_provider_mock.h" #include "components/sync/model/entity_change.h" #include "components/sync/model/metadata_batch.h" #include "components/sync/model/mock_model_type_change_processor.h" @@ -77,7 +76,6 @@ protected: SendTabToSelfBridgeTest() : store_(syncer::ModelTypeStoreTestUtil::CreateInMemoryStoreForTest()) { - provider_.Initialize("cache_guid", "machine"); scoped_feature_list_.InitAndEnableFeature(kSendTabToSelfShowSendingUI); } @@ -86,7 +84,7 @@ void InitializeBridge() { ON_CALL(mock_processor_, IsTrackingMetadata()).WillByDefault(Return(true)); bridge_ = std::make_unique<SendTabToSelfBridge>( - mock_processor_.CreateForwardingProcessor(), &provider_, &clock_, + mock_processor_.CreateForwardingProcessor(), &clock_, syncer::ModelTypeStoreTestUtil::MoveStoreToFactory(std::move(store_)), nullptr); bridge_->AddObserver(&mock_observer_); @@ -169,8 +167,6 @@ // In memory model type store needs to be able to post tasks. base::test::ScopedTaskEnvironment task_environment_; - syncer::LocalDeviceInfoProviderMock provider_; - std::unique_ptr<syncer::ModelTypeStore> store_; testing::NiceMock<syncer::MockModelTypeChangeProcessor> mock_processor_;
diff --git a/components/send_tab_to_self/send_tab_to_self_sync_service.cc b/components/send_tab_to_self/send_tab_to_self_sync_service.cc index 7fa4aca..e969891d 100644 --- a/components/send_tab_to_self/send_tab_to_self_sync_service.cc +++ b/components/send_tab_to_self/send_tab_to_self_sync_service.cc
@@ -12,7 +12,6 @@ #include "components/send_tab_to_self/send_tab_to_self_bridge.h" #include "components/send_tab_to_self/send_tab_to_self_model.h" #include "components/sync/base/report_unrecoverable_error.h" -#include "components/sync/device_info/local_device_info_provider.h" #include "components/sync/model/model_type_store.h" #include "components/sync/model_impl/client_tag_based_model_type_processor.h" @@ -22,15 +21,14 @@ SendTabToSelfSyncService::SendTabToSelfSyncService( version_info::Channel channel, - syncer::LocalDeviceInfoProvider* local_device_info_provider, syncer::OnceModelTypeStoreFactory create_store_callback, history::HistoryService* history_service) { bridge_ = std::make_unique<send_tab_to_self::SendTabToSelfBridge>( std::make_unique<syncer::ClientTagBasedModelTypeProcessor>( syncer::SEND_TAB_TO_SELF, base::BindRepeating(&syncer::ReportUnrecoverableError, channel)), - local_device_info_provider, base::DefaultClock::GetInstance(), - std::move(create_store_callback), history_service); + base::DefaultClock::GetInstance(), std::move(create_store_callback), + history_service); } SendTabToSelfSyncService::~SendTabToSelfSyncService() = default;
diff --git a/components/send_tab_to_self/send_tab_to_self_sync_service.h b/components/send_tab_to_self/send_tab_to_self_sync_service.h index 2aeb188..0eec5ea 100644 --- a/components/send_tab_to_self/send_tab_to_self_sync_service.h +++ b/components/send_tab_to_self/send_tab_to_self_sync_service.h
@@ -19,7 +19,6 @@ namespace syncer { class ModelTypeControllerDelegate; -class LocalDeviceInfoProvider; } // namespace syncer namespace send_tab_to_self { @@ -31,7 +30,6 @@ public: SendTabToSelfSyncService( version_info::Channel channel, - syncer::LocalDeviceInfoProvider* local_device_info_provider, syncer::OnceModelTypeStoreFactory create_store_callback, history::HistoryService* history_service); ~SendTabToSelfSyncService() override;
diff --git a/components/sync/BUILD.gn b/components/sync/BUILD.gn index dfa5a31..f49b3a0 100644 --- a/components/sync/BUILD.gn +++ b/components/sync/BUILD.gn
@@ -498,15 +498,6 @@ "nigori/nigori_sync_bridge.h", "nigori/nigori_sync_bridge_impl.cc", "nigori/nigori_sync_bridge_impl.h", - "protocol/proto_enum_conversions.cc", - "protocol/proto_enum_conversions.h", - "protocol/proto_memory_estimations.cc", - "protocol/proto_memory_estimations.h", - "protocol/proto_value_conversions.cc", - "protocol/proto_value_conversions.h", - "protocol/proto_visitors.h", - "protocol/sync_protocol_error.cc", - "protocol/sync_protocol_error.h", "syncable/base_node.cc", "syncable/base_node.h", "syncable/base_transaction.cc", @@ -593,6 +584,7 @@ "//base", "//components/invalidation/public", "//components/sync/protocol", + "//components/sync/protocol:util", "//net", "//third_party/leveldatabase", "//url", @@ -664,8 +656,6 @@ jumbo_static_library("user_events") { sources = [ - "user_events/fake_user_event_service.cc", - "user_events/fake_user_event_service.h", "user_events/no_op_user_event_service.cc", "user_events/no_op_user_event_service.h", "user_events/user_event_model_type_controller.cc", @@ -689,6 +679,24 @@ ] } +static_library("test_support_user_events") { + testonly = true + sources = [ + "user_events/fake_user_event_service.cc", + "user_events/fake_user_event_service.h", + ] + + public_deps = [ + ":test_support_base", + ] + + deps = [ + ":sync", + ":test_support_model", + ":user_events", + ] +} + static_library("test_support_base") { testonly = true sources = [ @@ -1026,6 +1034,7 @@ ":test_support_driver", ":test_support_engine", ":test_support_model", + ":test_support_user_events", ":user_events", "//base", "//base/test:test_support",
diff --git a/components/sync/engine_impl/net/server_connection_manager.cc b/components/sync/engine_impl/net/server_connection_manager.cc index 25a0ff88..57d3799 100644 --- a/components/sync/engine_impl/net/server_connection_manager.cc +++ b/components/sync/engine_impl/net/server_connection_manager.cc
@@ -15,7 +15,6 @@ #include "components/sync/engine_impl/syncer.h" #include "components/sync/protocol/sync.pb.h" #include "components/sync/syncable/directory.h" -#include "net/base/net_errors.h" #include "net/http/http_status_code.h" #include "url/gurl.h" @@ -51,11 +50,48 @@ } // namespace HttpResponse::HttpResponse() - : net_error_code(-1), + : server_status(NONE), + net_error_code(-1), http_status_code(-1), content_length(-1), - payload_length(-1), - server_status(NONE) {} + payload_length(-1) {} + +// static +HttpResponse HttpResponse::Uninitialized() { + return HttpResponse(); +} + +// static +HttpResponse HttpResponse::ForNetError(int net_error_code) { + HttpResponse response; + response.server_status = CONNECTION_UNAVAILABLE; + response.net_error_code = net_error_code; + return response; +} + +// static +HttpResponse HttpResponse::ForIoError() { + HttpResponse response; + response.server_status = IO_ERROR; + return response; +} + +// static +HttpResponse HttpResponse::ForHttpError(int http_status_code) { + HttpResponse response; + response.server_status = http_status_code == net::HTTP_UNAUTHORIZED + ? SYNC_AUTH_ERROR + : SYNC_SERVER_ERROR; + response.http_status_code = http_status_code; + return response; +} + +// static +HttpResponse HttpResponse::ForSuccess() { + HttpResponse response; + response.server_status = SERVER_CONNECTION_OK; + return response; +} ServerConnectionManager::Connection::Connection(ServerConnectionManager* scm) : scm_(scm) {} @@ -111,7 +147,7 @@ } // namespace -// TODO(chron): Use a GURL instead of string concatenation. +// TODO(crbug.com/951350): Use a GURL instead of string concatenation. string ServerConnectionManager::Connection::MakeConnectionURL( const string& sync_server, const string& path, @@ -141,7 +177,7 @@ sync_server_port_(port), use_ssl_(use_ssl), proto_sync_path_(kSyncServerSyncPath), - server_status_(HttpResponse::NONE), + server_response_(HttpResponse::Uninitialized()), cancelation_signal_(cancelation_signal) {} ServerConnectionManager::~ServerConnectionManager() = default; @@ -170,7 +206,7 @@ // second request. Need to notify sync frontend again to request new token, // otherwise backend will stay in SYNC_AUTH_ERROR state while frontend thinks // everything is fine and takes no actions. - SetServerStatus(HttpResponse::SYNC_AUTH_ERROR); + SetServerResponse(HttpResponse::ForHttpError(net::HTTP_UNAUTHORIZED)); return false; } @@ -178,22 +214,25 @@ access_token_.clear(); } -void ServerConnectionManager::SetServerStatus( - HttpResponse::ServerConnectionCode server_status) { - // SYNC_AUTH_ERROR is permanent error. Need to notify observer to take - // action externally to resolve. - if (server_status != HttpResponse::SYNC_AUTH_ERROR && - server_status_ == server_status) { - return; +void ServerConnectionManager::SetServerResponse( + const HttpResponse& server_response) { + // Notify only if the server status changed, except for SYNC_AUTH_ERROR: In + // that case, always notify in order to poke observers to do something about + // it. + bool notify = + (server_response.server_status == HttpResponse::SYNC_AUTH_ERROR || + server_response_.server_status != server_response.server_status); + server_response_ = server_response; + if (notify) { + NotifyStatusChanged(); } - server_status_ = server_status; - NotifyStatusChanged(); } void ServerConnectionManager::NotifyStatusChanged() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); for (auto& observer : listeners_) - observer.OnServerConnectionEvent(ServerConnectionEvent(server_status_)); + observer.OnServerConnectionEvent( + ServerConnectionEvent(server_response_.server_status)); } bool ServerConnectionManager::PostBufferWithCachedAuth( @@ -202,8 +241,7 @@ string path = MakeSyncServerPath(proto_sync_path(), MakeSyncQueryString(client_id_)); bool result = PostBufferToPath(params, path, access_token_); - SetServerStatus(params->response.server_status); - net_error_code_ = params->response.net_error_code; + SetServerResponse(params->response); return result; }
diff --git a/components/sync/engine_impl/net/server_connection_manager.h b/components/sync/engine_impl/net/server_connection_manager.h index 380941c..aa41b48 100644 --- a/components/sync/engine_impl/net/server_connection_manager.h +++ b/components/sync/engine_impl/net/server_connection_manager.h
@@ -28,7 +28,8 @@ // For uninitialized state. NONE, - // CONNECTION_UNAVAILABLE is returned when InternetConnect() fails. + // CONNECTION_UNAVAILABLE means either the request got canceled or it + // encountered a network error. CONNECTION_UNAVAILABLE, // IO_ERROR is returned when reading/writing to a buffer has failed. @@ -40,12 +41,17 @@ // SYNC_AUTH_ERROR is returned when the HTTP status code indicates that an // auth error has occurred (i.e. a 401). + // TODO(crbug.com/842096, crbug.com/951350): Remove this and instead use + // SYNC_SERVER_ERROR plus |http_status_code| == 401. SYNC_AUTH_ERROR, // SERVER_CONNECTION_OK is returned when request was handled correctly. SERVER_CONNECTION_OK, }; + // Identifies the type of failure, if any. + ServerConnectionCode server_status; + // The network error code. int net_error_code; @@ -58,9 +64,15 @@ // The size of a download request's payload. int64_t payload_length; - // Identifies the type of failure, if any. - ServerConnectionCode server_status; + static HttpResponse Uninitialized(); + static HttpResponse ForNetError(int net_error_code); + static HttpResponse ForIoError(); + static HttpResponse ForHttpError(int http_status_code); + static HttpResponse ForSuccess(); + private: + // Private to prevent accidental usage. Use Uninitialized() if you really need + // a "default" instance. HttpResponse(); }; @@ -88,7 +100,7 @@ struct PostBufferParams { std::string buffer_in; std::string buffer_out; - HttpResponse response; + HttpResponse response = HttpResponse::Uninitialized(); }; // Abstract class providing network-layer functionality to the @@ -100,6 +112,9 @@ virtual ~Connection(); // Called to initialize and perform an HTTP POST. + // TODO(crbug.com/951350): Return the HttpResponse by value. It's not + // obvious what the boolean return value means. (True means success or HTTP + // error, false means canceled or network error.) virtual bool Init(const char* path, const std::string& access_token, const std::string& payload, @@ -149,12 +164,12 @@ inline HttpResponse::ServerConnectionCode server_status() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return server_status_; + return server_response_.server_status; } inline int net_error_code() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return net_error_code_; + return server_response_.net_error_code; } const std::string client_id() const { return client_id_; } @@ -179,8 +194,9 @@ protected: inline std::string proto_sync_path() const { return proto_sync_path_; } - // Updates server_status_ and notifies listeners if server_status_ changed - void SetServerStatus(HttpResponse::ServerConnectionCode server_status); + // Updates server_response_ and notifies listeners if the server status + // changed. + void SetServerResponse(const HttpResponse& server_response); // NOTE: Tests rely on this protected function being virtual. // @@ -218,12 +234,7 @@ base::ObserverList<ServerConnectionEventListener>::Unchecked listeners_; - HttpResponse::ServerConnectionCode server_status_; - - // Contains the network error code if there is an error when making the - // connection with the server in which case |server_status_| is set to - // HttpResponse::CONNECTION_UNAVAILABLE. - int net_error_code_; + HttpResponse server_response_; SEQUENCE_CHECKER(sequence_checker_);
diff --git a/components/sync/engine_impl/net/sync_server_connection_manager.cc b/components/sync/engine_impl/net/sync_server_connection_manager.cc index 64fceb64..e5d0709 100644 --- a/components/sync/engine_impl/net/sync_server_connection_manager.cc +++ b/components/sync/engine_impl/net/sync_server_connection_manager.cc
@@ -60,6 +60,7 @@ int http_status_code = 0; if (!cancelation_signal_->TryRegisterHandler(this)) { // Return early because cancelation signal was signaled. + // TODO(crbug.com/951350): Introduce an extra status code for canceled? response->server_status = HttpResponse::CONNECTION_UNAVAILABLE; return false; }
diff --git a/components/sync/engine_impl/sync_scheduler_impl_unittest.cc b/components/sync/engine_impl/sync_scheduler_impl_unittest.cc index bf64b2cd..8aef51d6 100644 --- a/components/sync/engine_impl/sync_scheduler_impl_unittest.cc +++ b/components/sync/engine_impl/sync_scheduler_impl_unittest.cc
@@ -29,6 +29,7 @@ #include "components/sync/test/engine/mock_connection_manager.h" #include "components/sync/test/engine/mock_nudge_handler.h" #include "components/sync/test/mock_invalidation.h" +#include "net/http/http_status_code.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -1657,7 +1658,8 @@ DoAll(Invoke(test_util::SimulatePollSuccess), RecordSyncShareMultiple(×, kMinNumSamples, true))); - connection()->SetServerStatus(HttpResponse::SYNC_AUTH_ERROR); + connection()->SetServerResponse( + HttpResponse::ForHttpError(net::HTTP_UNAUTHORIZED)); StartSyncScheduler(base::Time()); // Run to wait for polling. @@ -1670,7 +1672,7 @@ .WillOnce(DoAll(Invoke(test_util::SimulatePollSuccess), RecordSyncShare(×, true))); scheduler()->OnCredentialsUpdated(); - connection()->SetServerStatus(HttpResponse::SERVER_CONNECTION_OK); + connection()->SetServerResponse(HttpResponse::ForSuccess()); RunLoop(); StopSyncScheduler(); }
diff --git a/components/sync/model_impl/forwarding_model_type_controller_delegate.cc b/components/sync/model_impl/forwarding_model_type_controller_delegate.cc index 9da506b..072d1df0 100644 --- a/components/sync/model_impl/forwarding_model_type_controller_delegate.cc +++ b/components/sync/model_impl/forwarding_model_type_controller_delegate.cc
@@ -11,7 +11,8 @@ ForwardingModelTypeControllerDelegate::ForwardingModelTypeControllerDelegate( ModelTypeControllerDelegate* other) : other_(other) { - DCHECK(other_); + // TODO(crbug.com/895340): Put "DCHECK(other_);"" back once + // FakeUserEventService provides a proper non-null test double. } ForwardingModelTypeControllerDelegate::
diff --git a/components/sync/model_impl/forwarding_model_type_controller_delegate.h b/components/sync/model_impl/forwarding_model_type_controller_delegate.h index 4e6c9a6..89bd950 100644 --- a/components/sync/model_impl/forwarding_model_type_controller_delegate.h +++ b/components/sync/model_impl/forwarding_model_type_controller_delegate.h
@@ -18,7 +18,7 @@ class ForwardingModelTypeControllerDelegate : public ModelTypeControllerDelegate { public: - // |other| must not be null and must outlive this object. + // Except for tests, |other| must not be null and must outlive this object. explicit ForwardingModelTypeControllerDelegate( ModelTypeControllerDelegate* other); ~ForwardingModelTypeControllerDelegate() override;
diff --git a/components/sync/protocol/BUILD.gn b/components/sync/protocol/BUILD.gn index 50c3e7f..9a9e42fc 100644 --- a/components/sync/protocol/BUILD.gn +++ b/components/sync/protocol/BUILD.gn
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/jumbo.gni") import("//third_party/protobuf/proto_library.gni") import("protocol_sources.gni") @@ -9,3 +10,24 @@ sources = sync_protocol_sources extra_configs = [ "//build/config/compiler:wexit_time_destructors" ] } + +jumbo_static_library("util") { + sources = [ + "proto_enum_conversions.cc", + "proto_enum_conversions.h", + "proto_memory_estimations.cc", + "proto_memory_estimations.h", + "proto_value_conversions.cc", + "proto_value_conversions.h", + "proto_visitors.h", + "sync_protocol_error.cc", + "sync_protocol_error.h", + ] + + configs += [ "//build/config:precompiled_headers" ] + + public_deps = [ + "//base", + "//components/sync:base", + ] +}
diff --git a/components/sync/test/engine/mock_connection_manager.cc b/components/sync/test/engine/mock_connection_manager.cc index f65915a..6121ca3 100644 --- a/components/sync/test/engine/mock_connection_manager.cc +++ b/components/sync/test/engine/mock_connection_manager.cc
@@ -14,6 +14,7 @@ #include "components/sync/syncable/directory.h" #include "components/sync/syncable/syncable_write_transaction.h" #include "components/sync/test/engine/test_id_factory.h" +#include "net/base/net_errors.h" #include "testing/gtest/include/gtest/gtest.h" using std::find; @@ -792,11 +793,9 @@ } void MockConnectionManager::UpdateConnectionStatus() { - if (!server_reachable_) { - SetServerStatus(HttpResponse::CONNECTION_UNAVAILABLE); - } else { - SetServerStatus(HttpResponse::SERVER_CONNECTION_OK); - } + SetServerResponse(server_reachable_ + ? HttpResponse::ForSuccess() + : HttpResponse::ForNetError(net::ERR_FAILED)); } } // namespace syncer
diff --git a/components/sync/test/engine/mock_connection_manager.h b/components/sync/test/engine/mock_connection_manager.h index 6eb29b6c..27964f24 100644 --- a/components/sync/test/engine/mock_connection_manager.h +++ b/components/sync/test/engine/mock_connection_manager.h
@@ -251,7 +251,7 @@ // requests. void UpdateConnectionStatus(); - using ServerConnectionManager::SetServerStatus; + using ServerConnectionManager::SetServerResponse; // Return by copy to be thread-safe. const std::string store_birthday() {
diff --git a/components/sync/user_events/fake_user_event_service.cc b/components/sync/user_events/fake_user_event_service.cc index 242aa97..6a74efc 100644 --- a/components/sync/user_events/fake_user_event_service.cc +++ b/components/sync/user_events/fake_user_event_service.cc
@@ -3,12 +3,14 @@ // found in the LICENSE file. #include "components/sync/user_events/fake_user_event_service.h" +#include "components/sync/model/fake_model_type_change_processor.h" using sync_pb::UserEventSpecifics; namespace syncer { -FakeUserEventService::FakeUserEventService() {} +FakeUserEventService::FakeUserEventService() + : fake_bridge_(std::make_unique<FakeModelTypeChangeProcessor>()) {} FakeUserEventService::~FakeUserEventService() {} @@ -24,7 +26,7 @@ } ModelTypeSyncBridge* FakeUserEventService::GetSyncBridge() { - return nullptr; + return &fake_bridge_; } const std::vector<UserEventSpecifics>&
diff --git a/components/sync/user_events/fake_user_event_service.h b/components/sync/user_events/fake_user_event_service.h index efbbd088..cbd97a7 100644 --- a/components/sync/user_events/fake_user_event_service.h +++ b/components/sync/user_events/fake_user_event_service.h
@@ -10,13 +10,12 @@ #include <vector> #include "base/macros.h" +#include "components/sync/model/fake_model_type_sync_bridge.h" #include "components/sync/protocol/user_event_specifics.pb.h" #include "components/sync/user_events/user_event_service.h" namespace syncer { -class ModelTypeSyncBridge; - // This implementation is intended to be used in unit tests, with public // accessors that allow reading all data to verify expectations. class FakeUserEventService : public UserEventService { @@ -28,12 +27,18 @@ void RecordUserEvent( std::unique_ptr<sync_pb::UserEventSpecifics> specifics) override; void RecordUserEvent(const sync_pb::UserEventSpecifics& specifics) override; + // TODO(crbug.com/895340): This is hard to mock, replace it (in the base + // class) by GetControllerDelegate(), then we can get rid of |fake_bridge_|. + // Maybe we can also expose a raw pointer to be consumed by + // ForwardingModelTypeControllerDelegate and not care about WeakPtrs anymore + // (but we need a nice solution for SyncClient). ModelTypeSyncBridge* GetSyncBridge() override; const std::vector<sync_pb::UserEventSpecifics>& GetRecordedUserEvents() const; private: std::vector<sync_pb::UserEventSpecifics> recorded_user_events_; + FakeModelTypeSyncBridge fake_bridge_; DISALLOW_COPY_AND_ASSIGN(FakeUserEventService); };
diff --git a/components/viz/service/frame_sinks/compositor_frame_sink_support.cc b/components/viz/service/frame_sinks/compositor_frame_sink_support.cc index 4a729685a..d45e2bb 100644 --- a/components/viz/service/frame_sinks/compositor_frame_sink_support.cc +++ b/components/viz/service/frame_sinks/compositor_frame_sink_support.cc
@@ -406,6 +406,9 @@ if (!ui::LatencyInfo::Verify(frame.metadata.latency_info, "RenderWidgetHostImpl::OnSwapCompositorFrame")) { + for (auto& info : frame.metadata.latency_info) { + info.Terminate(); + } std::vector<ui::LatencyInfo>().swap(frame.metadata.latency_info); } for (ui::LatencyInfo& latency : frame.metadata.latency_info) {
diff --git a/components/viz/service/surfaces/surface.cc b/components/viz/service/surfaces/surface.cc index a31c903..0e77d14a 100644 --- a/components/viz/service/surfaces/surface.cc +++ b/components/viz/service/surfaces/surface.cc
@@ -711,6 +711,9 @@ frame->metadata.latency_info.clear(); if (!ui::LatencyInfo::Verify(*latency_info, "Surface::TakeLatencyInfoFromFrame")) { + for (auto& info : *latency_info) { + info.Terminate(); + } latency_info->clear(); } }
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc index 758e5ee..d55cdbd 100644 --- a/content/browser/frame_host/navigation_request.cc +++ b/content/browser/frame_host/navigation_request.cc
@@ -139,8 +139,15 @@ return true; } -bool IsSecMetadataEnabled() { - return base::FeatureList::IsEnabled(network::features::kSecMetadata) || +bool IsFetchMetadataEnabled() { + return base::FeatureList::IsEnabled(network::features::kFetchMetadata) || + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableExperimentalWebPlatformFeatures); +} + +bool IsFetchMetadataDestinationEnabled() { + return base::FeatureList::IsEnabled( + network::features::kFetchMetadataDestination) || base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalWebPlatformFeatures); } @@ -207,7 +214,7 @@ // TODO(mkwst): Extract this logic out somewhere that can be shared between // Blink and //content. - if (IsSecMetadataEnabled() && IsOriginSecure(url)) { + if (IsFetchMetadataEnabled() && IsOriginSecure(url)) { std::string site_value = "cross-site"; std::string user_value = has_user_gesture ? "?1" : std::string(); @@ -251,7 +258,10 @@ destination = "nested-document"; mode = "nested-navigate"; } - headers->SetHeaderIfMissing("Sec-Fetch-Dest", destination.c_str()); + + if (IsFetchMetadataDestinationEnabled()) { + headers->SetHeaderIfMissing("Sec-Fetch-Dest", destination.c_str()); + } headers->SetHeaderIfMissing("Sec-Fetch-Mode", mode.c_str()); headers->SetHeaderIfMissing("Sec-Fetch-Site", site_value.c_str()); if (!user_value.empty())
diff --git a/content/browser/frame_host/sec_fetch_browsertest.cc b/content/browser/frame_host/sec_fetch_browsertest.cc index 5b0a48b..bc038189 100644 --- a/content/browser/frame_host/sec_fetch_browsertest.cc +++ b/content/browser/frame_host/sec_fetch_browsertest.cc
@@ -37,7 +37,10 @@ https_test_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); ASSERT_TRUE(https_test_server_.Start()); - feature_list_.InitAndEnableFeature(network::features::kSecMetadata); + feature_list_.InitWithFeatures( + {network::features::kFetchMetadata, + network::features::kFetchMetadataDestination}, + {}); } WebContents* web_contents() { return shell()->web_contents(); }
diff --git a/content/browser/worker_host/worker_script_fetch_initiator.cc b/content/browser/worker_host/worker_script_fetch_initiator.cc index b854cb7..0f3b4af2 100644 --- a/content/browser/worker_host/worker_script_fetch_initiator.cc +++ b/content/browser/worker_host/worker_script_fetch_initiator.cc
@@ -214,9 +214,11 @@ } // Set Fetch metadata headers if necessary. - if ((base::FeatureList::IsEnabled(network::features::kSecMetadata) || - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableExperimentalWebPlatformFeatures)) && + bool experimental_features_enabled = + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableExperimentalWebPlatformFeatures); + if ((base::FeatureList::IsEnabled(network::features::kFetchMetadata) || + experimental_features_enabled) && IsOriginSecure(resource_request->url)) { // The worker's origin can be different from the constructor's origin, for // example, when the worker created from the extension. @@ -227,13 +229,18 @@ url::Origin::Create(resource_request->url))) { site_value = "same-origin"; } - resource_request->headers.SetHeaderIfMissing("Sec-Fetch-Dest", - "sharedworker"); resource_request->headers.SetHeaderIfMissing("Sec-Fetch-Site", site_value.c_str()); resource_request->headers.SetHeaderIfMissing("Sec-Fetch-Mode", "same-origin"); // We don't set `Sec-Fetch-User` for subresource requests. + + if (base::FeatureList::IsEnabled( + network::features::kFetchMetadataDestination) || + experimental_features_enabled) { + resource_request->headers.SetHeaderIfMissing("Sec-Fetch-Dest", + "sharedworker"); + } } }
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index 614e3f7..f8aa1f1 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -201,8 +201,12 @@ // TODO(yashard): Remove |enable_experimental_web_platform_features| flag // since the feature should have been enabled when it is set to experimental - WebRuntimeFeatures::EnableSecMetadata( - base::FeatureList::IsEnabled(network::features::kSecMetadata) || + WebRuntimeFeatures::EnableFetchMetadata( + base::FeatureList::IsEnabled(network::features::kFetchMetadata) || + enable_experimental_web_platform_features); + WebRuntimeFeatures::EnableFetchMetadataDestination( + base::FeatureList::IsEnabled( + network::features::kFetchMetadataDestination) || enable_experimental_web_platform_features); WebRuntimeFeatures::EnableUserActivationPostMessageTransfer(
diff --git a/content/test/data/accessibility/css/inline-position-relative-expected-blink.txt b/content/test/data/accessibility/css/inline-position-relative-expected-blink.txt index 30e1405c2..6af34a76 100644 --- a/content/test/data/accessibility/css/inline-position-relative-expected-blink.txt +++ b/content/test/data/accessibility/css/inline-position-relative-expected-blink.txt
@@ -2,6 +2,5 @@ ++genericContainer pageLocation=(0, 0) ++++staticText pageLocation=(0, 0) name='Before' ++++++inlineTextBox pageLocation=(0, 0) name='Before' -++++genericContainer pageLocation=(100, 0) -++++++staticText pageLocation=(100, 0) name='After' -++++++++inlineTextBox pageLocation=(100, 0) name='After' +++++staticText pageLocation=(100, 0) name='After' +++++++inlineTextBox pageLocation=(100, 0) name='After' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/input-checkbox-label-expected-blink.txt b/content/test/data/accessibility/html/input-checkbox-label-expected-blink.txt index 75e73837..9b60741 100644 --- a/content/test/data/accessibility/html/input-checkbox-label-expected-blink.txt +++ b/content/test/data/accessibility/html/input-checkbox-label-expected-blink.txt
@@ -1,4 +1,3 @@ rootWebArea ++genericContainer -++++labelText -++++++checkBox name='Checkbox Title' checkedState=false +++++checkBox name='Checkbox Title' checkedState=false \ No newline at end of file
diff --git a/content/test/data/accessibility/html/input-checkbox-label-expected-mac.txt b/content/test/data/accessibility/html/input-checkbox-label-expected-mac.txt index 293d884..c3efe2e 100644 --- a/content/test/data/accessibility/html/input-checkbox-label-expected-mac.txt +++ b/content/test/data/accessibility/html/input-checkbox-label-expected-mac.txt
@@ -1,4 +1,3 @@ AXWebArea ++AXGroup -++++AXGroup -++++++AXCheckBox AXTitle='Checkbox Title' AXValue='0' +++++AXCheckBox AXTitle='Checkbox Title' AXValue='0'
diff --git a/infra/config/cr-buildbucket.cfg b/infra/config/cr-buildbucket.cfg index 13964b8..928c8c1 100644 --- a/infra/config/cr-buildbucket.cfg +++ b/infra/config/cr-buildbucket.cfg
@@ -1587,7 +1587,8 @@ } builders { name: "Mac FYI GPU ASAN Release" - mixins: "linux-gpu-fyi-ci" + # Builder/tester, thus needs Mac (not Linux like testers-only) + mixins: "mac-gpu-fyi-ci" execution_timeout_secs: 14400 # 4h } builders {
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 09de6cc..c47a981f 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -464,7 +464,7 @@ // If the current tab in |targetMode| is a NTP, it can be reused to open URL. // |completion| is executed after the tab is opened. After Tab is open the // virtual URL is set to the pending navigation item. -- (Tab*)openSelectedTabInMode:(ApplicationMode)targetMode +- (void)openSelectedTabInMode:(ApplicationMode)targetMode withURL:(const GURL&)url virtualURL:(const GURL&)virtualURL transition:(ui::PageTransition)transition @@ -473,7 +473,7 @@ // loads |url| in this tab. Otherwise, open |url| in a new tab in the target // BVC. // |tabDisplayedCompletion| will be called on the new tab (if not nil). -- (Tab*)openOrReuseTabInMode:(ApplicationMode)targetMode +- (void)openOrReuseTabInMode:(ApplicationMode)targetMode withURL:(const GURL&)url virtualURL:(const GURL&)virtualURL transition:(ui::PageTransition)transition @@ -1482,9 +1482,7 @@ _historyCoordinator = [[HistoryCoordinator alloc] initWithBaseViewController:self.currentBVC browserState:_mainBrowserState]; - _historyCoordinator.loader = UrlLoadingServiceFactory::GetForBrowserState( - [self.currentBVC browserState]) - ->GetUrlLoader(); + _historyCoordinator.loadStrategy = UrlLoadStrategy::NORMAL; _historyCoordinator.dispatcher = self.mainBVC.dispatcher; [_historyCoordinator start]; } @@ -1572,13 +1570,16 @@ } - (void)openURLInNewTab:(OpenNewTabCommand*)command { - UrlLoadParams* params = UrlLoadParams::InNewTab( - command.URL, command.virtualURL, command.referrer, command.inIncognito, - command.inBackground, command.appendTo); - params->origin_point = command.originPoint; - params->from_chrome = command.fromChrome; - params->user_initiated = command.userInitiated; - params->should_focus_omnibox = command.shouldFocusOmnibox; + UrlLoadParams params = + UrlLoadParams::InNewTab(command.URL, command.virtualURL); + params.SetInBackground(command.inBackground); + params.web_params.referrer = command.referrer; + params.in_incognito = command.inIncognito; + params.append_to = command.appendTo; + params.origin_point = command.originPoint; + params.from_chrome = command.fromChrome; + params.user_initiated = command.userInitiated; + params.should_focus_omnibox = command.shouldFocusOmnibox; _appURLLoadingService->LoadUrlInNewTab(params); } @@ -1683,6 +1684,7 @@ initWithBaseViewController:baseViewController browserState:_mainBrowserState]; _googleServicesNavigationCoordinator.delegate = self; + _googleServicesNavigationCoordinator.dispatcher = self; [_googleServicesNavigationCoordinator start]; } @@ -1773,8 +1775,6 @@ #pragma mark - AppURLLoadingServiceDelegate - (void)openURLInNewTabWithCommand:(OpenNewTabCommand*)command { - // TODO(crbug.com/907527): instead of AppUrlLoadingService calling - // openURLInNewTab, make openURLInNewTab call AppUrlLoadingService. [self openURLInNewTab:command]; } @@ -1834,10 +1834,10 @@ GURL result(defaultURL->url_ref().ReplaceSearchTerms( search_args, templateURLService->search_terms_data())); - web::NavigationManager::WebLoadParams params(result); - params.transition_type = ui::PAGE_TRANSITION_TYPED; + UrlLoadParams params = UrlLoadParams::InCurrentTab(result); + params.web_params.transition_type = ui::PAGE_TRANSITION_TYPED; UrlLoadingServiceFactory::GetForBrowserState([self.currentBVC browserState]) - ->Load(UrlLoadParams::InCurrentTab(params)); + ->Load(params); } // Loads the image from startup parameters as search-by-image in the current @@ -2253,7 +2253,7 @@ #pragma mark - Tab opening utility methods. -- (Tab*)openOrReuseTabInMode:(ApplicationMode)targetMode +- (void)openOrReuseTabInMode:(ApplicationMode)targetMode withURL:(const GURL&)URL virtualURL:(const GURL&)virtualURL transition:(ui::PageTransition)transition @@ -2273,7 +2273,7 @@ if (tabOpenedCompletion) { tabOpenedCompletion(); } - return currentTabInTargetBVC; + return; } // With kBrowserContainerContainsNTP enabled paired with a restored NTP @@ -2288,25 +2288,20 @@ !(currentTabInTargetBVC.webState && IsURLNtp(currentTabInTargetBVC.webState->GetVisibleURL()))) { [targetBVC appendTabAddedCompletion:tabOpenedCompletion]; - web::NavigationManager::WebLoadParams params(URL); - params.transition_type = transition; - params.virtual_url = virtualURL; - return [targetTabModel insertTabWithLoadParams:params - opener:nil - openedByDOM:NO - atIndex:targetTabModel.count - inBackground:NO]; + UrlLoadParams params = UrlLoadParams::InNewTab(URL, virtualURL); + params.web_params.transition_type = transition; + params.in_incognito = targetMode == ApplicationMode::INCOGNITO; + UrlLoadingServiceFactory::GetForBrowserState([targetBVC browserState]) + ->Load(params); + return; } // Otherwise, load |url| in the current tab. - Tab* newTab = currentTabInTargetBVC; - web::NavigationManager::WebLoadParams params(URL); - params.virtual_url = virtualURL; - newTab.webState->GetNavigationManager()->LoadURLWithParams(params); + UrlLoadingServiceFactory::GetForBrowserState([targetBVC browserState]) + ->Load(UrlLoadParams::InCurrentTab(URL, virtualURL)); if (tabOpenedCompletion) { tabOpenedCompletion(); } - return newTab; } - (ProceduralBlock)completionBlockForTriggeringAction: @@ -2337,7 +2332,7 @@ } } -- (Tab*)openSelectedTabInMode:(ApplicationMode)targetMode +- (void)openSelectedTabInMode:(ApplicationMode)targetMode withURL:(const GURL&)url virtualURL:(const GURL&)virtualURL transition:(ui::PageTransition)transition @@ -2368,7 +2363,6 @@ tabOpenedCompletion = completion; } - Tab* tab = nil; if (_tabSwitcherIsActive) { // If the tab switcher is already being dismissed, simply add the tab and // note that when the tab switcher finishes dismissing, the current BVC @@ -2379,37 +2373,34 @@ ? TabSwitcherDismissalMode::NORMAL : TabSwitcherDismissalMode::INCOGNITO; [targetInterface.bvc appendTabAddedCompletion:tabOpenedCompletion]; - web::NavigationManager::WebLoadParams params(url); - params.transition_type = transition; - params.virtual_url = virtualURL; - tab = [targetInterface.tabModel insertTabWithLoadParams:params - opener:nil - openedByDOM:NO - atIndex:tabIndex - inBackground:NO]; + UrlLoadParams params = UrlLoadParams::InNewTab(url, virtualURL); + params.web_params.transition_type = transition; + params.in_incognito = targetMode == ApplicationMode::INCOGNITO; + UrlLoadingServiceFactory::GetForBrowserState( + [targetInterface.bvc browserState]) + ->Load(params); } else { // Voice search, QRScanner and the omnibox are presented by the BVC. // They must be started after the BVC view is added in the hierarchy. self.NTPActionAfterTabSwitcherDismissal = [_startupParameters postOpeningAction]; [self setStartupParameters:nil]; - tab = [_tabSwitcher - dismissWithNewTabAnimationToModel:targetInterface.tabModel - withURL:url - virtualURL:virtualURL - atIndex:tabIndex - transition:transition]; + [_tabSwitcher dismissWithNewTabAnimationToModel:targetInterface.tabModel + withURL:url + virtualURL:virtualURL + atIndex:tabIndex + transition:transition]; } } else { if (!self.currentBVC.presentedViewController) { [targetInterface.bvc expectNewForegroundTab]; } [self setCurrentInterfaceForMode:targetMode]; - tab = [self openOrReuseTabInMode:targetMode - withURL:url - virtualURL:virtualURL - transition:transition - tabOpenedCompletion:tabOpenedCompletion]; + [self openOrReuseTabInMode:targetMode + withURL:url + virtualURL:virtualURL + transition:transition + tabOpenedCompletion:tabOpenedCompletion]; } if (_restoreHelper) { @@ -2424,8 +2415,6 @@ _restoreHelper = nil; }); } - - return tab; } - (void)dismissModalDialogsWithCompletion:(ProceduralBlock)completion
diff --git a/ios/chrome/browser/overlays/OWNERS b/ios/chrome/browser/overlays/OWNERS new file mode 100644 index 0000000..6eb89c5 --- /dev/null +++ b/ios/chrome/browser/overlays/OWNERS
@@ -0,0 +1,2 @@ +kkhorimoto@chromium.org +michaeldo@chromium.org
diff --git a/ios/chrome/browser/passwords/password_controller.mm b/ios/chrome/browser/passwords/password_controller.mm index 831abf4..4764bc2 100644 --- a/ios/chrome/browser/passwords/password_controller.mm +++ b/ios/chrome/browser/passwords/password_controller.mm
@@ -694,7 +694,8 @@ - (BOOL)canGeneratePasswordForForm:(NSString*)formName fieldIdentifier:(NSString*)fieldIdentifier fieldType:(NSString*)fieldType { - if (!features::IsAutomaticPasswordGenerationEnabled()) + if (!features::IsAutomaticPasswordGenerationEnabled() || + _passwordManagerClient->IsIncognito()) return NO; if (![fieldType isEqualToString:@"password"]) return NO;
diff --git a/ios/chrome/browser/sync/profile_sync_service_factory.cc b/ios/chrome/browser/sync/profile_sync_service_factory.cc index aea71fe4..81f0e75f 100644 --- a/ios/chrome/browser/sync/profile_sync_service_factory.cc +++ b/ios/chrome/browser/sync/profile_sync_service_factory.cc
@@ -40,6 +40,7 @@ #include "ios/chrome/browser/sync/consent_auditor_factory.h" #include "ios/chrome/browser/sync/device_info_sync_service_factory.h" #include "ios/chrome/browser/sync/ios_chrome_sync_client.h" +#include "ios/chrome/browser/sync/ios_user_event_service_factory.h" #include "ios/chrome/browser/sync/model_type_store_service_factory.h" #include "ios/chrome/browser/sync/session_sync_service_factory.h" #include "ios/chrome/browser/undo/bookmark_undo_service_factory.h" @@ -136,6 +137,7 @@ DependsOn(IOSChromeProfileInvalidationProviderFactory::GetInstance()); DependsOn( IOSChromeDeprecatedProfileInvalidationProviderFactory::GetInstance()); + DependsOn(IOSUserEventServiceFactory::GetInstance()); DependsOn(ModelTypeStoreServiceFactory::GetInstance()); DependsOn(ReadingListModelFactory::GetInstance()); DependsOn(SessionSyncServiceFactory::GetInstance());
diff --git a/ios/chrome/browser/sync/send_tab_to_self_sync_service_factory.mm b/ios/chrome/browser/sync/send_tab_to_self_sync_service_factory.mm index 0513c44..89d89f7 100644 --- a/ios/chrome/browser/sync/send_tab_to_self_sync_service_factory.mm +++ b/ios/chrome/browser/sync/send_tab_to_self_sync_service_factory.mm
@@ -7,11 +7,8 @@ #include "components/keyed_service/core/service_access_type.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/send_tab_to_self/send_tab_to_self_sync_service.h" -#include "components/sync/device_info/device_info_sync_service.h" -#include "components/sync/device_info/local_device_info_provider.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/history/history_service_factory.h" -#include "ios/chrome/browser/sync/device_info_sync_service_factory.h" #include "ios/chrome/browser/sync/model_type_store_service_factory.h" #include "ios/chrome/common/channel_info.h" @@ -39,7 +36,6 @@ : BrowserStateKeyedServiceFactory( "SendTabToSelfSyncService", BrowserStateDependencyManager::GetInstance()) { - DependsOn(DeviceInfoSyncServiceFactory::GetInstance()); DependsOn(ModelTypeStoreServiceFactory::GetInstance()); DependsOn(ios::HistoryServiceFactory::GetInstance()); } @@ -52,10 +48,6 @@ ios::ChromeBrowserState* browser_state = ios::ChromeBrowserState::FromBrowserState(context); - syncer::LocalDeviceInfoProvider* local_device_info_provider = - DeviceInfoSyncServiceFactory::GetForBrowserState(browser_state) - ->GetLocalDeviceInfoProvider(); - syncer::OnceModelTypeStoreFactory store_factory = ModelTypeStoreServiceFactory::GetForBrowserState(browser_state) ->GetStoreFactory(); @@ -65,6 +57,5 @@ browser_state, ServiceAccessType::EXPLICIT_ACCESS); return std::make_unique<SendTabToSelfSyncService>( - GetChannel(), local_device_info_provider, std::move(store_factory), - history_service); + GetChannel(), std::move(store_factory), history_service); }
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm b/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm index 98b6464..483f371 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm
@@ -1055,10 +1055,9 @@ new_tab_page_uma::ACTION_OPENED_BOOKMARK); base::RecordAction( base::UserMetricsAction("MobileBookmarkManagerEntryOpened")); - web::NavigationManager::WebLoadParams params(url); - params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; - UrlLoadingServiceFactory::GetForBrowserState(self.browserState) - ->Load(UrlLoadParams::InCurrentTab(params)); + UrlLoadParams params = UrlLoadParams::InCurrentTab(url); + params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; + UrlLoadingServiceFactory::GetForBrowserState(self.browserState)->Load(params); } - (void)addNewFolder {
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_interaction_controller.mm b/ios/chrome/browser/ui/bookmarks/bookmark_interaction_controller.mm index 486ab649..5004398 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_interaction_controller.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_interaction_controller.mm
@@ -546,10 +546,10 @@ LoadJavaScriptURL(url, _browserState, _webStateList->GetActiveWebState()); return; } - web::NavigationManager::WebLoadParams params(url); - params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; + UrlLoadParams params = UrlLoadParams::InCurrentTab(url); + params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; UrlLoadingServiceFactory::GetForBrowserState(_currentBrowserState) - ->Load(UrlLoadParams::InCurrentTab(params)); + ->Load(params); } - (void)openURLInNewTab:(const GURL&)url @@ -557,8 +557,11 @@ inBackground:(BOOL)inBackground { // TODO(crbug.com/695749): Open bookmarklet in new tab doesn't work. See how // to deal with this later. + UrlLoadParams params = UrlLoadParams::InNewTab(url); + params.SetInBackground(inBackground); + params.in_incognito = inIncognito; UrlLoadingServiceFactory::GetForBrowserState(_currentBrowserState) - ->Load(UrlLoadParams::InNewTab(url, inIncognito, inBackground, kLastTab)); + ->Load(params); } @end
diff --git a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm index 6803344..cd0ccb2a 100644 --- a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm
@@ -1169,12 +1169,10 @@ ->UpdateSnapshotWithCallback(nil); } - UrlLoadingServiceFactory::GetForBrowserState(self.browserState) - ->Load(UrlLoadParams::InNewTab( - web_navigation_util::CreateWebLoadParams( - GURL(kChromeUINewTabURL), ui::PAGE_TRANSITION_TYPED, nullptr), - /* in_incognito */ self.isOffTheRecord, - /* in_background */ NO, kLastTab)); + UrlLoadParams params = UrlLoadParams::InNewTab(GURL(kChromeUINewTabURL)); + params.web_params.transition_type = ui::PAGE_TRANSITION_TYPED; + params.in_incognito = self.isOffTheRecord; + UrlLoadingServiceFactory::GetForBrowserState(self.browserState)->Load(params); } - (void)appendTabAddedCompletion:(ProceduralBlock)tabAddedCompletion { @@ -3169,11 +3167,12 @@ if (!strongSelf) return; - UrlLoadParams* params = UrlLoadParams::InNewTab( - link, referrer, - /* in_incognito */ strongSelf.isOffTheRecord, - /* in_background */ YES, kCurrentTab); - params->origin_point = originPoint; + UrlLoadParams params = UrlLoadParams::InNewTab(link); + params.SetInBackground(YES); + params.web_params.referrer = referrer; + params.in_incognito = strongSelf.isOffTheRecord; + params.append_to = kCurrentTab; + params.origin_point = originPoint; UrlLoadingServiceFactory::GetForBrowserState(strongSelf.browserState) ->Load(params); }; @@ -3189,10 +3188,10 @@ Record(ACTION_OPEN_IN_INCOGNITO_TAB, isImage, isLink); - UrlLoadParams* params = - UrlLoadParams::InNewTab(link, referrer, - /* in_incognito */ YES, - /* in_background */ NO, kCurrentTab); + UrlLoadParams params = UrlLoadParams::InNewTab(link); + params.web_params.referrer = referrer; + params.in_incognito = YES; + params.append_to = kCurrentTab; UrlLoadingServiceFactory::GetForBrowserState(strongSelf.browserState) ->Load(params); }; @@ -3262,11 +3261,12 @@ if (!strongSelf) return; - UrlLoadParams* params = - UrlLoadParams::InNewTab(imageUrl, referrer, - /* in_incognito */ strongSelf.isOffTheRecord, - /* in_background */ YES, kCurrentTab); - params->origin_point = originPoint; + UrlLoadParams params = UrlLoadParams::InNewTab(imageUrl); + params.SetInBackground(YES); + params.web_params.referrer = referrer; + params.in_incognito = strongSelf.isOffTheRecord; + params.append_to = kCurrentTab; + params.origin_point = originPoint; UrlLoadingServiceFactory::GetForBrowserState(strongSelf.browserState) ->Load(params); }; @@ -3394,10 +3394,10 @@ web_navigation_util::CreateWebLoadParams( result, ui::PAGE_TRANSITION_TYPED, &postContent); if (inNewTab) { + UrlLoadParams params = UrlLoadParams::InNewTab(loadParams); + params.in_incognito = self.isOffTheRecord; UrlLoadingServiceFactory::GetForBrowserState(self.browserState) - ->Load(UrlLoadParams::InNewTab(loadParams, - /* in_incognito */ self.isOffTheRecord, - /* in_background */ NO, kLastTab)); + ->Load(params); } else { UrlLoadingServiceFactory::GetForBrowserState(self.browserState) ->Load(UrlLoadParams::InCurrentTab(loadParams)); @@ -4261,11 +4261,9 @@ - (void)showHelpPage { GURL helpUrl(l10n_util::GetStringUTF16(IDS_IOS_TOOLS_MENU_HELP_URL)); - UrlLoadParams* params = - UrlLoadParams::InNewTab(helpUrl, - /* in_incognito */ NO, - /* in_background */ NO, kCurrentTab); - params->user_initiated = NO; + UrlLoadParams params = UrlLoadParams::InNewTab(helpUrl); + params.append_to = kCurrentTab; + params.user_initiated = NO; UrlLoadingServiceFactory::GetForBrowserState(self.browserState)->Load(params); }
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm index f23259c..3a27611 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm
@@ -230,14 +230,14 @@ self.suggestionsService->user_classifier()->OnEvent( ntp_snippets::UserClassifier::Metric::SUGGESTIONS_USED); - web::NavigationManager::WebLoadParams params(suggestionItem.URL); // Use a referrer with a specific URL to mark this entry as coming from // ContentSuggestions. - params.referrer = + UrlLoadParams params = UrlLoadParams::InCurrentTab(suggestionItem.URL); + params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; + params.web_params.referrer = web::Referrer(GURL(ntp_snippets::GetContentSuggestionsReferrerURL()), web::ReferrerPolicyDefault); - params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; - _urlLoadingService->Load(UrlLoadParams::InCurrentTab(params)); + _urlLoadingService->Load(params); [self.NTPMetrics recordAction:new_tab_page_uma::ACTION_OPENED_SUGGESTION]; } @@ -281,9 +281,9 @@ [self logMostVisitedOpening:mostVisitedItem atIndex:mostVisitedIndex]; - web::NavigationManager::WebLoadParams params(mostVisitedItem.URL); - params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; - _urlLoadingService->Load(UrlLoadParams::InCurrentTab(params)); + UrlLoadParams params = UrlLoadParams::InCurrentTab(mostVisitedItem.URL); + params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; + _urlLoadingService->Load(params); } - (void)displayContextMenuForSuggestion:(CollectionViewItem*)item @@ -353,10 +353,8 @@ [self.NTPMetrics recordAction:new_tab_page_uma::ACTION_OPENED_PROMO]; if (notificationPromo->IsURLPromo()) { - UrlLoadParams* params = - UrlLoadParams::InNewTab(notificationPromo->url(), - /* in_incognito */ NO, - /* in_background */ NO, kCurrentTab); + UrlLoadParams params = UrlLoadParams::InNewTab(notificationPromo->url()); + params.append_to = kCurrentTab; _urlLoadingService->Load(params); return; } @@ -376,8 +374,7 @@ NewTabPageTabHelper::FromWebState(self.webState); if (NTPHelper && NTPHelper->IgnoreLoadRequests()) return; - GURL URL(kNTPHelpURL); - _urlLoadingService->Load(UrlLoadParams::InCurrentTab(URL)); + _urlLoadingService->Load(UrlLoadParams::InCurrentTab(GURL(kNTPHelpURL))); [self.NTPMetrics recordAction:new_tab_page_uma::ACTION_OPENED_LEARN_MORE]; } @@ -552,11 +549,11 @@ incognito:(BOOL)incognito originPoint:(CGPoint)originPoint { // Open the tab in background if it is non-incognito only. - UrlLoadParams* params = - UrlLoadParams::InNewTab(URL, - /* in_incognito */ incognito, - /* in_background */ !incognito, kCurrentTab); - params->origin_point = originPoint; + UrlLoadParams params = UrlLoadParams::InNewTab(URL); + params.SetInBackground(!incognito); + params.in_incognito = incognito; + params.append_to = kCurrentTab; + params.origin_point = originPoint; _urlLoadingService->Load(params); }
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm index 50cded6..ad1d8ce 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm
@@ -267,10 +267,10 @@ [mediator_ openPageForItemAtIndexPath:indexPath]; // Test. - EXPECT_EQ(url, url_loader_->last_params->web_params.url); + EXPECT_EQ(url, url_loader_->last_params.web_params.url); EXPECT_TRUE(ui::PageTransitionCoreTypeIs( ui::PAGE_TRANSITION_AUTO_BOOKMARK, - url_loader_->last_params->web_params.transition_type)); + url_loader_->last_params.web_params.transition_type)); } // Tests that the command is sent to the loader when opening a most visited. @@ -286,8 +286,8 @@ [mediator_ openMostVisitedItem:item atIndex:0]; // Test. - EXPECT_EQ(url, url_loader_->last_params->web_params.url); + EXPECT_EQ(url, url_loader_->last_params.web_params.url); EXPECT_TRUE(ui::PageTransitionCoreTypeIs( ui::PAGE_TRANSITION_AUTO_BOOKMARK, - url_loader_->last_params->web_params.transition_type)); + url_loader_->last_params.web_params.transition_type)); }
diff --git a/ios/chrome/browser/ui/history/BUILD.gn b/ios/chrome/browser/ui/history/BUILD.gn index 98bb8841..dbe170d4 100644 --- a/ios/chrome/browser/ui/history/BUILD.gn +++ b/ios/chrome/browser/ui/history/BUILD.gn
@@ -84,6 +84,7 @@ "//ios/chrome/browser/ui/table_view:styler", "//ios/chrome/browser/ui/table_view/cells", "//ios/chrome/browser/ui/util", + "//ios/chrome/browser/url_loading", "//ios/chrome/common/favicon", "//ui/base", ] @@ -106,6 +107,7 @@ "//ios/chrome/browser/ui/settings/clear_browsing_data", "//ios/chrome/browser/ui/table_view", "//ios/chrome/browser/ui/table_view:presentation", + "//ios/chrome/browser/url_loading", "//ios/web/public", ] }
diff --git a/ios/chrome/browser/ui/history/history_clear_browsing_data_coordinator.h b/ios/chrome/browser/ui/history/history_clear_browsing_data_coordinator.h index 9429de58..1081f5ff 100644 --- a/ios/chrome/browser/ui/history/history_clear_browsing_data_coordinator.h +++ b/ios/chrome/browser/ui/history/history_clear_browsing_data_coordinator.h
@@ -8,8 +8,9 @@ #import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" #import "ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_local_commands.h" +enum class UrlLoadStrategy; + @protocol ApplicationCommands; -@protocol UrlLoader; @protocol HistoryLocalCommands; @protocol HistoryPresentationDelegate; @protocol HistoryClearBrowsingDataLocalCommands; @@ -25,8 +26,8 @@ // Dispatcher for view controller. @property(nonatomic, weak) id<ApplicationCommands> dispatcher; -// The UrlLoader used by this coordinator. -@property(nonatomic, weak) id<UrlLoader> loader; +// Opaque instructions on how to open urls. +@property(nonatomic) UrlLoadStrategy loadStrategy; // Delegate used to make the Tab UI visible. @property(nonatomic, weak) id<HistoryPresentationDelegate> presentationDelegate;
diff --git a/ios/chrome/browser/ui/history/history_clear_browsing_data_coordinator.mm b/ios/chrome/browser/ui/history/history_clear_browsing_data_coordinator.mm index d7020aa..f55e251 100644 --- a/ios/chrome/browser/ui/history/history_clear_browsing_data_coordinator.mm +++ b/ios/chrome/browser/ui/history/history_clear_browsing_data_coordinator.mm
@@ -7,7 +7,6 @@ #import <UIKit/UIKit.h> #include "base/mac/foundation_util.h" -#import "ios/chrome/browser/ui/commands/open_new_tab_command.h" #include "ios/chrome/browser/ui/history/history_local_commands.h" #import "ios/chrome/browser/ui/history/public/history_presentation_delegate.h" #import "ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_local_commands.h" @@ -15,7 +14,9 @@ #import "ios/chrome/browser/ui/table_view/table_view_navigation_controller.h" #import "ios/chrome/browser/ui/table_view/table_view_presentation_controller.h" #import "ios/chrome/browser/ui/table_view/table_view_presentation_controller_delegate.h" -#import "ios/chrome/browser/ui/url_loader.h" +#import "ios/chrome/browser/url_loading/url_loading_params.h" +#import "ios/chrome/browser/url_loading/url_loading_service.h" +#import "ios/chrome/browser/url_loading/url_loading_service_factory.h" #import "ios/web/public/referrer.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -40,7 +41,6 @@ @synthesize dispatcher = _dispatcher; @synthesize historyClearBrowsingDataNavigationController = _historyClearBrowsingDataNavigationController; -@synthesize loader = _loader; @synthesize localDispatcher = _localDispatcher; @synthesize presentationDelegate = _presentationDelegate; @@ -99,15 +99,12 @@ - (void)openURL:(const GURL&)URL { DCHECK(self.historyClearBrowsingDataNavigationController); - OpenNewTabCommand* command = - [[OpenNewTabCommand alloc] initWithURL:URL - referrer:web::Referrer() - inIncognito:NO - inBackground:NO - appendTo:kLastTab]; + UrlLoadParams params = UrlLoadParams::InNewTab(URL); + params.load_strategy = self.loadStrategy; [self stopWithCompletion:^() { [self.localDispatcher dismissHistoryWithCompletion:^{ - [self.loader webPageOrderedOpen:command]; + UrlLoadingServiceFactory::GetForBrowserState(self.browserState) + ->Load(params); [self.presentationDelegate showActiveRegularTabFromHistory]; }]; }];
diff --git a/ios/chrome/browser/ui/history/history_coordinator.h b/ios/chrome/browser/ui/history/history_coordinator.h index bd12de9..67b2474 100644 --- a/ios/chrome/browser/ui/history/history_coordinator.h +++ b/ios/chrome/browser/ui/history/history_coordinator.h
@@ -10,16 +10,17 @@ #import "base/ios/block_types.h" #import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" +enum class UrlLoadStrategy; + @protocol ApplicationCommands; -@protocol UrlLoader; @protocol HistoryPresentationDelegate; // Coordinator that presents History. @interface HistoryCoordinator : ChromeCoordinator // The dispatcher for this Coordinator. @property(nonatomic, weak) id<ApplicationCommands> dispatcher; -// URL loader being managed by this Coordinator. -@property(nonatomic, weak) id<UrlLoader> loader; +// Opaque instructions on how to open urls. +@property(nonatomic) UrlLoadStrategy loadStrategy; // Delegate used to make the Tab UI visible. @property(nonatomic, weak) id<HistoryPresentationDelegate> presentationDelegate; // Stops this Coordinator then calls |completionHandler|.
diff --git a/ios/chrome/browser/ui/history/history_coordinator.mm b/ios/chrome/browser/ui/history/history_coordinator.mm index fda4a92..7f5b167b 100644 --- a/ios/chrome/browser/ui/history/history_coordinator.mm +++ b/ios/chrome/browser/ui/history/history_coordinator.mm
@@ -54,7 +54,6 @@ _historyClearBrowsingDataCoordinator; @synthesize historyNavigationController = _historyNavigationController; @synthesize historyTransitioningDelegate = _historyTransitioningDelegate; -@synthesize loader = _loader; @synthesize mediator = _mediator; @synthesize presentationDelegate = _presentationDelegate; @@ -62,7 +61,7 @@ // Initialize and configure HistoryTableViewController. self.historyTableViewController = [[HistoryTableViewController alloc] init]; self.historyTableViewController.browserState = self.browserState; - self.historyTableViewController.loader = self.loader; + self.historyTableViewController.loadStrategy = self.loadStrategy; // Initialize and set HistoryMediator self.mediator = @@ -147,7 +146,7 @@ self.historyClearBrowsingDataCoordinator.localDispatcher = self; self.historyClearBrowsingDataCoordinator.presentationDelegate = self.presentationDelegate; - self.historyClearBrowsingDataCoordinator.loader = self.loader; + self.historyClearBrowsingDataCoordinator.loadStrategy = self.loadStrategy; self.historyClearBrowsingDataCoordinator.dispatcher = self.dispatcher; [self.historyClearBrowsingDataCoordinator start]; }
diff --git a/ios/chrome/browser/ui/history/history_table_view_controller.h b/ios/chrome/browser/ui/history/history_table_view_controller.h index 23e32ef..4ce8eef 100644 --- a/ios/chrome/browser/ui/history/history_table_view_controller.h +++ b/ios/chrome/browser/ui/history/history_table_view_controller.h
@@ -13,11 +13,12 @@ class ChromeBrowserState; } +enum class UrlLoadStrategy; + @class ContextMenuCoordinator; @protocol TableViewFaviconDataSource; @protocol HistoryLocalCommands; @protocol HistoryPresentationDelegate; -@protocol UrlLoader; // ChromeTableViewController for displaying history items. @interface HistoryTableViewController @@ -27,8 +28,8 @@ // Abstraction to communicate with HistoryService and WebHistoryService. // Not owned by HistoryTableViewController. @property(nonatomic, assign) history::BrowsingHistoryService* historyService; -// The UrlLoader used by this ViewController. -@property(nonatomic, weak) id<UrlLoader> loader; +// Opaque instructions on how to open urls. +@property(nonatomic) UrlLoadStrategy loadStrategy; // Delegate for this HistoryTableView. @property(nonatomic, weak) id<HistoryLocalCommands> localDispatcher; // Delegate used to make the Tab UI visible.
diff --git a/ios/chrome/browser/ui/history/history_table_view_controller.mm b/ios/chrome/browser/ui/history/history_table_view_controller.mm index 3a7b187..8219098 100644 --- a/ios/chrome/browser/ui/history/history_table_view_controller.mm +++ b/ios/chrome/browser/ui/history/history_table_view_controller.mm
@@ -16,7 +16,6 @@ #import "ios/chrome/browser/metrics/new_tab_page_uma.h" #include "ios/chrome/browser/sync/sync_setup_service.h" #include "ios/chrome/browser/sync/sync_setup_service_factory.h" -#import "ios/chrome/browser/ui/commands/open_new_tab_command.h" #import "ios/chrome/browser/ui/context_menu/context_menu_coordinator.h" #include "ios/chrome/browser/ui/history/history_entries_status_item.h" #import "ios/chrome/browser/ui/history/history_entries_status_item_delegate.h" @@ -33,9 +32,11 @@ #import "ios/chrome/browser/ui/table_view/cells/table_view_url_item.h" #import "ios/chrome/browser/ui/table_view/table_view_favicon_data_source.h" #import "ios/chrome/browser/ui/table_view/table_view_navigation_controller_constants.h" -#import "ios/chrome/browser/ui/url_loader.h" #import "ios/chrome/browser/ui/util/pasteboard_util.h" #import "ios/chrome/browser/ui/util/top_view_controller.h" +#import "ios/chrome/browser/url_loading/url_loading_params.h" +#import "ios/chrome/browser/url_loading/url_loading_service.h" +#import "ios/chrome/browser/url_loading/url_loading_service_factory.h" #import "ios/chrome/common/favicon/favicon_view.h" #import "ios/chrome/common/ui_util/constraints_ui_util.h" #include "ios/chrome/grit/ios_strings.h" @@ -133,7 +134,6 @@ @synthesize finishedLoading = _finishedLoading; @synthesize historyService = _historyService; @synthesize imageDataSource = _imageDataSource; -@synthesize loader = _loader; @synthesize loading = _loading; @synthesize localDispatcher = _localDispatcher; @synthesize searchController = _searchController; @@ -1043,29 +1043,19 @@ // Opens URL in a new non-incognito tab and dismisses the history view. - (void)openURLInNewTab:(const GURL&)URL { - OpenNewTabCommand* command = - [[OpenNewTabCommand alloc] initWithURL:URL - referrer:web::Referrer() - inIncognito:NO - inBackground:NO - appendTo:kLastTab]; - + UrlLoadParams params = UrlLoadParams::InNewTab(URL); [self.localDispatcher dismissHistoryWithCompletion:^{ - [self.loader webPageOrderedOpen:command]; + UrlLoadingServiceFactory::GetForBrowserState(_browserState)->Load(params); [self.presentationDelegate showActiveRegularTabFromHistory]; }]; } // Opens URL in a new incognito tab and dismisses the history view. - (void)openURLInNewIncognitoTab:(const GURL&)URL { - OpenNewTabCommand* command = - [[OpenNewTabCommand alloc] initWithURL:URL - referrer:web::Referrer() - inIncognito:YES - inBackground:NO - appendTo:kLastTab]; + UrlLoadParams params = UrlLoadParams::InNewTab(URL); + params.in_incognito = YES; [self.localDispatcher dismissHistoryWithCompletion:^{ - [self.loader webPageOrderedOpen:command]; + UrlLoadingServiceFactory::GetForBrowserState(_browserState)->Load(params); [self.presentationDelegate showActiveIncognitoTabFromHistory]; }]; } @@ -1076,11 +1066,11 @@ - (void)openURL:(const GURL&)URL { new_tab_page_uma::RecordAction(_browserState, new_tab_page_uma::ACTION_OPENED_HISTORY_ENTRY); - web::NavigationManager::WebLoadParams params(URL); - params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; - ChromeLoadParams chromeParams(params); + UrlLoadParams params = UrlLoadParams::InCurrentTab(URL); + params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; + params.load_strategy = self.loadStrategy; [self.localDispatcher dismissHistoryWithCompletion:^{ - [self.loader loadURLWithParams:chromeParams]; + UrlLoadingServiceFactory::GetForBrowserState(_browserState)->Load(params); [self.presentationDelegate showActiveRegularTabFromHistory]; }]; }
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm index 7068caf..7adf81c 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm
@@ -245,14 +245,16 @@ // |loadURL|? It doesn't seem to be causing major problems. If we call // cancel before load, then any prerendered pages get destroyed before the // call to load. - web::NavigationManager::WebLoadParams params = + web::NavigationManager::WebLoadParams web_params = web_navigation_util::CreateWebLoadParams(url, transition, postContent); NSMutableDictionary* combinedExtraHeaders = [[self variationHeadersForURL:url] mutableCopy]; - [combinedExtraHeaders addEntriesFromDictionary:params.extra_headers]; - params.extra_headers = [combinedExtraHeaders copy]; + [combinedExtraHeaders addEntriesFromDictionary:web_params.extra_headers]; + web_params.extra_headers = [combinedExtraHeaders copy]; + UrlLoadParams params = UrlLoadParams::InCurrentTab(web_params); + params.disposition = disposition; UrlLoadingServiceFactory::GetForBrowserState(self.browserState) - ->Load(UrlLoadParams::InCurrentTab(params, disposition)); + ->Load(params); if (google_util::IsGoogleSearchUrl(url)) { UMA_HISTOGRAM_ENUMERATION( @@ -429,11 +431,11 @@ // It is necessary to include PAGE_TRANSITION_FROM_ADDRESS_BAR in the // transition type is so that query-in-the-omnibox is triggered for the // URL. - web::NavigationManager::WebLoadParams params(searchURL); - params.transition_type = ui::PageTransitionFromInt( + UrlLoadParams params = UrlLoadParams::InCurrentTab(searchURL); + params.web_params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); UrlLoadingServiceFactory::GetForBrowserState(self.browserState) - ->Load(UrlLoadParams::InCurrentTab(params)); + ->Load(params); } }
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm b/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm index 000b48b0b..839ba98 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm
@@ -140,18 +140,18 @@ (TestUrlLoadingService*)UrlLoadingServiceFactory::GetForBrowserState( browser_state_.get()); - EXPECT_EQ(url, url_loader->last_params->web_params.url); - EXPECT_TRUE(url_loader->last_params->web_params.referrer.url.is_empty()); + EXPECT_EQ(url, url_loader->last_params.web_params.url); + EXPECT_TRUE(url_loader->last_params.web_params.referrer.url.is_empty()); EXPECT_EQ(web::ReferrerPolicyDefault, - url_loader->last_params->web_params.referrer.policy); + url_loader->last_params.web_params.referrer.policy); EXPECT_TRUE(ui::PageTransitionCoreTypeIs( - transition, url_loader->last_params->web_params.transition_type)); - EXPECT_FALSE(url_loader->last_params->web_params.is_renderer_initiated); - ASSERT_EQ(1U, url_loader->last_params->web_params.extra_headers.count); - EXPECT_GT([url_loader->last_params->web_params.extra_headers[@"X-Client-Data"] + transition, url_loader->last_params.web_params.transition_type)); + EXPECT_FALSE(url_loader->last_params.web_params.is_renderer_initiated); + ASSERT_EQ(1U, url_loader->last_params.web_params.extra_headers.count); + EXPECT_GT([url_loader->last_params.web_params.extra_headers[@"X-Client-Data"] length], 0U); - EXPECT_EQ(disposition, url_loader->last_params->disposition); + EXPECT_EQ(disposition, url_loader->last_params.disposition); } // Calls -loadGURLFromLocationBar:transition: with https://www.nongoogle.com/ @@ -175,15 +175,15 @@ (TestUrlLoadingService*)UrlLoadingServiceFactory::GetForBrowserState( browser_state_.get()); - EXPECT_EQ(url, url_loader->last_params->web_params.url); - EXPECT_TRUE(url_loader->last_params->web_params.referrer.url.is_empty()); + EXPECT_EQ(url, url_loader->last_params.web_params.url); + EXPECT_TRUE(url_loader->last_params.web_params.referrer.url.is_empty()); EXPECT_EQ(web::ReferrerPolicyDefault, - url_loader->last_params->web_params.referrer.policy); + url_loader->last_params.web_params.referrer.policy); EXPECT_TRUE(ui::PageTransitionCoreTypeIs( - transition, url_loader->last_params->web_params.transition_type)); - EXPECT_FALSE(url_loader->last_params->web_params.is_renderer_initiated); - ASSERT_EQ(0U, url_loader->last_params->web_params.extra_headers.count); - EXPECT_EQ(disposition, url_loader->last_params->disposition); + transition, url_loader->last_params.web_params.transition_type)); + EXPECT_FALSE(url_loader->last_params.web_params.is_renderer_initiated); + ASSERT_EQ(0U, url_loader->last_params.web_params.extra_headers.count); + EXPECT_EQ(disposition, url_loader->last_params.disposition); } } // namespace
diff --git a/ios/chrome/browser/ui/main/browser_coordinator.mm b/ios/chrome/browser/ui/main/browser_coordinator.mm index 9c843eb..dcf7311a 100644 --- a/ios/chrome/browser/ui/main/browser_coordinator.mm +++ b/ios/chrome/browser/ui/main/browser_coordinator.mm
@@ -381,9 +381,7 @@ self.recentTabsCoordinator = [[RecentTabsCoordinator alloc] initWithBaseViewController:self.viewController browserState:self.browserState]; - self.recentTabsCoordinator.loader = - UrlLoadingServiceFactory::GetForBrowserState(self.browserState) - ->GetUrlLoader(); + self.recentTabsCoordinator.loadStrategy = UrlLoadStrategy::NORMAL; self.recentTabsCoordinator.dispatcher = self.applicationCommandHandler; self.recentTabsCoordinator.webStateList = self.tabModel.webStateList; [self.recentTabsCoordinator start]; @@ -428,10 +426,10 @@ #pragma mark - URLLoadingServiceDelegate -- (void)animateOpenBackgroundTabFromParams:(UrlLoadParams*)params +- (void)animateOpenBackgroundTabFromParams:(const UrlLoadParams&)params completion:(void (^)())completion { [self.viewController - animateOpenBackgroundTabFromOriginPoint:params->origin_point + animateOpenBackgroundTabFromOriginPoint:params.origin_point completion:completion]; }
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_coordinator_unittest.mm b/ios/chrome/browser/ui/ntp/new_tab_page_coordinator_unittest.mm index 1d4b129..6d69f0c 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_coordinator_unittest.mm
@@ -13,7 +13,6 @@ #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" #import "ios/chrome/browser/ui/ntp/incognito_view_controller.h" #import "ios/chrome/browser/ui/ntp/new_tab_page_controller_delegate.h" -#import "ios/chrome/browser/ui/url_loader.h" #import "ios/chrome/browser/web_state_list/fake_web_state_list_delegate.h" #include "ios/chrome/browser/web_state_list/web_state_list.h"
diff --git a/ios/chrome/browser/ui/omnibox/popup/shortcuts/shortcuts_mediator.mm b/ios/chrome/browser/ui/omnibox/popup/shortcuts/shortcuts_mediator.mm index e3f79552..492cfda 100644 --- a/ios/chrome/browser/ui/omnibox/popup/shortcuts/shortcuts_mediator.mm +++ b/ios/chrome/browser/ui/omnibox/popup/shortcuts/shortcuts_mediator.mm
@@ -14,7 +14,6 @@ #import "ios/chrome/browser/ui/favicon/favicon_attributes_provider.h" #import "ios/chrome/browser/ui/omnibox/popup/shortcuts/shortcuts_consumer.h" #import "ios/chrome/browser/ui/toolbar/public/omnibox_focuser.h" -#import "ios/chrome/browser/ui/url_loader.h" #import "ios/chrome/browser/url_loading/url_loading_params.h" #import "ios/chrome/browser/url_loading/url_loading_service.h" #import "ios/web/public/navigation_item.h" @@ -108,10 +107,10 @@ #pragma mark - ShortcutsViewControllerDelegate - (void)openMostVisitedItem:(ShortcutsMostVisitedItem*)item { - web::NavigationManager::WebLoadParams params(item.URL); - params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; [self.dispatcher cancelOmniboxEdit]; - _loadingService->Load(UrlLoadParams::InCurrentTab(params)); + UrlLoadParams params = UrlLoadParams::InCurrentTab(item.URL); + params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; + _loadingService->Load(params); } - (void)openBookmarks {
diff --git a/ios/chrome/browser/ui/page_info/page_info_legacy_coordinator.mm b/ios/chrome/browser/ui/page_info/page_info_legacy_coordinator.mm index 45687d84..146d1a06 100644 --- a/ios/chrome/browser/ui/page_info/page_info_legacy_coordinator.mm +++ b/ios/chrome/browser/ui/page_info/page_info_legacy_coordinator.mm
@@ -156,10 +156,8 @@ } - (void)showSecurityHelpPage { - UrlLoadParams* params = UrlLoadParams::InNewTab( - GURL(kPageInfoHelpCenterURL), - /* in_incognito */ self.browserState->IsOffTheRecord(), - /* in_background */ NO, kLastTab); + UrlLoadParams params = UrlLoadParams::InNewTab(GURL(kPageInfoHelpCenterURL)); + params.in_incognito = self.browserState->IsOffTheRecord(); UrlLoadingServiceFactory::GetForBrowserState(self.browserState)->Load(params); [self hidePageInfo]; }
diff --git a/ios/chrome/browser/ui/reading_list/reading_list_coordinator.mm b/ios/chrome/browser/ui/reading_list/reading_list_coordinator.mm index 8a3fdd5..4ebdac2 100644 --- a/ios/chrome/browser/ui/reading_list/reading_list_coordinator.mm +++ b/ios/chrome/browser/ui/reading_list/reading_list_coordinator.mm
@@ -365,20 +365,17 @@ // Use a referrer with a specific URL to signal that this entry should not be // taken into account for the Most Visited tiles. if (newTab) { - web::Referrer referrer = web::Referrer(GURL(kReadingListReferrerURL), - web::ReferrerPolicyDefault); - UrlLoadParams* params = - UrlLoadParams::InNewTab(loadURL, entryURL, referrer, - /* in_incognito */ incognito, - /* in_background */ NO, kLastTab); + UrlLoadParams params = UrlLoadParams::InNewTab(loadURL, entryURL); + params.in_incognito = incognito; + params.web_params.referrer = web::Referrer(GURL(kReadingListReferrerURL), + web::ReferrerPolicyDefault); UrlLoadingServiceFactory::GetForBrowserState(self.browserState) ->Load(params); } else { - web::NavigationManager::WebLoadParams web_params(loadURL); - web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; - web_params.referrer = web::Referrer(GURL(kReadingListReferrerURL), - web::ReferrerPolicyDefault); - UrlLoadParams* params = UrlLoadParams::InCurrentTab(web_params); + UrlLoadParams params = UrlLoadParams::InCurrentTab(loadURL); + params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; + params.web_params.referrer = web::Referrer(GURL(kReadingListReferrerURL), + web::ReferrerPolicyDefault); UrlLoadingServiceFactory::GetForBrowserState(self.browserState) ->Load(params); }
diff --git a/ios/chrome/browser/ui/recent_tabs/BUILD.gn b/ios/chrome/browser/ui/recent_tabs/BUILD.gn index 0a31daa9..18dec54 100644 --- a/ios/chrome/browser/ui/recent_tabs/BUILD.gn +++ b/ios/chrome/browser/ui/recent_tabs/BUILD.gn
@@ -31,6 +31,7 @@ "//ios/chrome/browser/ui/ntp", "//ios/chrome/browser/ui/table_view", "//ios/chrome/browser/ui/util", + "//ios/chrome/browser/url_loading", "//services/identity/public/cpp", "//ui/base", ]
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.h b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.h index 5baab5e..d088164 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.h +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.h
@@ -10,16 +10,16 @@ #import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" @protocol ApplicationCommands; -@protocol UrlLoader; +enum class UrlLoadStrategy; class WebStateList; // Coordinator that presents Recent Tabs. @interface RecentTabsCoordinator : ChromeCoordinator // The dispatcher for this Coordinator. @property(nonatomic, weak) id<ApplicationCommands> dispatcher; -// URL loader being managed by this Coordinator. -@property(nonatomic, weak) id<UrlLoader> loader; +// Opaque instructions on how to open urls. +@property(nonatomic) UrlLoadStrategy loadStrategy; // WebStateList managed by this Coordinator. @property(nonatomic, assign) WebStateList* webStateList;
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.mm b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.mm index ece2986f..2775ce36 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.mm +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.mm
@@ -14,6 +14,9 @@ #import "ios/chrome/browser/ui/recent_tabs/recent_tabs_transitioning_delegate.h" #import "ios/chrome/browser/ui/table_view/table_view_navigation_controller.h" #import "ios/chrome/browser/ui/table_view/table_view_navigation_controller_constants.h" +#import "ios/chrome/browser/url_loading/url_loading_params.h" +#import "ios/chrome/browser/url_loading/url_loading_service.h" +#import "ios/chrome/browser/url_loading/url_loading_service_factory.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -34,7 +37,6 @@ @implementation RecentTabsCoordinator @synthesize completion = _completion; @synthesize dispatcher = _dispatcher; -@synthesize loader = _loader; @synthesize mediator = _mediator; @synthesize recentTabsNavigationController = _recentTabsNavigationController; @synthesize recentTabsTransitioningDelegate = _recentTabsTransitioningDelegate; @@ -44,7 +46,7 @@ RecentTabsTableViewController* recentTabsTableViewController = [[RecentTabsTableViewController alloc] init]; recentTabsTableViewController.browserState = self.browserState; - recentTabsTableViewController.loader = self.loader; + recentTabsTableViewController.loadStrategy = self.loadStrategy; recentTabsTableViewController.dispatcher = self.dispatcher; recentTabsTableViewController.presentationDelegate = self; recentTabsTableViewController.webStateList = self.webStateList;
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm index d651ad7..84ffc499 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm
@@ -11,6 +11,7 @@ #include "base/bind.h" #include "components/sync/driver/sync_service.h" #include "components/sync/model/fake_model_type_controller_delegate.h" +#include "components/sync/user_events/global_id_mapper.h" #include "components/sync_sessions/open_tabs_ui_delegate.h" #include "components/sync_sessions/session_sync_service.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" @@ -102,6 +103,16 @@ bool(const sync_sessions::SyncedSession** local)); }; +class GlobalIdMapperMock : public syncer::GlobalIdMapper { + public: + GlobalIdMapperMock() {} + ~GlobalIdMapperMock() {} + + MOCK_METHOD1(AddGlobalIdChangeObserver, + void(syncer::GlobalIdChange callback)); + MOCK_METHOD1(GetLatestGlobalId, int64_t(int64_t global_id)); +}; + class RecentTabsTableCoordinatorTest : public BlockCleanupTest { public: RecentTabsTableCoordinatorTest() @@ -157,6 +168,8 @@ // initialization of SyncSetupServiceMock. ON_CALL(*session_sync_service, GetControllerDelegate()) .WillByDefault(Return(fake_controller_delegate_.GetWeakPtr())); + ON_CALL(*session_sync_service, GetGlobalIdMapper()) + .WillByDefault(Return(&global_id_mapper_)); SyncSetupServiceMock* syncSetupService = static_cast<SyncSetupServiceMock*>( SyncSetupServiceFactory::GetForBrowserState( @@ -191,6 +204,7 @@ syncer::FakeModelTypeControllerDelegate fake_controller_delegate_; testing::NiceMock<OpenTabsUIDelegateMock> open_tabs_ui_delegate_; + testing::NiceMock<GlobalIdMapperMock> global_id_mapper_; std::unique_ptr<TestChromeBrowserState> chrome_browser_state_; // Must be declared *after* |chrome_browser_state_| so it can outlive it.
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.h b/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.h index b65bbea3..0dc66fb0 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.h +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.h
@@ -12,12 +12,12 @@ namespace ios { class ChromeBrowserState; } +enum class UrlLoadStrategy; class WebStateList; @protocol ApplicationCommands; @protocol RecentTabsTableViewControllerDelegate; @protocol RecentTabsPresentationDelegate; -@protocol UrlLoader; @protocol TableViewFaviconDataSource; @interface RecentTabsTableViewController @@ -26,8 +26,8 @@ @property(nonatomic, assign) ios::ChromeBrowserState* browserState; // The dispatcher used by this ViewController. @property(nonatomic, weak) id<ApplicationCommands> dispatcher; -// UrlLoader used by this ViewController. -@property(nonatomic, weak) id<UrlLoader> loader; +// Opaque instructions on how to open urls. +@property(nonatomic) UrlLoadStrategy loadStrategy; // Disposition for tabs restored by this object. Defaults to CURRENT_TAB. @property(nonatomic, assign) WindowOpenDisposition restoredTabDisposition; // RecentTabsTableViewControllerDelegate delegate.
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.mm b/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.mm index 0ebfb71c..481484d 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.mm +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_table_view_controller.mm
@@ -44,10 +44,12 @@ #import "ios/chrome/browser/ui/table_view/cells/table_view_text_item.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_url_item.h" #import "ios/chrome/browser/ui/table_view/table_view_favicon_data_source.h" -#import "ios/chrome/browser/ui/url_loader.h" #import "ios/chrome/browser/ui/util/top_view_controller.h" #include "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/browser/url_loading/url_loading_params.h" +#import "ios/chrome/browser/url_loading/url_loading_service.h" +#import "ios/chrome/browser/url_loading/url_loading_service_factory.h" #import "ios/chrome/browser/url_loading/url_loading_util.h" #include "ios/chrome/browser/web_state_list/web_state_list.h" #include "ios/chrome/browser/web_state_list/web_state_opener.h" @@ -1036,14 +1038,12 @@ synced_sessions::DistantSession const* session = [self sessionForSection:section]; for (auto const& tab : session->tabs) { - OpenNewTabCommand* command = - [[OpenNewTabCommand alloc] initWithURL:tab->virtual_url - referrer:web::Referrer() - inIncognito:[self isIncognito] - inBackground:YES - appendTo:kLastTab]; - - [self.loader webPageOrderedOpen:command]; + UrlLoadParams params = UrlLoadParams::InNewTab(tab->virtual_url); + params.SetInBackground(YES); + params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; + params.load_strategy = self.loadStrategy; + params.in_incognito = self.isIncognito; + UrlLoadingServiceFactory::GetForBrowserState(_browserState)->Load(params); } [self.presentationDelegate showActiveRegularTabFromRecentTabs]; }
diff --git a/ios/chrome/browser/ui/sad_tab/sad_tab_view.mm b/ios/chrome/browser/ui/sad_tab/sad_tab_view.mm index 1e4cb73..215b403 100644 --- a/ios/chrome/browser/ui/sad_tab/sad_tab_view.mm +++ b/ios/chrome/browser/ui/sad_tab/sad_tab_view.mm
@@ -12,7 +12,6 @@ #include "ios/chrome/browser/chrome_url_constants.h" #import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/commands/application_commands.h" -#import "ios/chrome/browser/ui/url_loader.h" #import "ios/chrome/browser/ui/util/label_link_controller.h" #include "ios/chrome/browser/ui/util/rtl_geometry.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h"
diff --git a/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.h b/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.h index a2afd87..1d3f1d8 100644 --- a/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.h +++ b/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.h
@@ -8,6 +8,7 @@ #import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" @class AdvancedSigninSettingsCoordinator; +@protocol ApplicationCommands; // AdvancedSigninSettingsCoordinator delegate. @protocol AdvancedSigninSettingsCoordinatorDelegate <NSObject> @@ -26,6 +27,8 @@ // Delegate. @property(nonatomic, weak) id<AdvancedSigninSettingsCoordinatorDelegate> delegate; +// Global dispatcher. +@property(nonatomic, weak) id<ApplicationCommands> dispatcher; // Cancels the coordinator, and calls the delegate. This method does nothing if // called twice.
diff --git a/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.mm b/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.mm index 93e1770a..c1cdaac 100644 --- a/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.mm +++ b/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.mm
@@ -46,12 +46,15 @@ - (void)start { self.advancedSigninSettingsNavigationController = [[AdvancedSigninSettingsNavigationController alloc] init]; + self.advancedSigninSettingsNavigationController.modalPresentationStyle = + UIModalPresentationFormSheet; self.googleServicesSettingsCoordinator = [[GoogleServicesSettingsCoordinator alloc] initWithBaseViewController:self.advancedSigninSettingsNavigationController browserState:self.browserState mode: GoogleServicesSettingsModeAdvancedSigninSettings]; + self.googleServicesSettingsCoordinator.dispatcher = self.dispatcher; self.googleServicesSettingsCoordinator.navigationController = self.advancedSigninSettingsNavigationController; [self.googleServicesSettingsCoordinator start];
diff --git a/ios/chrome/browser/ui/settings/google_services/google_services_navigation_coordinator.h b/ios/chrome/browser/ui/settings/google_services/google_services_navigation_coordinator.h index d532f86..f87e1e02 100644 --- a/ios/chrome/browser/ui/settings/google_services/google_services_navigation_coordinator.h +++ b/ios/chrome/browser/ui/settings/google_services/google_services_navigation_coordinator.h
@@ -7,6 +7,7 @@ #import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" +@protocol ApplicationCommands; @class GoogleServicesNavigationCoordinator; // GoogleServicesNavigationCoordinator delegate. @@ -24,6 +25,8 @@ // Delegate. @property(nonatomic, weak) id<GoogleServicesNavigationCoordinatorDelegate> delegate; +// Global dispatcher. +@property(nonatomic, weak) id<ApplicationCommands> dispatcher; @end
diff --git a/ios/chrome/browser/ui/settings/google_services/google_services_navigation_coordinator.mm b/ios/chrome/browser/ui/settings/google_services/google_services_navigation_coordinator.mm index 7aada5d6..e58bc8d71 100644 --- a/ios/chrome/browser/ui/settings/google_services/google_services_navigation_coordinator.mm +++ b/ios/chrome/browser/ui/settings/google_services/google_services_navigation_coordinator.mm
@@ -34,11 +34,14 @@ - (void)start { self.navigationController = [[UINavigationController alloc] init]; + self.navigationController.modalPresentationStyle = + UIModalPresentationFormSheet; self.googleServicesSettingsCoordinator = [[GoogleServicesSettingsCoordinator alloc] initWithBaseViewController:self.navigationController browserState:self.browserState mode:GoogleServicesSettingsModeSettings]; + self.googleServicesSettingsCoordinator.dispatcher = self.dispatcher; self.googleServicesSettingsCoordinator.navigationController = self.navigationController; [self.googleServicesSettingsCoordinator start];
diff --git a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm index 03d0fe6..79a0161 100644 --- a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm +++ b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm
@@ -60,6 +60,8 @@ @implementation ManageSyncSettingsCoordinator - (void)start { + DCHECK(self.dispatcher); + DCHECK(self.navigationController); self.mediator = [[ManageSyncSettingsMediator alloc] initWithSyncService:self.syncService userPrefService:self.browserState->GetPrefs()]; @@ -73,7 +75,6 @@ self.viewController.presentationDelegate = self; self.viewController.modelDelegate = self.mediator; self.mediator.consumer = self.viewController; - DCHECK(self.navigationController); [self.navigationController pushViewController:self.viewController animated:YES]; _syncObserver.reset(new SyncObserverBridge(self, self.syncService));
diff --git a/ios/chrome/browser/ui/signin_interaction/signin_interaction_coordinator.mm b/ios/chrome/browser/ui/signin_interaction/signin_interaction_coordinator.mm index 29518e8..995f8e34 100644 --- a/ios/chrome/browser/ui/signin_interaction/signin_interaction_coordinator.mm +++ b/ios/chrome/browser/ui/signin_interaction/signin_interaction_coordinator.mm
@@ -250,6 +250,7 @@ initWithBaseViewController:self.presentingViewController browserState:self.browserState]; self.advancedSigninSettingsCoordinator.delegate = self; + self.advancedSigninSettingsCoordinator.dispatcher = self.dispatcher; [self.advancedSigninSettingsCoordinator start]; } else { [self signinDoneWithSuccess:YES];
diff --git a/ios/chrome/browser/ui/static_content/static_html_view_controller_unittest.mm b/ios/chrome/browser/ui/static_content/static_html_view_controller_unittest.mm index 9e39728..d1537c5 100644 --- a/ios/chrome/browser/ui/static_content/static_html_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/static_content/static_html_view_controller_unittest.mm
@@ -122,13 +122,11 @@ chrome_browser_state_.get()); EXPECT_EQ(0, url_loader->load_current_tab_call_count); EXPECT_EQ(0, url_loader->load_new_tab_call_count); - EXPECT_EQ(nullptr, url_loader->last_params); DryRunLoop(true); EXPECT_EQ(0, url_loader->load_current_tab_call_count); EXPECT_EQ(0, url_loader->load_new_tab_call_count); - EXPECT_EQ(nullptr, url_loader->last_params); ASSERT_OCMOCK_VERIFY((OCMockObject*)delegate); } @@ -163,13 +161,11 @@ chrome_browser_state_.get()); EXPECT_EQ(0, url_loader->load_current_tab_call_count); EXPECT_EQ(0, url_loader->load_new_tab_call_count); - EXPECT_EQ(nullptr, url_loader->last_params); DryRunLoop(true); EXPECT_EQ(0, url_loader->load_current_tab_call_count); EXPECT_EQ(0, url_loader->load_new_tab_call_count); - EXPECT_EQ(nullptr, url_loader->last_params); ASSERT_OCMOCK_VERIFY((OCMockObject*)delegate); }
diff --git a/ios/chrome/browser/ui/tab_grid/BUILD.gn b/ios/chrome/browser/ui/tab_grid/BUILD.gn index 120c145..836814a 100644 --- a/ios/chrome/browser/ui/tab_grid/BUILD.gn +++ b/ios/chrome/browser/ui/tab_grid/BUILD.gn
@@ -12,8 +12,6 @@ "tab_grid_coordinator.mm", "tab_grid_mediator.h", "tab_grid_mediator.mm", - "tab_grid_url_loader.h", - "tab_grid_url_loader.mm", ] configs += [ "//build/config/compiler:enable_arc" ] @@ -39,6 +37,7 @@ "//ios/chrome/browser/ui/main:tab_switcher", "//ios/chrome/browser/ui/recent_tabs", "//ios/chrome/browser/ui/recent_tabs:recent_tabs_ui", + "//ios/chrome/browser/url_loading", "//ios/chrome/browser/web", "//ios/chrome/browser/web_state_list", "//ios/chrome/browser/web_state_list/web_usage_enabler",
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_adaptor.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_adaptor.mm index 49620d3..509646d 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_adaptor.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_adaptor.mm
@@ -8,7 +8,6 @@ #import "ios/chrome/browser/tabs/tab_model.h" #import "ios/chrome/browser/ui/main/view_controller_swapping.h" #import "ios/chrome/browser/ui/tab_grid/tab_grid_paging.h" -#import "ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.h" #import "ios/web/public/navigation_manager.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -74,8 +73,6 @@ - (void)setOtrTabModel:(TabModel*)otrModel { DCHECK(self.incognitoMediator); self.incognitoMediator.tabModel = otrModel; - self.loader.incognitoWebStateList = otrModel.webStateList; - self.loader.incognitoBrowserState = otrModel.browserState; } @end
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_coordinator.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_coordinator.mm index 04941c2..92e6c54 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_coordinator.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_coordinator.mm
@@ -24,8 +24,8 @@ #import "ios/chrome/browser/ui/tab_grid/tab_grid_mediator.h" #import "ios/chrome/browser/ui/tab_grid/tab_grid_paging.h" #import "ios/chrome/browser/ui/tab_grid/tab_grid_transition_handler.h" -#import "ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.h" #import "ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.h" +#import "ios/chrome/browser/url_loading/url_loading_params.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -57,9 +57,6 @@ @property(nonatomic, strong) RecentTabsMediator* remoteTabsMediator; // Coordinator for history, which can be started from recent tabs. @property(nonatomic, strong) HistoryCoordinator* historyCoordinator; -// Specialized URL loader for tab grid, since tab grid has a different use case -// than BVC. -@property(nonatomic, strong) TabGridURLLoader* URLLoader; @end @implementation TabGridCoordinator @@ -189,13 +186,8 @@ self.remoteTabsMediator; baseViewController.remoteTabsViewController.dispatcher = static_cast<id<ApplicationCommands>>(self.dispatcher); - self.URLLoader = [[TabGridURLLoader alloc] - initWithRegularWebStateList:self.regularTabModel.webStateList - incognitoWebStateList:self.incognitoTabModel.webStateList - regularBrowserState:self.regularTabModel.browserState - incognitoBrowserState:self.incognitoTabModel.browserState]; - self.adaptor.loader = self.URLLoader; - baseViewController.remoteTabsViewController.loader = self.URLLoader; + baseViewController.remoteTabsViewController.loadStrategy = + UrlLoadStrategy::ALWAYS_NEW_FOREGROUND_TAB; baseViewController.remoteTabsViewController.restoredTabDisposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; baseViewController.remoteTabsViewController.webStateList = @@ -366,12 +358,13 @@ - (void)showHistoryFromRecentTabs { // A history coordinator from main_controller won't work properly from the - // tab grid. Using a local coordinator works better when hooked up with a - // specialized URL loader and tab presentation delegate. + // tab grid. Using a local coordinator works better and we need to set + // |loadStrategy| to YES to ALWAYS_NEW_FOREGROUND_TAB. self.historyCoordinator = [[HistoryCoordinator alloc] initWithBaseViewController:self.baseViewController browserState:self.regularTabModel.browserState]; - self.historyCoordinator.loader = self.URLLoader; + self.historyCoordinator.loadStrategy = + UrlLoadStrategy::ALWAYS_NEW_FOREGROUND_TAB; self.historyCoordinator.presentationDelegate = self; self.historyCoordinator.dispatcher = static_cast<id<ApplicationCommands>>(self.dispatcher);
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.h b/ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.h deleted file mode 100644 index 95503743..0000000 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_UI_TAB_GRID_TAB_GRID_URL_LOADER_H_ -#define IOS_CHROME_BROWSER_UI_TAB_GRID_TAB_GRID_URL_LOADER_H_ - -#import <Foundation/Foundation.h> - -#import "ios/chrome/browser/ui/url_loader.h" - -namespace ios { -class ChromeBrowserState; -} - -class WebStateList; - -// Specialized URLLoader for the tab grid. -// Loading a URL or sessionTab normally navigates the currently visible tab -// view, which meaning replacing the active WebState. When there is no currently -// visible tab view, loading a URL means adding a new WebState to the -// WebStateList. -@interface TabGridURLLoader : NSObject<UrlLoader> -- (instancetype) -initWithRegularWebStateList:(WebStateList*)regularWebStateList - incognitoWebStateList:(WebStateList*)incognitoWebStateList - regularBrowserState:(ios::ChromeBrowserState*)regularBrowserState - incognitoBrowserState:(ios::ChromeBrowserState*)incognitoBrowserState - NS_DESIGNATED_INITIALIZER; -- (instancetype)init NS_UNAVAILABLE; - -// The incognito WebStateList this loader manages. -@property(nonatomic, assign) WebStateList* incognitoWebStateList; -// The incognito BrowserState this loader manages. -@property(nonatomic, assign) ios::ChromeBrowserState* incognitoBrowserState; -@end - -#endif // IOS_CHROME_BROWSER_UI_TAB_GRID_TAB_GRID_URL_LOADER_H_
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.mm deleted file mode 100644 index 49330f5..0000000 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.mm +++ /dev/null
@@ -1,88 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ios/chrome/browser/ui/tab_grid/tab_grid_url_loader.h" - -#include "components/sessions/core/session_types.h" -#include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/sessions/session_util.h" -#include "ios/chrome/browser/ui/commands/open_new_tab_command.h" -#import "ios/chrome/browser/web_state_list/web_state_list.h" -#include "ios/chrome/browser/web_state_list/web_state_opener.h" -#import "ios/web/public/web_state/web_state.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -namespace { -// Appends and activates |web_state| to the end of |web_state_list|. -void AppendAndActivateWebState(WebStateList* web_state_list, - std::unique_ptr<web::WebState> web_state) { - web_state_list->InsertWebState( - web_state_list->count(), std::move(web_state), - (WebStateList::INSERT_FORCE_INDEX | WebStateList::INSERT_ACTIVATE), - WebStateOpener()); -} -} // namespace - -@interface TabGridURLLoader () -@property(nonatomic, assign) WebStateList* regularWebStateList; -@property(nonatomic, assign) ios::ChromeBrowserState* regularBrowserState; -@end - -@implementation TabGridURLLoader - -- (instancetype) -initWithRegularWebStateList:(WebStateList*)regularWebStateList - incognitoWebStateList:(WebStateList*)incognitoWebStateList - regularBrowserState:(ios::ChromeBrowserState*)regularBrowserState - incognitoBrowserState:(ios::ChromeBrowserState*)incognitoBrowserState { - if (self = [super init]) { - _regularWebStateList = regularWebStateList; - _regularBrowserState = regularBrowserState; - _incognitoWebStateList = incognitoWebStateList; - _incognitoBrowserState = incognitoBrowserState; - } - return self; -} - -#pragma mark - UrlLoader - -// In tab grid, |inBackground| is ignored, which means that the new WebState is -// activated. |appendTo| is also ignored, so the new WebState is always appended -// at the end of the list. The page transition type is explicit rather than -// linked. -- (void)webPageOrderedOpen:(OpenNewTabCommand*)command { - WebStateList* webStateList; - ios::ChromeBrowserState* browserState; - if (command.inIncognito) { - webStateList = self.incognitoWebStateList; - browserState = self.incognitoBrowserState; - } else { - webStateList = self.regularWebStateList; - browserState = self.regularBrowserState; - } - DCHECK(webStateList); - DCHECK(browserState); - web::WebState::CreateParams params(browserState); - std::unique_ptr<web::WebState> webState = web::WebState::Create(params); - web::NavigationManager::WebLoadParams loadParams(command.URL); - loadParams.referrer = command.referrer; - loadParams.transition_type = ui::PAGE_TRANSITION_TYPED; - webState->GetNavigationManager()->LoadURLWithParams(loadParams); - AppendAndActivateWebState(webStateList, std::move(webState)); -} - -// Opens |loadParams| in a new regular tab, rather than replacing the active -// tab. -- (void)loadURLWithParams:(const ChromeLoadParams&)loadParams { - DCHECK(self.regularBrowserState); - web::WebState::CreateParams params(self.regularBrowserState); - std::unique_ptr<web::WebState> webState = web::WebState::Create(params); - webState->GetNavigationManager()->LoadURLWithParams(loadParams.web_params); - AppendAndActivateWebState(self.regularWebStateList, std::move(webState)); -} - -@end
diff --git a/ios/chrome/browser/url_loading/app_url_loading_service.h b/ios/chrome/browser/url_loading/app_url_loading_service.h index c9c036d..da48c4c 100644 --- a/ios/chrome/browser/url_loading/app_url_loading_service.h +++ b/ios/chrome/browser/url_loading/app_url_loading_service.h
@@ -69,7 +69,7 @@ void SetDelegate(id<AppURLLoadingServiceDelegate> delegate); // Opens a url based on |params| in a new tab. - virtual void LoadUrlInNewTab(UrlLoadParams* params); + virtual void LoadUrlInNewTab(const UrlLoadParams& params); private: __weak id<AppURLLoadingServiceDelegate> delegate_;
diff --git a/ios/chrome/browser/url_loading/app_url_loading_service.mm b/ios/chrome/browser/url_loading/app_url_loading_service.mm index 7208812..2d75d44 100644 --- a/ios/chrome/browser/url_loading/app_url_loading_service.mm +++ b/ios/chrome/browser/url_loading/app_url_loading_service.mm
@@ -24,36 +24,37 @@ delegate_ = delegate; } -void AppUrlLoadingService::LoadUrlInNewTab(UrlLoadParams* params) { +void AppUrlLoadingService::LoadUrlInNewTab(const UrlLoadParams& params) { DCHECK(delegate_); - if (params->web_params.url.is_valid()) { - if (params->from_chrome) { + if (params.web_params.url.is_valid()) { + UrlLoadParams saved_params = params; + + if (params.from_chrome) { [delegate_ dismissModalDialogsWithCompletion:^{ [delegate_ openSelectedTabInMode:ApplicationMode::NORMAL - withURL:params->web_params.url - virtualURL:params->web_params.virtual_url + withURL:saved_params.web_params.url + virtualURL:saved_params.web_params.virtual_url transition:ui::PAGE_TRANSITION_TYPED completion:nil]; } dismissOmnibox:YES]; } else { - ApplicationMode mode = params->in_incognito ? ApplicationMode::INCOGNITO - : ApplicationMode::NORMAL; + ApplicationMode mode = params.in_incognito ? ApplicationMode::INCOGNITO + : ApplicationMode::NORMAL; [delegate_ dismissModalDialogsWithCompletion:^{ [delegate_ setCurrentInterfaceForMode:mode]; UrlLoadingServiceFactory::GetForBrowserState( [delegate_ currentBrowserState]) - ->Load(params); + ->Load(saved_params); } dismissOmnibox:YES]; } - } else { if ([delegate_ currentBrowserState] -> IsOffTheRecord() != - params->in_incognito) { + params.in_incognito) { // Must take a snapshot of the tab before we switch the incognito mode // because the currentTab will change after the switch. Tab* currentTab = [delegate_ currentTabModel].currentTab; @@ -63,8 +64,8 @@ } // Not for this browser state, switch and try again. - ApplicationMode mode = params->in_incognito ? ApplicationMode::INCOGNITO - : ApplicationMode::NORMAL; + ApplicationMode mode = params.in_incognito ? ApplicationMode::INCOGNITO + : ApplicationMode::NORMAL; [delegate_ expectNewForegroundTabForMode:mode]; [delegate_ setCurrentInterfaceForMode:mode]; LoadUrlInNewTab(params); @@ -74,7 +75,7 @@ // TODO(crbug.com/907527): move the following lines to Browser level making // openNewTabFromOriginPoint a delegate there. openNewTabFromOriginPoint is // only called from here. - [delegate_ openNewTabFromOriginPoint:params->origin_point - focusOmnibox:params->should_focus_omnibox]; + [delegate_ openNewTabFromOriginPoint:params.origin_point + focusOmnibox:params.should_focus_omnibox]; } }
diff --git a/ios/chrome/browser/url_loading/test_app_url_loading_service.h b/ios/chrome/browser/url_loading/test_app_url_loading_service.h index 4f6e5ba6..ebdcd81 100644 --- a/ios/chrome/browser/url_loading/test_app_url_loading_service.h +++ b/ios/chrome/browser/url_loading/test_app_url_loading_service.h
@@ -6,8 +6,7 @@ #define IOS_CHROME_BROWSER_URL_LOADING_TEST_APP_URL_LOADING_SERVICE_H_ #include "ios/chrome/browser/url_loading/app_url_loading_service.h" - -struct UrlLoadParams; +#import "ios/chrome/browser/url_loading/url_loading_params.h" // Service used to manage url loading at application level. class TestAppUrlLoadingService : public AppUrlLoadingService { @@ -15,10 +14,10 @@ TestAppUrlLoadingService(); // Opens a url based on |command| in a new tab. - void LoadUrlInNewTab(UrlLoadParams* params) override; + void LoadUrlInNewTab(const UrlLoadParams& params) override; // These are the last parameters passed to |LoadUrlInNewTab|. - UrlLoadParams* last_params = nullptr; + UrlLoadParams last_params; int load_new_tab_call_count = 0; };
diff --git a/ios/chrome/browser/url_loading/test_app_url_loading_service.mm b/ios/chrome/browser/url_loading/test_app_url_loading_service.mm index e56c0b1..58498a92 100644 --- a/ios/chrome/browser/url_loading/test_app_url_loading_service.mm +++ b/ios/chrome/browser/url_loading/test_app_url_loading_service.mm
@@ -4,15 +4,13 @@ #import "ios/chrome/browser/url_loading/test_app_url_loading_service.h" -#include "ios/chrome/browser/url_loading/url_loading_params.h" - #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif TestAppUrlLoadingService::TestAppUrlLoadingService() {} -void TestAppUrlLoadingService::LoadUrlInNewTab(UrlLoadParams* params) { +void TestAppUrlLoadingService::LoadUrlInNewTab(const UrlLoadParams& params) { last_params = params; load_new_tab_call_count++; }
diff --git a/ios/chrome/browser/url_loading/test_url_loading_service.h b/ios/chrome/browser/url_loading/test_url_loading_service.h index 8099bc9..591b14c 100644 --- a/ios/chrome/browser/url_loading/test_url_loading_service.h +++ b/ios/chrome/browser/url_loading/test_url_loading_service.h
@@ -5,29 +5,28 @@ #ifndef IOS_CHROME_BROWSER_URL_LOADING_TEST_URL_LOADING_SERVICE_H_ #define IOS_CHROME_BROWSER_URL_LOADING_TEST_URL_LOADING_SERVICE_H_ +#import "ios/chrome/browser/url_loading/url_loading_params.h" #include "ios/chrome/browser/url_loading/url_loading_service.h" -struct UrlLoadParams; - class TestUrlLoadingService : public UrlLoadingService { public: TestUrlLoadingService(UrlLoadingNotifier* notifier); // These are the last parameters passed to |OpenUrl|. - UrlLoadParams* last_params = nullptr; + UrlLoadParams last_params; int load_current_tab_call_count = 0; int switch_tab_call_count = 0; int load_new_tab_call_count = 0; private: // Switches to a tab that matches |params.web_params| or opens in a new tab. - void SwitchToTab(UrlLoadParams* params) override; + void SwitchToTab(const UrlLoadParams& params) override; // Opens a url based on |params| in current tab. - void LoadUrlInCurrentTab(UrlLoadParams* params) override; + void LoadUrlInCurrentTab(const UrlLoadParams& params) override; // Opens a url based on |params| in a new tab. - void LoadUrlInNewTab(UrlLoadParams* params) override; + void LoadUrlInNewTab(const UrlLoadParams& params) override; }; #endif // IOS_CHROME_BROWSER_URL_LOADING_TEST_URL_LOADING_SERVICE_H_
diff --git a/ios/chrome/browser/url_loading/test_url_loading_service.mm b/ios/chrome/browser/url_loading/test_url_loading_service.mm index da3d8d3..6627987 100644 --- a/ios/chrome/browser/url_loading/test_url_loading_service.mm +++ b/ios/chrome/browser/url_loading/test_url_loading_service.mm
@@ -6,7 +6,6 @@ #import "ios/chrome/browser/ui/commands/open_new_tab_command.h" #import "ios/chrome/browser/url_loading/url_loading_notifier.h" -#import "ios/chrome/browser/url_loading/url_loading_params.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -15,17 +14,17 @@ TestUrlLoadingService::TestUrlLoadingService(UrlLoadingNotifier* notifier) : UrlLoadingService(notifier) {} -void TestUrlLoadingService::LoadUrlInCurrentTab(UrlLoadParams* params) { +void TestUrlLoadingService::LoadUrlInCurrentTab(const UrlLoadParams& params) { last_params = params; load_current_tab_call_count++; } -void TestUrlLoadingService::LoadUrlInNewTab(UrlLoadParams* params) { +void TestUrlLoadingService::LoadUrlInNewTab(const UrlLoadParams& params) { last_params = params; load_new_tab_call_count++; } -void TestUrlLoadingService::SwitchToTab(UrlLoadParams* params) { +void TestUrlLoadingService::SwitchToTab(const UrlLoadParams& params) { last_params = params; switch_tab_call_count++; }
diff --git a/ios/chrome/browser/url_loading/url_loading_params.h b/ios/chrome/browser/url_loading/url_loading_params.h index 86ae5517..af33796f 100644 --- a/ios/chrome/browser/url_loading/url_loading_params.h +++ b/ios/chrome/browser/url_loading/url_loading_params.h
@@ -10,73 +10,38 @@ #import "ios/web/public/navigation_manager.h" #include "ui/base/window_open_disposition.h" +// Enum of ways of changing loading behavior, that can be passed around +// opaquely, and set by using |UrlLoadParams::LoadStrategy|. +enum class UrlLoadStrategy { + NORMAL = 0, + + ALWAYS_NEW_FOREGROUND_TAB = 1 << 0, +}; + // UrlLoadingService wrapper around web::NavigationManager::WebLoadParams, // WindowOpenDisposition and parameters from OpenNewTabCommand. // This is used when a URL is opened. struct UrlLoadParams { public: // Initializes a UrlLoadParams intended to open in current page. - static UrlLoadParams* InCurrentTab( - const web::NavigationManager::WebLoadParams& web_params, - WindowOpenDisposition disposition); - // Initializes a UrlLoadParams intended to open in current page, width - // disposition set to WindowOpenDisposition::CURRENT_TAB. - static UrlLoadParams* InCurrentTab( + static UrlLoadParams InCurrentTab( const web::NavigationManager::WebLoadParams& web_params); - // Initializes a UrlLoadParams intended to open in current page, width - // disposition set to WindowOpenDisposition::CURRENT_TAB. - static UrlLoadParams* InCurrentTab(const GURL& url); + static UrlLoadParams InCurrentTab(const GURL& url); + static UrlLoadParams InCurrentTab(const GURL& url, const GURL& virtual_url); // Initializes a UrlLoadParams intended to open in a new page. - static UrlLoadParams* InNewTab( - const web::NavigationManager::WebLoadParams& web_params, - bool in_incognito, - bool in_background, - OpenPosition append_to); - - // Initializes a UrlLoadParams intended to open in a new page. - static UrlLoadParams* InNewTab(const GURL& url, - const GURL& virtual_url, - const web::Referrer& referrer, - bool in_incognito, - bool in_background, - OpenPosition append_to); - - // Initializes a UrlLoadParams intended to open in a new page with virtual_url - // set to GURL::EmptyGURL(). - static UrlLoadParams* InNewTab(const GURL& url, - const web::Referrer& referrer, - bool in_incognito, - bool in_background, - OpenPosition append_to); - - // Initializes a UrlLoadParams intended to open in a new page with virtual_url - // set to GURL::EmptyGURL() and the default web::Referrer(). - static UrlLoadParams* InNewTab(const GURL& url, - bool in_incognito, - bool in_background, - OpenPosition append_to); - - // Initializes a UrlLoadParams intended to open a new page. - static UrlLoadParams* InNewEmptyTab(bool in_incognito, bool in_background); - - // Initializes a UrlLoadParams intended to open a URL from browser chrome - // (e.g., settings). This will always open in a new foreground tab in - // non-incognito mode. - static UrlLoadParams* InNewFromChromeTab(const GURL& url); - - // Initializes a UrlLoadParams with |in_incognito| and an |origin_point|. - static UrlLoadParams* InNewForegroundTab(bool in_incognito, - CGPoint origin_point); - - // Initializes a UrlLoadParams with |in_incognito| and an |origin_point| of - // CGPointZero. - static UrlLoadParams* InNewForegroundTab(bool in_incognito); + static UrlLoadParams InNewTab( + const web::NavigationManager::WebLoadParams& web_params); + static UrlLoadParams InNewTab(const GURL& url); + static UrlLoadParams InNewTab(const GURL& url, const GURL& virtual_url); // Initializes a UrlLoadParams intended to switch to tab. - static UrlLoadParams* SwitchToTab( + static UrlLoadParams SwitchToTab( const web::NavigationManager::WebLoadParams& web_params); + // Set appropriate parameters for background tab mode. + void SetInBackground(bool in_background); + // Allow copying UrlLoadParams. UrlLoadParams(const UrlLoadParams& other); UrlLoadParams& operator=(const UrlLoadParams& other); @@ -84,23 +49,22 @@ // The wrapped params. web::NavigationManager::WebLoadParams web_params; - // The disposition of the URL being opened. + // The disposition of the URL being opened. Defaults to + // |WindowOpenDisposition::NEW_FOREGROUND_TAB|. WindowOpenDisposition disposition; - // Parameters for when opening in new tab: - - // Whether this requests opening in incognito or not. + // Whether this requests opening in incognito or not. Defaults to |false|. bool in_incognito; - // Location where the new tab should be opened. + // Location where the new tab should be opened. Defaults to |kLastTab|. OpenPosition append_to; // Origin point of the action triggering this command, in main window - // coordinates. + // coordinates. Defaults to |CGPointZero|. CGPoint origin_point; // Whether or not this URL command comes from a chrome context (e.g., - // settings), as opposed to a web page context. + // settings), as opposed to a web page context. Defaults to |false|. bool from_chrome; // Whether the new tab command was initiated by the user (e.g. by tapping the @@ -110,14 +74,17 @@ bool user_initiated; // Whether the new tab command should also trigger the omnibox to be focused. - // Only used when the |web_params.url| isn't valid. + // Only used when the |web_params.url| isn't valid. Defaults to |false|. bool should_focus_omnibox; - bool in_background() { + // Opaque way of changing loading behavior. + UrlLoadStrategy load_strategy; + + bool in_background() const { return disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB; } - private: + // Public for testing only. UrlLoadParams(); };
diff --git a/ios/chrome/browser/url_loading/url_loading_params.mm b/ios/chrome/browser/url_loading/url_loading_params.mm index f5ab535f..c14d5e9 100644 --- a/ios/chrome/browser/url_loading/url_loading_params.mm +++ b/ios/chrome/browser/url_loading/url_loading_params.mm
@@ -8,116 +8,56 @@ #error "This file requires ARC support." #endif -UrlLoadParams* UrlLoadParams::InCurrentTab( - const web::NavigationManager::WebLoadParams& web_params, - WindowOpenDisposition disposition) { - UrlLoadParams* params = new UrlLoadParams(); - params->disposition = disposition; - params->web_params = web_params; - return params; -} - -UrlLoadParams* UrlLoadParams::InCurrentTab( +UrlLoadParams UrlLoadParams::InCurrentTab( const web::NavigationManager::WebLoadParams& web_params) { - return InCurrentTab(web_params, WindowOpenDisposition::CURRENT_TAB); -} - -UrlLoadParams* UrlLoadParams::InCurrentTab(const GURL& url) { - return InCurrentTab(web::NavigationManager::WebLoadParams(url)); -} - -UrlLoadParams* UrlLoadParams::InNewTab( - const web::NavigationManager::WebLoadParams& web_params, - bool in_incognito, - bool in_background, - OpenPosition append_to) { - UrlLoadParams* params = new UrlLoadParams(); - params->disposition = in_background - ? WindowOpenDisposition::NEW_BACKGROUND_TAB - : WindowOpenDisposition::NEW_FOREGROUND_TAB; - params->web_params = web_params; - params->in_incognito = in_incognito; - params->append_to = append_to; - params->user_initiated = true; + UrlLoadParams params = UrlLoadParams(); + params.disposition = WindowOpenDisposition::CURRENT_TAB; + params.web_params = web_params; return params; } -UrlLoadParams* UrlLoadParams::InNewTab(const GURL& url, - const GURL& virtual_url, - const web::Referrer& referrer, - bool in_incognito, - bool in_background, - OpenPosition append_to) { - UrlLoadParams* params = new UrlLoadParams(); - params->disposition = in_background - ? WindowOpenDisposition::NEW_BACKGROUND_TAB - : WindowOpenDisposition::NEW_FOREGROUND_TAB; - params->web_params = web::NavigationManager::WebLoadParams(url); - params->web_params.virtual_url = virtual_url; - params->web_params.referrer = referrer; - params->in_incognito = in_incognito; - params->append_to = append_to; - params->user_initiated = true; +UrlLoadParams UrlLoadParams::InCurrentTab(const GURL& url, + const GURL& virtual_url) { + UrlLoadParams params = UrlLoadParams(); + params.disposition = WindowOpenDisposition::CURRENT_TAB; + params.web_params = web::NavigationManager::WebLoadParams(url); + params.web_params.virtual_url = virtual_url; return params; } -UrlLoadParams* UrlLoadParams::InNewTab(const GURL& url, - const web::Referrer& referrer, - bool in_incognito, - bool in_background, - OpenPosition append_to) { - return InNewTab(url, GURL::EmptyGURL(), referrer, in_incognito, in_background, - append_to); -} - -UrlLoadParams* UrlLoadParams::InNewTab(const GURL& url, - bool in_incognito, - bool in_background, - OpenPosition append_to) { - return InNewTab(url, web::Referrer(), in_incognito, in_background, append_to); -} - -UrlLoadParams* UrlLoadParams::InNewEmptyTab(bool in_incognito, - bool in_background) { - UrlLoadParams* params = new UrlLoadParams(); - params->disposition = in_background - ? WindowOpenDisposition::NEW_BACKGROUND_TAB - : WindowOpenDisposition::NEW_FOREGROUND_TAB; - params->in_incognito = in_incognito; - params->user_initiated = true; +UrlLoadParams UrlLoadParams::InCurrentTab(const GURL& url) { + UrlLoadParams params = UrlLoadParams(); + params.disposition = WindowOpenDisposition::CURRENT_TAB; + params.web_params = web::NavigationManager::WebLoadParams(url); return params; } -UrlLoadParams* UrlLoadParams::InNewFromChromeTab(const GURL& url) { - UrlLoadParams* params = new UrlLoadParams(); - params->disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; - params->web_params = web::NavigationManager::WebLoadParams(url); - params->append_to = kLastTab; - params->from_chrome = true; - return params; -} - -UrlLoadParams* UrlLoadParams::InNewForegroundTab(bool in_incognito, - CGPoint origin_point) { - UrlLoadParams* params = new UrlLoadParams(); - params->disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; - params->origin_point = origin_point; - params->user_initiated = true; - return params; -} - -UrlLoadParams* UrlLoadParams::InNewForegroundTab(bool in_incognito) { - UrlLoadParams* params = new UrlLoadParams(); - params->disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; - params->user_initiated = true; - return params; -} - -UrlLoadParams* UrlLoadParams::SwitchToTab( +UrlLoadParams UrlLoadParams::InNewTab( const web::NavigationManager::WebLoadParams& web_params) { - UrlLoadParams* params = new UrlLoadParams(); - params->disposition = WindowOpenDisposition::SWITCH_TO_TAB; - params->web_params = web_params; + UrlLoadParams params = UrlLoadParams(); + params.web_params = web_params; + return params; +} + +UrlLoadParams UrlLoadParams::InNewTab(const GURL& url, + const GURL& virtual_url) { + UrlLoadParams params = UrlLoadParams(); + params.web_params = web::NavigationManager::WebLoadParams(url); + params.web_params.virtual_url = virtual_url; + return params; +} + +UrlLoadParams UrlLoadParams::InNewTab(const GURL& url) { + UrlLoadParams params = UrlLoadParams(); + params.web_params = web::NavigationManager::WebLoadParams(url); + return params; +} + +UrlLoadParams UrlLoadParams::SwitchToTab( + const web::NavigationManager::WebLoadParams& web_params) { + UrlLoadParams params = UrlLoadParams(); + params.disposition = WindowOpenDisposition::SWITCH_TO_TAB; + params.web_params = web_params; return params; } @@ -128,15 +68,35 @@ append_to(kLastTab), origin_point(CGPointZero), from_chrome(false), - user_initiated(false), - should_focus_omnibox(false) {} + user_initiated(true), + should_focus_omnibox(false), + load_strategy(UrlLoadStrategy::NORMAL) {} UrlLoadParams::UrlLoadParams(const UrlLoadParams& other) - : web_params(other.web_params), disposition(other.disposition) {} + : web_params(other.web_params), + disposition(other.disposition), + in_incognito(other.in_incognito), + append_to(other.append_to), + origin_point(other.origin_point), + from_chrome(other.from_chrome), + user_initiated(other.user_initiated), + should_focus_omnibox(other.should_focus_omnibox), + load_strategy(other.load_strategy) {} UrlLoadParams& UrlLoadParams::operator=(const UrlLoadParams& other) { web_params = other.web_params; disposition = other.disposition; - + in_incognito = other.in_incognito; + append_to = other.append_to; + origin_point = other.origin_point; + from_chrome = other.from_chrome; + user_initiated = other.user_initiated; + should_focus_omnibox = other.should_focus_omnibox; + load_strategy = other.load_strategy; return *this; } + +void UrlLoadParams::SetInBackground(bool in_background) { + this->disposition = in_background ? WindowOpenDisposition::NEW_BACKGROUND_TAB + : WindowOpenDisposition::NEW_FOREGROUND_TAB; +}
diff --git a/ios/chrome/browser/url_loading/url_loading_service.h b/ios/chrome/browser/url_loading/url_loading_service.h index e3b6508..f5954f7 100644 --- a/ios/chrome/browser/url_loading/url_loading_service.h +++ b/ios/chrome/browser/url_loading/url_loading_service.h
@@ -26,7 +26,7 @@ // Implementing delegate can do an animation using information in |params| when // opening a background tab, then call |completion|. -- (void)animateOpenBackgroundTabFromParams:(UrlLoadParams*)params +- (void)animateOpenBackgroundTabFromParams:(const UrlLoadParams&)params completion:(void (^)())completion; @end @@ -43,18 +43,22 @@ // TODO(crbug.com/907527): deprecate this when possible. id<UrlLoader> GetUrlLoader(); - // Opens a url depending on |params.disposition|. - virtual void Load(UrlLoadParams* params); + // Opens a url depending on |params.disposition|. Applies load strategy then + // calls| Dispatch|. + virtual void Load(const UrlLoadParams& params); private: + // Dispatches to action method below. + void Dispatch(const UrlLoadParams& params); + // Switches to a tab that matches |params.web_params| or loads in a new tab. - virtual void SwitchToTab(UrlLoadParams* params); + virtual void SwitchToTab(const UrlLoadParams& params); // Loads a url based on |params| in current tab. - virtual void LoadUrlInCurrentTab(UrlLoadParams* params); + virtual void LoadUrlInCurrentTab(const UrlLoadParams& params); // Loads a url based on |params| in a new tab. - virtual void LoadUrlInNewTab(UrlLoadParams* params); + virtual void LoadUrlInNewTab(const UrlLoadParams& params); __weak id<URLLoadingServiceDelegate> delegate_; AppUrlLoadingService* app_service_;
diff --git a/ios/chrome/browser/url_loading/url_loading_service.mm b/ios/chrome/browser/url_loading/url_loading_service.mm index 5133c475..f2ed0c8 100644 --- a/ios/chrome/browser/url_loading/url_loading_service.mm +++ b/ios/chrome/browser/url_loading/url_loading_service.mm
@@ -87,13 +87,16 @@ } - (void)webPageOrderedOpen:(OpenNewTabCommand*)command { - UrlLoadParams* params = UrlLoadParams::InNewTab( - command.URL, command.virtualURL, command.referrer, command.inIncognito, - command.inBackground, command.appendTo); - params->origin_point = command.originPoint; - params->from_chrome = command.fromChrome; - params->user_initiated = command.userInitiated; - params->should_focus_omnibox = command.shouldFocusOmnibox; + UrlLoadParams params = + UrlLoadParams::InNewTab(command.URL, command.virtualURL); + params.SetInBackground(command.inBackground); + params.web_params.referrer = command.referrer; + params.in_incognito = command.inIncognito; + params.append_to = command.appendTo; + params.origin_point = command.originPoint; + params.from_chrome = command.fromChrome; + params.user_initiated = command.userInitiated; + params.should_focus_omnibox = command.shouldFocusOmnibox; service_->Load(params); } @@ -114,8 +117,25 @@ browser_ = browser; } -void UrlLoadingService::Load(UrlLoadParams* params) { - switch (params->disposition) { +void UrlLoadingService::Load(const UrlLoadParams& params) { + // First apply any override load strategy. + switch (params.load_strategy) { + case UrlLoadStrategy::ALWAYS_NEW_FOREGROUND_TAB: { + UrlLoadParams fixed_params = params; + fixed_params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; + Dispatch(fixed_params); + break; + } + default: { + Dispatch(params); + break; + } + } +} + +void UrlLoadingService::Dispatch(const UrlLoadParams& params) { + // Then dispatch. + switch (params.disposition) { case WindowOpenDisposition::NEW_BACKGROUND_TAB: case WindowOpenDisposition::NEW_FOREGROUND_TAB: LoadUrlInNewTab(params); @@ -127,13 +147,13 @@ SwitchToTab(params); break; default: - // Unhandled disposition. + DCHECK(false) << "Unhandled url loading disposition."; break; } } -void UrlLoadingService::LoadUrlInCurrentTab(UrlLoadParams* params) { - web::NavigationManager::WebLoadParams web_params = params->web_params; +void UrlLoadingService::LoadUrlInCurrentTab(const UrlLoadParams& params) { + web::NavigationManager::WebLoadParams web_params = params.web_params; ios::ChromeBrowserState* browser_state = browser_->GetBrowserState(); @@ -169,11 +189,11 @@ if (browser_state->IsOffTheRecord() && !IsURLAllowedInIncognito(web_params.url)) { notifier_->TabFailedToLoadUrl(web_params.url, web_params.transition_type); - UrlLoadParams* new_tab_params = UrlLoadParams::InNewTab( - web_params.url, web_params.virtual_url, web::Referrer(), - /* in_incognito */ NO, - /* in_background */ NO, kCurrentTab); - LoadUrlInNewTab(new_tab_params); + UrlLoadParams params = + UrlLoadParams::InNewTab(web_params.url, web_params.virtual_url); + params.web_params.referrer = web::Referrer(); + params.append_to = kCurrentTab; + Load(params); return; } @@ -205,10 +225,10 @@ notifier_->TabDidLoadUrl(web_params.url, web_params.transition_type); } -void UrlLoadingService::SwitchToTab(UrlLoadParams* params) { +void UrlLoadingService::SwitchToTab(const UrlLoadParams& params) { DCHECK(app_service_); - web::NavigationManager::WebLoadParams web_params = params->web_params; + web::NavigationManager::WebLoadParams web_params = params.web_params; WebStateList* web_state_list = browser_->GetWebStateList(); NSInteger new_web_state_index = @@ -224,10 +244,11 @@ } else { // Load the URL in foreground. ios::ChromeBrowserState* browser_state = browser_->GetBrowserState(); - UrlLoadParams* new_tab_params = UrlLoadParams::InNewTab( - web_params.url, web_params.virtual_url, web::Referrer(), - /* in_incognito */ browser_state->IsOffTheRecord(), - /* in_background */ NO, kCurrentTab); + UrlLoadParams new_tab_params = + UrlLoadParams::InNewTab(web_params.url, web_params.virtual_url); + new_tab_params.web_params.referrer = web::Referrer(); + new_tab_params.in_incognito = browser_state->IsOffTheRecord(); + new_tab_params.append_to = kCurrentTab; app_service_->LoadUrlInNewTab(new_tab_params); } return; @@ -248,45 +269,48 @@ notifier_->DidSwitchToTabWithUrl(web_params.url, new_web_state_index); } -void UrlLoadingService::LoadUrlInNewTab(UrlLoadParams* params) { +void UrlLoadingService::LoadUrlInNewTab(const UrlLoadParams& params) { DCHECK(app_service_); DCHECK(delegate_); DCHECK(browser_); ios::ChromeBrowserState* browser_state = browser_->GetBrowserState(); - if (params->in_incognito != browser_state->IsOffTheRecord()) { + if (params.in_incognito != browser_state->IsOffTheRecord()) { // When sending a load request that switches modes, ensure the tab // ends up appended to the end of the model, not just next to what is // currently selected in the other mode. This is done with the |append_to| // parameter. - params->append_to = kLastTab; - app_service_->LoadUrlInNewTab(params); + UrlLoadParams app_params = params; + app_params.append_to = kLastTab; + app_service_->LoadUrlInNewTab(app_params); return; } // Notify only after checking incognito match, otherwise the delegate will // take of changing the mode and try again. Notifying before the checks can // lead to be calling it twice, and calling 'did' below once. - notifier_->NewTabWillLoadUrl(params->web_params.url, params->user_initiated); + notifier_->NewTabWillLoadUrl(params.web_params.url, params.user_initiated); TabModel* tab_model = browser_->GetTabModel(); Tab* adjacent_tab = nil; - if (params->append_to == kCurrentTab) + if (params.append_to == kCurrentTab) adjacent_tab = tab_model.currentTab; + UrlLoadParams saved_params = params; auto openTab = ^{ [tab_model - insertTabWithLoadParams:params->web_params + insertTabWithLoadParams:saved_params.web_params opener:adjacent_tab openedByDOM:NO atIndex:TabModelConstants::kTabPositionAutomatically - inBackground:params->in_background()]; + inBackground:saved_params.in_background()]; - notifier_->NewTabDidLoadUrl(params->web_params.url, params->user_initiated); + notifier_->NewTabDidLoadUrl(saved_params.web_params.url, + saved_params.user_initiated); }; - if (!params->in_background()) { + if (!params.in_background()) { openTab(); } else { [delegate_ animateOpenBackgroundTabFromParams:params completion:openTab];
diff --git a/ios/chrome/browser/url_loading/url_loading_service_unittest.mm b/ios/chrome/browser/url_loading/url_loading_service_unittest.mm index a3d8b724..db4d9f0 100644 --- a/ios/chrome/browser/url_loading/url_loading_service_unittest.mm +++ b/ios/chrome/browser/url_loading/url_loading_service_unittest.mm
@@ -94,7 +94,7 @@ - (void)openURLInNewTabWithCommand:(OpenNewTabCommand*)command { } -- (void)animateOpenBackgroundTabFromParams:(UrlLoadParams*)params +- (void)animateOpenBackgroundTabFromParams:(const UrlLoadParams&)params completion:(void (^)())completion { }
diff --git a/ios/public/provider/chrome/browser/chrome_browser_provider.h b/ios/public/provider/chrome/browser/chrome_browser_provider.h index 369c9d6b..732d4a1 100644 --- a/ios/public/provider/chrome/browser/chrome_browser_provider.h +++ b/ios/public/provider/chrome/browser/chrome_browser_provider.h
@@ -134,6 +134,9 @@ ios::ChromeBrowserState* browser_state, id<UrlLoader> loader) const NS_RETURNS_RETAINED; + virtual id<LogoVendor> CreateLogoVendor( + ios::ChromeBrowserState* browser_state) const NS_RETURNS_RETAINED; + // Returns an instance of the omaha service provider. virtual OmahaServiceProvider* GetOmahaServiceProvider() const;
diff --git a/ios/public/provider/chrome/browser/chrome_browser_provider.mm b/ios/public/provider/chrome/browser/chrome_browser_provider.mm index c1725acd..89359c0 100644 --- a/ios/public/provider/chrome/browser/chrome_browser_provider.mm +++ b/ios/public/provider/chrome/browser/chrome_browser_provider.mm
@@ -94,6 +94,11 @@ return nil; } +id<LogoVendor> ChromeBrowserProvider::CreateLogoVendor( + ios::ChromeBrowserState* browser_state) const { + return nil; +} + OmahaServiceProvider* ChromeBrowserProvider::GetOmahaServiceProvider() const { return nullptr; }
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 014b37d..4f3a9e87 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -3094,6 +3094,18 @@ hasUserGesture:[context[kUserIsInteractingKey] boolValue]]; [self updateSSLStatusForCurrentNavigationItem]; + // This is needed for some special pushState. See http://crbug.com/949305 . + NSString* replaceWebViewJS = [self javaScriptToReplaceWebViewURL:pushURL + stateObjectJSON:stateObject]; + __weak CRWWebController* weakSelf = self; + [self executeJavaScript:replaceWebViewJS + completionHandler:^(id, NSError*) { + CRWWebController* strongSelf = weakSelf; + if (strongSelf && !strongSelf->_isBeingDestroyed) { + [strongSelf optOutScrollsToTopForSubviews]; + [strongSelf didFinishNavigation:nullptr]; + } + }]; return YES; }
diff --git a/media/audio/alsa/alsa_wrapper.cc b/media/audio/alsa/alsa_wrapper.cc index 0696fbe..b24630d 100644 --- a/media/audio/alsa/alsa_wrapper.cc +++ b/media/audio/alsa/alsa_wrapper.cc
@@ -51,6 +51,10 @@ return snd_pcm_delay(handle, delay); } +int AlsaWrapper::PcmResume(snd_pcm_t* handle) { + return snd_pcm_resume(handle); +} + snd_pcm_sframes_t AlsaWrapper::PcmWritei(snd_pcm_t* handle, const void* buffer, snd_pcm_uframes_t size) { @@ -98,6 +102,10 @@ return snd_pcm_hw_params_any(handle, hw_params); } +int AlsaWrapper::PcmHwParamsCanResume(snd_pcm_hw_params_t* hw_params) { + return snd_pcm_hw_params_can_resume(hw_params); +} + int AlsaWrapper::PcmHwParamsSetRateResample(snd_pcm_t* handle, snd_pcm_hw_params_t* hw_params, unsigned int value) {
diff --git a/media/audio/alsa/alsa_wrapper.h b/media/audio/alsa/alsa_wrapper.h index 6998ca0..e5920ce 100644 --- a/media/audio/alsa/alsa_wrapper.h +++ b/media/audio/alsa/alsa_wrapper.h
@@ -33,6 +33,7 @@ virtual int PcmDrain(snd_pcm_t* handle); virtual int PcmDrop(snd_pcm_t* handle); virtual int PcmDelay(snd_pcm_t* handle, snd_pcm_sframes_t* delay); + virtual int PcmResume(snd_pcm_t* handle); virtual snd_pcm_sframes_t PcmWritei(snd_pcm_t* handle, const void* buffer, snd_pcm_uframes_t size); @@ -48,6 +49,7 @@ snd_pcm_uframes_t* period_size); virtual int PcmHwParamsMalloc(snd_pcm_hw_params_t** hw_params); virtual int PcmHwParamsAny(snd_pcm_t* handle, snd_pcm_hw_params_t* hw_params); + virtual int PcmHwParamsCanResume(snd_pcm_hw_params_t* hw_params); virtual int PcmHwParamsSetRateResample(snd_pcm_t* handle, snd_pcm_hw_params_t* hw_params, unsigned int value);
diff --git a/media/audio/alsa/mock_alsa_wrapper.h b/media/audio/alsa/mock_alsa_wrapper.h index f4fd16e..04aa2d0 100644 --- a/media/audio/alsa/mock_alsa_wrapper.h +++ b/media/audio/alsa/mock_alsa_wrapper.h
@@ -31,6 +31,7 @@ MOCK_METHOD1(PcmDrain, int(snd_pcm_t* handle)); MOCK_METHOD1(PcmDrop, int(snd_pcm_t* handle)); MOCK_METHOD2(PcmDelay, int(snd_pcm_t* handle, snd_pcm_sframes_t* delay)); + MOCK_METHOD1(PcmResume, int(snd_pcm_t* handle)); MOCK_METHOD3(PcmWritei, snd_pcm_sframes_t(snd_pcm_t* handle, const void* buffer, @@ -55,6 +56,8 @@ MOCK_METHOD1(PcmHwParamsMalloc, int(snd_pcm_hw_params_t** hw_params)); MOCK_METHOD2(PcmHwParamsAny, int(snd_pcm_t* handle, snd_pcm_hw_params_t* hw_params)); + MOCK_METHOD1(PcmHwParamsCanResume, int(snd_pcm_hw_params_t* hw_params)); + MOCK_METHOD3(PcmHwParamsSetRateResample, int(snd_pcm_t* handle, snd_pcm_hw_params_t* hw_params,
diff --git a/media/audio/mac/audio_manager_mac.cc b/media/audio/mac/audio_manager_mac.cc index a10919608..11cc384 100644 --- a/media/audio/mac/audio_manager_mac.cc +++ b/media/audio/mac/audio_manager_mac.cc
@@ -837,12 +837,17 @@ // stream must be able to FIFO requests appropriately when this happens. int buffer_size; if (has_valid_input_params) { + // Ensure the latency asked for is maintained, even if the sample rate is + // changed here. + const int scaled_buffer_size = input_params.frames_per_buffer() * + hardware_sample_rate / + input_params.sample_rate(); // If passed in via the input_params we allow buffer sizes to go as // low as the the kMinAudioBufferSize, ignoring what // ChooseBufferSize() normally returns. buffer_size = std::min(static_cast<int>(limits::kMaxAudioBufferSize), - std::max(input_params.frames_per_buffer(), + std::max(scaled_buffer_size, static_cast<int>(limits::kMinAudioBufferSize))); } else { buffer_size = ChooseBufferSize(false, hardware_sample_rate);
diff --git a/media/capabilities/learning_helper.cc b/media/capabilities/learning_helper.cc index d40815a0..bab24d2431 100644 --- a/media/capabilities/learning_helper.cc +++ b/media/capabilities/learning_helper.cc
@@ -21,23 +21,22 @@ using learning::SequenceBoundFeatureProvider; using learning::TargetValue; +// Remember that these are used to construct UMA histogram names! Be sure to +// update histograms.xml if you change them! // Dropped frame ratio, default features, regression tree. -const char* const kDroppedFrameRatioBaseTreeTaskName = - "DroppedFrameRatioBaseTreeTask"; +const char* const kDroppedFrameRatioBaseTreeTaskName = "BaseTree"; // Dropped frame ratio, default+FeatureLibrary features, regression tree. -const char* const kDroppedFrameRatioEnhancedTreeTaskName = - "DroppedFrameRatioEnhancedTreeTask"; +const char* const kDroppedFrameRatioEnhancedTreeTaskName = "EnhancedTree"; // Dropped frame ratio, default+FeatureLibrary features, regression tree, // examples are unweighted. const char* const kDroppedFrameRatioEnhancedUnweightedTreeTaskName = - "DroppedFrameRatioEnhancedUnweightedTreeTask"; + "EnhancedUnweightedTree"; // Binary smoothness, default+FeatureLibrary features, regression tree, // examples are unweighted. const char* const kBinarySmoothnessEnhancedUnweightedTreeTaskName = - "BinarySmoothnessTreeTask"; + "BinarySmoothnessTree"; // Dropped frame ratio, default features, lookup table. -const char* const kDroppedFrameRatioBaseTableTaskName = - "DroppedFrameRatioBaseTableTask"; +const char* const kDroppedFrameRatioBaseTableTaskName = "BaseTable"; // Threshold for the dropped frame to total frame ratio, at which we'll decide // that the playback was not smooth. @@ -69,11 +68,22 @@ LearningTask::ValueDescription( {"dropped_ratio", LearningTask::Ordering::kNumeric})); + // Report results hackily both in aggregate and by training data weight. dropped_frame_task.smoothness_threshold = kSmoothnessThreshold; + dropped_frame_task.uma_hacky_aggregate_confusion_matrix = true; + dropped_frame_task.uma_hacky_by_training_weight_confusion_matrix = true; - // Enable hacky reporting of accuracy. - dropped_frame_task.uma_hacky_confusion_matrix = - "Media.Learning.MediaCapabilities.DroppedFrameRatioTask.BaseTable"; + // Pick a max reporting weight that represents the total number of frames. + // This will record in bucket [0, 4999], [5000, 9999], etc. Unlike the + // existing mcap thresholds, these are not per-bucket. That's why they're 10x + // higher than the per-bucket thresholds we're using there. Mcap allows on + // the order of 2,500 frames in each of {resolution X fps X codec} buckets, + // while the reported training weight here would be total for the whole set. + // So, we multiply by about 20 to approximate the number of buckets to keep + // it about the same as the size of the cross product. + const double weighted_reporting_max = 49999.; + dropped_frame_task.max_reporting_weight = weighted_reporting_max; + learning_session_->RegisterTask(dropped_frame_task, SequenceBoundFeatureProvider()); base_table_controller_ = @@ -82,8 +92,6 @@ // Modify the task to use ExtraTrees. dropped_frame_task.name = kDroppedFrameRatioBaseTreeTaskName; dropped_frame_task.model = LearningTask::Model::kExtraTrees; - dropped_frame_task.uma_hacky_confusion_matrix = - "Media.Learning.MediaCapabilities.DroppedFrameRatioTask.BaseTree"; learning_session_->RegisterTask(dropped_frame_task, SequenceBoundFeatureProvider()); base_tree_controller_ = @@ -98,8 +106,6 @@ FeatureLibrary::NetworkType()); dropped_frame_task.feature_descriptions.push_back( FeatureLibrary::BatteryPower()); - dropped_frame_task.uma_hacky_confusion_matrix = - "Media.Learning.MediaCapabilities.DroppedFrameRatioTask.EnhancedTree"; learning_session_->RegisterTask(dropped_frame_task, feature_factory.Run(dropped_frame_task)); enhanced_tree_controller_ = @@ -108,9 +114,8 @@ // Duplicate the task with a new name and UMA histogram. We'll add // unweighted examples to it to see which one does better. dropped_frame_task.name = kDroppedFrameRatioEnhancedUnweightedTreeTaskName; - dropped_frame_task.uma_hacky_confusion_matrix = - "Media.Learning.MediaCapabilities.DroppedFrameRatioTask." - "EnhancedUnweightedTree"; + // Adjust the reporting weight since we'll have 100 or fewer examples. + dropped_frame_task.max_reporting_weight = 99.; learning_session_->RegisterTask(dropped_frame_task, feature_factory.Run(dropped_frame_task)); unweighted_tree_controller_ = @@ -127,13 +132,11 @@ dropped_frame_task.target_description = { "is_smooth", ::media::learning::LearningTask::Ordering::kUnordered}; */ - dropped_frame_task.uma_hacky_confusion_matrix = - "Media.Learning.MediaCapabilities.DroppedFrameRatioTask." - "BinarySmoothnessTree"; // We'll threshold the ratio when figuring out the binary label, so we just // want to pick the majority. Note that I have no idea if this is actually // the best threshold, but it seems like a good place to start. dropped_frame_task.smoothness_threshold = 0.5; + dropped_frame_task.max_reporting_weight = weighted_reporting_max; learning_session_->RegisterTask(dropped_frame_task, feature_factory.Run(dropped_frame_task)); binary_tree_controller_ =
diff --git a/media/gpu/linux/platform_video_frame_utils.cc b/media/gpu/linux/platform_video_frame_utils.cc index e68df74..72cf6f19 100644 --- a/media/gpu/linux/platform_video_frame_utils.cc +++ b/media/gpu/linux/platform_video_frame_utils.cc
@@ -28,8 +28,8 @@ const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, - gfx::BufferUsage buffer_usage, - base::TimeDelta timestamp) { + base::TimeDelta timestamp, + gfx::BufferUsage buffer_usage) { ui::OzonePlatform* platform = ui::OzonePlatform::GetInstance(); DCHECK(platform); ui::SurfaceFactoryOzone* factory = platform->GetSurfaceFactoryOzone(); @@ -88,11 +88,11 @@ const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, - gfx::BufferUsage buffer_usage, - base::TimeDelta timestamp) { + base::TimeDelta timestamp, + gfx::BufferUsage buffer_usage) { #if defined(USE_OZONE) return CreateVideoFrameOzone(pixel_format, coded_size, visible_rect, - natural_size, buffer_usage, timestamp); + natural_size, timestamp, buffer_usage); #endif // defined(USE_OZONE) NOTREACHED(); return nullptr;
diff --git a/media/gpu/linux/platform_video_frame_utils.h b/media/gpu/linux/platform_video_frame_utils.h index dde49a9..35065764 100644 --- a/media/gpu/linux/platform_video_frame_utils.h +++ b/media/gpu/linux/platform_video_frame_utils.h
@@ -22,8 +22,8 @@ const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, - gfx::BufferUsage buffer_usage, - base::TimeDelta timestamp); + base::TimeDelta timestamp, + gfx::BufferUsage buffer_usage); // Create a shared GPU memory handle to the |video_frame|'s data. MEDIA_GPU_EXPORT gfx::GpuMemoryBufferHandle CreateGpuMemoryBufferHandle(
diff --git a/media/gpu/test/image_processor/image_processor_client.cc b/media/gpu/test/image_processor/image_processor_client.cc index 4871aaac..c4549bc 100644 --- a/media/gpu/test/image_processor/image_processor_client.cc +++ b/media/gpu/test/image_processor/image_processor_client.cc
@@ -8,7 +8,6 @@ #include <utility> #include "base/bind.h" -#include "third_party/libyuv/include/libyuv/planar_functions.h" #include "base/bind_helpers.h" #include "base/logging.h" @@ -27,47 +26,6 @@ namespace media { namespace test { -namespace { -// TODO(crbug.com/917951): Move these functions to video_frame_helpers.h - -// Copy |src_frame| into a new VideoFrame with |dst_layout|. The created -// VideoFrame's content is the same as |src_frame|. Returns nullptr on failure. -scoped_refptr<VideoFrame> CloneVideoFrameWithLayout( - const VideoFrame* const src_frame, - const VideoFrameLayout& dst_layout) { - if (!src_frame) - return nullptr; - - LOG_ASSERT(src_frame->IsMappable()); - LOG_ASSERT(src_frame->format() == dst_layout.format()); - // Create VideoFrame, which allocates and owns data. - auto dst_frame = VideoFrame::CreateFrameWithLayout( - dst_layout, src_frame->visible_rect(), src_frame->natural_size(), - src_frame->timestamp(), false /* zero_initialize_memory*/); - if (!dst_frame) { - LOG(ERROR) << "Failed to create VideoFrame"; - return nullptr; - } - - // Copy every plane's content from |src_frame| to |dst_frame|. - const size_t num_planes = VideoFrame::NumPlanes(dst_layout.format()); - LOG_ASSERT(dst_layout.planes().size() == num_planes); - LOG_ASSERT(src_frame->layout().planes().size() == num_planes); - for (size_t i = 0; i < num_planes; ++i) { - // |width| in libyuv::CopyPlane() is in bytes, not pixels. - gfx::Size plane_size = VideoFrame::PlaneSize(dst_frame->format(), i, - dst_frame->natural_size()); - libyuv::CopyPlane( - src_frame->data(i), src_frame->layout().planes()[i].stride, - dst_frame->data(i), dst_frame->layout().planes()[i].stride, - plane_size.width(), plane_size.height()); - } - - return dst_frame; -} - -} // namespace - // static std::unique_ptr<ImageProcessorClient> ImageProcessorClient::Create( const ImageProcessor::PortConfig& input_config,
diff --git a/media/gpu/test/texture_ref.cc b/media/gpu/test/texture_ref.cc index a60c680..ab0c7eb 100644 --- a/media/gpu/test/texture_ref.cc +++ b/media/gpu/test/texture_ref.cc
@@ -7,12 +7,13 @@ #include <utility> #include <vector> +#include "base/logging.h" +#include "build/build_config.h" #include "media/gpu/test/video_frame_helpers.h" -#if defined(OS_CHROMEOS) +#if defined(OS_LINUX) #include <libdrm/drm_fourcc.h> -#include "base/logging.h" #include "media/gpu/linux/platform_video_frame_utils.h" #endif @@ -48,8 +49,11 @@ #if defined(OS_CHROMEOS) texture_ref = TextureRef::Create(texture_id, std::move(no_longer_needed_cb)); LOG_ASSERT(texture_ref); + // We set visible size to coded_size. The correct visible rectangle is set + // later in ExportVideoFrame(). texture_ref->frame_ = - CreatePlatformVideoFrame(pixel_format, size, buffer_usage); + CreatePlatformVideoFrame(pixel_format, size, gfx::Rect(size), size, + base::TimeDelta(), buffer_usage); #endif return texture_ref; }
diff --git a/media/gpu/test/video_frame_helpers.cc b/media/gpu/test/video_frame_helpers.cc index bf831e15..ce3655f 100644 --- a/media/gpu/test/video_frame_helpers.cc +++ b/media/gpu/test/video_frame_helpers.cc
@@ -155,18 +155,65 @@ return dst_frame; } -scoped_refptr<VideoFrame> CreatePlatformVideoFrame( - VideoPixelFormat pixel_format, - const gfx::Size& size, - gfx::BufferUsage buffer_usage) { - scoped_refptr<VideoFrame> video_frame; -#if defined(OS_CHROMEOS) - gfx::Rect visible_rect(size.width(), size.height()); - video_frame = media::CreatePlatformVideoFrame( - pixel_format, size, visible_rect, visible_rect.size(), buffer_usage, - base::TimeDelta()); - LOG_ASSERT(video_frame) << "Failed to create Dmabuf-backed VideoFrame"; -#endif +scoped_refptr<VideoFrame> CloneVideoFrameWithLayout( + const VideoFrame* const src_frame, + const VideoFrameLayout& dst_layout) { + if (!src_frame) + return nullptr; + + LOG_ASSERT(src_frame->IsMappable()); + LOG_ASSERT(src_frame->format() == dst_layout.format()); + // Create VideoFrame, which allocates and owns data. + auto dst_frame = VideoFrame::CreateFrameWithLayout( + dst_layout, src_frame->visible_rect(), src_frame->natural_size(), + src_frame->timestamp(), false /* zero_initialize_memory*/); + if (!dst_frame) { + LOG(ERROR) << "Failed to create VideoFrame"; + return nullptr; + } + + // Copy every plane's content from |src_frame| to |dst_frame|. + const size_t num_planes = VideoFrame::NumPlanes(dst_layout.format()); + LOG_ASSERT(dst_layout.planes().size() == num_planes); + LOG_ASSERT(src_frame->layout().planes().size() == num_planes); + for (size_t i = 0; i < num_planes; ++i) { + // |width| in libyuv::CopyPlane() is in bytes, not pixels. + gfx::Size plane_size = VideoFrame::PlaneSize(dst_frame->format(), i, + dst_frame->natural_size()); + libyuv::CopyPlane( + src_frame->data(i), src_frame->layout().planes()[i].stride, + dst_frame->data(i), dst_frame->layout().planes()[i].stride, + plane_size.width(), plane_size.height()); + } + + return dst_frame; +} + +scoped_refptr<const VideoFrame> CreateVideoFrameFromImage(const Image& image) { + DCHECK(image.IsLoaded()); + const auto format = image.PixelFormat(); + const auto& visible_size = image.Size(); + // Loaded image data must be tight. + DCHECK_EQ(image.DataSize(), VideoFrame::AllocationSize(format, visible_size)); + + // Create planes for layout. We cannot use WrapExternalData() because it + // calls GetDefaultLayout() and it supports only a few pixel formats. + base::Optional<VideoFrameLayout> layout = + CreateVideoFrameLayout(format, visible_size, 1u /* num_buffers */); + if (!layout) { + LOG(ERROR) << "Failed to create VideoFrameLayout"; + return nullptr; + } + + scoped_refptr<const VideoFrame> video_frame = + VideoFrame::WrapExternalDataWithLayout( + *layout, gfx::Rect(visible_size), visible_size, image.Data(), + image.DataSize(), base::TimeDelta()); + if (!video_frame) { + LOG(ERROR) << "Failed to create VideoFrame"; + return nullptr; + } + return video_frame; } @@ -200,33 +247,5 @@ std::move(buffer_sizes)); } -scoped_refptr<const VideoFrame> CreateVideoFrameFromImage(const Image& image) { - DCHECK(image.IsLoaded()); - const auto format = image.PixelFormat(); - const auto& visible_size = image.Size(); - // Loaded image data must be tight. - DCHECK_EQ(image.DataSize(), VideoFrame::AllocationSize(format, visible_size)); - - // Create planes for layout. We cannot use WrapExternalData() because it - // calls GetDefaultLayout() and it supports only a few pixel formats. - base::Optional<VideoFrameLayout> layout = - CreateVideoFrameLayout(format, visible_size, 1u /* num_buffers */); - if (!layout) { - LOG(ERROR) << "Failed to create VideoFrameLayout"; - return nullptr; - } - - scoped_refptr<const VideoFrame> video_frame = - VideoFrame::WrapExternalDataWithLayout( - *layout, gfx::Rect(visible_size), visible_size, image.Data(), - image.DataSize(), base::TimeDelta()); - if (!video_frame) { - LOG(ERROR) << "Failed to create VideoFrame"; - return nullptr; - } - - return video_frame; -} - } // namespace test } // namespace media
diff --git a/media/gpu/test/video_frame_helpers.h b/media/gpu/test/video_frame_helpers.h index cf11a65d..bb9fd43 100644 --- a/media/gpu/test/video_frame_helpers.h +++ b/media/gpu/test/video_frame_helpers.h
@@ -50,12 +50,18 @@ scoped_refptr<VideoFrame> ConvertVideoFrame(const VideoFrame* src_frame, VideoPixelFormat dst_pixel_format); -// Create a platform-specific DMA-buffer-backed video frame with specified -// |pixel_format|, |size| and |buffer_usage|. -scoped_refptr<VideoFrame> CreatePlatformVideoFrame( - VideoPixelFormat pixel_format, - const gfx::Size& size, - gfx::BufferUsage buffer_usage = gfx::BufferUsage::SCANOUT_VDA_WRITE); +// Copy |src_frame| into a new VideoFrame with |dst_layout|. This doesn't +// convert pixel format. That is, |dst_layout|'s format must be the same as +// |src_frame|'s format. This function supports all formats. The created +// VideoFrame's content is the same as |src_frame|. The created VideoFrame owns +// the buffer. Returns nullptr on failure. +scoped_refptr<VideoFrame> CloneVideoFrameWithLayout( + const VideoFrame* const src_frame, + const VideoFrameLayout& dst_layout); + +// Get VideoFrame that contains Load()ed data. The returned VideoFrame doesn't +// own the data and thus must not be changed. +scoped_refptr<const VideoFrame> CreateVideoFrameFromImage(const Image& image); // Create a video frame layout for the specified |pixel_format| and // |coded_size|. If |single_buffer| is true, the created VideoFrameLayout @@ -66,10 +72,6 @@ const gfx::Size& size, bool single_buffer); -// Get VideoFrame that contains Load()ed data. The returned VideoFrame doesn't -// own the data and thus must not be changed. -scoped_refptr<const VideoFrame> CreateVideoFrameFromImage(const Image& image); - } // namespace test } // namespace media
diff --git a/media/gpu/test/video_player/test_vda_video_decoder.cc b/media/gpu/test/video_player/test_vda_video_decoder.cc index bff983e..45566062 100644 --- a/media/gpu/test/video_player/test_vda_video_decoder.cc +++ b/media/gpu/test/video_player/test_vda_video_decoder.cc
@@ -185,8 +185,12 @@ // Create a video frame for each of the picture buffers and provide memory // handles to the video frame's data to the decoder. for (const PictureBuffer& picture_buffer : picture_buffers) { - scoped_refptr<VideoFrame> video_frame = - CreatePlatformVideoFrame(pixel_format, size); + scoped_refptr<VideoFrame> video_frame; +#if defined(OS_LINUX) + video_frame = CreatePlatformVideoFrame( + pixel_format, size, gfx::Rect(size), size, base::TimeDelta(), + gfx::BufferUsage::SCANOUT_VDA_WRITE); +#endif LOG_ASSERT(video_frame) << "Failed to create video frame"; video_frames_.emplace(picture_buffer.id(), video_frame); gfx::GpuMemoryBufferHandle handle;
diff --git a/media/learning/common/learning_task.h b/media/learning/common/learning_task.h index 0e4eb5a..ed5f4f7 100644 --- a/media/learning/common/learning_task.h +++ b/media/learning/common/learning_task.h
@@ -107,16 +107,10 @@ // we currently have, which might be less than |max_data_set_size|. double min_new_data_fraction = 0.1; - // If set, then we'll record a confusion matrix hackily to UMA using this as - // the histogram name. If we're using a (single) feature subset, then we'll - // slide the x-axis to the right by multiples of 6 (== size of one confusion - // matrix, see enums.xml) to match the chosen feature index. - std::string uma_hacky_confusion_matrix; - // If provided, then we'll randomly select a |*feature_subset_size|-sized set // of feature to train the model with, to allow for feature importance - // measurement. Note that |uma_hacky_confusion_matrix| reporting only - // supports subsets of size one, or the whole set. + // measurement. Note that UMA reporting only supports subsets of size one, or + // the whole set. base::Optional<int> feature_subset_size; // RandomForest parameters @@ -138,7 +132,57 @@ // // In particular, if the percentage of dropped frames is greater than this, // then report "false" (not smooth), else we report true. + // + // A better, non-hacky approach would be to report the predictions and + // observations directly, and do offline analysis with whatever threshold we + // like. This would remove the thresholding requirement, and also permit + // additional types of analysis for general regression tasks, such measuring + // the prediction error directly. + // + // The UKM reporter will support this. double smoothness_threshold = 0.1; + + // If set, then we'll record a confusion matrix (hackily, see + // |smoothness_threshold|, above, for what that means) to UMA for all + // predictions. Add this task's name to histograms.xml, in the histogram + // suffixes for "Media.Learning.BinaryThreshold.Aggregate". The threshold is + // chosen by |smoothness_threshold|. + // + // This option is ignored if feature subset selection is in use. + bool uma_hacky_aggregate_confusion_matrix = false; + + // If set, then we'll record a histogram of many confusion matrices, split out + // by the total training data weight that was used to construct the model. Be + // sure to add this task's name to histograms.xml, in the histogram suffixes + // for "Media.Learning.BinaryThreshold.ByTrainingWeight". The threshold is + // chosen by |smoothness_threshold|. + // + // This option is ignored if feature subset selection is in use. + bool uma_hacky_by_training_weight_confusion_matrix = false; + + // If set, then we'll record a histogram of many confusion matrices, split out + // by the (single) selected feature subset. This does nothing if we're not + // using feature subsets, or if the subset size isn't one. Be sure to add + // this tasks' name to histograms.xml, in the histogram suffixes for + // "Media.Learning.BinaryThreshold.ByFeature" too. + bool uma_hacky_by_feature_subset_confusion_matrix = false; + + // Maximum training weight for UMA reporting. We'll report results offset + // into different confusion matrices in the same histogram, evenly spaced + // from 0 to |max_reporting_weight|, with one additional bucket for everything + // larger than that. The number of buckets is |num_reporting_weight_buckets|. + double max_reporting_weight = 99.; + + // Number of buckets that we'll use to split out the confusion matrix by + // training weight. The last one is reserved for "all", while the others are + // split evenly from 0 to |max_reporting_weight|, inclusive. One can select + // up to 15 buckets. We use 11 by default, so it breaks up the default weight + // into buckets of size 10. + // + // In other words, the defaults will make these buckets: + // [0-9] [10-19] ... [90-99] [100 and up]. This makes sense if the training + // set maximum size is the default of 100, and each example has a weight of 1. + int num_reporting_weight_buckets = 11; }; } // namespace learning
diff --git a/media/learning/impl/distribution_reporter.cc b/media/learning/impl/distribution_reporter.cc index 9213028..a42f2c5 100644 --- a/media/learning/impl/distribution_reporter.cc +++ b/media/learning/impl/distribution_reporter.cc
@@ -10,84 +10,170 @@ namespace media { namespace learning { -// Low order bit is "observed", second bit is "predicted", third bit is "could -// not make a prediction". +// UMA histogram base names. +static const char* kAggregateBase = "Media.Learning.BinaryThreshold.Aggregate."; +static const char* kByTrainingWeightBase = + "Media.Learning.BinaryThreshold.ByTrainingWeight."; +static const char* kByFeatureBase = "Media.Learning.BinaryThreshold.ByFeature."; + +enum /* not class */ Bits { + // These are meant to be bitwise-or'd together, so both false cases just mean + // "don't set any bits". + PredictedFalse = 0x00, + ObservedFalse = 0x00, + ObservedTrue = 0x01, + PredictedTrue = 0x02, + // Special value to mean that no prediction was made. + PredictedNothing = 0x04, +}; + +// Low order bit is "observed", second bit is "predicted", third bit is +// "could not make a prediction". enum class ConfusionMatrix { - TrueNegative = 0, // predicted == observed == false - FalseNegative = 1, // predicted == false, observed == true - FalsePositive = 2, // predicted == true, observed == false - TruePositive = 3, // predicted == observed == true - SkippedNegative = 4, // predicted == N/A, observed == false - SkippedPositive = 5, // predicted == N/A, observed == true + TrueNegative = Bits::PredictedFalse | Bits::ObservedFalse, + FalseNegative = Bits::PredictedFalse | Bits::ObservedTrue, + FalsePositive = Bits::PredictedTrue | Bits::ObservedFalse, + TruePositive = Bits::PredictedTrue | Bits::ObservedTrue, + SkippedNegative = Bits::PredictedNothing | Bits::ObservedFalse, + SkippedPositive = Bits::PredictedNothing | Bits::ObservedTrue, kMaxValue = SkippedPositive }; // TODO(liberato): Currently, this implementation is a hack to collect some // sanity-checking data for local learning with MediaCapabilities. We assume // that the prediction is the "percentage of dropped frames". -// -// Please see https://chromium-review.googlesource.com/c/chromium/src/+/1385107 -// for an actual UKM-based implementation. -class RegressionReporter : public DistributionReporter { +class UmaRegressionReporter : public DistributionReporter { public: - RegressionReporter(const LearningTask& task) : DistributionReporter(task) {} + UmaRegressionReporter(const LearningTask& task) + : DistributionReporter(task) {} - void OnPrediction(TargetHistogram observed, + void OnPrediction(const PredictionInfo& info, TargetHistogram predicted) override { DCHECK_EQ(task().target_description.ordering, LearningTask::Ordering::kNumeric); - DCHECK(!task().uma_hacky_confusion_matrix.empty()); // As a complete hack, record accuracy with a fixed threshold. The average // is the observed / predicted percentage of dropped frames. - bool observed_smooth = observed.Average() <= task().smoothness_threshold; + bool observed_smooth = info.observed.value() <= task().smoothness_threshold; // See if we made a prediction. - int predicted_bits = 4; // N/A + int prediction_bit_mask = Bits::PredictedNothing; if (predicted.total_counts() != 0) { bool predicted_smooth = predicted.Average() <= task().smoothness_threshold; DVLOG(2) << "Learning: " << task().name << ": predicted: " << predicted_smooth << " (" << predicted.Average() << ") observed: " << observed_smooth - << " (" << observed.Average() << ")"; - predicted_bits = predicted_smooth ? 2 : 0; + << " (" << info.observed.value() << ")"; + prediction_bit_mask = + predicted_smooth ? Bits::PredictedTrue : Bits::PredictedFalse; } else { DVLOG(2) << "Learning: " << task().name << ": predicted: N/A observed: " << observed_smooth << " (" - << observed.Average() << ")"; + << info.observed.value() << ")"; } - // Convert to a bucket from which we can get the confusion matrix. - ConfusionMatrix uma_bucket = static_cast<ConfusionMatrix>( - (observed_smooth ? 1 : 0) | predicted_bits); + // Figure out the ConfusionMatrix enum value. + ConfusionMatrix confusion_matrix_value = static_cast<ConfusionMatrix>( + (observed_smooth ? Bits::ObservedTrue : Bits::ObservedFalse) | + prediction_bit_mask); - if (!feature_indices() || - feature_indices()->size() == task().feature_descriptions.size()) { - base::UmaHistogramEnumeration(task().uma_hacky_confusion_matrix, - uma_bucket); - } else if (feature_indices()->size() == 1) { - // Slide the matrix over by whatever feature we're measuring. - constexpr int matrix_size = - static_cast<int>(ConfusionMatrix::kMaxValue) + 1; - int value_max = matrix_size * task().feature_descriptions.size() - 1; - int feature_index = *feature_indices()->begin(); - base::UmaHistogramExactLinear( - task().uma_hacky_confusion_matrix, - static_cast<int>(uma_bucket) + feature_index * matrix_size, - value_max); - } // else do nothing -- we only support one feature for UMA reporting. + // |uma_bucket_number| is the bucket number that we'll fill in with this + // count. It ranges from 0 to |max_buckets-1|, inclusive. Each bucket is + // is separated from the start of the previous bucket by |uma_bucket_size|. + int uma_bucket_number = 0; + constexpr int matrix_size = + static_cast<int>(ConfusionMatrix::kMaxValue) + 1; + + // The enum.xml entries separate the buckets by 10, to make it easy to see + // by inspection what bucket number we're in (e.g., x-axis position 23 is + // bucket 2 * 10 + PredictedTrue|ObservedTrue). The label in enum.xml for + // MegaConfusionMatrix also provides the bucket number for easy reading. + constexpr int uma_bucket_size = 10; + DCHECK_LE(matrix_size, uma_bucket_size); + + // Maximum number of buckets defined in enums.xml, numbered from 0. + constexpr int max_buckets = 16; + + // Sparse histograms can technically go past 100 exactly-stored elements, + // but we limit it anyway. Note that we don't care about |uma_bucket_size|, + // since it's a sparse histogram. Only |matrix_size| elements are used in + // each bucket. + DCHECK_LE(max_buckets * matrix_size, 100); + + // If we're splitting by feature, then record it and stop. The others + // aren't meaningful to record if we're using random feature subsets. + if (task().uma_hacky_by_feature_subset_confusion_matrix && + feature_indices() && feature_indices()->size() == 1) { + // The bucket number is just the feature number that was selected. + uma_bucket_number = + std::min(*feature_indices()->begin(), max_buckets - 1); + + std::string base(kByFeatureBase); + base::UmaHistogramSparse(base + task().name, + static_cast<int>(confusion_matrix_value) + + uma_bucket_number * uma_bucket_size); + + // Early return since no other measurements are meaningful when we're + // using feature subsets. + return; + } + + // If we're selecting a feature subset that's bigger than one but smaller + // than all of them, then we don't know how to report that. + if (feature_indices() && + feature_indices()->size() != task().feature_descriptions.size()) { + return; + } + + // Do normal reporting. + + // Record the aggregate confusion matrix. + if (task().uma_hacky_aggregate_confusion_matrix) { + std::string base(kAggregateBase); + base::UmaHistogramEnumeration(base + task().name, confusion_matrix_value); + } + + if (task().uma_hacky_by_training_weight_confusion_matrix) { + // Adjust |uma_bucket_offset| by the training weight, and store the + // results in that bucket in the ByTrainingWeight histogram. + // + // This will bucket from 0 in even steps, with the last bucket holding + // |max_reporting_weight+1| and everything above it. + + const int n_buckets = task().num_reporting_weight_buckets; + DCHECK_LE(n_buckets, max_buckets); + + // We use one fewer buckets, to save one for the overflow. Buckets are + // numbered from 0 to |n_buckets-1|, inclusive. In other words, when the + // training weight is equal to |max_reporting_weight|, we still want to + // be in bucket |n_buckets - 2|. That's why we add one to the max before + // we divide; only things over the max go into the last bucket. + uma_bucket_number = + std::min<int>((n_buckets - 1) * info.total_training_weight / + (task().max_reporting_weight + 1), + n_buckets - 1); + + std::string base(kByTrainingWeightBase); + base::UmaHistogramSparse(base + task().name, + static_cast<int>(confusion_matrix_value) + + uma_bucket_number * uma_bucket_size); + } } }; std::unique_ptr<DistributionReporter> DistributionReporter::Create( const LearningTask& task) { - // Hacky reporting is the only thing we know how to report. - if (task.uma_hacky_confusion_matrix.empty()) + // We only know how to report regression tasks right now. + if (task.target_description.ordering != LearningTask::Ordering::kNumeric) return nullptr; - if (task.target_description.ordering == LearningTask::Ordering::kNumeric) - return std::make_unique<RegressionReporter>(task); + if (task.uma_hacky_aggregate_confusion_matrix || + task.uma_hacky_by_training_weight_confusion_matrix || + task.uma_hacky_by_feature_subset_confusion_matrix) { + return std::make_unique<UmaRegressionReporter>(task); + } + return nullptr; } @@ -97,9 +183,9 @@ DistributionReporter::~DistributionReporter() = default; Model::PredictionCB DistributionReporter::GetPredictionCallback( - TargetHistogram observed) { + const PredictionInfo& info) { return base::BindOnce(&DistributionReporter::OnPrediction, - weak_factory_.GetWeakPtr(), observed); + weak_factory_.GetWeakPtr(), info); } void DistributionReporter::SetFeatureSubset(
diff --git a/media/learning/impl/distribution_reporter.h b/media/learning/impl/distribution_reporter.h index aa2ef6e..99310aa0 100644 --- a/media/learning/impl/distribution_reporter.h +++ b/media/learning/impl/distribution_reporter.h
@@ -24,14 +24,30 @@ // specific learning task. class COMPONENT_EXPORT(LEARNING_IMPL) DistributionReporter { public: + // Extra information provided to the reporter for each prediction. + struct PredictionInfo { + // What value was observed? + TargetValue observed; + + // Total weight of the training data used to create this model. + double total_training_weight = 0.; + + // Total number of examples (unweighted) in the training set. + size_t total_training_examples = 0u; + + // TODO(liberato): Move the feature subset here. + }; + // Create a DistributionReporter that's suitable for |task|. static std::unique_ptr<DistributionReporter> Create(const LearningTask& task); virtual ~DistributionReporter(); - // Returns a prediction CB that will be compared to |observed|. |observed| is - // the total number of counts that we observed. - virtual Model::PredictionCB GetPredictionCallback(TargetHistogram observed); + // Returns a prediction CB that will be compared to |prediction_info.observed| + // TODO(liberato): This is too complicated. Skip the callback and just call + // us with the predicted value. + virtual Model::PredictionCB GetPredictionCallback( + const PredictionInfo& prediction_info); // Set the subset of features that is being used to train the model. This is // used for feature importance measuremnts. @@ -48,7 +64,7 @@ const LearningTask& task() const { return task_; } // Implemented by subclasses to report a prediction. - virtual void OnPrediction(TargetHistogram observed, + virtual void OnPrediction(const PredictionInfo& prediction_info, TargetHistogram predicted) = 0; const base::Optional<std::set<int>>& feature_indices() const {
diff --git a/media/learning/impl/distribution_reporter_unittest.cc b/media/learning/impl/distribution_reporter_unittest.cc index 7908c4e4..43679be 100644 --- a/media/learning/impl/distribution_reporter_unittest.cc +++ b/media/learning/impl/distribution_reporter_unittest.cc
@@ -16,6 +16,12 @@ class DistributionReporterTest : public testing::Test { public: + DistributionReporterTest() { + task_.name = "TaskName"; + // UMA reporting requires a numeric target. + task_.target_description.ordering = LearningTask::Ordering::kNumeric; + } + base::test::ScopedTaskEnvironment scoped_task_environment_; LearningTask task_; @@ -25,35 +31,27 @@ TEST_F(DistributionReporterTest, DistributionReporterDoesNotCrash) { // Make sure that we request some sort of reporting. - task_.target_description.ordering = LearningTask::Ordering::kNumeric; - task_.uma_hacky_confusion_matrix = "test"; + task_.uma_hacky_aggregate_confusion_matrix = true; reporter_ = DistributionReporter::Create(task_); EXPECT_NE(reporter_, nullptr); + // Observe an average of 2 / 3. + DistributionReporter::PredictionInfo info; + info.observed = TargetValue(2.0 / 3.0); + auto cb = reporter_->GetPredictionCallback(info); + + TargetHistogram predicted; const TargetValue Zero(0); const TargetValue One(1); - TargetHistogram observed; - // Observe an average of 2 / 3. - observed[Zero] = 100; - observed[One] = 200; - auto cb = reporter_->GetPredictionCallback(observed); - - TargetHistogram predicted; // Predict an average of 5 / 9. predicted[Zero] = 40; predicted[One] = 50; std::move(cb).Run(predicted); - - // TODO(liberato): When we switch to ukm, use a TestUkmRecorder to make sure - // that it fills in the right stuff. - // https://chromium-review.googlesource.com/c/chromium/src/+/1385107 . } -TEST_F(DistributionReporterTest, DistributionReporterNeedsUmaName) { +TEST_F(DistributionReporterTest, DistributionReporterMustBeRequested) { // Make sure that we don't get a reporter if we don't request any reporting. - task_.target_description.ordering = LearningTask::Ordering::kNumeric; - task_.uma_hacky_confusion_matrix = ""; reporter_ = DistributionReporter::Create(task_); EXPECT_EQ(reporter_, nullptr); } @@ -62,10 +60,28 @@ DistributionReporterHackyConfusionMatrixNeedsRegression) { // Hacky confusion matrix reporting only works with regression. task_.target_description.ordering = LearningTask::Ordering::kUnordered; - task_.uma_hacky_confusion_matrix = "test"; + task_.uma_hacky_aggregate_confusion_matrix = true; reporter_ = DistributionReporter::Create(task_); EXPECT_EQ(reporter_, nullptr); } +TEST_F(DistributionReporterTest, ProvidesAggregateReporter) { + task_.uma_hacky_aggregate_confusion_matrix = true; + reporter_ = DistributionReporter::Create(task_); + EXPECT_NE(reporter_, nullptr); +} + +TEST_F(DistributionReporterTest, ProvidesByTrainingWeightReporter) { + task_.uma_hacky_by_training_weight_confusion_matrix = true; + reporter_ = DistributionReporter::Create(task_); + EXPECT_NE(reporter_, nullptr); +} + +TEST_F(DistributionReporterTest, ProvidesByFeatureSubsetReporter) { + task_.uma_hacky_by_feature_subset_confusion_matrix = true; + reporter_ = DistributionReporter::Create(task_); + EXPECT_NE(reporter_, nullptr); +} + } // namespace learning } // namespace media
diff --git a/media/learning/impl/learning_fuzzertest.cc b/media/learning/impl/learning_fuzzertest.cc index 122d031a..f886ffb9 100644 --- a/media/learning/impl/learning_fuzzertest.cc +++ b/media/learning/impl/learning_fuzzertest.cc
@@ -47,7 +47,9 @@ task.name = provider.ConsumeRandomLengthString(100); task.model = provider.ConsumeEnum<LearningTask::Model>(); task.use_one_hot_conversion = provider.ConsumeBool(); - task.uma_hacky_confusion_matrix = provider.ConsumeRandomLengthString(10); + task.uma_hacky_aggregate_confusion_matrix = provider.ConsumeBool(); + task.uma_hacky_by_training_weight_confusion_matrix = provider.ConsumeBool(); + task.uma_hacky_by_feature_subset_confusion_matrix = provider.ConsumeBool(); int n_features = provider.ConsumeIntegralInRange(0, 100); int subset_size = provider.ConsumeIntegralInRange<uint8_t>(0, n_features); if (subset_size)
diff --git a/media/learning/impl/learning_task_controller_impl.cc b/media/learning/impl/learning_task_controller_impl.cc index c663f5b..544218a 100644 --- a/media/learning/impl/learning_task_controller_impl.cc +++ b/media/learning/impl/learning_task_controller_impl.cc
@@ -9,6 +9,7 @@ #include <vector> #include "base/bind.h" +#include "media/learning/impl/distribution_reporter.h" #include "media/learning/impl/extra_trees_trainer.h" #include "media/learning/impl/lookup_table_trainer.h" @@ -107,9 +108,11 @@ if (model_ && reporter_) { TargetHistogram predicted = model_->PredictDistribution(example.features); - TargetHistogram observed; - observed += example.target_value; - reporter_->GetPredictionCallback(observed).Run(predicted); + DistributionReporter::PredictionInfo info; + info.observed = example.target_value; + info.total_training_weight = last_training_weight_; + info.total_training_examples = last_training_size_; + reporter_->GetPredictionCallback(info).Run(predicted); } // Can't train more than one model concurrently. @@ -125,7 +128,8 @@ num_untrained_examples_ = 0; TrainedModelCB model_cb = - base::BindOnce(&LearningTaskControllerImpl::OnModelTrained, AsWeakPtr()); + base::BindOnce(&LearningTaskControllerImpl::OnModelTrained, AsWeakPtr(), + training_data_->total_weight(), training_data_->size()); training_is_in_progress_ = true; // Note that this copies the training data, so it's okay if we add more // examples to our copy before this returns. @@ -135,10 +139,15 @@ trainer_->Train(task_, *training_data_, std::move(model_cb)); } -void LearningTaskControllerImpl::OnModelTrained(std::unique_ptr<Model> model) { +void LearningTaskControllerImpl::OnModelTrained(double training_weight, + int training_size, + std::unique_ptr<Model> model) { DCHECK(training_is_in_progress_); training_is_in_progress_ = false; model_ = std::move(model); + // Record these for metrics. + last_training_weight_ = training_weight; + last_training_size_ = training_size; } void LearningTaskControllerImpl::SetTrainerForTesting(
diff --git a/media/learning/impl/learning_task_controller_impl.h b/media/learning/impl/learning_task_controller_impl.h index ea9d95e..eae031b 100644 --- a/media/learning/impl/learning_task_controller_impl.h +++ b/media/learning/impl/learning_task_controller_impl.h
@@ -21,6 +21,7 @@ namespace media { namespace learning { +class DistributionReporter; class LearningTaskControllerImplTest; // Controller for a single learning task. Takes training examples, and forwards @@ -55,8 +56,11 @@ // Add |example| to the training data, and process it. void AddFinishedExample(LabelledExample example); - // Called by |training_cb_| when the model is trained. - void OnModelTrained(std::unique_ptr<Model> model); + // Called by |training_cb_| when the model is trained. |training_weight| and + // |training_size| are the training set's total weight and number of examples. + void OnModelTrained(double training_weight, + int training_size, + std::unique_ptr<Model> model); void SetTrainerForTesting(std::unique_ptr<TrainingAlgorithm> trainer); @@ -78,6 +82,10 @@ // This helps us decide when to train a new model. int num_untrained_examples_ = 0; + // Total weight and number of examples in the most recently trained model. + double last_training_weight_ = 0.; + size_t last_training_size_ = 0u; + // Training algorithm that we'll use. std::unique_ptr<TrainingAlgorithm> trainer_;
diff --git a/media/learning/impl/learning_task_controller_impl_unittest.cc b/media/learning/impl/learning_task_controller_impl_unittest.cc index fdabda3..e1620c0 100644 --- a/media/learning/impl/learning_task_controller_impl_unittest.cc +++ b/media/learning/impl/learning_task_controller_impl_unittest.cc
@@ -28,10 +28,12 @@ } protected: - void OnPrediction(TargetHistogram observed, + void OnPrediction(const PredictionInfo& info, TargetHistogram predicted) override { num_reported_++; - if (observed == predicted) + TargetHistogram dist; + dist += info.observed; + if (dist == predicted) num_correct_++; } @@ -132,7 +134,6 @@ // Number of models that we trained. int num_models_ = 0; - FakeModel* last_model_ = nullptr; // Two distinct targets. const TargetValue predicted_target_;
diff --git a/remoting/base/BUILD.gn b/remoting/base/BUILD.gn index e362c45..16a71c5 100644 --- a/remoting/base/BUILD.gn +++ b/remoting/base/BUILD.gn
@@ -91,8 +91,6 @@ "gaia_oauth_client.cc", "gaia_oauth_client.h", "oauth_client.h", - "oauth_helper.cc", - "oauth_helper.h", "oauth_token_getter.cc", "oauth_token_getter.h", "oauth_token_getter_impl.cc", @@ -167,7 +165,6 @@ "buffered_socket_writer_unittest.cc", "capabilities_unittest.cc", "compound_buffer_unittest.cc", - "oauth_helper_unittest.cc", "rate_counter_unittest.cc", "result_unittest.cc", "rsa_key_pair_unittest.cc",
diff --git a/remoting/base/oauth_helper.cc b/remoting/base/oauth_helper.cc deleted file mode 100644 index 62f4066f..0000000 --- a/remoting/base/oauth_helper.cc +++ /dev/null
@@ -1,74 +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 "remoting/base/oauth_helper.h" - -#include "base/strings/stringprintf.h" -#include "google_apis/google_api_keys.h" -#include "net/base/escape.h" -#include "url/third_party/mozilla/url_parse.h" - -namespace { - -std::string GetComponent(const std::string& url, - const url::Component component) { - if (component.len < 0) { - return std::string(); - } - return url.substr(component.begin, component.len); -} - -} // namespace - -namespace remoting { - -std::string GetOauthScope() { - return "https://www.googleapis.com/auth/chromoting " - "https://www.googleapis.com/auth/googletalk " - "https://www.googleapis.com/auth/userinfo.email "; -} - -std::string GetOauthStartUrl(const std::string& redirect_url) { - return base::StringPrintf( - "https://accounts.google.com/o/oauth2/auth" - "?scope=%s" - "&redirect_uri=%s" - "&response_type=code" - "&client_id=%s" - "&access_type=offline" - "&approval_prompt=force", - net::EscapeUrlEncodedData(GetOauthScope(), true).c_str(), - redirect_url.c_str(), - net::EscapeUrlEncodedData( - google_apis::GetOAuth2ClientID(google_apis::CLIENT_REMOTING), true) - .c_str()); -} - -std::string GetOauthCodeInUrl(const std::string& url, - const std::string& redirect_url) { - url::Parsed url_parsed; - ParseStandardURL(url.c_str(), url.length(), &url_parsed); - url::Parsed redirect_url_parsed; - ParseStandardURL(redirect_url.c_str(), redirect_url.length(), - &redirect_url_parsed); - if (GetComponent(url, url_parsed.scheme) != - GetComponent(redirect_url, redirect_url_parsed.scheme)) { - return std::string(); - } - if (GetComponent(url, url_parsed.host) != - GetComponent(redirect_url, redirect_url_parsed.host)) { - return std::string(); - } - url::Component query = url_parsed.query; - url::Component key; - url::Component value; - while (ExtractQueryKeyValue(url.c_str(), &query, &key, &value)) { - if (GetComponent(url, key) == "code") { - return GetComponent(url, value); - } - } - return std::string(); -} - -} // namespace remoting
diff --git a/remoting/base/oauth_helper.h b/remoting/base/oauth_helper.h deleted file mode 100644 index c659e1a..0000000 --- a/remoting/base/oauth_helper.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef REMOTING_BASE_OAUTH_HELPER_H -#define REMOTING_BASE_OAUTH_HELPER_H - -#include <string> - -namespace remoting { - -// Gets the OAuth scope of the host's refresh token. -std::string GetOauthScope(); - -// Gets a URL at which the OAuth dance starts. -std::string GetOauthStartUrl(const std::string& redirect_url); - -// Returns the OAuth authorization code embedded in a URL, or the empty string -// if there is no such code. -// To get an OAuth authorization code, (i) start a browser, (ii) navigate it -// to |GetOauthStartUrl()|, (iii) ask the user to sign on to their account, -// and grant the requested permissions, (iv) monitor the URLs that the browser -// shows, passing each one to |GetOauthCodeInUrl()|, until that function returns -// a non-empty string. That string is the authorization code. -std::string GetOauthCodeInUrl(const std::string& url, - const std::string& redirect_url); - -} // namespace remoting - -#endif // REMOTING_BASE_OAUTH_HELPER_H
diff --git a/remoting/base/oauth_helper_unittest.cc b/remoting/base/oauth_helper_unittest.cc deleted file mode 100644 index 71ea3a7..0000000 --- a/remoting/base/oauth_helper_unittest.cc +++ /dev/null
@@ -1,78 +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 "remoting/base/oauth_helper.h" - -#include <stddef.h> - -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -std::string Replace(const std::string& s, - const std::string& old_substr, - const std::string& new_substr) { - size_t pos = s.find(old_substr); - if (pos == std::string::npos) { - return s; - } - return s.substr(0, pos) + new_substr + - s.substr(pos + old_substr.length(), std::string::npos); -} - -std::string GetTestRedirectUrl() { - return std::string("https://google.com/redirect"); -} - -} // namespace - -namespace remoting { - -TEST(OauthHelperTest, TestNotCode) { - ASSERT_EQ("", GetOauthCodeInUrl("notURL", GetTestRedirectUrl())); -} - -TEST(OauthHelperTest, TestVeryShort) { - ASSERT_EQ("", GetOauthCodeInUrl(GetTestRedirectUrl(), GetTestRedirectUrl())); -} - -TEST(OauthHelperTest, TestEmptyQuery) { - ASSERT_EQ( - "", GetOauthCodeInUrl(GetTestRedirectUrl() + "?", GetTestRedirectUrl())); -} - -TEST(OauthHelperTest, TestNoQueryValue) { - ASSERT_EQ("", GetOauthCodeInUrl(GetTestRedirectUrl() + "?code", - GetTestRedirectUrl())); -} - -TEST(OauthHelperTest, TestEmptyCode) { - ASSERT_EQ("", GetOauthCodeInUrl(GetTestRedirectUrl() + "?code=", - GetTestRedirectUrl())); -} - -TEST(OauthHelperTest, TestCode) { - ASSERT_EQ("Dummy", GetOauthCodeInUrl(GetTestRedirectUrl() + "?code=Dummy", - GetTestRedirectUrl())); -} - -TEST(OauthHelperTest, TestCodeInLongQuery) { - ASSERT_EQ("Dummy", - GetOauthCodeInUrl(GetTestRedirectUrl() + "?x=1&code=Dummy&y=2", - GetTestRedirectUrl())); -} - -TEST(OauthHelperTest, TestBadScheme) { - std::string url = GetTestRedirectUrl() + "?code=Dummy"; - url = Replace(url, "https:", "http"); - ASSERT_EQ("", GetOauthCodeInUrl(url, GetTestRedirectUrl())); -} - -TEST(OauthHelperTest, TestBadHost) { - std::string url = GetTestRedirectUrl() + "?code=Dummy"; - url = Replace(url, "google", "goggle"); - ASSERT_EQ("", GetOauthCodeInUrl(url, GetTestRedirectUrl())); -} - -} // namespace remoting
diff --git a/remoting/base/oauth_token_getter_impl.cc b/remoting/base/oauth_token_getter_impl.cc index 5bc231b..30628bfd 100644 --- a/remoting/base/oauth_token_getter_impl.cc +++ b/remoting/base/oauth_token_getter_impl.cc
@@ -12,7 +12,6 @@ #include "base/strings/string_util.h" #include "google_apis/google_api_keys.h" #include "remoting/base/logging.h" -#include "remoting/base/oauth_helper.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace remoting {
diff --git a/remoting/host/setup/host_starter.cc b/remoting/host/setup/host_starter.cc index 2769d9f..da166d52 100644 --- a/remoting/host/setup/host_starter.cc +++ b/remoting/host/setup/host_starter.cc
@@ -15,7 +15,6 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "google_apis/google_api_keys.h" -#include "remoting/base/oauth_helper.h" #include "remoting/host/pin_hash.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/remoting/host/setup/start_host_main.cc b/remoting/host/setup/start_host_main.cc index ded0027..ce7e25f 100644 --- a/remoting/host/setup/start_host_main.cc +++ b/remoting/host/setup/start_host_main.cc
@@ -21,7 +21,6 @@ #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_context_getter.h" #include "remoting/base/logging.h" -#include "remoting/base/oauth_helper.h" #include "remoting/base/service_urls.h" #include "remoting/base/url_request_context_getter.h" #include "remoting/host/setup/host_starter.h"
diff --git a/services/network/public/cpp/features.cc b/services/network/public/cpp/features.cc index 7592729..f7bf09f21 100644 --- a/services/network/public/cpp/features.cc +++ b/services/network/public/cpp/features.cc
@@ -60,8 +60,14 @@ "EnforceRequestInitiatorLockForCorb", base::FEATURE_ENABLED_BY_DEFAULT}; // Implementation of https://mikewest.github.io/sec-metadata/ -const base::Feature kSecMetadata{"SecMetadata", - base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kFetchMetadata{"FetchMetadata", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// The `Sec-Fetch-Dest` header is split out from the main "FetchMetadata" +// feature so we can ship the broader feature without this specifific bit +// while we continue discussion. +const base::Feature kFetchMetadataDestination{ + "FetchMetadataDestination", base::FEATURE_DISABLED_BY_DEFAULT}; bool ShouldEnableOutOfBlinkCors() { // OOR-CORS requires NetworkService.
diff --git a/services/network/public/cpp/features.h b/services/network/public/cpp/features.h index bd1a4fa..d10a61c 100644 --- a/services/network/public/cpp/features.h +++ b/services/network/public/cpp/features.h
@@ -28,7 +28,9 @@ COMPONENT_EXPORT(NETWORK_CPP) extern const base::Feature kEnforceRequestInitiatorLockForCorb; COMPONENT_EXPORT(NETWORK_CPP) -extern const base::Feature kSecMetadata; +extern const base::Feature kFetchMetadata; +COMPONENT_EXPORT(NETWORK_CPP) +extern const base::Feature kFetchMetadataDestination; COMPONENT_EXPORT(NETWORK_CPP) bool ShouldEnableOutOfBlinkCors();
diff --git a/storage/browser/fileapi/obfuscated_file_util_delegate.h b/storage/browser/fileapi/obfuscated_file_util_delegate.h index 6a63cdf..7b9a1d0 100644 --- a/storage/browser/fileapi/obfuscated_file_util_delegate.h +++ b/storage/browser/fileapi/obfuscated_file_util_delegate.h
@@ -20,6 +20,7 @@ virtual ~ObfuscatedFileUtilDelegate() = default; virtual bool DirectoryExists(const base::FilePath& path) = 0; + virtual size_t ComputeDirectorySize(const base::FilePath& path) = 0; virtual bool DeleteFileOrDirectory(const base::FilePath& path, bool recursive) = 0; virtual bool IsLink(const base::FilePath& file_path) = 0;
diff --git a/storage/browser/fileapi/obfuscated_file_util_disk_delegate.cc b/storage/browser/fileapi/obfuscated_file_util_disk_delegate.cc index 36d34aa..fbd2a32e 100644 --- a/storage/browser/fileapi/obfuscated_file_util_disk_delegate.cc +++ b/storage/browser/fileapi/obfuscated_file_util_disk_delegate.cc
@@ -18,6 +18,11 @@ return base::DirectoryExists(path); } +size_t ObfuscatedFileUtilDiskDelegate::ComputeDirectorySize( + const base::FilePath& path) { + return base::ComputeDirectorySize(path); +} + bool ObfuscatedFileUtilDiskDelegate::DeleteFileOrDirectory( const base::FilePath& path, bool recursive) {
diff --git a/storage/browser/fileapi/obfuscated_file_util_disk_delegate.h b/storage/browser/fileapi/obfuscated_file_util_disk_delegate.h index 50373442..05ea948 100644 --- a/storage/browser/fileapi/obfuscated_file_util_disk_delegate.h +++ b/storage/browser/fileapi/obfuscated_file_util_disk_delegate.h
@@ -22,6 +22,7 @@ ~ObfuscatedFileUtilDiskDelegate() override; bool DirectoryExists(const base::FilePath& path) override; + size_t ComputeDirectorySize(const base::FilePath& path) override; bool DeleteFileOrDirectory(const base::FilePath& path, bool recursive) override; bool IsLink(const base::FilePath& file_path) override;
diff --git a/storage/browser/fileapi/obfuscated_file_util_memory_delegate.cc b/storage/browser/fileapi/obfuscated_file_util_memory_delegate.cc index 6112f03..f5d9f5f3 100644 --- a/storage/browser/fileapi/obfuscated_file_util_memory_delegate.cc +++ b/storage/browser/fileapi/obfuscated_file_util_memory_delegate.cc
@@ -6,7 +6,7 @@ #include <utility> -#include "base/numerics/safe_conversions.h" +#include "base/numerics/checked_math.h" #include "build/build_config.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" @@ -401,6 +401,29 @@ return true; } +size_t ObfuscatedFileUtilMemoryDelegate::ComputeDirectorySize( + const base::FilePath& path) { + base::Optional<DecomposedPath> dp = ParsePath(path); + if (!dp || !dp->entry || dp->entry->type != Entry::kDirectory) + return 0; + + base::CheckedNumeric<size_t> running_sum = 0; + std::vector<Entry*> directories; + directories.push_back(dp->entry); + + while (!directories.empty()) { + Entry* current = directories.back(); + directories.pop_back(); + for (auto& child : current->directory_content) { + if (child.second.type == Entry::kDirectory) + directories.push_back(&child.second); + else + running_sum += child.second.file_content.size(); + } + } + return running_sum.ValueOrDefault(0); +} + int ObfuscatedFileUtilMemoryDelegate::ReadFile(const base::FilePath& path, int64_t offset, net::IOBuffer* buf,
diff --git a/storage/browser/fileapi/obfuscated_file_util_memory_delegate.h b/storage/browser/fileapi/obfuscated_file_util_memory_delegate.h index fc90d21..2ce6d15 100644 --- a/storage/browser/fileapi/obfuscated_file_util_memory_delegate.h +++ b/storage/browser/fileapi/obfuscated_file_util_memory_delegate.h
@@ -73,6 +73,11 @@ NativeFileUtil::CopyOrMoveMode mode) override; base::File::Error DeleteFile(const base::FilePath& path) override; + // Returns the total number of bytes used by all the files under |path|. + // If the path does not exist or the total number of bytes doesn't fit in + // |size_t|, the function returns 0. + size_t ComputeDirectorySize(const base::FilePath& path) override; + // Reads |buf_len| bytes from the file at |path|, starting from |offset|. // If successful, read bytes are written to |buf| and actual number of read // bytes are returned. Otherwise a net::Error value is returned.
diff --git a/storage/browser/fileapi/obfuscated_file_util_memory_delegate_unittest.cc b/storage/browser/fileapi/obfuscated_file_util_memory_delegate_unittest.cc index cabde48e..90f23a0 100644 --- a/storage/browser/fileapi/obfuscated_file_util_memory_delegate_unittest.cc +++ b/storage/browser/fileapi/obfuscated_file_util_memory_delegate_unittest.cc
@@ -653,4 +653,31 @@ EXPECT_EQ(file_info1.last_modified, file_info2.last_modified); } +TEST_F(ObfuscatedFileUtilMemoryDelegateTest, ComputeDirectorySize) { + base::FilePath file_name0 = Path("test_file0"); + base::FilePath dir_name1 = Path("dir1"); + base::FilePath file_name1 = dir_name1.AppendASCII("test_file1"); + base::FilePath dir_name2 = dir_name1.AppendASCII("dir2"); + base::FilePath file_name2 = dir_name2.AppendASCII("test_file2"); + char content[] = "01234567890123456789"; + + ASSERT_EQ(base::File::FILE_OK, + file_util()->CreateDirectory(dir_name2, false /* exclusive */, + true /* recursive */)); + + ASSERT_EQ(base::File::FILE_OK, + file_util()->CreateFileForTesting( + file_name0, base::span<const char>(content, 10))); + ASSERT_EQ(base::File::FILE_OK, + file_util()->CreateFileForTesting( + file_name1, base::span<const char>(content, 15))); + ASSERT_EQ(base::File::FILE_OK, + file_util()->CreateFileForTesting( + file_name2, base::span<const char>(content, 20))); + + ASSERT_EQ(20u, file_util()->ComputeDirectorySize(dir_name2)); + ASSERT_EQ(35u, file_util()->ComputeDirectorySize(dir_name1)); + ASSERT_EQ(45u, file_util()->ComputeDirectorySize(Path())); +} + } // namespace storage \ No newline at end of file
diff --git a/storage/browser/fileapi/obfuscated_file_util_unittest.cc b/storage/browser/fileapi/obfuscated_file_util_unittest.cc index d9a00812..c14332d 100644 --- a/storage/browser/fileapi/obfuscated_file_util_unittest.cc +++ b/storage/browser/fileapi/obfuscated_file_util_unittest.cc
@@ -20,16 +20,20 @@ #include "base/macros.h" #include "base/run_loop.h" #include "base/stl_util.h" +#include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/services/filesystem/public/interfaces/types.mojom.h" +#include "net/base/io_buffer.h" #include "storage/browser/fileapi/external_mount_points.h" #include "storage/browser/fileapi/file_system_backend.h" #include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_features.h" #include "storage/browser/fileapi/file_system_operation_context.h" #include "storage/browser/fileapi/file_system_usage_cache.h" #include "storage/browser/fileapi/obfuscated_file_util.h" +#include "storage/browser/fileapi/obfuscated_file_util_memory_delegate.h" #include "storage/browser/fileapi/sandbox_directory_database.h" #include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" #include "storage/browser/fileapi/sandbox_isolated_origin_database.h" @@ -60,11 +64,13 @@ namespace { +enum TestMode { kRegular, kIncognitoDisabled, kIncognitoEnabled }; + bool FileExists(const base::FilePath& path) { return base::PathExists(path) && !base::DirectoryExists(path); } -int64_t GetSize(const base::FilePath& path) { +int64_t GetLocalFileSize(const base::FilePath& path) { int64_t size; EXPECT_TRUE(base::GetFileSize(path, &size)); return size; @@ -153,19 +159,32 @@ // compliance test, and only the subclass-specific bits that look into the // implementation would need to be written per-subclass. class ObfuscatedFileUtilTest : public testing::Test, - public ::testing::WithParamInterface<bool> { + public ::testing::WithParamInterface<TestMode> { public: ObfuscatedFileUtilTest() - : is_incognito_(GetParam()), - scoped_task_environment_( + : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO), - origin_(GURL("http://www.example.com")), type_(storage::kFileSystemTypeTemporary), sandbox_file_system_(origin_, type_), quota_status_(blink::mojom::QuotaStatusCode::kUnknown), usage_(-1), - weak_factory_(this) {} + weak_factory_(this) { + if (GetParam() == TestMode::kRegular) { + is_incognito_ = false; + return; + } + is_incognito_ = true; + if (GetParam() == TestMode::kIncognitoDisabled) { + feature_list_.InitAndDisableFeature( + storage::features::kEnableFilesystemInIncognito); + } else { + feature_list_.InitAndEnableFeature( + storage::features::kEnableFilesystemInIncognito); + } + } + + bool in_memory_test() { return GetParam() == TestMode::kIncognitoEnabled; } void SetUp() override { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); @@ -187,8 +206,11 @@ // it creates another context, which creates another path manager, // another sandbox_backend, and another OFU. // We need to pass in the context to skip all that. - file_system_context_ = CreateFileSystemContextForTesting( - quota_manager_->proxy(), data_dir_.GetPath()); + file_system_context_ = + in_memory_test() ? CreateIncognitoFileSystemContextForTesting( + quota_manager_->proxy(), data_dir_.GetPath()) + : CreateFileSystemContextForTesting( + quota_manager_->proxy(), data_dir_.GetPath()); sandbox_file_system_.SetUp(file_system_context_.get()); @@ -315,6 +337,16 @@ return error == base::File::FILE_OK; } + int64_t GetPathSize(const FileSystemURL& url) { + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); + base::File::Info file_info; + base::FilePath platform_path; + EXPECT_EQ( + base::File::FILE_OK, + ofu()->GetFileInfo(context.get(), url, &file_info, &platform_path)); + return file_info.size; + } + bool DirectoryExists(const FileSystemURL& url) { return AsyncFileTestHelper::DirectoryExists(file_system_context(), url); } @@ -336,34 +368,45 @@ return sandbox_file_system_.CreateURL(path); } - void CheckFileAndCloseHandle(const FileSystemURL& url, base::File file) { + void CheckFile(const FileSystemURL& url) { std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); base::FilePath local_path; EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url, &local_path)); + EXPECT_EQ(0, GetPathSize(url)); base::File::Info file_info0; base::FilePath data_path; EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo(context.get(), url, &file_info0, &data_path)); EXPECT_EQ(data_path, local_path); - EXPECT_TRUE(FileExists(data_path)); - EXPECT_EQ(0, GetSize(data_path)); + EXPECT_EQ(!in_memory_test(), FileExists(data_path)); const char data[] = "test data"; const int length = base::size(data) - 1; - if (!file.IsValid()) { - file.Initialize(data_path, - base::File::FLAG_OPEN | base::File::FLAG_WRITE); + base::File file = ofu()->CreateOrOpen( + context.get(), url, base::File::FLAG_WRITE | base::File::FLAG_OPEN); + if (in_memory_test()) { + ASSERT_FALSE(file.IsValid()); + auto* memory_delegate = + static_cast<storage::ObfuscatedFileUtilMemoryDelegate*>( + ofu()->delegate()); + ASSERT_EQ( + length, + memory_delegate->WriteFile( + local_path, 0, + base::MakeRefCounted<net::StringIOBuffer>(data).get(), length)); + } else { ASSERT_TRUE(file.IsValid()); - EXPECT_FALSE(file.created()); + ASSERT_EQ(length, file.Write(0, data, length)); + file.Close(); } - ASSERT_EQ(length, file.Write(0, data, length)); - file.Close(); base::File::Info file_info1; - EXPECT_EQ(length, GetSize(data_path)); + if (!in_memory_test()) + EXPECT_EQ(length, GetLocalFileSize(data_path)); + EXPECT_EQ(length, GetPathSize(url)); context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo(context.get(), url, &file_info1, &data_path)); @@ -380,12 +423,12 @@ context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), url, length * 2)); - EXPECT_EQ(length * 2, GetSize(data_path)); + EXPECT_EQ(length * 2, GetPathSize(url)); context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), url, 0)); - EXPECT_EQ(0, GetSize(data_path)); + EXPECT_EQ(0, GetPathSize(url)); } void ValidateTestDirectory( @@ -615,7 +658,7 @@ &data_path)); EXPECT_NE(data_path, src_file_path); EXPECT_TRUE(FileExists(data_path)); - EXPECT_EQ(src_file_length, GetSize(data_path)); + EXPECT_EQ(src_file_length, GetLocalFileSize(data_path)); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(context.get(), dest_url)); @@ -687,10 +730,6 @@ } void MaybeDropDatabasesAliveCaseTestBody() { - // TODO(https://crbug.com/43417): Enable test after finishing incognito - // implementation. - if (is_incognito_) - return; std::unique_ptr<ObfuscatedFileUtil> file_util = CreateObfuscatedFileUtil(nullptr); file_util->InitOriginDatabase(GURL(), true /*create*/); @@ -721,10 +760,6 @@ } void DestroyDirectoryDatabase_IsolatedTestBody() { - // TODO(https://crbug.com/43417): Enable test after finishing incognito - // implementation. - if (is_incognito_) - return; storage_policy_->AddIsolated(origin_); std::unique_ptr<ObfuscatedFileUtil> file_util = CreateObfuscatedFileUtil(storage_policy_.get()); @@ -744,10 +779,6 @@ } void GetDirectoryDatabase_IsolatedTestBody() { - // TODO(https://crbug.com/43417): Enable test after finishing incognito - // implementation. - if (is_incognito_) - return; storage_policy_->AddIsolated(origin_); std::unique_ptr<ObfuscatedFileUtil> file_util = CreateObfuscatedFileUtil(storage_policy_.get()); @@ -781,8 +812,17 @@ const base::FilePath& data_dir_path() const { return data_dir_.GetPath(); } + void CheckFileSize(FileSystemURL& url, + base::FilePath& local_path, + int64_t expected_size) { + if (!in_memory_test()) + EXPECT_EQ(expected_size, GetLocalFileSize(local_path)); + EXPECT_EQ(expected_size, GetPathSize(url)); + } + protected: bool is_incognito_; + base::test::ScopedFeatureList feature_list_; std::unique_ptr<leveldb::Env> incognito_leveldb_environment_; base::test::ScopedTaskEnvironment scoped_task_environment_; base::ScopedTempDir data_dir_; @@ -802,16 +842,20 @@ DISALLOW_COPY_AND_ASSIGN(ObfuscatedFileUtilTest); }; -INSTANTIATE_TEST_SUITE_P(, ObfuscatedFileUtilTest, ::testing::Bool()); +INSTANTIATE_TEST_SUITE_P(, + ObfuscatedFileUtilTest, + testing::Values(TestMode::kRegular, + TestMode::kIncognitoDisabled, + TestMode::kIncognitoEnabled)); TEST_P(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { FileSystemURL url = CreateURLFromUTF8("fake/file"); std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); - int file_flags = base::File::FLAG_CREATE | base::File::FLAG_WRITE; + bool created; - base::File file = ofu()->CreateOrOpen(context.get(), url, file_flags); - EXPECT_FALSE(file.IsValid()); - EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file.error_details()); + base::File::Error result = + ofu()->EnsureFileExists(context.get(), url, &created); + EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, result); context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, @@ -825,25 +869,26 @@ context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(url.path()) - 1); - file = ofu()->CreateOrOpen(context.get(), url, file_flags); - EXPECT_FALSE(file.IsValid()); - ASSERT_EQ(base::File::FILE_ERROR_NO_SPACE, file.error_details()); + result = ofu()->EnsureFileExists(context.get(), url, &created); + ASSERT_EQ(base::File::FILE_ERROR_NO_SPACE, result); context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(url.path())); - file = ofu()->CreateOrOpen(context.get(), url, file_flags); - EXPECT_TRUE(file.IsValid()); - ASSERT_TRUE(file.created()); + created = false; + result = ofu()->EnsureFileExists(context.get(), url, &created); + ASSERT_EQ(base::File::FILE_OK, result); + ASSERT_TRUE(created); EXPECT_EQ(1, change_observer()->get_and_reset_create_file_count()); - CheckFileAndCloseHandle(url, std::move(file)); + CheckFile(url); context.reset(NewContext(nullptr)); base::FilePath local_path; EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url, &local_path)); - EXPECT_TRUE(base::PathExists(local_path)); + EXPECT_EQ(!in_memory_test(), base::PathExists(local_path)); + EXPECT_TRUE(PathExists(url)); // Verify that deleting a file isn't stopped by zero quota, and that it frees // up quote from its path. @@ -851,7 +896,7 @@ context->set_allowed_bytes_growth(0); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(context.get(), url)); EXPECT_EQ(1, change_observer()->get_and_reset_remove_file_count()); - EXPECT_FALSE(base::PathExists(local_path)); + EXPECT_FALSE(PathExists(url)); EXPECT_EQ(ObfuscatedFileUtil::ComputeFilePathCost(url.path()), context->allowed_bytes_growth()); @@ -868,22 +913,24 @@ EXPECT_EQ(3, change_observer()->get_and_reset_create_directory_count()); context.reset(NewContext(nullptr)); - file = ofu()->CreateOrOpen(context.get(), url, file_flags); - ASSERT_TRUE(file.IsValid()); - ASSERT_TRUE(file.created()); + created = false; + result = ofu()->EnsureFileExists(context.get(), url, &created); + ASSERT_TRUE(created); + ASSERT_EQ(base::File::FILE_OK, result); EXPECT_EQ(1, change_observer()->get_and_reset_create_file_count()); - CheckFileAndCloseHandle(url, std::move(file)); + CheckFile(url); context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url, &local_path)); - EXPECT_TRUE(base::PathExists(local_path)); + EXPECT_EQ(!in_memory_test(), base::PathExists(local_path)); + EXPECT_TRUE(PathExists(url)); context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(context.get(), url)); EXPECT_EQ(1, change_observer()->get_and_reset_remove_file_count()); - EXPECT_FALSE(base::PathExists(local_path)); + EXPECT_FALSE(PathExists(url)); // Make sure we have no unexpected changes. EXPECT_TRUE(change_observer()->HasNoChange()); @@ -907,17 +954,17 @@ base::FilePath local_path; EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url, &local_path)); - EXPECT_EQ(0, GetSize(local_path)); + CheckFileSize(url, local_path, 0); context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), url, 10)); EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count()); - EXPECT_EQ(10, GetSize(local_path)); + CheckFileSize(url, local_path, 10); context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), url, 1)); - EXPECT_EQ(1, GetSize(local_path)); EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count()); + CheckFileSize(url, local_path, 1); EXPECT_FALSE(DirectoryExists(url)); EXPECT_TRUE(PathExists(url)); @@ -968,16 +1015,20 @@ ASSERT_EQ(1019, ComputeTotalFileSize()); } - // Delete backing file to make following truncation fail. - base::FilePath local_path; - ASSERT_EQ(base::File::FILE_OK, - ofu()->GetLocalFilePath(UnlimitedContext().get(), url, - &local_path)); - ASSERT_FALSE(local_path.empty()); - ASSERT_TRUE(base::DeleteFile(local_path, false)); + if (!in_memory_test()) { + // Delete backing file to make following truncation fail. + base::FilePath local_path; + ASSERT_EQ( + base::File::FILE_OK, + ofu()->GetLocalFilePath(UnlimitedContext().get(), url, &local_path)); + ASSERT_FALSE(local_path.empty()); + ASSERT_TRUE(base::DeleteFile(local_path, false)); - EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, - ofu()->Truncate(LimitedContext(1234).get(), url, 1234)); + EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, + ofu()->Truncate(LimitedContext(1234).get(), url, 1234)); + } else { + EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(NewContext(nullptr), url)); + } ASSERT_EQ(0, ComputeTotalFileSize()); } @@ -1008,7 +1059,7 @@ ASSERT_TRUE(created); EXPECT_EQ(1, change_observer()->get_and_reset_create_file_count()); - CheckFileAndCloseHandle(url, base::File()); + CheckFile(url); context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, @@ -1520,6 +1571,9 @@ } TEST_P(ObfuscatedFileUtilTest, TestCopyInForeignFile) { + // TODO(crbug.com/93417): Update test for in-memory mode. + if (in_memory_test()) + return; TestCopyInForeignFileHelper(false /* overwrite */); TestCopyInForeignFileHelper(true /* overwrite */); } @@ -1641,6 +1695,9 @@ } TEST_P(ObfuscatedFileUtilTest, TestRevokeUsageCache) { + // TODO(crbug.com/93417): Update test for in-memory mode. + if (in_memory_test()) + return; std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); int64_t expected_quota = 0; @@ -1751,14 +1808,12 @@ ofu()->DestroyDirectoryDatabase(origin(), type_string()); context.reset(NewContext(nullptr)); - base::File file = - ofu()->CreateOrOpen(context.get(), kPath1, - base::File::FLAG_READ | base::File::FLAG_CREATE); - EXPECT_TRUE(file.IsValid()); - EXPECT_TRUE(file.created()); + created = false; + EXPECT_EQ(base::File::FILE_OK, + ofu()->EnsureFileExists(context.get(), kPath1, &created)); + EXPECT_TRUE(created); - EXPECT_TRUE(file.GetInfo(&file_info)); - EXPECT_EQ(0, file_info.size); + EXPECT_EQ(0, GetPathSize(kPath1)); } TEST_P(ObfuscatedFileUtilTest, TestIncompleteDirectoryReading) { @@ -1784,10 +1839,7 @@ file_system_context(), empty_path, &entries)); EXPECT_EQ(3u, entries.size()); - base::FilePath local_path; - EXPECT_EQ(base::File::FILE_OK, - ofu()->GetLocalFilePath(context.get(), kPath[0], &local_path)); - EXPECT_TRUE(base::DeleteFile(local_path, false)); + EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(context.get(), kPath[0])); entries.clear(); EXPECT_EQ(base::File::FILE_OK, @@ -1839,32 +1891,26 @@ url = FileSystemURLAppendUTF8(dir_url, "CreateOrOpen_file"); ClearTimestamp(dir_url); context.reset(NewContext(nullptr)); - base::File file = - ofu()->CreateOrOpen(context.get(), url, - base::File::FLAG_CREATE | base::File::FLAG_WRITE); - - EXPECT_TRUE(file.IsValid()); - EXPECT_TRUE(file.created()); - file.Close(); + created = false; + EXPECT_EQ(base::File::FILE_OK, + ofu()->EnsureFileExists(context.get(), url, &created)); + EXPECT_TRUE(created); EXPECT_NE(base::Time(), GetModifiedTime(dir_url)); // open case. ClearTimestamp(dir_url); context.reset(NewContext(nullptr)); - file = ofu()->CreateOrOpen(context.get(), url, - base::File::FLAG_OPEN | base::File::FLAG_WRITE); - EXPECT_TRUE(file.IsValid()); - EXPECT_FALSE(file.created()); - file.Close(); + EXPECT_EQ(base::File::FILE_OK, + ofu()->EnsureFileExists(context.get(), url, &created)); + EXPECT_FALSE(created); EXPECT_EQ(base::Time(), GetModifiedTime(dir_url)); // fail case ClearTimestamp(dir_url); context.reset(NewContext(nullptr)); - file = ofu()->CreateOrOpen(context.get(), url, - base::File::FLAG_CREATE | base::File::FLAG_WRITE); - EXPECT_FALSE(file.IsValid()); - EXPECT_EQ(base::File::FILE_ERROR_EXISTS, file.error_details()); + EXPECT_EQ(base::File::FILE_OK, + ofu()->EnsureFileExists(context.get(), url, &created)); + EXPECT_FALSE(created); EXPECT_EQ(base::Time(), GetModifiedTime(dir_url)); // CreateDirectory, create case. @@ -2334,12 +2380,10 @@ ASSERT_EQ(0, ComputeTotalFileSize()); // Opening it, which shouldn't change the usage. - base::File file = - ofu()->CreateOrOpen(AllowUsageIncrease(0)->context(), url, - base::File::FLAG_OPEN | base::File::FLAG_WRITE); - ASSERT_TRUE(file.IsValid()); + ASSERT_EQ( + base::File::FILE_OK, + ofu()->EnsureFileExists(AllowUsageIncrease(0)->context(), url, &created)); ASSERT_EQ(0, ComputeTotalFileSize()); - file.Close(); const int length = 33; ASSERT_EQ(base::File::FILE_OK, @@ -2347,10 +2391,17 @@ AllowUsageIncrease(length)->context(), url, length)); ASSERT_EQ(length, ComputeTotalFileSize()); + // TODO(https://crbug.com/936722): After CreateOrOpen is modified to return + // file error instead of file, the in-memory test can proceed through the next + // steps. + if (in_memory_test()) + return; + // Opening it with CREATE_ALWAYS flag, which should truncate the file size. - file = ofu()->CreateOrOpen( - AllowUsageIncrease(-length)->context(), url, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); + base::File file = ofu()->CreateOrOpen( + AllowUsageIncrease(-length)->context(), url, + base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); + ASSERT_TRUE(file.IsValid()); ASSERT_EQ(0, ComputeTotalFileSize()); file.Close(); @@ -2395,11 +2446,9 @@ ofu()->EnsureFileExists(UnlimitedContext().get(), url, &created)); ASSERT_TRUE(created); - int file_flags = base::File::FLAG_CREATE | base::File::FLAG_WRITE; - base::File file = - ofu()->CreateOrOpen(UnlimitedContext().get(), path_in_file, file_flags); - ASSERT_FALSE(file.IsValid()); - ASSERT_EQ(base::File::FILE_ERROR_NOT_A_DIRECTORY, file.error_details()); + ASSERT_EQ(base::File::FILE_ERROR_NOT_A_DIRECTORY, + ofu()->EnsureFileExists(UnlimitedContext().get(), path_in_file, + &created)); ASSERT_EQ(base::File::FILE_ERROR_NOT_A_DIRECTORY, ofu()->CreateDirectory(UnlimitedContext().get(),
diff --git a/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc b/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc index d50a6e83..5bca9d4d 100644 --- a/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc +++ b/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc
@@ -422,8 +422,10 @@ base::FilePath base_path = GetBaseDirectoryForOriginAndType(origin_url, type, false); - if (base_path.empty() || !base::DirectoryExists(base_path)) + if (base_path.empty() || + !obfuscated_file_util()->delegate()->DirectoryExists(base_path)) { return 0; + } base::FilePath usage_file_path = base_path.Append(FileSystemUsageCache::kUsageFileName);
diff --git a/storage/browser/test/sandbox_file_system_test_helper.cc b/storage/browser/test/sandbox_file_system_test_helper.cc index cc2d38cb..c353dd69 100644 --- a/storage/browser/test/sandbox_file_system_test_helper.cc +++ b/storage/browser/test/sandbox_file_system_test_helper.cc
@@ -14,6 +14,7 @@ #include "storage/browser/fileapi/file_system_operation_runner.h" #include "storage/browser/fileapi/file_system_url.h" #include "storage/browser/fileapi/file_system_usage_cache.h" +#include "storage/browser/fileapi/obfuscated_file_util.h" #include "storage/browser/fileapi/sandbox_file_system_backend.h" #include "storage/browser/quota/quota_manager_proxy.h" #include "storage/browser/test/mock_special_storage_policy.h" @@ -102,14 +103,17 @@ int64_t SandboxFileSystemTestHelper::ComputeCurrentOriginUsage() { usage_cache()->CloseCacheFiles(); - int64_t size = base::ComputeDirectorySize(GetOriginRootPath()); - if (base::PathExists(GetUsageCachePath())) + + int64_t size = + file_util_delegate()->ComputeDirectorySize(GetOriginRootPath()); + if (file_util_delegate()->PathExists(GetUsageCachePath())) size -= storage::FileSystemUsageCache::kUsageFileSize; + return size; } int64_t SandboxFileSystemTestHelper::ComputeCurrentDirectoryDatabaseUsage() { - return base::ComputeDirectorySize( + return file_util_delegate()->ComputeDirectorySize( GetOriginRootPath().AppendASCII("Paths")); } @@ -143,6 +147,13 @@ return file_system_context()->sandbox_delegate()->usage_cache(); } +storage::ObfuscatedFileUtilDelegate* +SandboxFileSystemTestHelper::file_util_delegate() { + return file_system_context_->sandbox_delegate() + ->obfuscated_file_util() + ->delegate(); +} + void SandboxFileSystemTestHelper::SetUpFileSystem() { DCHECK(file_system_context_.get()); DCHECK(file_system_context_->sandbox_backend()->CanHandleType(type_)); @@ -154,7 +165,9 @@ file_system_context_->sandbox_delegate()-> GetBaseDirectoryForOriginAndType(origin_, type_, true /* create */); - // Initialize the usage cache file. + // Initialize the usage cache file. The directory does not exist and should be + // created for in memory tests. + base::CreateDirectory(GetUsageCachePath().DirName()); base::FilePath usage_cache_path = GetUsageCachePath(); if (!usage_cache_path.empty()) usage_cache()->UpdateUsage(usage_cache_path, 0);
diff --git a/storage/browser/test/sandbox_file_system_test_helper.h b/storage/browser/test/sandbox_file_system_test_helper.h index c7d532e1..cf1712e 100644 --- a/storage/browser/test/sandbox_file_system_test_helper.h +++ b/storage/browser/test/sandbox_file_system_test_helper.h
@@ -32,6 +32,7 @@ class FileSystemFileUtil; class FileSystemOperationContext; class FileSystemOperationRunner; +class ObfuscatedFileUtilDelegate; } namespace content { @@ -93,6 +94,8 @@ storage::FileSystemFileUtil* file_util() const { return file_util_; } storage::FileSystemUsageCache* usage_cache(); + storage::ObfuscatedFileUtilDelegate* file_util_delegate(); + private: void SetUpFileSystem();
diff --git a/storage/browser/test/test_file_system_options.cc b/storage/browser/test/test_file_system_options.cc index f0d30056..809c8cf9 100644 --- a/storage/browser/test/test_file_system_options.cc +++ b/storage/browser/test/test_file_system_options.cc
@@ -18,7 +18,7 @@ additional_allowed_schemes.push_back("chrome-extension"); #endif return FileSystemOptions(FileSystemOptions::PROFILE_MODE_INCOGNITO, - false /* force_in_memory */, + true /* force_in_memory */, additional_allowed_schemes); }
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_relr_relocations.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_relr_relocations.cpp index 10a47d1..740d7d74 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_relr_relocations.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_relr_relocations.cpp
@@ -4,6 +4,8 @@ #include "crazy_linker_relr_relocations.h" +#include <type_traits> + namespace crazy { // Apply a single RELR relocation at virtual |offset| address, using @@ -35,6 +37,12 @@ // An odd value corresponds to a bitmap of 31 or 63 words, based // on the CPU bitness / word_size. ELF::Addr offset = base; + + // Right shift of signed integers has undefined behaviour before C++20. + static_assert( + std::is_unsigned<decltype(entry)>::value, + "The ELF::Relr type should be unsigned to avoid undefined behaviour"); + while (entry != 0) { entry >>= 1; if ((entry & 1) != 0)
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_relr_relocations_unittest.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_relr_relocations_unittest.cpp index 8d3162b..c35e9c2 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_relr_relocations_unittest.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_relr_relocations_unittest.cpp
@@ -71,7 +71,7 @@ ELF::Relr relr_table[kRelrSize] = {}; for (size_t n = 0; n < kDataSize; ++n) { if ((n % 3) == 0) - relr_table[n / kBitsPerWord] |= (1 | (2 << (n % kBitsPerWord))); + relr_table[n / kBitsPerWord] |= 1U | (ELF::Relr(2) << (n % kBitsPerWord)); } RelrRelocations relr; relr.SetAddress(reinterpret_cast<uintptr_t>(relr_table));
diff --git a/third_party/blink/public/platform/web_runtime_features.h b/third_party/blink/public/platform/web_runtime_features.h index 2c0bc8cc..dd4a7aa 100644 --- a/third_party/blink/public/platform/web_runtime_features.h +++ b/third_party/blink/public/platform/web_runtime_features.h
@@ -171,7 +171,8 @@ BLINK_PLATFORM_EXPORT static void EnableScriptedSpeechRecognition(bool); BLINK_PLATFORM_EXPORT static void EnableScriptedSpeechSynthesis(bool); BLINK_PLATFORM_EXPORT static void EnableScrollAnchorSerialization(bool); - BLINK_PLATFORM_EXPORT static void EnableSecMetadata(bool); + BLINK_PLATFORM_EXPORT static void EnableFetchMetadata(bool); + BLINK_PLATFORM_EXPORT static void EnableFetchMetadataDestination(bool); BLINK_PLATFORM_EXPORT static void EnableSharedArrayBuffer(bool); BLINK_PLATFORM_EXPORT static void EnableSharedWorker(bool); BLINK_PLATFORM_EXPORT static void EnableTextFragmentAnchor(bool);
diff --git a/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc b/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc index 41825fc..0f74638 100644 --- a/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc
@@ -10,6 +10,7 @@ #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "third_party/blink/renderer/core/testing/garbage_collected_script_wrappable.h" #include "third_party/blink/renderer/platform/heap/heap.h" +#include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/vector.h" #define TEST_TOV8(expected, value) \ @@ -55,6 +56,8 @@ }; class OffHeapGarbageCollectedHolder { + STACK_ALLOCATED(); + public: OffHeapGarbageCollectedHolder( GarbageCollectedScriptWrappable* script_wrappable)
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_embedder_graph_builder.cc b/third_party/blink/renderer/bindings/core/v8/v8_embedder_graph_builder.cc index 3d10cec..096a4c1 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_embedder_graph_builder.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_embedder_graph_builder.cc
@@ -11,6 +11,7 @@ #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" +#include "third_party/blink/renderer/platform/wtf/allocator.h" namespace blink { @@ -89,6 +90,8 @@ }; class NodeBuilder final { + USING_FAST_MALLOC(NodeBuilder); + public: explicit NodeBuilder(Graph* graph) : graph_(graph) {} @@ -202,6 +205,8 @@ }; class State final { + USING_FAST_MALLOC(State); + public: State(Traceable traceable, const char* name, DomTreeState dom_tree_state) : traceable_(traceable), name_(name), dom_tree_state_(dom_tree_state) {} @@ -248,6 +253,8 @@ // WorklistItemBase is used for different kinds of items that require // processing the regular worklist. class WorklistItemBase { + USING_FAST_MALLOC(WorklistItemBase); + public: explicit WorklistItemBase(State* parent, State* to_process) : parent_(parent), to_process_(to_process) {}
diff --git a/third_party/blink/renderer/bindings/scripts/code_generator_v8.py b/third_party/blink/renderer/bindings/scripts/code_generator_v8.py index 60d3d3a..95564ba 100644 --- a/third_party/blink/renderer/bindings/scripts/code_generator_v8.py +++ b/third_party/blink/renderer/bindings/scripts/code_generator_v8.py
@@ -202,7 +202,8 @@ cpp_template_filename = 'interface.cc.tmpl' interface_context = v8_interface.interface_context - template_context = interface_context(interface, definitions.interfaces) + component_info = self.info_provider.component_info + template_context = interface_context(interface, definitions.interfaces, component_info) includes.update(interface_info.get('cpp_includes', {}).get(component, set())) if not interface.is_partial and not is_testing_target(full_path): template_context['header_includes'].add(self.info_provider.include_path_for_export) @@ -237,8 +238,9 @@ header_template = self.jinja_env.get_template('dictionary_v8.h.tmpl') cpp_template = self.jinja_env.get_template('dictionary_v8.cc.tmpl') interface_info = interfaces_info[dictionary_name] + component_info = self.info_provider.component_info template_context = v8_dictionary.dictionary_context( - dictionary, interfaces_info) + dictionary, interfaces_info, component_info) include_paths = interface_info.get('dependencies_include_paths') # Add the include for interface itself template_context['header_includes'].add(interface_info['include_path'])
diff --git a/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py b/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py index 0bafc86..4930013a 100755 --- a/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py +++ b/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py
@@ -55,6 +55,7 @@ from utilities import read_idl_files_list_from_file from utilities import shorten_union_name from utilities import to_snake_case +from utilities import read_pickle_file from utilities import write_pickle_file @@ -75,6 +76,7 @@ parser.add_option('--idl-files-list', help='file listing IDL files') parser.add_option('--interfaces-info-file', help='interface info pickle file') parser.add_option('--component-info-file', help='component wide info pickle file') + parser.add_option('--runtime-enabled-features-file', help='runtime-enabled features pickle file') options, args = parser.parse_args() if options.interfaces_info_file is None: @@ -329,12 +331,13 @@ 'partial_interface_files': dict(self.partial_interface_files), } - def get_component_info_as_dict(self): + def get_component_info_as_dict(self, runtime_enabled_features): """Returns component wide information as a dict.""" return { 'callback_functions': self.callback_functions, 'enumerations': dict((enum.name, enum.values) for enum in self.enumerations.values()), + 'runtime_enabled_features': runtime_enabled_features, 'typedefs': self.typedefs, 'union_types': self.union_types, } @@ -357,8 +360,9 @@ write_pickle_file(options.interfaces_info_file, info_collector.get_info_as_dict()) + runtime_enabled_features = read_pickle_file(options.runtime_enabled_features_file) write_pickle_file(options.component_info_file, - info_collector.get_component_info_as_dict()) + info_collector.get_component_info_as_dict(runtime_enabled_features)) if __name__ == '__main__': sys.exit(main())
diff --git a/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py b/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py index 9eb6063..0ec3953 100755 --- a/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py +++ b/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py
@@ -20,7 +20,7 @@ from utilities import (create_component_info_provider, write_file, idl_filename_to_component) from v8_utilities import (binding_header_filename, v8_class_name, - v8_class_name_or_partial) + v8_class_name_or_partial, origin_trial_feature_name) # Make sure extension is .py, not .pyc or .pyo, so doesn't depend on caching MODULE_PYNAME = os.path.splitext(os.path.basename(__file__))[0] + '.py' @@ -39,7 +39,7 @@ be installed on those interfaces. """ return [ - {'condition': 'origin_trials::%sEnabled' % feature_name, + {'condition': 'RuntimeEnabledFeatures::%sEnabled' % feature_name, 'name': feature_name, 'install_method': 'Install%s' % feature_name, 'interface_is_global': interface_info.is_global, @@ -49,19 +49,19 @@ for interface_info in interfaces] -def get_origin_trial_feature_names_from_interface(interface): +def get_origin_trial_feature_names_from_interface(interface, runtime_features): feature_names = set() - if ('OriginTrialEnabled' in interface.extended_attributes and - interface.is_partial): - feature_names.add(interface.extended_attributes['OriginTrialEnabled']) + + def add_if_not_none(value): + if value: + feature_names.add(value) + + if interface.is_partial: + add_if_not_none(origin_trial_feature_name(interface, runtime_features)) for operation in interface.operations: - if 'OriginTrialEnabled' in operation.extended_attributes: - feature_names.add( - operation.extended_attributes['OriginTrialEnabled']) + add_if_not_none(origin_trial_feature_name(operation, runtime_features)) for attribute in interface.attributes: - if 'OriginTrialEnabled' in attribute.extended_attributes: - feature_names.add( - attribute.extended_attributes['OriginTrialEnabled']) + add_if_not_none(origin_trial_feature_name(attribute, runtime_features)) return feature_names @@ -91,10 +91,11 @@ features_for_type = defaultdict(set) types_for_feature = defaultdict(set) include_files = set() + runtime_features = info_provider.component_info['runtime_enabled_features'] for idl_filename in idl_filenames: interface, includes = read_idl_file(reader, idl_filename) - feature_names = get_origin_trial_feature_names_from_interface(interface) + feature_names = get_origin_trial_feature_names_from_interface(interface, runtime_features) # If this interface is a mixin, we don't generate V8 bindings code for # it. @@ -108,7 +109,7 @@ mixin, _ = read_idl_file( reader, info_provider.interfaces_info[include.mixin].get('full_path')) - feature_names |= get_origin_trial_feature_names_from_interface(mixin) + feature_names |= get_origin_trial_feature_names_from_interface(mixin, runtime_features) feature_names = list(feature_names) if feature_names:
diff --git a/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py b/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py index 58dd824..aa33eb1 100644 --- a/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py +++ b/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py
@@ -85,10 +85,11 @@ indexed_property_getter = None is_global = False named_property_getter = None + component_info = self._info_provider.component_info if interface.name in SNAPSHOTTED_INTERFACES: - attributes = [v8_attributes.attribute_context(interface, attribute, interfaces) + attributes = [v8_attributes.attribute_context(interface, attribute, interfaces, component_info) for attribute in interface.attributes] - methods = v8_interface.methods_context(interface)['methods'] + methods = v8_interface.methods_context(interface, component_info)['methods'] is_global = 'Global' in interface.extended_attributes named_property_getter = v8_interface.property_getter(
diff --git a/third_party/blink/renderer/bindings/scripts/scripts.gni b/third_party/blink/renderer/bindings/scripts/scripts.gni index 7d31660..eae3faf3 100644 --- a/third_party/blink/renderer/bindings/scripts/scripts.gni +++ b/third_party/blink/renderer/bindings/scripts/scripts.gni
@@ -92,8 +92,14 @@ visibility = invoker.visibility } - inputs = [ "$bindings_scripts_dir/utilities.py" ] + idl_compiler_files + - invoker.sources + build_scripts_output_dir = + "$root_gen_dir/third_party/blink/renderer/build/scripts" + runtime_enabled_features_file = + "$build_scripts_output_dir/runtime_enabled_features.pickle" + inputs = [ + "$bindings_scripts_dir/utilities.py", + runtime_enabled_features_file, + ] + idl_compiler_files + invoker.sources outputs = [ invoker.interfaces_info_file, invoker.component_info_file, @@ -109,9 +115,14 @@ rebase_path(invoker.interfaces_info_file, root_build_dir), "--component-info-file", rebase_path(invoker.component_info_file, root_build_dir), + "--runtime-enabled-features-file", + rebase_path(runtime_enabled_features_file, root_build_dir), ] - deps = [ "//third_party/blink/renderer/bindings/scripts:cached_lex_yacc_tables" ] + invoker.deps + deps = [ + "//third_party/blink/renderer/bindings/scripts:cached_lex_yacc_tables", + "//third_party/blink/renderer/platform:runtime_enabled_features", + ] + invoker.deps } }
diff --git a/third_party/blink/renderer/bindings/scripts/v8_attributes.py b/third_party/blink/renderer/bindings/scripts/v8_attributes.py index 3e875c8..bad74d2c 100644 --- a/third_party/blink/renderer/bindings/scripts/v8_attributes.py +++ b/third_party/blink/renderer/bindings/scripts/v8_attributes.py
@@ -51,7 +51,7 @@ uncapitalize, extended_attribute_value_as_list, is_unforgeable) -def attribute_context(interface, attribute, interfaces): +def attribute_context(interface, attribute, interfaces, component_info): """Creates a Jinja template context for an attribute of an interface. Args: @@ -59,6 +59,7 @@ attribute: An attribute to create the context for interfaces: A dict which maps an interface name to the definition which can be referred if needed + component_info: A dict containing component wide information Returns: A Jinja template context for |attribute| @@ -135,6 +136,8 @@ (constructor_type and not (measure_as or deprecate_as)) or \ (str(idl_type) == 'Window' and attribute.name in ('frames', 'self', 'window')) + runtime_features = component_info['runtime_enabled_features'] + context = { 'activity_logging_world_list_for_getter': v8_utilities.activity_logging_world_list(attribute, 'Getter'), # [ActivityLogging] 'activity_logging_world_list_for_setter': v8_utilities.activity_logging_world_list(attribute, 'Setter'), # [ActivityLogging] @@ -194,7 +197,7 @@ 'on_instance': v8_utilities.on_instance(interface, attribute), 'on_interface': v8_utilities.on_interface(interface, attribute), 'on_prototype': v8_utilities.on_prototype(interface, attribute), - 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(attribute), # [OriginTrialEnabled] + 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(attribute, runtime_features), # [OriginTrialEnabled] 'use_output_parameter_for_result': idl_type.use_output_parameter_for_result, 'measure_as': measure_as, 'name': attribute.name, @@ -203,7 +206,7 @@ 'reflect_invalid': extended_attributes.get('ReflectInvalid', ''), 'reflect_missing': extended_attributes.get('ReflectMissing'), 'reflect_only': extended_attribute_value_as_list(attribute, 'ReflectOnly'), - 'runtime_enabled_feature_name': v8_utilities.runtime_enabled_feature_name(attribute), # [RuntimeEnabled] + 'runtime_enabled_feature_name': v8_utilities.runtime_enabled_feature_name(attribute, runtime_features), # [RuntimeEnabled] 'secure_context_test': v8_utilities.secure_context(attribute, interface), # [SecureContext] 'cached_accessor_name': '%s%sCachedAccessor' % (interface.name, attribute.name.capitalize()), 'world_suffixes': (
diff --git a/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py b/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py index d61d406..d1e2f8e 100644 --- a/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py +++ b/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py
@@ -75,7 +75,7 @@ IdlTypeBase.callback_cpp_type = property(_cpp_type) -def callback_interface_context(callback_interface, _): +def callback_interface_context(callback_interface, _, component_info): is_legacy_callback_interface = len(callback_interface.constants) > 0 includes.clear() @@ -102,7 +102,7 @@ break return { - 'constants': [constant_context(constant, callback_interface) + 'constants': [constant_context(constant, callback_interface, component_info) for constant in callback_interface.constants], 'cpp_class': callback_interface.name, 'do_not_check_constants': 'DoNotCheckConstants' in callback_interface.extended_attributes,
diff --git a/third_party/blink/renderer/bindings/scripts/v8_dictionary.py b/third_party/blink/renderer/bindings/scripts/v8_dictionary.py index e06325a..88f010f 100644 --- a/third_party/blink/renderer/bindings/scripts/v8_dictionary.py +++ b/third_party/blink/renderer/bindings/scripts/v8_dictionary.py
@@ -58,7 +58,7 @@ # Context for V8 bindings -def dictionary_context(dictionary, interfaces_info): +def dictionary_context(dictionary, interfaces_info, component_info): includes.clear() includes.update(DICTIONARY_CPP_INCLUDES) @@ -66,7 +66,7 @@ raise Exception( 'Dictionary cannot be RuntimeEnabled: %s' % dictionary.name) - members = [member_context(dictionary, member) + members = [member_context(dictionary, member, component_info) for member in sorted(dictionary.members, key=operator.attrgetter('name'))] @@ -80,6 +80,7 @@ if member['origin_trial_feature_name']: has_origin_trial_members = True includes.add('core/origin_trials/origin_trials.h') + includes.add('core/execution_context/execution_context.h') break cpp_class = v8_utilities.cpp_name(dictionary) @@ -105,7 +106,7 @@ return context -def member_context(dictionary, member): +def member_context(_, member, component_info): extended_attributes = member.extended_attributes idl_type = member.idl_type idl_type.add_includes_for_type(extended_attributes) @@ -148,6 +149,7 @@ has_value_or_default = snake_case_name + "_has_value_or_default" getter_name = getter_name_for_dictionary_member(member) is_deprecated_dictionary = unwrapped_idl_type.name == 'Dictionary' + runtime_features = component_info['runtime_enabled_features'] return { 'cpp_default_value': cpp_default_value, @@ -171,8 +173,8 @@ 'is_string_type': idl_type.preprocessed_type.is_string_type, 'is_required': member.is_required, 'name': member.name, - 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(member), # [OriginTrialEnabled] - 'runtime_enabled_feature_name': v8_utilities.runtime_enabled_feature_name(member), # [RuntimeEnabled] + 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(member, runtime_features), # [OriginTrialEnabled] + 'runtime_enabled_feature_name': v8_utilities.runtime_enabled_feature_name(member, runtime_features), # [RuntimeEnabled] 'setter_name': setter_name_for_dictionary_member(member), 'has_value_or_default': has_value_or_default, 'null_setter_name': null_setter_name_for_dictionary_member(member),
diff --git a/third_party/blink/renderer/bindings/scripts/v8_interface.py b/third_party/blink/renderer/bindings/scripts/v8_interface.py index e587f236..bcd1627 100644 --- a/third_party/blink/renderer/bindings/scripts/v8_interface.py +++ b/third_party/blink/renderer/bindings/scripts/v8_interface.py
@@ -151,7 +151,8 @@ if features: includes.add('platform/bindings/script_state.h') - includes.add('core/origin_trials/origin_trials.h') + includes.add('platform/runtime_enabled_features.h') + includes.add('core/execution_context/execution_context.h') return features @@ -194,13 +195,15 @@ 'named_property_setter_counter': counter_prefix + 'NamedPropertySetter', } -def interface_context(interface, interfaces): + +def interface_context(interface, interfaces, component_info): """Creates a Jinja template context for an interface. Args: interface: An interface to create the context for interfaces: A dict which maps an interface name to the definition which can be referred if needed + component_info: A dict containing component wide information Returns: A Jinja template context for |interface| @@ -279,6 +282,8 @@ needs_runtime_enabled_installer = v8_class_name in [ 'V8Window', 'V8HTMLDocument', 'V8Document', 'V8Node', 'V8EventTarget'] + runtime_features = component_info['runtime_enabled_features'] + context = { 'active_scriptwrappable': active_scriptwrappable, 'context_enabled_feature_name': context_enabled_feature_name(interface), # [ContextEnabled] @@ -304,11 +309,11 @@ 'is_typed_array_type': is_typed_array_type, 'measure_as': v8_utilities.measure_as(interface, None), # [MeasureAs] 'needs_runtime_enabled_installer': needs_runtime_enabled_installer, - 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(interface), + 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(interface, runtime_features), 'parent_interface': parent_interface, 'pass_cpp_type': cpp_name(interface) + '*', 'runtime_call_stats': runtime_call_stats_context(interface), - 'runtime_enabled_feature_name': runtime_enabled_feature_name(interface), # [RuntimeEnabled] + 'runtime_enabled_feature_name': runtime_enabled_feature_name(interface, runtime_features), # [RuntimeEnabled] 'snake_case_v8_class': NameStyleConverter(v8_class_name).to_snake_case(), 'v8_class': v8_class_name, 'v8_class_or_partial': v8_class_name_or_partial, @@ -369,10 +374,10 @@ unscopables = [] for attribute in interface.attributes: if 'Unscopable' in attribute.extended_attributes: - unscopables.append((attribute.name, runtime_enabled_feature_name(attribute))) + unscopables.append((attribute.name, runtime_enabled_feature_name(attribute, runtime_features))) for method in interface.operations: if 'Unscopable' in method.extended_attributes: - unscopables.append((method.name, runtime_enabled_feature_name(method))) + unscopables.append((method.name, runtime_enabled_feature_name(method, runtime_features))) # [CEReactions] setter_or_deleters = ( @@ -399,12 +404,12 @@ # Constants context.update({ - 'constants': [constant_context(constant, interface) for constant in interface.constants], + 'constants': [constant_context(constant, interface, component_info) for constant in interface.constants], 'do_not_check_constants': 'DoNotCheckConstants' in extended_attributes, }) # Attributes - attributes = attributes_context(interface, interfaces) + attributes = attributes_context(interface, interfaces, component_info) context.update({ 'attributes': attributes, @@ -427,7 +432,7 @@ }) # Methods - context.update(methods_context(interface)) + context.update(methods_context(interface, component_info)) methods = context['methods'] context.update({ 'has_origin_safe_method_setter': any(method['is_cross_origin'] and not method['is_unforgeable'] @@ -525,7 +530,7 @@ return context -def attributes_context(interface, interfaces): +def attributes_context(interface, interfaces, component_info): """Creates a list of Jinja template contexts for attributes of an interface. Args: @@ -537,7 +542,7 @@ A list of attribute contexts """ - attributes = [v8_attributes.attribute_context(interface, attribute, interfaces) + attributes = [v8_attributes.attribute_context(interface, attribute, interfaces, component_info) for attribute in interface.attributes] has_conditional_attributes = any(attribute['exposed_test'] for attribute in attributes) @@ -559,16 +564,17 @@ size_attribute.is_read_only = True size_attribute.extended_attributes['NotEnumerable'] = None attributes.append(v8_attributes.attribute_context( - interface, size_attribute, interfaces)) + interface, size_attribute, interfaces, component_info)) return attributes -def methods_context(interface): +def methods_context(interface, component_info): """Creates a list of Jinja template contexts for methods of an interface. Args: interface: An interface to create contexts for + component_info: A dict containing component wide information Returns: A dictionary with 3 keys: @@ -581,16 +587,16 @@ methods = [] if interface.original_interface: - methods.extend([v8_methods.method_context(interface, operation, is_visible=False) + methods.extend([v8_methods.method_context(interface, operation, component_info, is_visible=False) for operation in interface.original_interface.operations if operation.name]) - methods.extend([v8_methods.method_context(interface, method) + methods.extend([v8_methods.method_context(interface, method, component_info) for method in interface.operations if method.name]) # Skip anonymous special operations (methods) if interface.partial_interfaces: assert len(interface.partial_interfaces) == len(set(interface.partial_interfaces)) for partial_interface in interface.partial_interfaces: - methods.extend([v8_methods.method_context(interface, operation, is_visible=False) + methods.extend([v8_methods.method_context(interface, operation, component_info, is_visible=False) for operation in partial_interface.operations if operation.name]) compute_method_overloads_context(interface, methods) @@ -606,7 +612,7 @@ if implemented_as is None: implemented_as = name + 'ForBinding' operation.extended_attributes['ImplementedAs'] = implemented_as - return v8_methods.method_context(interface, operation) + return v8_methods.method_context(interface, operation, component_info) def generated_argument(idl_type, name, is_optional=False, extended_attributes=None): argument = IdlArgument() @@ -815,8 +821,9 @@ # [DeprecateAs], [OriginTrialEnabled], [Reflect], [RuntimeEnabled] -def constant_context(constant, interface): +def constant_context(constant, interface, component_info): extended_attributes = constant.extended_attributes + runtime_features = component_info['runtime_enabled_features'] return { 'camel_case_name': NameStyleConverter(constant.name).to_upper_camel_case(), @@ -827,11 +834,11 @@ 'measure_as': v8_utilities.measure_as(constant, interface), # [MeasureAs] 'high_entropy': v8_utilities.high_entropy(constant), # [HighEntropy] 'name': constant.name, - 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(constant), # [OriginTrialEnabled] + 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(constant, runtime_features), # [OriginTrialEnabled] # FIXME: use 'reflected_name' as correct 'name' 'rcs_counter': 'Blink_' + v8_utilities.cpp_name(interface) + '_' + constant.name + '_ConstantGetter', 'reflected_name': extended_attributes.get('Reflect', reflected_name(constant.name)), - 'runtime_enabled_feature_name': runtime_enabled_feature_name(constant), # [RuntimeEnabled] + 'runtime_enabled_feature_name': runtime_enabled_feature_name(constant, runtime_features), # [RuntimeEnabled] 'value': constant.value, }
diff --git a/third_party/blink/renderer/bindings/scripts/v8_methods.py b/third_party/blink/renderer/bindings/scripts/v8_methods.py index 47fb7ab..4f38701 100644 --- a/third_party/blink/renderer/bindings/scripts/v8_methods.py +++ b/third_party/blink/renderer/bindings/scripts/v8_methods.py
@@ -126,7 +126,7 @@ } -def method_context(interface, method, is_visible=True): +def method_context(interface, method, component_info, is_visible=True): arguments = method.arguments extended_attributes = method.extended_attributes idl_type = method.idl_type @@ -182,6 +182,8 @@ argument_context(interface, method, argument, index, is_visible=is_visible) for index, argument in enumerate(arguments)] + runtime_features = component_info['runtime_enabled_features'] + return { 'activity_logging_world_list': v8_utilities.activity_logging_world_list(method), # [ActivityLogging] 'arguments': argument_contexts, @@ -238,11 +240,11 @@ 'on_instance': v8_utilities.on_instance(interface, method), 'on_interface': v8_utilities.on_interface(interface, method), 'on_prototype': v8_utilities.on_prototype(interface, method), - 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(method), # [OriginTrialEnabled] + 'origin_trial_feature_name': v8_utilities.origin_trial_feature_name(method, runtime_features), # [OriginTrialEnabled] 'property_attributes': property_attributes(interface, method), 'returns_promise': method.returns_promise, 'runtime_call_stats': runtime_call_stats_context(interface, method), - 'runtime_enabled_feature_name': v8_utilities.runtime_enabled_feature_name(method), # [RuntimeEnabled] + 'runtime_enabled_feature_name': v8_utilities.runtime_enabled_feature_name(method, runtime_features), # [RuntimeEnabled] 'secure_context_test': v8_utilities.secure_context(method, interface), # [SecureContext] 'side_effect_type': side_effect_type, # [Affects] 'snake_case_name': NameStyleConverter(name).to_snake_case(),
diff --git a/third_party/blink/renderer/bindings/scripts/v8_utilities.py b/third_party/blink/renderer/bindings/scripts/v8_utilities.py index 4483e47..9eecac3 100644 --- a/third_party/blink/renderer/bindings/scripts/v8_utilities.py +++ b/third_party/blink/renderer/bindings/scripts/v8_utilities.py
@@ -425,17 +425,32 @@ # [OriginTrialEnabled] -def origin_trial_feature_name(definition_or_member): - """Returns the name of the feature for the OriginTrialEnabled attribute. +def _is_origin_trial_feature(feature_name, runtime_features): + assert feature_name in runtime_features, feature_name + ' is not a runtime feature.' + feature = runtime_features[feature_name] + return feature['in_origin_trial'] - An exception is raised if OriginTrialEnabled is used in conjunction with any - of the following (which must be mutually exclusive with origin trials): - - RuntimeEnabled - If the OriginTrialEnabled extended attribute is found, the includes are - also updated as a side-effect. +def origin_trial_feature_name(definition_or_member, runtime_features): + """ + Returns the name of the origin trial feature if found, None otherwise. + Looks for origin trial feature specified by either OriginTrialEnabled or + RuntimeEnabled attributes. + + An exception is raised if OriginTrialEnabled is used in conjunction with + RuntimeEnabled attribute. + + If the feature name is found, the includes are also updated as a side-effect. """ extended_attributes = definition_or_member.extended_attributes + feature_name = extended_attributes.get('RuntimeEnabled') + if feature_name and _is_origin_trial_feature(feature_name, runtime_features): + return feature_name + + # TODO(yashard): Remove this part. + # This part handles the deprecated OriginTrialEnabled attribute. Remove this + # logic after the support for origin trial features through RuntimeEnabled + # attribute is added. feature_name = extended_attributes.get('OriginTrialEnabled') if feature_name and 'RuntimeEnabled' in extended_attributes: @@ -448,7 +463,7 @@ def origin_trial_function_call(feature_name, execution_context=None): """Returns a function call to determine if an origin trial is enabled.""" - return 'origin_trials::{feature_name}Enabled({context})'.format( + return 'RuntimeEnabledFeatures::{feature_name}Enabled({context})'.format( feature_name=feature_name, context=execution_context if execution_context else "execution_context") @@ -469,12 +484,12 @@ # [RuntimeEnabled] -def runtime_enabled_feature_name(definition_or_member): +def runtime_enabled_feature_name(definition_or_member, runtime_features): extended_attributes = definition_or_member.extended_attributes - if 'RuntimeEnabled' not in extended_attributes: - return None - includes.add('platform/runtime_enabled_features.h') - return extended_attributes['RuntimeEnabled'] + feature_name = extended_attributes.get('RuntimeEnabled') + if feature_name and not _is_origin_trial_feature(feature_name, runtime_features): + includes.add('platform/runtime_enabled_features.h') + return feature_name # [Unforgeable]
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_constants.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_constants.idl index 8c604a6..d19752f 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_constants.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_constants.idl
@@ -27,13 +27,17 @@ // Extended attributes [DeprecateAs=Constant] const short DEPRECATED_CONSTANT = 1; [MeasureAs=Constant] const short MEASURED_CONSTANT = 1; - [RuntimeEnabled=FeatureName1] const short FEATURE1_ENABLED_CONST1 = 1; - [RuntimeEnabled=FeatureName1] const short FEATURE1_ENABLED_CONST2 = 2; - [RuntimeEnabled=FeatureName2] const short FEATURE2_ENABLED_CONST1 = 3; - [RuntimeEnabled=FeatureName2] const short FEATURE2_ENABLED_CONST2 = 4; + [RuntimeEnabled=RuntimeFeature1] const short FEATURE1_ENABLED_CONST1 = 1; + [RuntimeEnabled=RuntimeFeature1] const short FEATURE1_ENABLED_CONST2 = 2; + [RuntimeEnabled=RuntimeFeature2] const short FEATURE2_ENABLED_CONST1 = 3; + [RuntimeEnabled=RuntimeFeature2] const short FEATURE2_ENABLED_CONST2 = 4; [OriginTrialEnabled=FeatureName1] const short FEATURE1_ORIGIN_TRIAL_ENABLED_CONST1 = 6; [OriginTrialEnabled=FeatureName1] const short FEATURE1_ORIGIN_TRIAL_ENABLED_CONST2 = 7; [OriginTrialEnabled=FeatureName2] const short FEATURE2_ORIGIN_TRIAL_ENABLED_CONST1 = 8; [OriginTrialEnabled=FeatureName2] const short FEATURE2_ORIGIN_TRIAL_ENABLED_CONST2 = 9; + [RuntimeEnabled=OriginTrialFeature1] const short FEATURE3_ORIGIN_TRIAL_ENABLED_CONST1 = 10; + [RuntimeEnabled=OriginTrialFeature1] const short FEATURE3_ORIGIN_TRIAL_ENABLED_CONST2 = 11; + [RuntimeEnabled=OriginTrialFeature2] const short FEATURE4_ORIGIN_TRIAL_ENABLED_CONST1 = 12; + [RuntimeEnabled=OriginTrialFeature2] const short FEATURE4_ORIGIN_TRIAL_ENABLED_CONST2 = 13; [Reflect=CONST_IMPL] const short CONST_JAVASCRIPT = 1; };
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_dictionary.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_dictionary.idl index baa9a92f..d597473f 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_dictionary.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_dictionary.idl
@@ -41,6 +41,8 @@ [RuntimeEnabled=RuntimeFeature] boolean runtimeSecondMember; [OriginTrialEnabled=FeatureName] boolean originTrialMember; [OriginTrialEnabled=FeatureName1] boolean originTrialSecondMember; + [RuntimeEnabled=OriginTrialFeature] boolean originTrialThirdMember; + [RuntimeEnabled=OriginTrialFeature1] boolean originTrialFourthMember; record<ByteString, byte> recordMember; record<USVString, TestObject> garbageCollectedRecordMember; record<ByteString, (long or boolean)> unionInRecordMember;
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_interface.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_interface.idl index 7ccf5620..9e30358 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_interface.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_interface.idl
@@ -36,8 +36,8 @@ Custom=LegacyCallAsFunction, DoNotCheckConstants, ImplementedAs=TestInterfaceImplementation, - RuntimeEnabled=FeatureName, - ContextEnabled=FeatureName, + RuntimeEnabled=RuntimeFeature, + ContextEnabled=RuntimeFeature, Exposed=(Worker,Window) ] interface TestInterface : TestInterfaceEmpty { // members needed to test [ImplementedAs], as this affect attribute @@ -58,13 +58,13 @@ attribute DOMStringOrDouble stringOrDoubleAttribute; attribute [EnforceRange] long withExtendedAttributeStringAttribute; [ImplementedAs=CapitalImplementation] attribute Implementation uncapitalAttribute; - [RuntimeEnabled=FeatureName] attribute long conditionalLongAttribute; - [RuntimeEnabled=FeatureName] readonly attribute long conditionalReadOnlyLongAttribute; + [RuntimeEnabled=RuntimeFeature] attribute long conditionalLongAttribute; + [RuntimeEnabled=RuntimeFeature] readonly attribute long conditionalReadOnlyLongAttribute; static attribute DOMString staticStringAttribute; static attribute TestInterface staticReturnDOMWrapperAttribute; static readonly attribute DOMString staticReadOnlyStringAttribute; static readonly attribute TestInterface staticReadOnlyReturnDOMWrapperAttribute; - [RuntimeEnabled=FeatureName] static readonly attribute long staticConditionalReadOnlyLongAttribute; + [RuntimeEnabled=RuntimeFeature] static readonly attribute long staticConditionalReadOnlyLongAttribute; attribute [TreatNullAs=EmptyString] DOMString stringNullAsEmptyAttribute; attribute USVString? usvStringOrNullAttribute; @@ -91,6 +91,7 @@ [Exposed=Worker] void workerExposedMethod(); [Exposed=Window] void windowExposedMethod(); [Exposed=Window,OriginTrialEnabled=TestFeature] void originTrialWindowExposedMethod(); + [Exposed=Window,RuntimeEnabled=OriginTrialFeature] void originTrialWindowExposedMethod2(); static void alwaysExposedStaticMethod(); [Exposed=Worker] static void workerExposedStaticMethod(); @@ -101,10 +102,10 @@ [Exposed=Worker] attribute long workerExposedAttribute; [Exposed=Window] attribute long windowExposedAttribute; - [Exposed=Window, RuntimeEnabled=FeatureName] void methodWithExposedAndRuntimeEnabledFlag(); + [Exposed=Window, RuntimeEnabled=RuntimeFeature] void methodWithExposedAndRuntimeEnabledFlag(); [Exposed=Window] void overloadMethodWithExposedAndRuntimeEnabledFlag(long longArg); - [Exposed=Window, RuntimeEnabled=FeatureName] void overloadMethodWithExposedAndRuntimeEnabledFlag(DOMString string); - [Exposed=Window, RuntimeEnabled=FeatureName2] void overloadMethodWithExposedAndRuntimeEnabledFlag(Window window); + [Exposed=Window, RuntimeEnabled=RuntimeFeature] void overloadMethodWithExposedAndRuntimeEnabledFlag(DOMString string); + [Exposed=Window, RuntimeEnabled=RuntimeFeature2] void overloadMethodWithExposedAndRuntimeEnabledFlag(Window window); [Exposed(Window FeatureName, Worker FeatureName2)] void methodWithExposedHavingRuntimeEnabldFlag();
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_2.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_2.idl index 39f0c26..210d569 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_2.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_2.idl
@@ -41,7 +41,7 @@ Exposed(Window FeatureName) // Conflicts with Exposed=(Window,Worker) ] interface TestInterface2 { // This interface has only runtime enabled constants. - [RuntimeEnabled=FeatureName] const unsigned short CONST_VALUE_1 = 1; + [RuntimeEnabled=RuntimeFeature] const unsigned short CONST_VALUE_1 = 1; // Indexed property operations with an identifier [RaisesException] getter TestInterfaceEmpty item(unsigned long index);
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_check_security.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_check_security.idl index bc241e8..4794143 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_check_security.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_check_security.idl
@@ -43,6 +43,6 @@ [CrossOrigin, PerWorldBindings] void doNotCheckSecurityPerWorldBindingsVoidMethod(); [CrossOrigin, Unforgeable] void doNotCheckSecurityUnforgeableVoidMethod(); [CrossOrigin] void doNotCheckSecurityVoidOverloadMethod(String argument1, String argument2); - [CrossOrigin, RuntimeEnabled=FeatureName] void doNotCheckSecurityVoidOverloadMethod(String argument1, optional long argument2); - [SecureContext, RuntimeEnabled=FeatureName] void secureContextRuntimeEnabledMethod(String arg); + [CrossOrigin, RuntimeEnabled=RuntimeFeature] void doNotCheckSecurityVoidOverloadMethod(String argument1, optional long argument2); + [SecureContext, RuntimeEnabled=RuntimeFeature] void secureContextRuntimeEnabledMethod(String arg); };
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_mixin.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_mixin.idl index 4fa87f9..a1d6481 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_mixin.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_mixin.idl
@@ -39,7 +39,7 @@ const unsigned short MIXIN_CONSTANT_1 = 1; [Reflect=MIXIN_REFLECT_CONSTANT] const unsigned short MIXIN_CONSTANT_2 = 2; - [RuntimeEnabled=MixinFeatureName] attribute Node mixinRuntimeEnabledNodeAttribute; + [RuntimeEnabled=MixinRuntimeFeature] attribute Node mixinRuntimeEnabledNodeAttribute; [NotEnumerable] stringifier; };
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_mixin_2.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_mixin_2.idl index 7f940c4..946cab8 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_mixin_2.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_mixin_2.idl
@@ -30,7 +30,7 @@ [ LegacyTreatAsPartialInterface, // Conflicts with default mixin behavior - RuntimeEnabled=Mixin2FeatureName // conflicts with [RuntimeEnabled] on member + RuntimeEnabled=Mixin2RuntimeFeature // conflicts with [RuntimeEnabled] on member ] interface mixin TestInterfaceMixin2 { attribute DOMString mixin2StringAttribute; void mixin2VoidMethod();
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_origin_trial_enabled.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_origin_trial_enabled.idl index 959db4b..6b1f656 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_origin_trial_enabled.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_origin_trial_enabled.idl
@@ -13,10 +13,10 @@ const short CONST_JAVASCRIPT = 1; attribute double doubleAttribute; - [RuntimeEnabled=FeatureName] attribute long conditionalLongAttribute; - [RuntimeEnabled=FeatureName] readonly attribute long conditionalReadOnlyLongAttribute; + [RuntimeEnabled=RuntimeFeature] attribute long conditionalLongAttribute; + [RuntimeEnabled=RuntimeFeature] readonly attribute long conditionalReadOnlyLongAttribute; static attribute DOMString staticStringAttribute; - [RuntimeEnabled=FeatureName] static readonly attribute long staticConditionalReadOnlyLongAttribute; + [RuntimeEnabled=RuntimeFeature] static readonly attribute long staticConditionalReadOnlyLongAttribute; void voidMethodDoubleArgFloatArg(double doubleArg, float floatArg);
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_partial.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_partial.idl index fe896b2..1b464bd 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_interface_partial.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_interface_partial.idl
@@ -38,7 +38,7 @@ [Custom] callback PartialCallbackType = void (PartialString value); [ ImplementedAs=TestInterfacePartial, - RuntimeEnabled=PartialFeatureName + RuntimeEnabled=PartialRuntimeFeature ] partial interface TestInterface { const unsigned short PARTIAL_UNSIGNED_SHORT = 0; const double PARTIAL_DOUBLE = 3.14;
diff --git a/third_party/blink/renderer/bindings/tests/idls/core/test_object.idl b/third_party/blink/renderer/bindings/tests/idls/core/test_object.idl index 51fa5e7..cffc076 100644 --- a/third_party/blink/renderer/bindings/tests/idls/core/test_object.idl +++ b/third_party/blink/renderer/bindings/tests/idls/core/test_object.idl
@@ -157,6 +157,7 @@ [MeasureAs=TestFeature] attribute long measureAsLongAttribute; [NotEnumerable] attribute long notEnumerableLongAttribute; [OriginTrialEnabled=FeatureName] attribute long originTrialEnabledLongAttribute; + [RuntimeEnabled=OriginTrialFeature] attribute long originTrialEnabledLongAttribute2; [PerWorldBindings] readonly attribute TestInterfaceEmpty perWorldBindingsReadonlyTestInterfaceEmptyAttribute; [LogActivity, LogAllWorlds, PerWorldBindings] attribute long activityLoggingAccessPerWorldBindingsLongAttribute; [LogActivity, PerWorldBindings] attribute long activityLoggingAccessForIsolatedWorldsPerWorldBindingsLongAttribute; @@ -200,7 +201,7 @@ [Replaceable] readonly attribute long replaceableReadonlyLongAttribute; [PutForwards=href] readonly attribute TestNode locationPutForwards; - [RuntimeEnabled=FeatureName] attribute long runtimeEnabledLongAttribute; + [RuntimeEnabled=RuntimeFeature] attribute long runtimeEnabledLongAttribute; [SetterCallWith=ExecutionContext] attribute DOMString setterCallWithExecutionContextStringAttribute; attribute [TreatNullAs=EmptyString] DOMString treatNullAsEmptyStringStringAttribute; [Reflect, URL] attribute DOMString urlStringAttribute; @@ -212,9 +213,9 @@ [SameObject, SaveSameObject] static readonly attribute TestInterface staticSaveSameObjectAttribute; [Unscopable] attribute long unscopableLongAttribute; [Unscopable, OriginTrialEnabled=FeatureName] attribute long unscopableOriginTrialEnabledLongAttribute; - [Unscopable, RuntimeEnabled=FeatureName] attribute long unscopableRuntimeEnabledLongAttribute; + [Unscopable, RuntimeEnabled=RuntimeFeature] attribute long unscopableRuntimeEnabledLongAttribute; [Unscopable] void unscopableVoidMethod(); - [Unscopable, RuntimeEnabled=FeatureName] void unscopableRuntimeEnabledVoidMethod(); + [Unscopable, RuntimeEnabled=RuntimeFeature] void unscopableRuntimeEnabledVoidMethod(); // Methods // @@ -521,14 +522,14 @@ [RaisesException] TestInterfaceEmpty raisesExceptionTestInterfaceEmptyVoidMethod(); [RaisesException] XPathNSResolver raisesExceptionXPathNSResolverVoidMethod(); [CallWith=ExecutionContext, RaisesException] void callWithExecutionContextRaisesExceptionVoidMethodLongArg(long longArg); - [RuntimeEnabled=FeatureName] void runtimeEnabledVoidMethod(); - [PerWorldBindings, RuntimeEnabled=FeatureName] void perWorldBindingsRuntimeEnabledVoidMethod(); - [RuntimeEnabled=FeatureName] void runtimeEnabledOverloadedVoidMethod(DOMString stringArg); - [RuntimeEnabled=FeatureName] void runtimeEnabledOverloadedVoidMethod(long longArg); - [RuntimeEnabled=FeatureName1] void partiallyRuntimeEnabledOverloadedVoidMethod(DOMString stringArg); - [RuntimeEnabled=FeatureName2] void partiallyRuntimeEnabledOverloadedVoidMethod(TestInterface testInterfaceArg); + [RuntimeEnabled=RuntimeFeature] void runtimeEnabledVoidMethod(); + [PerWorldBindings, RuntimeEnabled=RuntimeFeature] void perWorldBindingsRuntimeEnabledVoidMethod(); + [RuntimeEnabled=RuntimeFeature] void runtimeEnabledOverloadedVoidMethod(DOMString stringArg); + [RuntimeEnabled=RuntimeFeature] void runtimeEnabledOverloadedVoidMethod(long longArg); + [RuntimeEnabled=RuntimeFeature1] void partiallyRuntimeEnabledOverloadedVoidMethod(DOMString stringArg); + [RuntimeEnabled=RuntimeFeature2] void partiallyRuntimeEnabledOverloadedVoidMethod(TestInterface testInterfaceArg); void partiallyRuntimeEnabledOverloadedVoidMethod(long longArg, DOMString stringArg); - [RuntimeEnabled=FeatureName3] void partiallyRuntimeEnabledOverloadedVoidMethod(long longArg, DOMString stringArg, TestInterface testInterfaceArg); + [RuntimeEnabled=RuntimeFeature3] void partiallyRuntimeEnabledOverloadedVoidMethod(long longArg, DOMString stringArg, TestInterface testInterfaceArg); // Avoid redundant type checking void useToImpl4ArgumentsCheckingIfPossibleWithOptionalArg(Node node1, optional Node node2); void useToImpl4ArgumentsCheckingIfPossibleWithNullableArg(Node node1, Node? node2); @@ -543,5 +544,5 @@ attribute TestInterface testInterfaceAttribute; // [ImplementedAs] maplike<[EnforceRange] long, DOMStringOrDouble>; - [RuntimeEnabled=FeatureName, CallWith=ScriptState, RaisesException, ImplementedAs=myMaplikeClear] boolean clear(); + [RuntimeEnabled=RuntimeFeature, CallWith=ScriptState, RaisesException, ImplementedAs=myMaplikeClear] boolean clear(); };
diff --git a/third_party/blink/renderer/bindings/tests/idls/modules/test_interface_2_partial.idl b/third_party/blink/renderer/bindings/tests/idls/modules/test_interface_2_partial.idl index 34da9ce..fe11d22 100644 --- a/third_party/blink/renderer/bindings/tests/idls/modules/test_interface_2_partial.idl +++ b/third_party/blink/renderer/bindings/tests/idls/modules/test_interface_2_partial.idl
@@ -9,10 +9,10 @@ // TestInterface2Partial2.idl). // // This test ensures that TestInterface2Partial2 is NOT conditional on the -// Interface2PartialFeatureName runtime flag. +// Interface2PartialRuntimeFeature runtime flag. [ ImplementedAs=TestInterface2Partial, - RuntimeEnabled=Interface2PartialFeatureName + RuntimeEnabled=Interface2PartialRuntimeFeature ] partial interface TestInterface2 { void voidMethodPartial1(DOMString value);
diff --git a/third_party/blink/renderer/bindings/tests/idls/modules/test_interface_5.idl b/third_party/blink/renderer/bindings/tests/idls/modules/test_interface_5.idl index 6962d83a..aa560bf 100644 --- a/third_party/blink/renderer/bindings/tests/idls/modules/test_interface_5.idl +++ b/third_party/blink/renderer/bindings/tests/idls/modules/test_interface_5.idl
@@ -39,7 +39,7 @@ Custom=LegacyCallAsFunction, DoNotCheckConstants, ImplementedAs=TestInterface5Implementation, - RuntimeEnabled=FeatureName, + RuntimeEnabled=RuntimeFeature, Exposed=(Worker,Window) ] interface TestInterface5 : TestInterfaceEmpty { // members needed to test [ImplementedAs], as this affect attribute
diff --git a/third_party/blink/renderer/bindings/tests/idls/runtime_enabled_features.json5 b/third_party/blink/renderer/bindings/tests/idls/runtime_enabled_features.json5 new file mode 100644 index 0000000..1f962be6 --- /dev/null +++ b/third_party/blink/renderer/bindings/tests/idls/runtime_enabled_features.json5
@@ -0,0 +1,61 @@ +{ + // This list declares all [RuntimeEnabled] test features in the test idls. + // It is used to determine whether the feature is a runtime feature or an + // origin trial feature. + // + // Use one of the existing features here or add new ones for your tests. + + parameters: { + // Used to specify if the feature is an origin trial feature. + in_origin_trial: { + valid_type: "bool", + default: false, + }, + }, + + data: [ + { + name: "Interface2PartialRuntimeFeature", + }, + { + name: "MixinRuntimeFeature", + }, + { + name: "Mixin2RuntimeFeature", + }, + { + name: "OriginTrialFeature", + in_origin_trial: true, + }, + { + name: "OriginTrialFeature1", + in_origin_trial: true, + }, + { + name: "OriginTrialFeature2", + in_origin_trial: true, + }, + { + name: "OriginTrialFeature3", + in_origin_trial: true, + }, + { + name: "PartialRuntimeFeature", + }, + { + name: "RuntimeFeature", + }, + { + name: "RuntimeFeature1", + }, + { + name: "RuntimeFeature2", + }, + { + name: "RuntimeFeature3", + }, + { + name: "SecureFeature", + }, + ], +}
diff --git a/third_party/blink/renderer/bindings/tests/results/core/origin_trial_features_for_core.cc b/third_party/blink/renderer/bindings/tests/results/core/origin_trial_features_for_core.cc index 9f2cb3a..eb8ab96e 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/origin_trial_features_for_core.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/origin_trial_features_for_core.cc
@@ -60,13 +60,21 @@ // TODO(iclelland): Extract this common code out of OriginTrialFeaturesForCore // and OriginTrialFeaturesForModules into a block. if (wrapper_type_info == V8TestInterface::GetWrapperTypeInfo()) { - if (origin_trials::TestFeatureEnabled(execution_context)) { + if (RuntimeEnabledFeatures::OriginTrialFeatureEnabled(execution_context)) { + V8TestInterface::InstallOriginTrialFeature( + isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + } + if (RuntimeEnabledFeatures::TestFeatureEnabled(execution_context)) { V8TestInterface::InstallTestFeature( isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); } } if (wrapper_type_info == V8TestObject::GetWrapperTypeInfo()) { - if (origin_trials::FeatureNameEnabled(execution_context)) { + if (RuntimeEnabledFeatures::OriginTrialFeatureEnabled(execution_context)) { + V8TestObject::InstallOriginTrialFeature( + isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + } + if (RuntimeEnabledFeatures::FeatureNameEnabled(execution_context)) { V8TestObject::InstallFeatureName( isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); } @@ -93,6 +101,19 @@ } break; } + case OriginTrialFeature::kOriginTrialFeature: { + if (context_data->GetExistingConstructorAndPrototypeForType( + V8TestInterface::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { + V8TestInterface::InstallOriginTrialFeature( + isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + } + if (context_data->GetExistingConstructorAndPrototypeForType( + V8TestObject::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { + V8TestObject::InstallOriginTrialFeature( + isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + } + break; + } case OriginTrialFeature::kTestFeature: { if (context_data->GetExistingConstructorAndPrototypeForType( V8TestInterface::GetWrapperTypeInfo(), &prototype_object, &interface_object)) {
diff --git a/third_party/blink/renderer/bindings/tests/results/core/test_dictionary.h b/third_party/blink/renderer/bindings/tests/results/core/test_dictionary.h index 3a16af6..56dd9686 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/test_dictionary.h +++ b/third_party/blink/renderer/bindings/tests/results/core/test_dictionary.h
@@ -242,6 +242,13 @@ void setObjectOrNullMember(ScriptValue); void setObjectOrNullMemberToNull(); + bool hasOriginTrialFourthMember() const { return has_origin_trial_fourth_member_; } + bool originTrialFourthMember() const { + DCHECK(has_origin_trial_fourth_member_); + return origin_trial_fourth_member_; + } + inline void setOriginTrialFourthMember(bool); + bool hasOriginTrialMember() const { return has_origin_trial_member_; } bool originTrialMember() const { DCHECK(has_origin_trial_member_); @@ -256,6 +263,13 @@ } inline void setOriginTrialSecondMember(bool); + bool hasOriginTrialThirdMember() const { return has_origin_trial_third_member_; } + bool originTrialThirdMember() const { + DCHECK(has_origin_trial_third_member_); + return origin_trial_third_member_; + } + inline void setOriginTrialThirdMember(bool); + bool hasOtherDoubleOrStringMember() const { return !other_double_or_string_member_.IsNull(); } const DoubleOrString& otherDoubleOrStringMember() const { return other_double_or_string_member_; @@ -474,8 +488,10 @@ bool has_is_public_ = false; bool has_long_member_ = false; bool has_member_with_hyphen_in_name_ = false; + bool has_origin_trial_fourth_member_ = false; bool has_origin_trial_member_ = false; bool has_origin_trial_second_member_ = false; + bool has_origin_trial_third_member_ = false; bool has_record_member_ = false; bool has_restricted_double_member_ = false; bool has_runtime_member_ = false; @@ -521,8 +537,10 @@ bool member_with_hyphen_in_name_; ScriptValue object_member_; ScriptValue object_or_null_member_; + bool origin_trial_fourth_member_; bool origin_trial_member_; bool origin_trial_second_member_; + bool origin_trial_third_member_; DoubleOrString other_double_or_string_member_; Vector<std::pair<String, int8_t>> record_member_; Member<V8VoidCallbackFunction> required_callback_function_member_; @@ -630,6 +648,11 @@ has_member_with_hyphen_in_name_ = true; } +void TestDictionary::setOriginTrialFourthMember(bool value) { + origin_trial_fourth_member_ = value; + has_origin_trial_fourth_member_ = true; +} + void TestDictionary::setOriginTrialMember(bool value) { origin_trial_member_ = value; has_origin_trial_member_ = true; @@ -640,6 +663,11 @@ has_origin_trial_second_member_ = true; } +void TestDictionary::setOriginTrialThirdMember(bool value) { + origin_trial_third_member_ = value; + has_origin_trial_third_member_ = true; +} + void TestDictionary::setRestrictedDoubleMember(double value) { restricted_double_member_ = value; has_restricted_double_member_ = true;
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_constants.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_constants.cc index d4bed19..47a7db5 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_constants.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_constants.cc
@@ -17,7 +17,6 @@ #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/deprecation.h" #include "third_party/blink/renderer/core/frame/use_counter.h" -#include "third_party/blink/renderer/core/origin_trials/origin_trials.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" @@ -157,6 +156,10 @@ static_assert(7 == TestConstants::kFeature1OriginTrialEnabledConst2, "the value of TestConstants_kFeature1OriginTrialEnabledConst2 does not match with implementation"); static_assert(8 == TestConstants::kFeature2OriginTrialEnabledConst1, "the value of TestConstants_kFeature2OriginTrialEnabledConst1 does not match with implementation"); static_assert(9 == TestConstants::kFeature2OriginTrialEnabledConst2, "the value of TestConstants_kFeature2OriginTrialEnabledConst2 does not match with implementation"); + static_assert(10 == TestConstants::kFeature3OriginTrialEnabledConst1, "the value of TestConstants_kFeature3OriginTrialEnabledConst1 does not match with implementation"); + static_assert(11 == TestConstants::kFeature3OriginTrialEnabledConst2, "the value of TestConstants_kFeature3OriginTrialEnabledConst2 does not match with implementation"); + static_assert(12 == TestConstants::kFeature4OriginTrialEnabledConst1, "the value of TestConstants_kFeature4OriginTrialEnabledConst1 does not match with implementation"); + static_assert(13 == TestConstants::kFeature4OriginTrialEnabledConst2, "the value of TestConstants_kFeature4OriginTrialEnabledConst2 does not match with implementation"); static_assert(1 == TestConstants::CONST_IMPL, "the value of TestConstants_CONST_IMPL does not match with implementation"); // Custom signature @@ -177,7 +180,7 @@ ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. - if (RuntimeEnabledFeatures::FeatureName1Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature1Enabled()) { static constexpr V8DOMConfiguration::ConstantConfiguration kConfigurations[] = { {"FEATURE1_ENABLED_CONST1", V8DOMConfiguration::kConstantTypeShort, static_cast<int>(1)}, {"FEATURE1_ENABLED_CONST2", V8DOMConfiguration::kConstantTypeShort, static_cast<int>(2)}, @@ -186,7 +189,7 @@ isolate, interface_template, prototype_template, kConfigurations, base::size(kConfigurations)); } - if (RuntimeEnabledFeatures::FeatureName2Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature2Enabled()) { static constexpr V8DOMConfiguration::ConstantConfiguration kConfigurations[] = { {"FEATURE2_ENABLED_CONST1", V8DOMConfiguration::kConstantTypeShort, static_cast<int>(3)}, {"FEATURE2_ENABLED_CONST2", V8DOMConfiguration::kConstantTypeShort, static_cast<int>(4)}, @@ -261,6 +264,68 @@ InstallFeatureName2(script_state, v8::Local<v8::Object>()); } +void V8TestConstants::InstallOriginTrialFeature1( + v8::Isolate* isolate, + const DOMWrapperWorld& world, + v8::Local<v8::Object> instance, + v8::Local<v8::Object> prototype, + v8::Local<v8::Function> interface) { + static constexpr V8DOMConfiguration::ConstantConfiguration + kFEATURE3ORIGINTRIALENABLEDCONST1Configuration = {"FEATURE3_ORIGIN_TRIAL_ENABLED_CONST1", V8DOMConfiguration::kConstantTypeShort, static_cast<int>(10)}; + V8DOMConfiguration::InstallConstant( + isolate, interface, prototype, kFEATURE3ORIGINTRIALENABLEDCONST1Configuration); + static constexpr V8DOMConfiguration::ConstantConfiguration + kFEATURE3ORIGINTRIALENABLEDCONST2Configuration = {"FEATURE3_ORIGIN_TRIAL_ENABLED_CONST2", V8DOMConfiguration::kConstantTypeShort, static_cast<int>(11)}; + V8DOMConfiguration::InstallConstant( + isolate, interface, prototype, kFEATURE3ORIGINTRIALENABLEDCONST2Configuration); +} + +void V8TestConstants::InstallOriginTrialFeature1( + ScriptState* script_state, v8::Local<v8::Object> instance) { + V8PerContextData* per_context_data = script_state->PerContextData(); + v8::Local<v8::Object> prototype = per_context_data->PrototypeForType( + V8TestConstants::GetWrapperTypeInfo()); + v8::Local<v8::Function> interface = per_context_data->ConstructorForType( + V8TestConstants::GetWrapperTypeInfo()); + ALLOW_UNUSED_LOCAL(interface); + InstallOriginTrialFeature1(script_state->GetIsolate(), script_state->World(), instance, prototype, interface); +} + +void V8TestConstants::InstallOriginTrialFeature1(ScriptState* script_state) { + InstallOriginTrialFeature1(script_state, v8::Local<v8::Object>()); +} + +void V8TestConstants::InstallOriginTrialFeature2( + v8::Isolate* isolate, + const DOMWrapperWorld& world, + v8::Local<v8::Object> instance, + v8::Local<v8::Object> prototype, + v8::Local<v8::Function> interface) { + static constexpr V8DOMConfiguration::ConstantConfiguration + kFEATURE4ORIGINTRIALENABLEDCONST1Configuration = {"FEATURE4_ORIGIN_TRIAL_ENABLED_CONST1", V8DOMConfiguration::kConstantTypeShort, static_cast<int>(12)}; + V8DOMConfiguration::InstallConstant( + isolate, interface, prototype, kFEATURE4ORIGINTRIALENABLEDCONST1Configuration); + static constexpr V8DOMConfiguration::ConstantConfiguration + kFEATURE4ORIGINTRIALENABLEDCONST2Configuration = {"FEATURE4_ORIGIN_TRIAL_ENABLED_CONST2", V8DOMConfiguration::kConstantTypeShort, static_cast<int>(13)}; + V8DOMConfiguration::InstallConstant( + isolate, interface, prototype, kFEATURE4ORIGINTRIALENABLEDCONST2Configuration); +} + +void V8TestConstants::InstallOriginTrialFeature2( + ScriptState* script_state, v8::Local<v8::Object> instance) { + V8PerContextData* per_context_data = script_state->PerContextData(); + v8::Local<v8::Object> prototype = per_context_data->PrototypeForType( + V8TestConstants::GetWrapperTypeInfo()); + v8::Local<v8::Function> interface = per_context_data->ConstructorForType( + V8TestConstants::GetWrapperTypeInfo()); + ALLOW_UNUSED_LOCAL(interface); + InstallOriginTrialFeature2(script_state->GetIsolate(), script_state->World(), instance, prototype, interface); +} + +void V8TestConstants::InstallOriginTrialFeature2(ScriptState* script_state) { + InstallOriginTrialFeature2(script_state, v8::Local<v8::Object>()); +} + v8::Local<v8::FunctionTemplate> V8TestConstants::DomTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world) { return V8DOMConfiguration::DomClassTemplate(
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_constants.h b/third_party/blink/renderer/bindings/tests/results/core/v8_test_constants.h index b05cb0a..4557820 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_constants.h +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_constants.h
@@ -53,6 +53,14 @@ static void InstallFeatureName2(ScriptState*, v8::Local<v8::Object> instance); static void InstallFeatureName2(ScriptState*); + static void InstallOriginTrialFeature1(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface); + static void InstallOriginTrialFeature1(ScriptState*, v8::Local<v8::Object> instance); + static void InstallOriginTrialFeature1(ScriptState*); + + static void InstallOriginTrialFeature2(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface); + static void InstallOriginTrialFeature2(ScriptState*, v8::Local<v8::Object> instance); + static void InstallOriginTrialFeature2(ScriptState*); + // Callback functions CORE_EXPORT static void DEPRECATEDCONSTANTConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&); CORE_EXPORT static void MEASUREDCONSTANTConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_dictionary.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_dictionary.cc index f0c425d..7fde8bc 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_dictionary.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_dictionary.cc
@@ -25,6 +25,7 @@ #include "third_party/blink/renderer/bindings/core/v8/v8_treat_non_object_as_null_void_function.h" #include "third_party/blink/renderer/bindings/core/v8/v8_uint8_array.h" #include "third_party/blink/renderer/bindings/core/v8/v8_void_callback_function.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/deprecation.h" #include "third_party/blink/renderer/core/origin_trials/origin_trials.h" #include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h" @@ -65,8 +66,10 @@ "member-with-hyphen-in-name", "objectMember", "objectOrNullMember", + "originTrialFourthMember", "originTrialMember", "originTrialSecondMember", + "originTrialThirdMember", "otherDoubleOrStringMember", "public", "recordMember", @@ -573,7 +576,7 @@ } v8::Local<v8::Value> other_double_or_string_member_value; - if (!v8Object->Get(context, keys[31].Get(isolate)).ToLocal(&other_double_or_string_member_value)) { + if (!v8Object->Get(context, keys[33].Get(isolate)).ToLocal(&other_double_or_string_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -588,7 +591,7 @@ } v8::Local<v8::Value> public_value; - if (!v8Object->Get(context, keys[32].Get(isolate)).ToLocal(&public_value)) { + if (!v8Object->Get(context, keys[34].Get(isolate)).ToLocal(&public_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -602,7 +605,7 @@ } v8::Local<v8::Value> record_member_value; - if (!v8Object->Get(context, keys[33].Get(isolate)).ToLocal(&record_member_value)) { + if (!v8Object->Get(context, keys[35].Get(isolate)).ToLocal(&record_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -616,7 +619,7 @@ } v8::Local<v8::Value> required_callback_function_member_value; - if (!v8Object->Get(context, keys[34].Get(isolate)).ToLocal(&required_callback_function_member_value)) { + if (!v8Object->Get(context, keys[36].Get(isolate)).ToLocal(&required_callback_function_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -633,7 +636,7 @@ } v8::Local<v8::Value> restricted_double_member_value; - if (!v8Object->Get(context, keys[35].Get(isolate)).ToLocal(&restricted_double_member_value)) { + if (!v8Object->Get(context, keys[37].Get(isolate)).ToLocal(&restricted_double_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -647,7 +650,7 @@ } v8::Local<v8::Value> string_member_value; - if (!v8Object->Get(context, keys[38].Get(isolate)).ToLocal(&string_member_value)) { + if (!v8Object->Get(context, keys[40].Get(isolate)).ToLocal(&string_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -661,7 +664,7 @@ } v8::Local<v8::Value> string_or_null_member_value; - if (!v8Object->Get(context, keys[39].Get(isolate)).ToLocal(&string_or_null_member_value)) { + if (!v8Object->Get(context, keys[41].Get(isolate)).ToLocal(&string_or_null_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -675,7 +678,7 @@ } v8::Local<v8::Value> string_or_null_record_member_value; - if (!v8Object->Get(context, keys[40].Get(isolate)).ToLocal(&string_or_null_record_member_value)) { + if (!v8Object->Get(context, keys[42].Get(isolate)).ToLocal(&string_or_null_record_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -689,7 +692,7 @@ } v8::Local<v8::Value> string_or_null_sequence_member_value; - if (!v8Object->Get(context, keys[41].Get(isolate)).ToLocal(&string_or_null_sequence_member_value)) { + if (!v8Object->Get(context, keys[43].Get(isolate)).ToLocal(&string_or_null_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -703,7 +706,7 @@ } v8::Local<v8::Value> string_sequence_member_value; - if (!v8Object->Get(context, keys[42].Get(isolate)).ToLocal(&string_sequence_member_value)) { + if (!v8Object->Get(context, keys[44].Get(isolate)).ToLocal(&string_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -717,7 +720,7 @@ } v8::Local<v8::Value> test_enum_or_null_or_test_enum_sequence_member_value; - if (!v8Object->Get(context, keys[43].Get(isolate)).ToLocal(&test_enum_or_null_or_test_enum_sequence_member_value)) { + if (!v8Object->Get(context, keys[45].Get(isolate)).ToLocal(&test_enum_or_null_or_test_enum_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -732,7 +735,7 @@ } v8::Local<v8::Value> test_enum_or_test_enum_or_null_sequence_member_value; - if (!v8Object->Get(context, keys[44].Get(isolate)).ToLocal(&test_enum_or_test_enum_or_null_sequence_member_value)) { + if (!v8Object->Get(context, keys[46].Get(isolate)).ToLocal(&test_enum_or_test_enum_or_null_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -747,7 +750,7 @@ } v8::Local<v8::Value> test_enum_or_test_enum_sequence_member_value; - if (!v8Object->Get(context, keys[45].Get(isolate)).ToLocal(&test_enum_or_test_enum_sequence_member_value)) { + if (!v8Object->Get(context, keys[47].Get(isolate)).ToLocal(&test_enum_or_test_enum_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -762,7 +765,7 @@ } v8::Local<v8::Value> test_interface_2_or_uint8_array_member_value; - if (!v8Object->Get(context, keys[46].Get(isolate)).ToLocal(&test_interface_2_or_uint8_array_member_value)) { + if (!v8Object->Get(context, keys[48].Get(isolate)).ToLocal(&test_interface_2_or_uint8_array_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -777,7 +780,7 @@ } v8::Local<v8::Value> test_interface_member_value; - if (!v8Object->Get(context, keys[47].Get(isolate)).ToLocal(&test_interface_member_value)) { + if (!v8Object->Get(context, keys[49].Get(isolate)).ToLocal(&test_interface_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -793,7 +796,7 @@ } v8::Local<v8::Value> test_interface_or_null_member_value; - if (!v8Object->Get(context, keys[48].Get(isolate)).ToLocal(&test_interface_or_null_member_value)) { + if (!v8Object->Get(context, keys[50].Get(isolate)).ToLocal(&test_interface_or_null_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -811,7 +814,7 @@ } v8::Local<v8::Value> test_interface_sequence_member_value; - if (!v8Object->Get(context, keys[49].Get(isolate)).ToLocal(&test_interface_sequence_member_value)) { + if (!v8Object->Get(context, keys[51].Get(isolate)).ToLocal(&test_interface_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -825,7 +828,7 @@ } v8::Local<v8::Value> test_object_sequence_member_value; - if (!v8Object->Get(context, keys[50].Get(isolate)).ToLocal(&test_object_sequence_member_value)) { + if (!v8Object->Get(context, keys[52].Get(isolate)).ToLocal(&test_object_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -839,7 +842,7 @@ } v8::Local<v8::Value> treat_non_null_obj_member_value; - if (!v8Object->Get(context, keys[51].Get(isolate)).ToLocal(&treat_non_null_obj_member_value)) { + if (!v8Object->Get(context, keys[53].Get(isolate)).ToLocal(&treat_non_null_obj_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -855,7 +858,7 @@ } v8::Local<v8::Value> treat_null_as_string_sequence_member_value; - if (!v8Object->Get(context, keys[52].Get(isolate)).ToLocal(&treat_null_as_string_sequence_member_value)) { + if (!v8Object->Get(context, keys[54].Get(isolate)).ToLocal(&treat_null_as_string_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -869,7 +872,7 @@ } v8::Local<v8::Value> uint8_array_member_value; - if (!v8Object->Get(context, keys[53].Get(isolate)).ToLocal(&uint8_array_member_value)) { + if (!v8Object->Get(context, keys[55].Get(isolate)).ToLocal(&uint8_array_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -887,7 +890,7 @@ } v8::Local<v8::Value> union_in_record_member_value; - if (!v8Object->Get(context, keys[54].Get(isolate)).ToLocal(&union_in_record_member_value)) { + if (!v8Object->Get(context, keys[56].Get(isolate)).ToLocal(&union_in_record_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -901,7 +904,7 @@ } v8::Local<v8::Value> union_member_with_sequence_default_value; - if (!v8Object->Get(context, keys[55].Get(isolate)).ToLocal(&union_member_with_sequence_default_value)) { + if (!v8Object->Get(context, keys[57].Get(isolate)).ToLocal(&union_member_with_sequence_default_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -916,7 +919,7 @@ } v8::Local<v8::Value> union_or_null_record_member_value; - if (!v8Object->Get(context, keys[56].Get(isolate)).ToLocal(&union_or_null_record_member_value)) { + if (!v8Object->Get(context, keys[58].Get(isolate)).ToLocal(&union_or_null_record_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -930,7 +933,7 @@ } v8::Local<v8::Value> union_or_null_sequence_member_value; - if (!v8Object->Get(context, keys[57].Get(isolate)).ToLocal(&union_or_null_sequence_member_value)) { + if (!v8Object->Get(context, keys[59].Get(isolate)).ToLocal(&union_or_null_sequence_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -944,7 +947,7 @@ } v8::Local<v8::Value> union_with_annotated_type_member_value; - if (!v8Object->Get(context, keys[58].Get(isolate)).ToLocal(&union_with_annotated_type_member_value)) { + if (!v8Object->Get(context, keys[60].Get(isolate)).ToLocal(&union_with_annotated_type_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -959,7 +962,7 @@ } v8::Local<v8::Value> union_with_typedefs_value; - if (!v8Object->Get(context, keys[59].Get(isolate)).ToLocal(&union_with_typedefs_value)) { + if (!v8Object->Get(context, keys[61].Get(isolate)).ToLocal(&union_with_typedefs_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -974,7 +977,7 @@ } v8::Local<v8::Value> unrestricted_double_member_value; - if (!v8Object->Get(context, keys[60].Get(isolate)).ToLocal(&unrestricted_double_member_value)) { + if (!v8Object->Get(context, keys[62].Get(isolate)).ToLocal(&unrestricted_double_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -988,7 +991,7 @@ } v8::Local<v8::Value> usv_string_or_null_member_value; - if (!v8Object->Get(context, keys[61].Get(isolate)).ToLocal(&usv_string_or_null_member_value)) { + if (!v8Object->Get(context, keys[63].Get(isolate)).ToLocal(&usv_string_or_null_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -1003,7 +1006,7 @@ if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { v8::Local<v8::Value> runtime_member_value; - if (!v8Object->Get(context, keys[36].Get(isolate)).ToLocal(&runtime_member_value)) { + if (!v8Object->Get(context, keys[38].Get(isolate)).ToLocal(&runtime_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -1017,7 +1020,7 @@ } v8::Local<v8::Value> runtime_second_member_value; - if (!v8Object->Get(context, keys[37].Get(isolate)).ToLocal(&runtime_second_member_value)) { + if (!v8Object->Get(context, keys[39].Get(isolate)).ToLocal(&runtime_second_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -1031,9 +1034,9 @@ } } - if (origin_trials::FeatureNameEnabled(executionContext)) { + if (RuntimeEnabledFeatures::FeatureNameEnabled(executionContext)) { v8::Local<v8::Value> origin_trial_member_value; - if (!v8Object->Get(context, keys[29].Get(isolate)).ToLocal(&origin_trial_member_value)) { + if (!v8Object->Get(context, keys[30].Get(isolate)).ToLocal(&origin_trial_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -1047,9 +1050,9 @@ } } - if (origin_trials::FeatureName1Enabled(executionContext)) { + if (RuntimeEnabledFeatures::FeatureName1Enabled(executionContext)) { v8::Local<v8::Value> origin_trial_second_member_value; - if (!v8Object->Get(context, keys[30].Get(isolate)).ToLocal(&origin_trial_second_member_value)) { + if (!v8Object->Get(context, keys[31].Get(isolate)).ToLocal(&origin_trial_second_member_value)) { exception_state.RethrowV8Exception(block.Exception()); return; } @@ -1062,6 +1065,38 @@ impl->setOriginTrialSecondMember(origin_trial_second_member_cpp_value); } } + + if (RuntimeEnabledFeatures::OriginTrialFeatureEnabled(executionContext)) { + v8::Local<v8::Value> origin_trial_third_member_value; + if (!v8Object->Get(context, keys[32].Get(isolate)).ToLocal(&origin_trial_third_member_value)) { + exception_state.RethrowV8Exception(block.Exception()); + return; + } + if (origin_trial_third_member_value.IsEmpty() || origin_trial_third_member_value->IsUndefined()) { + // Do nothing. + } else { + bool origin_trial_third_member_cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(isolate, origin_trial_third_member_value, exception_state); + if (exception_state.HadException()) + return; + impl->setOriginTrialThirdMember(origin_trial_third_member_cpp_value); + } + } + + if (RuntimeEnabledFeatures::OriginTrialFeature1Enabled(executionContext)) { + v8::Local<v8::Value> origin_trial_fourth_member_value; + if (!v8Object->Get(context, keys[29].Get(isolate)).ToLocal(&origin_trial_fourth_member_value)) { + exception_state.RethrowV8Exception(block.Exception()); + return; + } + if (origin_trial_fourth_member_value.IsEmpty() || origin_trial_fourth_member_value->IsUndefined()) { + // Do nothing. + } else { + bool origin_trial_fourth_member_cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(isolate, origin_trial_fourth_member_value, exception_state); + if (exception_state.HadException()) + return; + impl->setOriginTrialFourthMember(origin_trial_fourth_member_cpp_value); + } + } } v8::Local<v8::Value> TestDictionary::ToV8Impl(v8::Local<v8::Object> creationContext, v8::Isolate* isolate) const { @@ -1444,7 +1479,7 @@ other_double_or_string_member_has_value_or_default = true; } if (other_double_or_string_member_has_value_or_default && - !create_property(31, other_double_or_string_member_value)) { + !create_property(33, other_double_or_string_member_value)) { return false; } @@ -1455,7 +1490,7 @@ public_has_value_or_default = true; } if (public_has_value_or_default && - !create_property(32, public_value)) { + !create_property(34, public_value)) { return false; } @@ -1466,7 +1501,7 @@ record_member_has_value_or_default = true; } if (record_member_has_value_or_default && - !create_property(33, record_member_value)) { + !create_property(35, record_member_value)) { return false; } @@ -1479,7 +1514,7 @@ NOTREACHED(); } if (required_callback_function_member_has_value_or_default && - !create_property(34, required_callback_function_member_value)) { + !create_property(36, required_callback_function_member_value)) { return false; } @@ -1493,7 +1528,7 @@ restricted_double_member_has_value_or_default = true; } if (restricted_double_member_has_value_or_default && - !create_property(35, restricted_double_member_value)) { + !create_property(37, restricted_double_member_value)) { return false; } @@ -1504,7 +1539,7 @@ string_member_has_value_or_default = true; } if (string_member_has_value_or_default && - !create_property(38, string_member_value)) { + !create_property(40, string_member_value)) { return false; } @@ -1518,7 +1553,7 @@ string_or_null_member_has_value_or_default = true; } if (string_or_null_member_has_value_or_default && - !create_property(39, string_or_null_member_value)) { + !create_property(41, string_or_null_member_value)) { return false; } @@ -1529,7 +1564,7 @@ string_or_null_record_member_has_value_or_default = true; } if (string_or_null_record_member_has_value_or_default && - !create_property(40, string_or_null_record_member_value)) { + !create_property(42, string_or_null_record_member_value)) { return false; } @@ -1540,7 +1575,7 @@ string_or_null_sequence_member_has_value_or_default = true; } if (string_or_null_sequence_member_has_value_or_default && - !create_property(41, string_or_null_sequence_member_value)) { + !create_property(43, string_or_null_sequence_member_value)) { return false; } @@ -1554,7 +1589,7 @@ string_sequence_member_has_value_or_default = true; } if (string_sequence_member_has_value_or_default && - !create_property(42, string_sequence_member_value)) { + !create_property(44, string_sequence_member_value)) { return false; } @@ -1565,7 +1600,7 @@ test_enum_or_null_or_test_enum_sequence_member_has_value_or_default = true; } if (test_enum_or_null_or_test_enum_sequence_member_has_value_or_default && - !create_property(43, test_enum_or_null_or_test_enum_sequence_member_value)) { + !create_property(45, test_enum_or_null_or_test_enum_sequence_member_value)) { return false; } @@ -1576,7 +1611,7 @@ test_enum_or_test_enum_or_null_sequence_member_has_value_or_default = true; } if (test_enum_or_test_enum_or_null_sequence_member_has_value_or_default && - !create_property(44, test_enum_or_test_enum_or_null_sequence_member_value)) { + !create_property(46, test_enum_or_test_enum_or_null_sequence_member_value)) { return false; } @@ -1587,7 +1622,7 @@ test_enum_or_test_enum_sequence_member_has_value_or_default = true; } if (test_enum_or_test_enum_sequence_member_has_value_or_default && - !create_property(45, test_enum_or_test_enum_sequence_member_value)) { + !create_property(47, test_enum_or_test_enum_sequence_member_value)) { return false; } @@ -1598,7 +1633,7 @@ test_interface_2_or_uint8_array_member_has_value_or_default = true; } if (test_interface_2_or_uint8_array_member_has_value_or_default && - !create_property(46, test_interface_2_or_uint8_array_member_value)) { + !create_property(48, test_interface_2_or_uint8_array_member_value)) { return false; } @@ -1609,7 +1644,7 @@ test_interface_member_has_value_or_default = true; } if (test_interface_member_has_value_or_default && - !create_property(47, test_interface_member_value)) { + !create_property(49, test_interface_member_value)) { return false; } @@ -1620,7 +1655,7 @@ test_interface_or_null_member_has_value_or_default = true; } if (test_interface_or_null_member_has_value_or_default && - !create_property(48, test_interface_or_null_member_value)) { + !create_property(50, test_interface_or_null_member_value)) { return false; } @@ -1634,7 +1669,7 @@ test_interface_sequence_member_has_value_or_default = true; } if (test_interface_sequence_member_has_value_or_default && - !create_property(49, test_interface_sequence_member_value)) { + !create_property(51, test_interface_sequence_member_value)) { return false; } @@ -1645,7 +1680,7 @@ test_object_sequence_member_has_value_or_default = true; } if (test_object_sequence_member_has_value_or_default && - !create_property(50, test_object_sequence_member_value)) { + !create_property(52, test_object_sequence_member_value)) { return false; } @@ -1656,7 +1691,7 @@ treat_non_null_obj_member_has_value_or_default = true; } if (treat_non_null_obj_member_has_value_or_default && - !create_property(51, treat_non_null_obj_member_value)) { + !create_property(53, treat_non_null_obj_member_value)) { return false; } @@ -1670,7 +1705,7 @@ treat_null_as_string_sequence_member_has_value_or_default = true; } if (treat_null_as_string_sequence_member_has_value_or_default && - !create_property(52, treat_null_as_string_sequence_member_value)) { + !create_property(54, treat_null_as_string_sequence_member_value)) { return false; } @@ -1681,7 +1716,7 @@ uint8_array_member_has_value_or_default = true; } if (uint8_array_member_has_value_or_default && - !create_property(53, uint8_array_member_value)) { + !create_property(55, uint8_array_member_value)) { return false; } @@ -1692,7 +1727,7 @@ union_in_record_member_has_value_or_default = true; } if (union_in_record_member_has_value_or_default && - !create_property(54, union_in_record_member_value)) { + !create_property(56, union_in_record_member_value)) { return false; } @@ -1706,7 +1741,7 @@ union_member_with_sequence_default_has_value_or_default = true; } if (union_member_with_sequence_default_has_value_or_default && - !create_property(55, union_member_with_sequence_default_value)) { + !create_property(57, union_member_with_sequence_default_value)) { return false; } @@ -1717,7 +1752,7 @@ union_or_null_record_member_has_value_or_default = true; } if (union_or_null_record_member_has_value_or_default && - !create_property(56, union_or_null_record_member_value)) { + !create_property(58, union_or_null_record_member_value)) { return false; } @@ -1728,7 +1763,7 @@ union_or_null_sequence_member_has_value_or_default = true; } if (union_or_null_sequence_member_has_value_or_default && - !create_property(57, union_or_null_sequence_member_value)) { + !create_property(59, union_or_null_sequence_member_value)) { return false; } @@ -1739,7 +1774,7 @@ union_with_annotated_type_member_has_value_or_default = true; } if (union_with_annotated_type_member_has_value_or_default && - !create_property(58, union_with_annotated_type_member_value)) { + !create_property(60, union_with_annotated_type_member_value)) { return false; } @@ -1750,7 +1785,7 @@ union_with_typedefs_has_value_or_default = true; } if (union_with_typedefs_has_value_or_default && - !create_property(59, union_with_typedefs_value)) { + !create_property(61, union_with_typedefs_value)) { return false; } @@ -1764,7 +1799,7 @@ unrestricted_double_member_has_value_or_default = true; } if (unrestricted_double_member_has_value_or_default && - !create_property(60, unrestricted_double_member_value)) { + !create_property(62, unrestricted_double_member_value)) { return false; } @@ -1778,7 +1813,7 @@ usv_string_or_null_member_has_value_or_default = true; } if (usv_string_or_null_member_has_value_or_default && - !create_property(61, usv_string_or_null_member_value)) { + !create_property(63, usv_string_or_null_member_value)) { return false; } @@ -1790,7 +1825,7 @@ runtime_member_has_value_or_default = true; } if (runtime_member_has_value_or_default && - !create_property(36, runtime_member_value)) { + !create_property(38, runtime_member_value)) { return false; } @@ -1801,12 +1836,12 @@ runtime_second_member_has_value_or_default = true; } if (runtime_second_member_has_value_or_default && - !create_property(37, runtime_second_member_value)) { + !create_property(39, runtime_second_member_value)) { return false; } } - if (origin_trials::FeatureNameEnabled(executionContext)) { + if (RuntimeEnabledFeatures::FeatureNameEnabled(executionContext)) { v8::Local<v8::Value> origin_trial_member_value; bool origin_trial_member_has_value_or_default = false; if (impl->hasOriginTrialMember()) { @@ -1814,12 +1849,12 @@ origin_trial_member_has_value_or_default = true; } if (origin_trial_member_has_value_or_default && - !create_property(29, origin_trial_member_value)) { + !create_property(30, origin_trial_member_value)) { return false; } } - if (origin_trials::FeatureName1Enabled(executionContext)) { + if (RuntimeEnabledFeatures::FeatureName1Enabled(executionContext)) { v8::Local<v8::Value> origin_trial_second_member_value; bool origin_trial_second_member_has_value_or_default = false; if (impl->hasOriginTrialSecondMember()) { @@ -1827,7 +1862,33 @@ origin_trial_second_member_has_value_or_default = true; } if (origin_trial_second_member_has_value_or_default && - !create_property(30, origin_trial_second_member_value)) { + !create_property(31, origin_trial_second_member_value)) { + return false; + } + } + + if (RuntimeEnabledFeatures::OriginTrialFeatureEnabled(executionContext)) { + v8::Local<v8::Value> origin_trial_third_member_value; + bool origin_trial_third_member_has_value_or_default = false; + if (impl->hasOriginTrialThirdMember()) { + origin_trial_third_member_value = v8::Boolean::New(isolate, impl->originTrialThirdMember()); + origin_trial_third_member_has_value_or_default = true; + } + if (origin_trial_third_member_has_value_or_default && + !create_property(32, origin_trial_third_member_value)) { + return false; + } + } + + if (RuntimeEnabledFeatures::OriginTrialFeature1Enabled(executionContext)) { + v8::Local<v8::Value> origin_trial_fourth_member_value; + bool origin_trial_fourth_member_has_value_or_default = false; + if (impl->hasOriginTrialFourthMember()) { + origin_trial_fourth_member_value = v8::Boolean::New(isolate, impl->originTrialFourthMember()); + origin_trial_fourth_member_has_value_or_default = true; + } + if (origin_trial_fourth_member_has_value_or_default && + !create_property(29, origin_trial_fourth_member_value)) { return false; } }
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.cc index 946b9702..b2728446 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.cc
@@ -35,7 +35,6 @@ #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/use_counter.h" #include "third_party/blink/renderer/core/inspector/console_message.h" -#include "third_party/blink/renderer/core/origin_trials/origin_trials.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h" @@ -1670,6 +1669,12 @@ impl->originTrialWindowExposedMethod(); } +static void OriginTrialWindowExposedMethod2Method(const v8::FunctionCallbackInfo<v8::Value>& info) { + TestInterfaceImplementation* impl = V8TestInterface::ToImpl(info.Holder()); + + impl->originTrialWindowExposedMethod2(); +} + static void AlwaysExposedStaticMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestInterfaceImplementation::alwaysExposedStaticMethod(); } @@ -1736,7 +1741,7 @@ switch (std::min(1, info.Length())) { case 1: - if (RuntimeEnabledFeatures::FeatureName2Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature2Enabled()) { if (V8Window::HasInstance(info[0], info.GetIsolate())) { OverloadMethodWithExposedAndRuntimeEnabledFlag3Method(info); return; @@ -1746,7 +1751,7 @@ OverloadMethodWithExposedAndRuntimeEnabledFlag1Method(info); return; } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { if (true) { OverloadMethodWithExposedAndRuntimeEnabledFlag2Method(info); return; @@ -3343,6 +3348,12 @@ test_interface_implementation_v8_internal::OriginTrialWindowExposedMethodMethod(info); } +void V8TestInterface::OriginTrialWindowExposedMethod2MethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { + RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestInterfaceImplementation_originTrialWindowExposedMethod2"); + + test_interface_implementation_v8_internal::OriginTrialWindowExposedMethod2Method(info); +} + void V8TestInterface::AlwaysExposedStaticMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestInterfaceImplementation_alwaysExposedStaticMethod"); @@ -3881,7 +3892,7 @@ ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. - if (RuntimeEnabledFeatures::PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::PartialRuntimeFeatureEnabled()) { static constexpr V8DOMConfiguration::ConstantConfiguration kConfigurations[] = { {"PARTIAL_UNSIGNED_SHORT", V8DOMConfiguration::kConstantTypeUnsignedShort, static_cast<int>(0)}, {"PARTIAL_DOUBLE", V8DOMConfiguration::kConstantTypeDouble, static_cast<double>(3.14)}, @@ -3891,17 +3902,7 @@ kConfigurations, base::size(kConfigurations)); } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { - static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = { - { "conditionalReadOnlyLongAttribute", V8TestInterface::ConditionalReadOnlyLongAttributeAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, - { "staticConditionalReadOnlyLongAttribute", V8TestInterface::StaticConditionalReadOnlyLongAttributeAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnInterface, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, - { "conditionalLongAttribute", V8TestInterface::ConditionalLongAttributeAttributeGetterCallback, V8TestInterface::ConditionalLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, - }; - V8DOMConfiguration::InstallAccessors( - isolate, world, instance_template, prototype_template, interface_template, - signature, kConfigurations, base::size(kConfigurations)); - } - if (RuntimeEnabledFeatures::Mixin2FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::Mixin2RuntimeFeatureEnabled()) { static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = { { "mixin2StringAttribute", V8TestInterface::Mixin2StringAttributeAttributeGetterCallback, V8TestInterface::Mixin2StringAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, }; @@ -3909,7 +3910,7 @@ isolate, world, instance_template, prototype_template, interface_template, signature, kConfigurations, base::size(kConfigurations)); } - if (RuntimeEnabledFeatures::MixinFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::MixinRuntimeFeatureEnabled()) { static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = { { "mixinRuntimeEnabledNodeAttribute", V8TestInterface::MixinRuntimeEnabledNodeAttributeAttributeGetterCallback, V8TestInterface::MixinRuntimeEnabledNodeAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, }; @@ -3917,7 +3918,7 @@ isolate, world, instance_template, prototype_template, interface_template, signature, kConfigurations, base::size(kConfigurations)); } - if (RuntimeEnabledFeatures::PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::PartialRuntimeFeatureEnabled()) { static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = { { "partialCallWithExecutionContextLongAttribute", V8TestInterface::PartialCallWithExecutionContextLongAttributeAttributeGetterCallback, V8TestInterface::PartialCallWithExecutionContextLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, { "partialLongAttribute", V8TestInterface::PartialLongAttributeAttributeGetterCallback, V8TestInterface::PartialLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, @@ -3928,9 +3929,19 @@ isolate, world, instance_template, prototype_template, interface_template, signature, kConfigurations, base::size(kConfigurations)); } + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { + static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = { + { "conditionalReadOnlyLongAttribute", V8TestInterface::ConditionalReadOnlyLongAttributeAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, + { "staticConditionalReadOnlyLongAttribute", V8TestInterface::StaticConditionalReadOnlyLongAttributeAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnInterface, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, + { "conditionalLongAttribute", V8TestInterface::ConditionalLongAttributeAttributeGetterCallback, V8TestInterface::ConditionalLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, + }; + V8DOMConfiguration::InstallAccessors( + isolate, world, instance_template, prototype_template, interface_template, + signature, kConfigurations, base::size(kConfigurations)); + } // Custom signature - if (RuntimeEnabledFeatures::Mixin2FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::Mixin2RuntimeFeatureEnabled()) { { // Install mixin2VoidMethod configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -3943,7 +3954,7 @@ } } } - if (RuntimeEnabledFeatures::PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::PartialRuntimeFeatureEnabled()) { { // Install partialVoidMethod configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -3956,7 +3967,7 @@ } } } - if (RuntimeEnabledFeatures::PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::PartialRuntimeFeatureEnabled()) { { // Install partialStaticVoidMethod configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -3969,7 +3980,7 @@ } } } - if (RuntimeEnabledFeatures::PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::PartialRuntimeFeatureEnabled()) { { // Install partialVoidMethodLongArg configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -3982,7 +3993,7 @@ } } } - if (RuntimeEnabledFeatures::PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::PartialRuntimeFeatureEnabled()) { { // Install partialCallWithExecutionContextRaisesExceptionVoidMethod configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -3995,7 +4006,7 @@ } } } - if (RuntimeEnabledFeatures::PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::PartialRuntimeFeatureEnabled()) { { // Install partialVoidMethodPartialCallbackTypeArg configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -4049,6 +4060,45 @@ InstallTestFeature(script_state, v8::Local<v8::Object>()); } +void V8TestInterface::InstallOriginTrialFeature( + v8::Isolate* isolate, + const DOMWrapperWorld& world, + v8::Local<v8::Object> instance, + v8::Local<v8::Object> prototype, + v8::Local<v8::Function> interface) { + v8::Local<v8::FunctionTemplate> interface_template = + V8TestInterface::GetWrapperTypeInfo()->DomTemplate(isolate, world); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); + ALLOW_UNUSED_LOCAL(signature); + ExecutionContext* execution_context = ToExecutionContext(isolate->GetCurrentContext()); + if (execution_context && (execution_context->IsDocument())) { + static constexpr V8DOMConfiguration::MethodConfiguration + kOriginTrialWindowExposedMethod2Configurations[] = { + {"originTrialWindowExposedMethod2", V8TestInterface::OriginTrialWindowExposedMethod2MethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds} + }; + for (const auto& config : kOriginTrialWindowExposedMethod2Configurations) { + V8DOMConfiguration::InstallMethod( + isolate, world, instance, prototype, + interface, signature, config); + } + } +} + +void V8TestInterface::InstallOriginTrialFeature( + ScriptState* script_state, v8::Local<v8::Object> instance) { + V8PerContextData* per_context_data = script_state->PerContextData(); + v8::Local<v8::Object> prototype = per_context_data->PrototypeForType( + V8TestInterface::GetWrapperTypeInfo()); + v8::Local<v8::Function> interface = per_context_data->ConstructorForType( + V8TestInterface::GetWrapperTypeInfo()); + ALLOW_UNUSED_LOCAL(interface); + InstallOriginTrialFeature(script_state->GetIsolate(), script_state->World(), instance, prototype, interface); +} + +void V8TestInterface::InstallOriginTrialFeature(ScriptState* script_state) { + InstallOriginTrialFeature(script_state, v8::Local<v8::Object>()); +} + v8::Local<v8::FunctionTemplate> V8TestInterface::DomTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world) { return V8DOMConfiguration::DomClassTemplate( @@ -4110,7 +4160,7 @@ isolate, world, instance_object, prototype_object, interface_object, signature, accessor_configurations, base::size(accessor_configurations)); - if (RuntimeEnabledFeatures::PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::PartialRuntimeFeatureEnabled()) { static const V8DOMConfiguration::AccessorConfiguration accessor_configurations[] = { { "partialSecureContextLongAttribute", V8TestInterface::PartialSecureContextLongAttributeAttributeGetterCallback, V8TestInterface::PartialSecureContextLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, }; @@ -4224,7 +4274,7 @@ } } if (execution_context && (execution_context->IsDocument())) { - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { { // Install methodWithExposedAndRuntimeEnabledFlag configuration const V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.h b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.h index b31ac380..7406383 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.h +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.h
@@ -75,6 +75,10 @@ static void InstallTestFeature(ScriptState*, v8::Local<v8::Object> instance); static void InstallTestFeature(ScriptState*); + static void InstallOriginTrialFeature(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface); + static void InstallOriginTrialFeature(ScriptState*, v8::Local<v8::Object> instance); + static void InstallOriginTrialFeature(ScriptState*); + // Callback functions CORE_EXPORT static void TestInterfaceAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); @@ -191,6 +195,7 @@ CORE_EXPORT static void WorkerExposedMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void WindowExposedMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void OriginTrialWindowExposedMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); + CORE_EXPORT static void OriginTrialWindowExposedMethod2MethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void AlwaysExposedStaticMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void WorkerExposedStaticMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void WindowExposedStaticMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&);
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_2.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_2.cc index 5b1b7ef..fb6be871 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_2.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_2.cc
@@ -817,7 +817,7 @@ ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { static constexpr V8DOMConfiguration::ConstantConfiguration kConfigurations[] = { {"CONST_VALUE_1", V8DOMConfiguration::kConstantTypeUnsignedShort, static_cast<int>(1)}, };
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_check_security.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_check_security.cc index 6ab7a5d..6dee00d9 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_check_security.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_check_security.cc
@@ -403,7 +403,7 @@ } static int DoNotCheckSecurityVoidOverloadMethodMethodLength() { - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { return 1; } return 2; @@ -416,7 +416,7 @@ switch (std::min(2, info.Length())) { case 1: - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { if (true) { DoNotCheckSecurityVoidOverloadMethod2Method(info); return; @@ -424,13 +424,13 @@ } break; case 2: - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { if (info[1]->IsUndefined()) { DoNotCheckSecurityVoidOverloadMethod2Method(info); return; } } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { if (info[1]->IsNumber()) { DoNotCheckSecurityVoidOverloadMethod2Method(info); return; @@ -440,7 +440,7 @@ DoNotCheckSecurityVoidOverloadMethod1Method(info); return; } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { if (true) { DoNotCheckSecurityVoidOverloadMethod2Method(info); return; @@ -950,7 +950,7 @@ if (!instance_object.IsEmpty()) { if (is_secure_context) { - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { { // Install secureContextRuntimeEnabledMethod configuration const V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_origin_trial_enabled.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_origin_trial_enabled.cc index 2e44452..db981b2 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_origin_trial_enabled.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_origin_trial_enabled.cc
@@ -358,7 +358,7 @@ // Register IDL constants, attributes and operations. - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = { { "conditionalReadOnlyLongAttribute", V8TestInterfaceOriginTrialEnabled::ConditionalReadOnlyLongAttributeAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, { "staticConditionalReadOnlyLongAttribute", V8TestInterfaceOriginTrialEnabled::StaticConditionalReadOnlyLongAttributeAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnInterface, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds },
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc index 65a8c04d..74c46b8 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc
@@ -63,7 +63,6 @@ #include "third_party/blink/renderer/core/html/html_table_rows_collection.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/inspector/console_message.h" -#include "third_party/blink/renderer/core/origin_trials/origin_trials.h" #include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h" #include "third_party/blink/renderer/core/typed_arrays/flexible_array_buffer_view.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" @@ -2470,6 +2469,34 @@ impl->setOriginTrialEnabledLongAttribute(cpp_value); } +static void OriginTrialEnabledLongAttribute2AttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { + v8::Local<v8::Object> holder = info.Holder(); + + TestObject* impl = V8TestObject::ToImpl(holder); + + V8SetReturnValueInt(info, impl->originTrialEnabledLongAttribute2()); +} + +static void OriginTrialEnabledLongAttribute2AttributeSetter( + v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) { + v8::Isolate* isolate = info.GetIsolate(); + ALLOW_UNUSED_LOCAL(isolate); + + v8::Local<v8::Object> holder = info.Holder(); + ALLOW_UNUSED_LOCAL(holder); + + TestObject* impl = V8TestObject::ToImpl(holder); + + ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "originTrialEnabledLongAttribute2"); + + // Prepare the value to be set. + int32_t cpp_value = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), v8_value, exception_state); + if (exception_state.HadException()) + return; + + impl->setOriginTrialEnabledLongAttribute2(cpp_value); +} + static void PerWorldBindingsReadonlyTestInterfaceEmptyAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); @@ -8728,17 +8755,17 @@ } static int PartiallyRuntimeEnabledOverloadedVoidMethodMethodLength() { - if (RuntimeEnabledFeatures::FeatureName1Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature1Enabled()) { return 1; } - if (RuntimeEnabledFeatures::FeatureName2Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature2Enabled()) { return 1; } return 2; } static int PartiallyRuntimeEnabledOverloadedVoidMethodMethodMaxArg() { - if (RuntimeEnabledFeatures::FeatureName3Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature3Enabled()) { return 3; } return 2; @@ -8751,13 +8778,13 @@ switch (std::min(test_object_v8_internal::PartiallyRuntimeEnabledOverloadedVoidMethodMethodMaxArg(), info.Length())) { case 1: - if (RuntimeEnabledFeatures::FeatureName2Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature2Enabled()) { if (V8TestInterface::HasInstance(info[0], info.GetIsolate())) { PartiallyRuntimeEnabledOverloadedVoidMethod2Method(info); return; } } - if (RuntimeEnabledFeatures::FeatureName1Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature1Enabled()) { if (true) { PartiallyRuntimeEnabledOverloadedVoidMethod1Method(info); return; @@ -8771,7 +8798,7 @@ } break; case 3: - if (RuntimeEnabledFeatures::FeatureName3Enabled()) { + if (RuntimeEnabledFeatures::RuntimeFeature3Enabled()) { if (true) { PartiallyRuntimeEnabledOverloadedVoidMethod4Method(info); return; @@ -10567,6 +10594,21 @@ test_object_v8_internal::OriginTrialEnabledLongAttributeAttributeSetter(v8_value, info); } +void V8TestObject::OriginTrialEnabledLongAttribute2AttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { + RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_originTrialEnabledLongAttribute2_Getter"); + + test_object_v8_internal::OriginTrialEnabledLongAttribute2AttributeGetter(info); +} + +void V8TestObject::OriginTrialEnabledLongAttribute2AttributeSetterCallback( + const v8::FunctionCallbackInfo<v8::Value>& info) { + RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_originTrialEnabledLongAttribute2_Setter"); + + v8::Local<v8::Value> v8_value = info[0]; + + test_object_v8_internal::OriginTrialEnabledLongAttribute2AttributeSetter(v8_value, info); +} + void V8TestObject::PerWorldBindingsReadonlyTestInterfaceEmptyAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_perWorldBindingsReadonlyTestInterfaceEmptyAttribute_Getter"); @@ -13499,7 +13541,7 @@ // Register IDL constants, attributes and operations. - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = { { "runtimeEnabledLongAttribute", V8TestObject::RuntimeEnabledLongAttributeAttributeGetterCallback, V8TestObject::RuntimeEnabledLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, { "unscopableRuntimeEnabledLongAttribute", V8TestObject::UnscopableRuntimeEnabledLongAttributeAttributeGetterCallback, V8TestObject::UnscopableRuntimeEnabledLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, @@ -13510,7 +13552,7 @@ } // Custom signature - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { { // Install unscopableRuntimeEnabledVoidMethod configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -13523,7 +13565,7 @@ } } } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { { // Install runtimeEnabledVoidMethod configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -13536,7 +13578,7 @@ } } } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { { // Install perWorldBindingsRuntimeEnabledVoidMethod configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -13550,7 +13592,7 @@ } } } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { { // Install runtimeEnabledOverloadedVoidMethod configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -13563,7 +13605,7 @@ } } } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { { // Install clear configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = { @@ -13578,6 +13620,41 @@ } } +void V8TestObject::InstallOriginTrialFeature( + v8::Isolate* isolate, + const DOMWrapperWorld& world, + v8::Local<v8::Object> instance, + v8::Local<v8::Object> prototype, + v8::Local<v8::Function> interface) { + v8::Local<v8::FunctionTemplate> interface_template = + V8TestObject::GetWrapperTypeInfo()->DomTemplate(isolate, world); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); + ALLOW_UNUSED_LOCAL(signature); + static constexpr V8DOMConfiguration::AccessorConfiguration + koriginTrialEnabledLongAttribute2Configurations[] = { + { "originTrialEnabledLongAttribute2", V8TestObject::OriginTrialEnabledLongAttribute2AttributeGetterCallback, V8TestObject::OriginTrialEnabledLongAttribute2AttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds } + }; + for (const auto& config : koriginTrialEnabledLongAttribute2Configurations) { + V8DOMConfiguration::InstallAccessor(isolate, world, instance, prototype, + interface, signature, config); + } +} + +void V8TestObject::InstallOriginTrialFeature( + ScriptState* script_state, v8::Local<v8::Object> instance) { + V8PerContextData* per_context_data = script_state->PerContextData(); + v8::Local<v8::Object> prototype = per_context_data->PrototypeForType( + V8TestObject::GetWrapperTypeInfo()); + v8::Local<v8::Function> interface = per_context_data->ConstructorForType( + V8TestObject::GetWrapperTypeInfo()); + ALLOW_UNUSED_LOCAL(interface); + InstallOriginTrialFeature(script_state->GetIsolate(), script_state->World(), instance, prototype, interface); +} + +void V8TestObject::InstallOriginTrialFeature(ScriptState* script_state) { + InstallOriginTrialFeature(script_state, v8::Local<v8::Object>()); +} + void V8TestObject::InstallFeatureName( v8::Isolate* isolate, const DOMWrapperWorld& world, @@ -13707,12 +13784,12 @@ unscopables->CreateDataProperty( context, V8AtomicString(isolate, "unscopableOriginTrialEnabledLongAttribute"), v8::True(isolate)) .FromJust(); - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { unscopables->CreateDataProperty( context, V8AtomicString(isolate, "unscopableRuntimeEnabledLongAttribute"), v8::True(isolate)) .FromJust(); } - if (RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { unscopables->CreateDataProperty( context, V8AtomicString(isolate, "unscopableRuntimeEnabledVoidMethod"), v8::True(isolate)) .FromJust();
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.h b/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.h index 9e34b07..dea927ec 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.h +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.h
@@ -78,6 +78,10 @@ v8::Local<v8::Function> interface_object, v8::Local<v8::FunctionTemplate> interface_template); + static void InstallOriginTrialFeature(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface); + static void InstallOriginTrialFeature(ScriptState*, v8::Local<v8::Object> instance); + static void InstallOriginTrialFeature(ScriptState*); + static void InstallFeatureName(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface); static void InstallFeatureName(ScriptState*, v8::Local<v8::Object> instance); static void InstallFeatureName(ScriptState*); @@ -255,6 +259,8 @@ CORE_EXPORT static void NotEnumerableLongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void OriginTrialEnabledLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void OriginTrialEnabledLongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); + CORE_EXPORT static void OriginTrialEnabledLongAttribute2AttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); + CORE_EXPORT static void OriginTrialEnabledLongAttribute2AttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void PerWorldBindingsReadonlyTestInterfaceEmptyAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void PerWorldBindingsReadonlyTestInterfaceEmptyAttributeAttributeGetterCallbackForMainWorld(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void ActivityLoggingAccessPerWorldBindingsLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&);
diff --git a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_2_partial.cc b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_2_partial.cc index 479d30e..254c581 100644 --- a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_2_partial.cc +++ b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_2_partial.cc
@@ -123,7 +123,7 @@ // Register IDL constants, attributes and operations. // Custom signature - if (RuntimeEnabledFeatures::Interface2PartialFeatureNameEnabled()) { + if (RuntimeEnabledFeatures::Interface2PartialRuntimeFeatureEnabled()) { { // Install voidMethodPartial1 configuration constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
diff --git a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_5.cc b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_5.cc index 9a9eb07b..00236e4 100644 --- a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_5.cc +++ b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_5.cc
@@ -1000,7 +1000,7 @@ // Initialize the interface object's template. V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, V8TestInterface5::GetWrapperTypeInfo()->interface_name, V8TestInterfaceEmpty::DomTemplate(isolate, world), V8TestInterface5::kInternalFieldCount); - if (!RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (!RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { return; } @@ -1067,7 +1067,7 @@ v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) { - if (!RuntimeEnabledFeatures::FeatureNameEnabled()) { + if (!RuntimeEnabledFeatures::RuntimeFeatureEnabled()) { return; }
diff --git a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_partial.cc b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_partial.cc index 81937c6..23ad1728 100644 --- a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_partial.cc +++ b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_partial.cc
@@ -24,7 +24,6 @@ #include "third_party/blink/renderer/bindings/tests/idls/modules/test_interface_partial_3_implementation.h" #include "third_party/blink/renderer/bindings/tests/idls/modules/test_interface_partial_4.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" -#include "third_party/blink/renderer/core/origin_trials/origin_trials.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
diff --git a/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py b/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py index b0fd5dd..8b7413f 100755 --- a/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py +++ b/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py
@@ -38,7 +38,9 @@ # We want exactly the same parsing as RuntimeFeatureWriter # but generate different files. -class InternalRuntimeFlagsWriter(make_runtime_features.RuntimeFeatureWriter): +class InternalRuntimeFlagsWriter(make_runtime_features.BaseRuntimeFeatureWriter): + class_name = 'InternalRuntimeFlags' + file_basename = 'internal_runtime_flags' def __init__(self, json5_file_path, output_dir): super(InternalRuntimeFlagsWriter, self).__init__(json5_file_path, output_dir)
diff --git a/third_party/blink/renderer/build/scripts/make_origin_trials.py b/third_party/blink/renderer/build/scripts/make_origin_trials.py index 4c76e13..2ae235af 100755 --- a/third_party/blink/renderer/build/scripts/make_origin_trials.py +++ b/third_party/blink/renderer/build/scripts/make_origin_trials.py
@@ -37,7 +37,7 @@ # We want exactly the same parsing as RuntimeFeatureWriter # but generate different files. -class OriginTrialsWriter(make_runtime_features.RuntimeFeatureWriter): +class OriginTrialsWriter(make_runtime_features.BaseRuntimeFeatureWriter): file_basename = 'origin_trials' def __init__(self, json5_file_path, output_dir):
diff --git a/third_party/blink/renderer/build/scripts/make_runtime_features.py b/third_party/blink/renderer/build/scripts/make_runtime_features.py index a46e4f1..b5fb70f 100755 --- a/third_party/blink/renderer/build/scripts/make_runtime_features.py +++ b/third_party/blink/renderer/build/scripts/make_runtime_features.py
@@ -28,6 +28,8 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import copy +import cPickle as pickle +import os import sys from blinkbuild.name_style_converter import NameStyleConverter @@ -36,15 +38,19 @@ import template_expander -class RuntimeFeatureWriter(json5_generator.Writer): - class_name = 'RuntimeEnabledFeatures' - file_basename = 'runtime_enabled_features' +class BaseRuntimeFeatureWriter(json5_generator.Writer): + # |class_name| should be passed as a template input to generate the target + # class. Set this variable if the template generates a class. + class_name = None + # |file_basename| must be set by subclasses since it is used to generate + # the header guard. + file_basename = None def __init__(self, json5_file_path, output_dir): - super(RuntimeFeatureWriter, self).__init__(json5_file_path, output_dir) - self._outputs = {(self.file_basename + '.h'): self.generate_header, - (self.file_basename + '.cc'): self.generate_implementation, - } + super(BaseRuntimeFeatureWriter, self).__init__(json5_file_path, output_dir) + # Subclasses should add generated output files and their contents to this dict. + self._outputs = {} + assert self.file_basename self._features = self.json5_file.name_dictionaries # Dependency graph specified by 'depends_on' attribute. @@ -100,6 +106,41 @@ platforms = self.json5_file.parameters['status']['valid_keys'] return [platform for platform in platforms if platform != 'default'] + +class RuntimeFeatureWriter(BaseRuntimeFeatureWriter): + class_name = 'RuntimeEnabledFeatures' + file_basename = 'runtime_enabled_features' + + def __init__(self, json5_file_path, output_dir): + super(RuntimeFeatureWriter, self).__init__(json5_file_path, output_dir) + self._outputs = { + (self.file_basename + '.h'): self.generate_header, + (self.file_basename + '.cc'): self.generate_implementation, + } + + # Write features to file for bindings generation + self._write_features_to_pickle_file(output_dir) + + def _write_features_to_pickle_file(self, platform_output_dir): + # TODO(yashard): Get the file path from args instead of hardcoding it. + file_name = os.path.join(platform_output_dir, '..', 'build', 'scripts', 'runtime_enabled_features.pickle') + features_map = {} + for feature in self._features: + features_map[str(feature['name'])] = { + 'in_origin_trial': feature['in_origin_trial'] + } + if os.path.isfile(file_name): + with open(os.path.abspath(file_name)) as pickle_file: + # pylint: disable=broad-except + try: + if pickle.load(pickle_file) == features_map: + return + except Exception: + # If trouble unpickling, overwrite + pass + with open(os.path.abspath(file_name), 'w') as pickle_file: + pickle.dump(features_map, pickle_file) + def _template_inputs(self): return { 'features': self._features, @@ -120,7 +161,7 @@ return self._template_inputs() -class RuntimeFeatureTestHelpersWriter(RuntimeFeatureWriter): +class RuntimeFeatureTestHelpersWriter(BaseRuntimeFeatureWriter): class_name = 'ScopedRuntimeEnabledFeatureForTest' file_basename = 'runtime_enabled_features_test_helpers' @@ -139,6 +180,7 @@ def generate_header(self): return self._template_inputs() + if __name__ == '__main__': json5_generator.Maker(RuntimeFeatureWriter).main() json5_generator.Maker(RuntimeFeatureTestHelpersWriter).main()
diff --git a/third_party/blink/renderer/build/scripts/make_web_origin_trials.py b/third_party/blink/renderer/build/scripts/make_web_origin_trials.py index 6ba2b2e8..d698f9c 100755 --- a/third_party/blink/renderer/build/scripts/make_web_origin_trials.py +++ b/third_party/blink/renderer/build/scripts/make_web_origin_trials.py
@@ -10,7 +10,7 @@ # We want exactly the same parsing as RuntimeFeatureWriter but generate # different files. -class OriginTrialsWriter(make_runtime_features.RuntimeFeatureWriter): +class OriginTrialsWriter(make_runtime_features.BaseRuntimeFeatureWriter): file_basename = 'web_origin_trials' def __init__(self, json5_file_path, output_dir):
diff --git a/third_party/blink/renderer/core/animation/scroll_timeline.idl b/third_party/blink/renderer/core/animation/scroll_timeline.idl index 91fad5c..329f260f 100644 --- a/third_party/blink/renderer/core/animation/scroll_timeline.idl +++ b/third_party/blink/renderer/core/animation/scroll_timeline.idl
@@ -9,7 +9,7 @@ ConstructorCallWith=Document, MeasureAs=ScrollTimelineConstructor, RaisesException=Constructor, - OriginTrialEnabled=AnimationWorklet + RuntimeEnabled=AnimationWorklet ] interface ScrollTimeline : AnimationTimeline { readonly attribute Element? scrollSource; readonly attribute ScrollDirection orientation;
diff --git a/third_party/blink/renderer/core/animation/svg_angle_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_angle_interpolation_type.cc index d870f7b..053572b 100644 --- a/third_party/blink/renderer/core/animation/svg_angle_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_angle_interpolation_type.cc
@@ -7,6 +7,7 @@ #include "third_party/blink/renderer/core/animation/interpolation_environment.h" #include "third_party/blink/renderer/core/animation/string_keyframe.h" #include "third_party/blink/renderer/core/svg/svg_angle.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -28,7 +29,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { double double_value = ToInterpolableNumber(interpolable_value).Value(); - SVGAngle* result = SVGAngle::Create(); + auto* result = MakeGarbageCollected<SVGAngle>(); result->NewValueSpecifiedUnits(SVGAngle::kSvgAngletypeDeg, double_value); return result; }
diff --git a/third_party/blink/renderer/core/animation/svg_integer_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_integer_interpolation_type.cc index 5612f94..a7ca4bc 100644 --- a/third_party/blink/renderer/core/animation/svg_integer_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_integer_interpolation_type.cc
@@ -6,6 +6,7 @@ #include "third_party/blink/renderer/core/animation/interpolation_environment.h" #include "third_party/blink/renderer/core/svg/svg_integer.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -27,7 +28,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { double value = ToInterpolableNumber(interpolable_value).Value(); - return SVGInteger::Create(round(value)); + return MakeGarbageCollected<SVGInteger>(round(value)); } } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.cc index 6e6df42d..9e93285 100644 --- a/third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.cc
@@ -5,8 +5,11 @@ #include "third_party/blink/renderer/core/animation/svg_integer_optional_integer_interpolation_type.h" #include <memory> +#include <utility> + #include "third_party/blink/renderer/core/animation/interpolation_environment.h" #include "third_party/blink/renderer/core/svg/svg_integer_optional_integer.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -37,7 +40,7 @@ } static SVGInteger* ToPositiveInteger(const InterpolableValue* number) { - return SVGInteger::Create( + return MakeGarbageCollected<SVGInteger>( clampTo<int>(roundf(ToInterpolableNumber(number)->Value()), 1)); } @@ -45,8 +48,8 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { const InterpolableList& list = ToInterpolableList(interpolable_value); - return SVGIntegerOptionalInteger::Create(ToPositiveInteger(list.Get(0)), - ToPositiveInteger(list.Get(1))); + return MakeGarbageCollected<SVGIntegerOptionalInteger>( + ToPositiveInteger(list.Get(0)), ToPositiveInteger(list.Get(1))); } } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/svg_length_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_length_interpolation_type.cc index 3de83c0..4f9fbedb2 100644 --- a/third_party/blink/renderer/core/animation/svg_length_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_length_interpolation_type.cc
@@ -5,12 +5,15 @@ #include "third_party/blink/renderer/core/animation/svg_length_interpolation_type.h" #include <memory> +#include <utility> + #include "third_party/blink/renderer/core/animation/string_keyframe.h" #include "third_party/blink/renderer/core/animation/svg_interpolation_environment.h" #include "third_party/blink/renderer/core/css/css_resolution_units.h" #include "third_party/blink/renderer/core/svg/svg_element.h" #include "third_party/blink/renderer/core/svg/svg_length.h" #include "third_party/blink/renderer/core/svg/svg_length_context.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -86,7 +89,8 @@ if (negative_values_forbidden && value < 0) value = 0; - SVGLength* result = SVGLength::Create(unit_mode); // defaults to the length 0 + auto* result = + MakeGarbageCollected<SVGLength>(unit_mode); // defaults to the length 0 result->NewValueSpecifiedUnits(unit_type, value); return result; }
diff --git a/third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.cc index 7071b1c..c3b58361 100644 --- a/third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.cc
@@ -5,10 +5,13 @@ #include "third_party/blink/renderer/core/animation/svg_length_list_interpolation_type.h" #include <memory> +#include <utility> + #include "third_party/blink/renderer/core/animation/svg_interpolation_environment.h" #include "third_party/blink/renderer/core/animation/svg_length_interpolation_type.h" #include "third_party/blink/renderer/core/animation/underlying_length_checker.h" #include "third_party/blink/renderer/core/svg/svg_length_list.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -88,7 +91,7 @@ SVGElement& element = ToSVGInterpolationEnvironment(environment).SvgElement(); SVGLengthContext length_context(&element); - SVGLengthList* result = SVGLengthList::Create(unit_mode_); + auto* result = MakeGarbageCollected<SVGLengthList>(unit_mode_); const InterpolableList& list = ToInterpolableList(interpolable_value); for (wtf_size_t i = 0; i < list.length(); i++) { result->Append(SVGLengthInterpolationType::ResolveInterpolableSVGLength(
diff --git a/third_party/blink/renderer/core/animation/svg_number_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_number_interpolation_type.cc index 8e9f553..9a8dad7 100644 --- a/third_party/blink/renderer/core/animation/svg_number_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_number_interpolation_type.cc
@@ -4,10 +4,13 @@ #include "third_party/blink/renderer/core/animation/svg_number_interpolation_type.h" +#include <memory> + #include "third_party/blink/renderer/core/animation/interpolation_environment.h" #include "third_party/blink/renderer/core/animation/string_keyframe.h" #include "third_party/blink/renderer/core/svg/properties/svg_animated_property.h" #include "third_party/blink/renderer/core/svg/svg_number.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -29,7 +32,8 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { double value = ToInterpolableNumber(interpolable_value).Value(); - return SVGNumber::Create(is_non_negative_ && value < 0 ? 0 : value); + return MakeGarbageCollected<SVGNumber>(is_non_negative_ && value < 0 ? 0 + : value); } } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.cc index 876a645..a20d97e7 100644 --- a/third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.cc
@@ -5,9 +5,12 @@ #include "third_party/blink/renderer/core/animation/svg_number_list_interpolation_type.h" #include <memory> +#include <utility> + #include "third_party/blink/renderer/core/animation/interpolation_environment.h" #include "third_party/blink/renderer/core/animation/underlying_length_checker.h" #include "third_party/blink/renderer/core/svg/svg_number_list.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -95,11 +98,12 @@ SVGPropertyBase* SVGNumberListInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { - SVGNumberList* result = SVGNumberList::Create(); + auto* result = MakeGarbageCollected<SVGNumberList>(); const InterpolableList& list = ToInterpolableList(interpolable_value); - for (wtf_size_t i = 0; i < list.length(); i++) - result->Append( - SVGNumber::Create(ToInterpolableNumber(list.Get(i))->Value())); + for (wtf_size_t i = 0; i < list.length(); i++) { + result->Append(MakeGarbageCollected<SVGNumber>( + ToInterpolableNumber(list.Get(i))->Value())); + } return result; }
diff --git a/third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.cc index 9a874ba..ca685ba 100644 --- a/third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.cc
@@ -5,8 +5,11 @@ #include "third_party/blink/renderer/core/animation/svg_number_optional_number_interpolation_type.h" #include <memory> +#include <utility> + #include "third_party/blink/renderer/core/animation/interpolation_environment.h" #include "third_party/blink/renderer/core/svg/svg_number_optional_number.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -40,9 +43,11 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { const InterpolableList& list = ToInterpolableList(interpolable_value); - return SVGNumberOptionalNumber::Create( - SVGNumber::Create(ToInterpolableNumber(list.Get(0))->Value()), - SVGNumber::Create(ToInterpolableNumber(list.Get(1))->Value())); + return MakeGarbageCollected<SVGNumberOptionalNumber>( + MakeGarbageCollected<SVGNumber>( + ToInterpolableNumber(list.Get(0))->Value()), + MakeGarbageCollected<SVGNumber>( + ToInterpolableNumber(list.Get(1))->Value())); } } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/svg_path_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_path_interpolation_type.cc index 4987dbbf..04c2674 100644 --- a/third_party/blink/renderer/core/animation/svg_path_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_path_interpolation_type.cc
@@ -5,8 +5,8 @@ #include "third_party/blink/renderer/core/animation/svg_path_interpolation_type.h" #include "third_party/blink/renderer/core/animation/path_interpolation_functions.h" - #include "third_party/blink/renderer/core/svg/svg_path.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -46,7 +46,7 @@ SVGPropertyBase* SVGPathInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value) const { - return SVGPath::Create( + return MakeGarbageCollected<SVGPath>( cssvalue::CSSPathValue::Create(PathInterpolationFunctions::AppliedValue( interpolable_value, non_interpolable_value))); }
diff --git a/third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.cc index f0e25b02..86b32f0 100644 --- a/third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.cc
@@ -5,10 +5,13 @@ #include "third_party/blink/renderer/core/animation/svg_point_list_interpolation_type.h" #include <memory> +#include <utility> + #include "third_party/blink/renderer/core/animation/interpolation_environment.h" #include "third_party/blink/renderer/core/animation/string_keyframe.h" #include "third_party/blink/renderer/core/animation/underlying_length_checker.h" #include "third_party/blink/renderer/core/svg/svg_point_list.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -77,7 +80,7 @@ SVGPropertyBase* SVGPointListInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { - SVGPointList* result = SVGPointList::Create(); + auto* result = MakeGarbageCollected<SVGPointList>(); const InterpolableList& list = ToInterpolableList(interpolable_value); DCHECK_EQ(list.length() % 2, 0U); @@ -85,7 +88,7 @@ FloatPoint point = FloatPoint(ToInterpolableNumber(list.Get(i))->Value(), ToInterpolableNumber(list.Get(i + 1))->Value()); - result->Append(SVGPoint::Create(point)); + result->Append(MakeGarbageCollected<SVGPoint>(point)); } return result;
diff --git a/third_party/blink/renderer/core/animation/svg_rect_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_rect_interpolation_type.cc index 51f06ce..39ad352 100644 --- a/third_party/blink/renderer/core/animation/svg_rect_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_rect_interpolation_type.cc
@@ -4,9 +4,12 @@ #include "third_party/blink/renderer/core/animation/svg_rect_interpolation_type.h" #include <memory> +#include <utility> + #include "third_party/blink/renderer/core/animation/interpolation_environment.h" #include "third_party/blink/renderer/core/animation/string_keyframe.h" #include "third_party/blink/renderer/core/svg/svg_rect.h" +#include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" namespace blink { @@ -46,7 +49,7 @@ const InterpolableValue& interpolable_value, const NonInterpolableValue*) const { const InterpolableList& list = ToInterpolableList(interpolable_value); - SVGRect* result = SVGRect::Create(); + auto* result = MakeGarbageCollected<SVGRect>(); result->SetX(ToInterpolableNumber(list.Get(kRectX))->Value()); result->SetY(ToInterpolableNumber(list.Get(kRectY))->Value()); result->SetWidth(ToInterpolableNumber(list.Get(kRectWidth))->Value());
diff --git a/third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc index 779b179..56bcdeb 100644 --- a/third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc
@@ -14,6 +14,7 @@ #include "third_party/blink/renderer/core/animation/svg_interpolation_environment.h" #include "third_party/blink/renderer/core/svg/svg_transform.h" #include "third_party/blink/renderer/core/svg/svg_transform_list.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -58,7 +59,8 @@ SVGTransform* TranslateFromInterpolableValue(const InterpolableValue& value) { const InterpolableList& list = ToInterpolableList(value); - SVGTransform* transform = SVGTransform::Create(SVGTransformType::kTranslate); + auto* transform = + MakeGarbageCollected<SVGTransform>(SVGTransformType::kTranslate); transform->SetTranslate(ToInterpolableNumber(list.Get(0))->Value(), ToInterpolableNumber(list.Get(1))->Value()); return transform; @@ -76,7 +78,8 @@ SVGTransform* ScaleFromInterpolableValue(const InterpolableValue& value) { const InterpolableList& list = ToInterpolableList(value); - SVGTransform* transform = SVGTransform::Create(SVGTransformType::kScale); + auto* transform = + MakeGarbageCollected<SVGTransform>(SVGTransformType::kScale); transform->SetScale(ToInterpolableNumber(list.Get(0))->Value(), ToInterpolableNumber(list.Get(1))->Value()); return transform; @@ -95,7 +98,8 @@ SVGTransform* RotateFromInterpolableValue(const InterpolableValue& value) { const InterpolableList& list = ToInterpolableList(value); - SVGTransform* transform = SVGTransform::Create(SVGTransformType::kRotate); + auto* transform = + MakeGarbageCollected<SVGTransform>(SVGTransformType::kRotate); transform->SetRotate(ToInterpolableNumber(list.Get(0))->Value(), ToInterpolableNumber(list.Get(1))->Value(), ToInterpolableNumber(list.Get(2))->Value()); @@ -108,7 +112,8 @@ } SVGTransform* SkewXFromInterpolableValue(const InterpolableValue& value) { - SVGTransform* transform = SVGTransform::Create(SVGTransformType::kSkewx); + auto* transform = + MakeGarbageCollected<SVGTransform>(SVGTransformType::kSkewx); transform->SetSkewX(ToInterpolableNumber(value).Value()); return transform; } @@ -119,7 +124,8 @@ } SVGTransform* SkewYFromInterpolableValue(const InterpolableValue& value) { - SVGTransform* transform = SVGTransform::Create(SVGTransformType::kSkewy); + auto* transform = + MakeGarbageCollected<SVGTransform>(SVGTransformType::kSkewy); transform->SetSkewY(ToInterpolableNumber(value).Value()); return transform; } @@ -279,7 +285,7 @@ SVGPropertyBase* SVGTransformListInterpolationType::AppliedSVGValue( const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value) const { - SVGTransformList* result = SVGTransformList::Create(); + auto* result = MakeGarbageCollected<SVGTransformList>(); const InterpolableList& list = ToInterpolableList(interpolable_value); const Vector<SVGTransformType>& transform_types = ToSVGTransformNonInterpolableValue(non_interpolable_value)
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index 445ff6dd..be029f1 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -275,6 +275,7 @@ #include "third_party/blink/renderer/platform/cross_thread_functional.h" #include "third_party/blink/renderer/platform/date_components.h" #include "third_party/blink/renderer/platform/geometry/length_functions.h" +#include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/histogram.h" #include "third_party/blink/renderer/platform/instance_counters.h" #include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/frame_resource_coordinator.h" @@ -1673,7 +1674,7 @@ Element* element = documentElement(); if (IsSVGSVGElement(element)) { if (!title_element_) { - title_element_ = SVGTitleElement::Create(*this); + title_element_ = MakeGarbageCollected<SVGTitleElement>(*this); element->InsertBefore(title_element_.Get(), element->firstChild()); } if (auto* svg_title = ToSVGTitleElementOrNull(title_element_)) @@ -3853,41 +3854,35 @@ void Document::write(v8::Isolate* isolate, const Vector<String>& text, ExceptionState& exception_state) { - if (IsTrustedTypesEnabledForDoc()) { - DCHECK(origin_trials::TrustedDOMTypesEnabled(this)); - exception_state.ThrowTypeError( - "This document can only write `TrustedHTML` objects."); - return; - } - if (!AllowedToUseDynamicMarkUpInsertion("write", exception_state)) return; StringBuilder builder; for (const String& string : text) builder.Append(string); - write(builder.ToString(), EnteredDOMWindow(isolate)->document(), - exception_state); + String string = + GetStringFromTrustedHTML(builder.ToString(), this, exception_state); + if (exception_state.HadException()) + return; + + write(string, EnteredDOMWindow(isolate)->document(), exception_state); } void Document::writeln(v8::Isolate* isolate, const Vector<String>& text, ExceptionState& exception_state) { - if (IsTrustedTypesEnabledForDoc()) { - DCHECK(origin_trials::TrustedDOMTypesEnabled(this)); - exception_state.ThrowTypeError( - "This document can only write `TrustedHTML` objects."); - return; - } - if (!AllowedToUseDynamicMarkUpInsertion("writeln", exception_state)) return; StringBuilder builder; for (const String& string : text) builder.Append(string); - writeln(builder.ToString(), EnteredDOMWindow(isolate)->document(), - exception_state); + String string = + GetStringFromTrustedHTML(builder.ToString(), this, exception_state); + if (exception_state.HadException()) + return; + + writeln(string, EnteredDOMWindow(isolate)->document(), exception_state); } bool Document::IsTrustedTypesEnabledForDoc() const {
diff --git a/third_party/blink/renderer/core/dom/document.idl b/third_party/blink/renderer/core/dom/document.idl index 53d4e05..fdef9500 100644 --- a/third_party/blink/renderer/core/dom/document.idl +++ b/third_party/blink/renderer/core/dom/document.idl
@@ -121,8 +121,8 @@ [CallWith=Isolate, CEReactions, CustomElementCallbacks, RaisesException] void writeln(DOMString... text); // TrustedTypes variants of the above. - // Note: This should be gated on [OriginTrialEnabled=TrustedDOMTypes], but - // since OriginTrialEnabled isn't compatible with overloaded methods, we're + // Note: This should be gated on [RuntimeEnabled=TrustedDOMTypes], but + // since RuntimeEnabled isn't compatible with overloaded methods, we're // handling these unconditionally. [CallWith=Isolate, CEReactions, CustomElementCallbacks, RaisesException] void write(TrustedHTML text); [CallWith=Isolate, CEReactions, CustomElementCallbacks, RaisesException] void writeln(TrustedHTML text); @@ -169,7 +169,7 @@ // Custom Elements // https://w3c.github.io/webcomponents/spec/custom/#extensions-to-document-interface-to-register // FIXME: The registerElement return type should be Function. - [OriginTrialEnabled=CustomElementsV0, CallWith=ScriptState, CustomElementCallbacks, RaisesException, DeprecateAs=DocumentRegisterElement] any registerElement(DOMString type, optional ElementRegistrationOptions options); + [RuntimeEnabled=CustomElementsV0, CallWith=ScriptState, CustomElementCallbacks, RaisesException, DeprecateAs=DocumentRegisterElement] any registerElement(DOMString type, optional ElementRegistrationOptions options); // https://w3c.github.io/webcomponents/spec/custom/#extensions-to-document-interface-to-instantiate [CustomElementCallbacks, PerWorldBindings, RaisesException, ImplementedAs=CreateElementForBinding] Element createElement(DOMString localName, (DOMString or ElementCreationOptions) options); [CustomElementCallbacks, RaisesException] Element createElementNS(DOMString? namespaceURI, DOMString qualifiedName, (DOMString or ElementCreationOptions) options);
diff --git a/third_party/blink/renderer/core/dom/element.idl b/third_party/blink/renderer/core/dom/element.idl index 39aeb5b..e133a96 100644 --- a/third_party/blink/renderer/core/dom/element.idl +++ b/third_party/blink/renderer/core/dom/element.idl
@@ -122,8 +122,8 @@ // Non-standard API [MeasureAs=ElementScrollIntoViewIfNeeded] void scrollIntoViewIfNeeded(optional boolean centerIfNeeded); - [OriginTrialEnabled=ShadowDOMV0, RaisesException, DeprecateAs=ElementCreateShadowRoot] ShadowRoot createShadowRoot(); - [OriginTrialEnabled=ShadowDOMV0] NodeList getDestinationInsertionPoints(); + [RuntimeEnabled=ShadowDOMV0, RaisesException, DeprecateAs=ElementCreateShadowRoot] ShadowRoot createShadowRoot(); + [RuntimeEnabled=ShadowDOMV0] NodeList getDestinationInsertionPoints(); // Experimental accessibility API [RuntimeEnabled=ComputedAccessibilityInfo] readonly attribute DOMString? computedRole;
diff --git a/third_party/blink/renderer/core/dom/global_event_handlers.idl b/third_party/blink/renderer/core/dom/global_event_handlers.idl index aa26190..db74edf 100644 --- a/third_party/blink/renderer/core/dom/global_event_handlers.idl +++ b/third_party/blink/renderer/core/dom/global_event_handlers.idl
@@ -120,10 +120,10 @@ // Touch Events // https://w3c.github.io/touch-events/#extensions-to-the-globaleventhandlers-interface - [OriginTrialEnabled=TouchEventFeatureDetection] attribute EventHandler ontouchcancel; - [OriginTrialEnabled=TouchEventFeatureDetection] attribute EventHandler ontouchend; - [OriginTrialEnabled=TouchEventFeatureDetection] attribute EventHandler ontouchmove; - [OriginTrialEnabled=TouchEventFeatureDetection] attribute EventHandler ontouchstart; + [RuntimeEnabled=TouchEventFeatureDetection] attribute EventHandler ontouchcancel; + [RuntimeEnabled=TouchEventFeatureDetection] attribute EventHandler ontouchend; + [RuntimeEnabled=TouchEventFeatureDetection] attribute EventHandler ontouchmove; + [RuntimeEnabled=TouchEventFeatureDetection] attribute EventHandler ontouchstart; // Selection API // https://w3c.github.io/selection-api/#extensions-to-globaleventhandlers
diff --git a/third_party/blink/renderer/core/dom/range.cc b/third_party/blink/renderer/core/dom/range.cc index cc19b21..1f121cc 100644 --- a/third_party/blink/renderer/core/dom/range.cc +++ b/third_party/blink/renderer/core/dom/range.cc
@@ -58,6 +58,7 @@ #include "third_party/blink/renderer/core/trustedtypes/trusted_types_util.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/geometry/float_quad.h" +#include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" @@ -1017,7 +1018,7 @@ if (document.IsSVGDocument()) { element = document.documentElement(); if (!element) - element = SVGSVGElement::Create(document); + element = MakeGarbageCollected<SVGSVGElement>(document); } else { // Optimization over spec: try to reuse the existing <body> element, if it // is available.
diff --git a/third_party/blink/renderer/core/dom/text.idl b/third_party/blink/renderer/core/dom/text.idl index 7c814da..36f98f54 100644 --- a/third_party/blink/renderer/core/dom/text.idl +++ b/third_party/blink/renderer/core/dom/text.idl
@@ -31,5 +31,5 @@ [ImplementedAs=assignedSlotForBinding] readonly attribute HTMLSlotElement? assignedSlot; // Non-standard API: - [OriginTrialEnabled=ShadowDOMV0] NodeList getDestinationInsertionPoints(); + [RuntimeEnabled=ShadowDOMV0] NodeList getDestinationInsertionPoints(); };
diff --git a/third_party/blink/renderer/core/fetch/request_init.idl b/third_party/blink/renderer/core/fetch/request_init.idl index 267391de..82e7336 100644 --- a/third_party/blink/renderer/core/fetch/request_init.idl +++ b/third_party/blink/renderer/core/fetch/request_init.idl
@@ -21,7 +21,7 @@ RequestRedirect redirect; DOMString integrity; boolean keepalive; - [OriginTrialEnabled=PriorityHints] RequestImportance importance; + [RuntimeEnabled=PriorityHints] RequestImportance importance; AbortSignal? signal; // TODO(domfarolino): add support for RequestInit window member. //any window; // can only be set to null
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index afe1f27..1612018 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -961,11 +961,11 @@ if (nested_layout_count_) return; -#if DCHECK_IS_ON() + // TODO(crbug.com/946004): Move the following line into a DCHECK_IS_ON() block + // when we no longer see missing layout reports in LayoutNG. // Post-layout assert that nobody was re-marked as needing layout during // layout. GetLayoutView()->AssertSubtreeIsLaidOut(); -#endif if (frame_->IsMainFrame()) { // Scrollbars changing state can cause a visual viewport size change. @@ -2884,9 +2884,9 @@ // These asserts ensure that parent frames are clean, when child frames // finished updating layout and style. CheckDoesNotNeedLayout(); -#if DCHECK_IS_ON() + // TODO(crbug.com/946004): Move the following line into a DCHECK_IS_ON() block + // when we no longer see missing layout reports in LayoutNG. frame_->GetDocument()->GetLayoutView()->AssertLaidOut(); -#endif UpdateGeometriesIfNeeded();
diff --git a/third_party/blink/renderer/core/frame/navigator_scheduling.idl b/third_party/blink/renderer/core/frame/navigator_scheduling.idl index 5fa17284..76d9e9b 100644 --- a/third_party/blink/renderer/core/frame/navigator_scheduling.idl +++ b/third_party/blink/renderer/core/frame/navigator_scheduling.idl
@@ -6,7 +6,7 @@ [ Exposed=Window, ImplementedAs=NavigatorScheduling, - OriginTrialEnabled=ExperimentalIsInputPending + RuntimeEnabled=ExperimentalIsInputPending ] partial interface Navigator { readonly attribute Scheduling scheduling; };
diff --git a/third_party/blink/renderer/core/frame/scheduling.idl b/third_party/blink/renderer/core/frame/scheduling.idl index 6da75165..61441a9 100644 --- a/third_party/blink/renderer/core/frame/scheduling.idl +++ b/third_party/blink/renderer/core/frame/scheduling.idl
@@ -3,7 +3,7 @@ // found in the LICENSE file. // https://github.com/tdresser/is-input-pending -[OriginTrialEnabled=ExperimentalIsInputPending] +[RuntimeEnabled=ExperimentalIsInputPending] interface Scheduling { - [CallWith=ScriptState, MeasureAs=SchedulingIsInputPending, OriginTrialEnabled=ExperimentalIsInputPending] boolean isInputPending(optional sequence<DOMString> inputTypes = []); + [CallWith=ScriptState, MeasureAs=SchedulingIsInputPending, RuntimeEnabled=ExperimentalIsInputPending] boolean isInputPending(optional sequence<DOMString> inputTypes = []); };
diff --git a/third_party/blink/renderer/core/frame/window.idl b/third_party/blink/renderer/core/frame/window.idl index 9f3ed35..a438328 100644 --- a/third_party/blink/renderer/core/frame/window.idl +++ b/third_party/blink/renderer/core/frame/window.idl
@@ -215,7 +215,7 @@ attribute DOMMatrixConstructor WebKitCSSMatrix; // TrustedTypes API: http://github.com/wicg/trusted-types - [OriginTrialEnabled=TrustedDOMTypes, Unforgeable] readonly attribute TrustedTypePolicyFactory TrustedTypes; + [RuntimeEnabled=TrustedDOMTypes, Unforgeable] readonly attribute TrustedTypePolicyFactory TrustedTypes; }; Window includes GlobalEventHandlers;
diff --git a/third_party/blink/renderer/core/html/html_anchor_element.idl b/third_party/blink/renderer/core/html/html_anchor_element.idl index 96902d9..bc7dc363 100644 --- a/third_party/blink/renderer/core/html/html_anchor_element.idl +++ b/third_party/blink/renderer/core/html/html_anchor_element.idl
@@ -27,7 +27,7 @@ [CEReactions, Reflect] attribute DOMString rel; [SameObject, PutForwards=value] readonly attribute DOMTokenList relList; [CEReactions, Reflect] attribute DOMString hreflang; - [OriginTrialEnabled=HrefTranslate, CEReactions, Reflect] attribute DOMString hrefTranslate; + [RuntimeEnabled=HrefTranslate, CEReactions, Reflect] attribute DOMString hrefTranslate; [CEReactions, Reflect] attribute DOMString type; [CEReactions, Reflect, ReflectOnly=("","no-referrer","origin","no-referrer-when-downgrade","origin-when-cross-origin","unsafe-url"), ReflectMissing="", ReflectInvalid=""] attribute DOMString referrerPolicy;
diff --git a/third_party/blink/renderer/core/html/html_image_element.idl b/third_party/blink/renderer/core/html/html_image_element.idl index f7f066d..4d332ec 100644 --- a/third_party/blink/renderer/core/html/html_image_element.idl +++ b/third_party/blink/renderer/core/html/html_image_element.idl
@@ -41,7 +41,7 @@ readonly attribute DOMString currentSrc; [CEReactions, Reflect, ReflectOnly=("","no-referrer","origin","no-referrer-when-downgrade","origin-when-cross-origin","unsafe-url"), ReflectMissing="", ReflectInvalid=""] attribute DOMString referrerPolicy; [CEReactions, Reflect, ReflectOnly=("async", "sync", "auto"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString decoding; - [CEReactions, MeasureAs=PriorityHints, OriginTrialEnabled=PriorityHints, Reflect, ReflectOnly=("low", "auto", "high"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString importance; + [CEReactions, MeasureAs=PriorityHints, RuntimeEnabled=PriorityHints, Reflect, ReflectOnly=("low", "auto", "high"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString importance; // https://github.com/ojanvafai/intrinsicsize-attribute/blob/master/README.md [RuntimeEnabled=ExperimentalProductivityFeatures, CEReactions, Reflect] attribute DOMString intrinsicSize; [RuntimeEnabled=LazyImageLoading, CEReactions, Reflect, ReflectOnly=("lazy", "eager", "auto"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString loading;
diff --git a/third_party/blink/renderer/core/html/html_link_element.idl b/third_party/blink/renderer/core/html/html_link_element.idl index 2390dbb..e812054 100644 --- a/third_party/blink/renderer/core/html/html_link_element.idl +++ b/third_party/blink/renderer/core/html/html_link_element.idl
@@ -35,7 +35,7 @@ [Reflect, ReflectOnly=("script","style","image", "track", "font", "fetch")] attribute DOMString as; [CEReactions, Reflect, ReflectOnly=("","no-referrer","origin","no-referrer-when-downgrade","origin-when-cross-origin","unsafe-url"), ReflectMissing="", ReflectInvalid=""] attribute DOMString referrerPolicy; [PutForwards=value] readonly attribute DOMTokenList sizes; - [CEReactions, MeasureAs=PriorityHints, OriginTrialEnabled=PriorityHints, Reflect, ReflectOnly=("low", "auto", "high"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString importance; + [CEReactions, MeasureAs=PriorityHints, RuntimeEnabled=PriorityHints, Reflect, ReflectOnly=("low", "auto", "high"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString importance; [CEReactions, Reflect] attribute DOMString imageSrcset; [CEReactions, Reflect] attribute DOMString imageSizes; @@ -51,7 +51,7 @@ // HTML Imports // https://w3c.github.io/webcomponents/spec/imports/#interface-import - [OriginTrialEnabled=HTMLImports] readonly attribute Document? import; + [RuntimeEnabled=HTMLImports] readonly attribute Document? import; // Subresource Integrity // https://w3c.github.io/webappsec-subresource-integrity/#HTMLLinkElement
diff --git a/third_party/blink/renderer/core/html/html_script_element.idl b/third_party/blink/renderer/core/html/html_script_element.idl index 49bceea..475f5516 100644 --- a/third_party/blink/renderer/core/html/html_script_element.idl +++ b/third_party/blink/renderer/core/html/html_script_element.idl
@@ -29,7 +29,7 @@ [CEReactions, Reflect, ReflectOnly=("anonymous","use-credentials"), ReflectEmpty="anonymous", ReflectInvalid="anonymous"] attribute DOMString? crossOrigin; [CEReactions, RaisesException=Setter] attribute ScriptString text; [CEReactions, Reflect, ReflectOnly=("", "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url"), ReflectEmpty="", ReflectInvalid=""] attribute DOMString? referrerPolicy; - [CEReactions, MeasureAs=PriorityHints, OriginTrialEnabled=PriorityHints, Reflect, ReflectOnly=("low", "auto", "high"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString importance; + [CEReactions, MeasureAs=PriorityHints, RuntimeEnabled=PriorityHints, Reflect, ReflectOnly=("low", "auto", "high"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString importance; // obsolete members // https://html.spec.whatwg.org/C/#HTMLScriptElement-partial
diff --git a/third_party/blink/renderer/core/layout/layout_object.h b/third_party/blink/renderer/core/layout/layout_object.h index 8e03acb..401f04d 100644 --- a/third_party/blink/renderer/core/layout/layout_object.h +++ b/third_party/blink/renderer/core/layout/layout_object.h
@@ -392,6 +392,11 @@ LayoutObject& layout_object_; bool preexisting_forbidden_; }; +#endif // DCHECK_IS_ON() + + // TODO(crbug.com/946004): When we no longer see missing layouts in LayoutNG, + // move the following two functions back to the DCHECK_IS_ON() block and + // remove relevant branches and CHECK. void AssertLaidOut() const { #ifndef NDEBUG @@ -399,9 +404,16 @@ ShowLayoutTreeForThis(); #endif SECURITY_DCHECK(!NeedsLayout() || LayoutBlockedByDisplayLock()); + if (!RuntimeEnabledFeatures::LayoutNGEnabled()) + return; + CHECK(!NeedsLayout() || LayoutBlockedByDisplayLock()) << this; } void AssertSubtreeIsLaidOut() const { +#if !DCHECK_IS_ON() + if (!RuntimeEnabledFeatures::LayoutNGEnabled()) + return; +#endif for (const LayoutObject* layout_object = this; layout_object; layout_object = layout_object->LayoutBlockedByDisplayLock() ? layout_object->NextInPreOrderAfterChildren() @@ -410,6 +422,7 @@ } } +#if DCHECK_IS_ON() void AssertClearedPaintInvalidationFlags() const { #ifndef NDEBUG if (PaintInvalidationStateIsDirty() && !PrePaintBlockedByDisplayLock()) { @@ -428,7 +441,7 @@ } } -#endif +#endif // DCHECK_IS_ON() // LayoutObject tree manipulation //////////////////////////////////////////
diff --git a/third_party/blink/renderer/core/layout/layout_object_test.cc b/third_party/blink/renderer/core/layout/layout_object_test.cc index c4d21205..b7ef26d 100644 --- a/third_party/blink/renderer/core/layout/layout_object_test.cc +++ b/third_party/blink/renderer/core/layout/layout_object_test.cc
@@ -17,6 +17,7 @@ #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" #include "third_party/blink/renderer/core/testing/sim/sim_request.h" #include "third_party/blink/renderer/core/testing/sim/sim_test.h" +#include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/json/json_values.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" @@ -760,7 +761,7 @@ )HTML"); Element* span = GetDocument().getElementById("span"); - SVGGElement* svg_element = SVGGElement::Create(GetDocument()); + auto* svg_element = MakeGarbageCollected<SVGGElement>(GetDocument()); Text* text = Text::Create(GetDocument(), "text"); svg_element->appendChild(text); span->appendChild(svg_element);
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc index a794cca..11ef8316 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc
@@ -21,13 +21,15 @@ #include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.h" #include "third_party/blink/renderer/core/svg/svg_linear_gradient_element.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { LayoutSVGResourceLinearGradient::LayoutSVGResourceLinearGradient( SVGLinearGradientElement* node) : LayoutSVGResourceGradient(node), - attributes_wrapper_(LinearGradientAttributesWrapper::Create()) {} + attributes_wrapper_( + MakeGarbageCollected<LinearGradientAttributesWrapper>()) {} LayoutSVGResourceLinearGradient::~LayoutSVGResourceLinearGradient() = default;
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc index 34353ae..8d59e14b 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc
@@ -34,6 +34,7 @@ #include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -48,7 +49,7 @@ LayoutSVGResourcePattern::LayoutSVGResourcePattern(SVGPatternElement* node) : LayoutSVGResourcePaintServer(node), should_collect_pattern_attributes_(true), - attributes_wrapper_(PatternAttributesWrapper::Create()), + attributes_wrapper_(MakeGarbageCollected<PatternAttributesWrapper>()), pattern_map_(MakeGarbageCollected<PatternMap>()) {} void LayoutSVGResourcePattern::RemoveAllClientsFromCache(
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc index 5d970f9..8bd1e0d 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc
@@ -22,13 +22,15 @@ #include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.h" #include "third_party/blink/renderer/core/svg/svg_radial_gradient_element.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { LayoutSVGResourceRadialGradient::LayoutSVGResourceRadialGradient( SVGRadialGradientElement* node) : LayoutSVGResourceGradient(node), - attributes_wrapper_(RadialGradientAttributesWrapper::Create()) {} + attributes_wrapper_( + MakeGarbageCollected<RadialGradientAttributesWrapper>()) {} LayoutSVGResourceRadialGradient::~LayoutSVGResourceRadialGradient() = default;
diff --git a/third_party/blink/renderer/core/loader/base_fetch_context.cc b/third_party/blink/renderer/core/loader/base_fetch_context.cc index 32ad63e..7f8582e8 100644 --- a/third_party/blink/renderer/core/loader/base_fetch_context.cc +++ b/third_party/blink/renderer/core/loader/base_fetch_context.cc
@@ -144,7 +144,7 @@ scoped_refptr<SecurityOrigin> url_origin = SecurityOrigin::Create(request.Url()); - if (blink::RuntimeEnabledFeatures::SecMetadataEnabled() && + if (blink::RuntimeEnabledFeatures::FetchMetadataEnabled() && url_origin->IsPotentiallyTrustworthy()) { const char* destination_value = GetDestinationFromContext(request.GetRequestContext()); @@ -154,7 +154,7 @@ if (strlen(destination_value) == 0) destination_value = "empty"; - // We'll handle adding the header to navigations outside of Blink. + // We'll handle adding these headers to navigations outside of Blink. if (strncmp(destination_value, "document", 8) != 0 && request.GetRequestContext() != mojom::RequestContextType::INTERNAL) { const char* site_value = "cross-site"; @@ -173,7 +173,10 @@ } } - request.SetHttpHeaderField("Sec-Fetch-Dest", destination_value); + if (blink::RuntimeEnabledFeatures::FetchMetadataDestinationEnabled()) { + request.SetHttpHeaderField("Sec-Fetch-Dest", destination_value); + } + request.SetHttpHeaderField( "Sec-Fetch-Mode", FetchRequestModeToString(request.GetFetchRequestMode()));
diff --git a/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc b/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc index 84fe45a..39c1afc0 100644 --- a/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc +++ b/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc
@@ -39,6 +39,7 @@ #include "third_party/blink/renderer/core/svg/svg_uri_reference.h" #include "third_party/blink/renderer/core/xlink_names.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/math_extras.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -53,6 +54,8 @@ Cancelable::kNo, repeat); } + RepeatEvent(const AtomicString& type, int repeat) + : RepeatEvent(type, Bubbles::kNo, Cancelable::kNo, repeat) {} RepeatEvent(const AtomicString& type, Bubbles bubbles, Cancelable cancelable, @@ -1241,7 +1244,8 @@ if (event_type == "repeatn") { unsigned repeat_event_count = repeat_event_count_list_.front(); repeat_event_count_list_.EraseAt(0); - DispatchEvent(*RepeatEvent::Create(event_type, repeat_event_count)); + DispatchEvent( + *MakeGarbageCollected<RepeatEvent>(event_type, repeat_event_count)); } else { DispatchEvent(*Event::Create(event_type)); }
diff --git a/third_party/blink/renderer/core/svg/linear_gradient_attributes.h b/third_party/blink/renderer/core/svg/linear_gradient_attributes.h index a4de407..26c26add 100644 --- a/third_party/blink/renderer/core/svg/linear_gradient_attributes.h +++ b/third_party/blink/renderer/core/svg/linear_gradient_attributes.h
@@ -23,6 +23,7 @@ #include "third_party/blink/renderer/core/svg/gradient_attributes.h" #include "third_party/blink/renderer/core/svg/svg_length.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { @@ -31,10 +32,10 @@ public: LinearGradientAttributes() - : x1_(SVGLength::Create(SVGLengthMode::kWidth)), - y1_(SVGLength::Create(SVGLengthMode::kHeight)), - x2_(SVGLength::Create(SVGLengthMode::kWidth)), - y2_(SVGLength::Create(SVGLengthMode::kHeight)), + : x1_(MakeGarbageCollected<SVGLength>(SVGLengthMode::kWidth)), + y1_(MakeGarbageCollected<SVGLength>(SVGLengthMode::kHeight)), + x2_(MakeGarbageCollected<SVGLength>(SVGLengthMode::kWidth)), + y2_(MakeGarbageCollected<SVGLength>(SVGLengthMode::kHeight)), x1_set_(false), y1_set_(false), x2_set_(false),
diff --git a/third_party/blink/renderer/core/svg/pattern_attributes.h b/third_party/blink/renderer/core/svg/pattern_attributes.h index 85e7696..970243f 100644 --- a/third_party/blink/renderer/core/svg/pattern_attributes.h +++ b/third_party/blink/renderer/core/svg/pattern_attributes.h
@@ -23,6 +23,7 @@ #include "third_party/blink/renderer/core/svg/svg_length.h" #include "third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/transforms/affine_transform.h" namespace blink { @@ -34,12 +35,12 @@ public: PatternAttributes() - : x_(SVGLength::Create(SVGLengthMode::kWidth)), - y_(SVGLength::Create(SVGLengthMode::kHeight)), - width_(SVGLength::Create(SVGLengthMode::kWidth)), - height_(SVGLength::Create(SVGLengthMode::kHeight)), + : x_(MakeGarbageCollected<SVGLength>(SVGLengthMode::kWidth)), + y_(MakeGarbageCollected<SVGLength>(SVGLengthMode::kHeight)), + width_(MakeGarbageCollected<SVGLength>(SVGLengthMode::kWidth)), + height_(MakeGarbageCollected<SVGLength>(SVGLengthMode::kHeight)), view_box_(), - preserve_aspect_ratio_(SVGPreserveAspectRatio::Create()), + preserve_aspect_ratio_(MakeGarbageCollected<SVGPreserveAspectRatio>()), pattern_units_(SVGUnitTypes::kSvgUnitTypeObjectboundingbox), pattern_content_units_(SVGUnitTypes::kSvgUnitTypeUserspaceonuse), pattern_content_element_(nullptr),
diff --git a/third_party/blink/renderer/core/svg/properties/svg_animated_property.h b/third_party/blink/renderer/core/svg/properties/svg_animated_property.h index fcb9952..66ed2fb 100644 --- a/third_party/blink/renderer/core/svg/properties/svg_animated_property.h +++ b/third_party/blink/renderer/core/svg/properties/svg_animated_property.h
@@ -37,6 +37,7 @@ #include "third_party/blink/renderer/core/svg/properties/svg_property_info.h" #include "third_party/blink/renderer/core/svg/properties/svg_property_tear_off.h" #include "third_party/blink/renderer/core/svg/svg_parsing_error.h" +#include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/heap/member.h" namespace blink { @@ -259,16 +260,16 @@ // Use currentValue() from C++ code. virtual TearOffType* baseVal() { if (!base_val_tear_off_) { - base_val_tear_off_ = - TearOffType::Create(this->BaseValue(), this, kPropertyIsNotAnimVal); + base_val_tear_off_ = MakeGarbageCollected<TearOffType>( + this->BaseValue(), this, kPropertyIsNotAnimVal); } return base_val_tear_off_; } TearOffType* animVal() { if (!anim_val_tear_off_) { - anim_val_tear_off_ = - TearOffType::Create(this->CurrentValue(), this, kPropertyIsAnimVal); + anim_val_tear_off_ = MakeGarbageCollected<TearOffType>( + this->CurrentValue(), this, kPropertyIsAnimVal); } return anim_val_tear_off_; }
diff --git a/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h b/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h index 2e9b227..8668172 100644 --- a/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h +++ b/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h
@@ -35,6 +35,7 @@ #include "third_party/blink/renderer/core/svg/svg_animation_element.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" +#include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/vector.h" @@ -106,7 +107,7 @@ bool IsEmpty() const { return !length(); } virtual Derived* Clone() { - Derived* svg_list = Derived::Create(); + auto* svg_list = MakeGarbageCollected<Derived>(); svg_list->DeepCopy(static_cast<Derived*>(this)); return svg_list; } @@ -140,7 +141,7 @@ String SerializeList() const; virtual ItemPropertyType* CreatePaddingItem() const { - return ItemPropertyType::Create(); + return MakeGarbageCollected<ItemPropertyType>(); } private:
diff --git a/third_party/blink/renderer/core/svg/svg_g_element.cc b/third_party/blink/renderer/core/svg/svg_g_element.cc index cbfaae7..160c5de 100644 --- a/third_party/blink/renderer/core/svg/svg_g_element.cc +++ b/third_party/blink/renderer/core/svg/svg_g_element.cc
@@ -26,8 +26,7 @@ namespace blink { -inline SVGGElement::SVGGElement(Document& document, - ConstructionType construction_type) +SVGGElement::SVGGElement(Document& document, ConstructionType construction_type) : SVGGraphicsElement(svg_names::kGTag, document, construction_type) {} DEFINE_NODE_FACTORY(SVGGElement)
diff --git a/third_party/blink/renderer/core/svg/svg_length.h b/third_party/blink/renderer/core/svg/svg_length.h index 27b03f6..79a92d20 100644 --- a/third_party/blink/renderer/core/svg/svg_length.h +++ b/third_party/blink/renderer/core/svg/svg_length.h
@@ -57,7 +57,7 @@ static constexpr int kInitialValueBits = 3; static SVGLength* Create(Initial, SVGLengthMode); - explicit SVGLength(SVGLengthMode); + explicit SVGLength(SVGLengthMode = SVGLengthMode::kOther); SVGLength(const CSSPrimitiveValue&, SVGLengthMode); SVGLength(const SVGLength&);
diff --git a/third_party/blink/renderer/core/svg/svg_length_list.h b/third_party/blink/renderer/core/svg/svg_length_list.h index e8317624..1407280f9 100644 --- a/third_party/blink/renderer/core/svg/svg_length_list.h +++ b/third_party/blink/renderer/core/svg/svg_length_list.h
@@ -48,7 +48,7 @@ return MakeGarbageCollected<SVGLengthList>(mode); } - explicit SVGLengthList(SVGLengthMode); + explicit SVGLengthList(SVGLengthMode = SVGLengthMode::kOther); ~SVGLengthList() override; SVGParsingError SetValueAsString(const String&);
diff --git a/third_party/blink/renderer/core/svg/svg_number.h b/third_party/blink/renderer/core/svg/svg_number.h index efd281a..456f49e 100644 --- a/third_party/blink/renderer/core/svg/svg_number.h +++ b/third_party/blink/renderer/core/svg/svg_number.h
@@ -48,7 +48,7 @@ return MakeGarbageCollected<SVGNumber>(value); } - explicit SVGNumber(float); + explicit SVGNumber(float = 0.0f); virtual SVGNumber* Clone() const;
diff --git a/third_party/blink/renderer/core/svg/svg_svg_element.cc b/third_party/blink/renderer/core/svg/svg_svg_element.cc index 0a18c3ea..61eef2c1 100644 --- a/third_party/blink/renderer/core/svg/svg_svg_element.cc +++ b/third_party/blink/renderer/core/svg/svg_svg_element.cc
@@ -61,7 +61,7 @@ namespace blink { -inline SVGSVGElement::SVGSVGElement(Document& doc) +SVGSVGElement::SVGSVGElement(Document& doc) : SVGGraphicsElement(svg_names::kSVGTag, doc), SVGFitToViewBox(this), x_(SVGAnimatedLength::Create(this,
diff --git a/third_party/blink/renderer/core/svg/svg_title_element.cc b/third_party/blink/renderer/core/svg/svg_title_element.cc index 8609f51d..36e60b4 100644 --- a/third_party/blink/renderer/core/svg/svg_title_element.cc +++ b/third_party/blink/renderer/core/svg/svg_title_element.cc
@@ -28,7 +28,7 @@ namespace blink { -inline SVGTitleElement::SVGTitleElement(Document& document) +SVGTitleElement::SVGTitleElement(Document& document) : SVGElement(svg_names::kTitleTag, document), ignore_title_updates_when_children_change_(false) {}
diff --git a/third_party/blink/renderer/core/svg/svg_transform.h b/third_party/blink/renderer/core/svg/svg_transform.h index e7ae164..5f77e3a 100644 --- a/third_party/blink/renderer/core/svg/svg_transform.h +++ b/third_party/blink/renderer/core/svg/svg_transform.h
@@ -63,7 +63,8 @@ } SVGTransform(); - SVGTransform(SVGTransformType, ConstructionMode); + explicit SVGTransform(SVGTransformType, + ConstructionMode = kConstructIdentityTransform); explicit SVGTransform(const AffineTransform&); SVGTransform(SVGTransformType, float,
diff --git a/third_party/blink/renderer/core/testing/origin_trials_test.idl b/third_party/blink/renderer/core/testing/origin_trials_test.idl index 8f5717be..0efc139 100644 --- a/third_party/blink/renderer/core/testing/origin_trials_test.idl +++ b/third_party/blink/renderer/core/testing/origin_trials_test.idl
@@ -3,11 +3,11 @@ // found in the LICENSE file. interface OriginTrialsTest { - [OriginTrialEnabled=OriginTrialsSampleAPI] readonly attribute boolean normalAttribute; - [OriginTrialEnabled=OriginTrialsSampleAPI] static readonly attribute boolean staticAttribute; - [OriginTrialEnabled=OriginTrialsSampleAPI] boolean normalMethod(); - [OriginTrialEnabled=OriginTrialsSampleAPI] static boolean staticMethod(); - [OriginTrialEnabled=OriginTrialsSampleAPI] const unsigned short CONSTANT = 1; + [RuntimeEnabled=OriginTrialsSampleAPI] readonly attribute boolean normalAttribute; + [RuntimeEnabled=OriginTrialsSampleAPI] static readonly attribute boolean staticAttribute; + [RuntimeEnabled=OriginTrialsSampleAPI] boolean normalMethod(); + [RuntimeEnabled=OriginTrialsSampleAPI] static boolean staticMethod(); + [RuntimeEnabled=OriginTrialsSampleAPI] const unsigned short CONSTANT = 1; // This attribute uses native code to test whether the trial is enabled, // and throws an exception in JavaScript if it is not. @@ -33,22 +33,22 @@ // secure context [SecureContext] readonly attribute boolean secureUnconditionalAttribute; // TODO(chasej): Add [SecureContext] when that attribute is fixed to work on - // static attributes. That problem is not related to [OriginTrialEnabled]. + // static attributes. That problem is not related to [RuntimeEnabled]. static readonly attribute boolean secureStaticUnconditionalAttribute; [SecureContext] boolean secureUnconditionalMethod(); [SecureContext] static boolean secureStaticUnconditionalMethod(); // These are only available if the trial is enabled, as well as in secure // context. - [SecureContext, OriginTrialEnabled=OriginTrialsSampleAPI] readonly attribute boolean secureAttribute; - [SecureContext, OriginTrialEnabled=OriginTrialsSampleAPI] static readonly attribute boolean secureStaticAttribute; - [SecureContext, OriginTrialEnabled=OriginTrialsSampleAPI] boolean secureMethod(); - [SecureContext, OriginTrialEnabled=OriginTrialsSampleAPI] static boolean secureStaticMethod(); + [SecureContext, RuntimeEnabled=OriginTrialsSampleAPI] readonly attribute boolean secureAttribute; + [SecureContext, RuntimeEnabled=OriginTrialsSampleAPI] static readonly attribute boolean secureStaticAttribute; + [SecureContext, RuntimeEnabled=OriginTrialsSampleAPI] boolean secureMethod(); + [SecureContext, RuntimeEnabled=OriginTrialsSampleAPI] static boolean secureStaticMethod(); // These are available if the specified trial is available, and also if the // implied by trial is enabled - [OriginTrialEnabled=OriginTrialsSampleAPIImplied] readonly attribute boolean impliedAttribute; + [RuntimeEnabled=OriginTrialsSampleAPIImplied] readonly attribute boolean impliedAttribute; // These are not available even with the token present. - [OriginTrialEnabled=OriginTrialsSampleAPIInvalidOS] readonly attribute boolean invalidOSAttribute; + [RuntimeEnabled=OriginTrialsSampleAPIInvalidOS] readonly attribute boolean invalidOSAttribute; };
diff --git a/third_party/blink/renderer/core/testing/origin_trials_test_dictionary.idl b/third_party/blink/renderer/core/testing/origin_trials_test_dictionary.idl index afbb73133..1f0ff3a 100644 --- a/third_party/blink/renderer/core/testing/origin_trials_test_dictionary.idl +++ b/third_party/blink/renderer/core/testing/origin_trials_test_dictionary.idl
@@ -4,5 +4,5 @@ dictionary OriginTrialsTestDictionary { boolean unconditionalBool = true; - [OriginTrialEnabled=OriginTrialsSampleAPI] boolean normalBool = true; + [RuntimeEnabled=OriginTrialsSampleAPI] boolean normalBool = true; };
diff --git a/third_party/blink/renderer/core/testing/origin_trials_test_partial.idl b/third_party/blink/renderer/core/testing/origin_trials_test_partial.idl index 9cf0e48..fc39c78 100644 --- a/third_party/blink/renderer/core/testing/origin_trials_test_partial.idl +++ b/third_party/blink/renderer/core/testing/origin_trials_test_partial.idl
@@ -4,7 +4,7 @@ [ ImplementedAs=OriginTrialsTestPartial, - OriginTrialEnabled=OriginTrialsSampleAPI + RuntimeEnabled=OriginTrialsSampleAPI ] partial interface OriginTrialsTest { const unsigned short CONSTANT_PARTIAL = 2; readonly attribute boolean normalAttributePartial;
diff --git a/third_party/blink/renderer/core/timing/memory_info.idl b/third_party/blink/renderer/core/timing/memory_info.idl index f3f531e..dcac531 100644 --- a/third_party/blink/renderer/core/timing/memory_info.idl +++ b/third_party/blink/renderer/core/timing/memory_info.idl
@@ -37,6 +37,6 @@ [Measure] readonly attribute unsigned long long totalJSHeapSize; [Measure] readonly attribute unsigned long long usedJSHeapSize; [Measure] readonly attribute unsigned long long jsHeapSizeLimit; - [OriginTrialEnabled=LegacyPerformanceMemoryCounters] readonly attribute unsigned long long usedJSHeapSizeWithoutExternalMemory; - [OriginTrialEnabled=LegacyPerformanceMemoryCounters] readonly attribute unsigned long long totalJSHeapSizeWithoutExternalMemory; + [RuntimeEnabled=LegacyPerformanceMemoryCounters] readonly attribute unsigned long long usedJSHeapSizeWithoutExternalMemory; + [RuntimeEnabled=LegacyPerformanceMemoryCounters] readonly attribute unsigned long long totalJSHeapSizeWithoutExternalMemory; };
diff --git a/third_party/blink/renderer/core/timing/performance.idl b/third_party/blink/renderer/core/timing/performance.idl index 1409ca8..496ef9f 100644 --- a/third_party/blink/renderer/core/timing/performance.idl +++ b/third_party/blink/renderer/core/timing/performance.idl
@@ -53,16 +53,16 @@ // Element Timing // https://github.com/npm1/Element-Timing - [MeasureAs=ElementTimingExplicitlyRequested, OriginTrialEnabled=ElementTiming] void clearElementTimings(); - [MeasureAs=ElementTimingExplicitlyRequested, OriginTrialEnabled=ElementTiming] void setElementTimingBufferMaxSize(unsigned long maxSize); - [MeasureAs=ElementTimingExplicitlyRequested, OriginTrialEnabled=ElementTiming] attribute EventHandler onelementtimingbufferfull; + [MeasureAs=ElementTimingExplicitlyRequested, RuntimeEnabled=ElementTiming] void clearElementTimings(); + [MeasureAs=ElementTimingExplicitlyRequested, RuntimeEnabled=ElementTiming] void setElementTimingBufferMaxSize(unsigned long maxSize); + [MeasureAs=ElementTimingExplicitlyRequested, RuntimeEnabled=ElementTiming] attribute EventHandler onelementtimingbufferfull; // Event Timing // https://github.com/wicg/event-timing - [MeasureAs=PerformanceEventTimingBuffer, OriginTrialEnabled=EventTiming] void clearEventTimings(); - [MeasureAs=PerformanceEventTimingBuffer, OriginTrialEnabled=EventTiming] void setEventTimingBufferMaxSize(unsigned long maxSize); - [MeasureAs=PerformanceEventTimingBuffer, OriginTrialEnabled=EventTiming] attribute EventHandler oneventtimingbufferfull; + [MeasureAs=PerformanceEventTimingBuffer, RuntimeEnabled=EventTiming] void clearEventTimings(); + [MeasureAs=PerformanceEventTimingBuffer, RuntimeEnabled=EventTiming] void setEventTimingBufferMaxSize(unsigned long maxSize); + [MeasureAs=PerformanceEventTimingBuffer, RuntimeEnabled=EventTiming] attribute EventHandler oneventtimingbufferfull; // Navigation Timing // https://w3c.github.io/navigation-timing/#extensions-to-the-performance-interface
diff --git a/third_party/blink/renderer/core/timing/performance_element_timing.idl b/third_party/blink/renderer/core/timing/performance_element_timing.idl index 99eb393..e91161fd 100644 --- a/third_party/blink/renderer/core/timing/performance_element_timing.idl +++ b/third_party/blink/renderer/core/timing/performance_element_timing.idl
@@ -3,7 +3,7 @@ // found in the LICENSE file. // https://docs.google.com/document/d/1blFeMVdqxB0V3BAJh60ptOBFY7cJSXnf7VyW3wspbZ8 -[OriginTrialEnabled=ElementTiming] +[RuntimeEnabled=ElementTiming] interface PerformanceElementTiming : PerformanceEntry { readonly attribute DOMRectReadOnly intersectionRect; readonly attribute DOMHighResTimeStamp responseEnd;
diff --git a/third_party/blink/renderer/core/timing/performance_event_timing.idl b/third_party/blink/renderer/core/timing/performance_event_timing.idl index ef577a5..364422b8 100644 --- a/third_party/blink/renderer/core/timing/performance_event_timing.idl +++ b/third_party/blink/renderer/core/timing/performance_event_timing.idl
@@ -5,7 +5,7 @@ // https://github.com/wicg/event-timing [ Exposed=Window, - OriginTrialEnabled=EventTiming + RuntimeEnabled=EventTiming ] interface PerformanceEventTiming : PerformanceEntry { readonly attribute DOMHighResTimeStamp processingStart; readonly attribute DOMHighResTimeStamp processingEnd;
diff --git a/third_party/blink/renderer/core/timing/performance_layout_jank.idl b/third_party/blink/renderer/core/timing/performance_layout_jank.idl index a50bfc4..c458b1c 100644 --- a/third_party/blink/renderer/core/timing/performance_layout_jank.idl +++ b/third_party/blink/renderer/core/timing/performance_layout_jank.idl
@@ -3,7 +3,7 @@ // found in the LICENSE file. // https://gist.github.com/skobes/2f296da1b0a88cc785a4bf10a42bca07 -[Exposed=Window, OriginTrialEnabled=LayoutJankAPI] +[Exposed=Window, RuntimeEnabled=LayoutJankAPI] interface PerformanceLayoutJank : PerformanceEntry { readonly attribute double fraction;
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_html.idl b/third_party/blink/renderer/core/trustedtypes/trusted_html.idl index fc33951..995d8149 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_html.idl +++ b/third_party/blink/renderer/core/trustedtypes/trusted_html.idl
@@ -8,7 +8,7 @@ [ Exposed=Window, - OriginTrialEnabled=TrustedDOMTypes + RuntimeEnabled=TrustedDOMTypes ] interface TrustedHTML { stringifier; };
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_script.idl b/third_party/blink/renderer/core/trustedtypes/trusted_script.idl index 7761036..a8f86e4 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_script.idl +++ b/third_party/blink/renderer/core/trustedtypes/trusted_script.idl
@@ -8,7 +8,7 @@ [ Exposed=Window, - OriginTrialEnabled=TrustedDOMTypes + RuntimeEnabled=TrustedDOMTypes ] interface TrustedScript { stringifier; };
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_script_url.idl b/third_party/blink/renderer/core/trustedtypes/trusted_script_url.idl index e1a4c0c..3a4faee 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_script_url.idl +++ b/third_party/blink/renderer/core/trustedtypes/trusted_script_url.idl
@@ -8,7 +8,7 @@ [ Exposed=Window, - OriginTrialEnabled=TrustedDOMTypes + RuntimeEnabled=TrustedDOMTypes ] interface TrustedScriptURL { stringifier; };
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl index b6985b33..60f712be 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl +++ b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl
@@ -8,7 +8,7 @@ [ Exposed=Window, - OriginTrialEnabled=TrustedDOMTypes + RuntimeEnabled=TrustedDOMTypes ] interface TrustedTypePolicy { [Unforgeable] readonly attribute DOMString name; [CallWith=ScriptState, RaisesException, Unforgeable] TrustedHTML createHTML(DOMString input);
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl index a34cc910..c97f4a63 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl +++ b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl
@@ -6,7 +6,7 @@ [ Exposed=(Window, Worker), - OriginTrialEnabled=TrustedDOMTypes + RuntimeEnabled=TrustedDOMTypes ] interface TrustedTypePolicyFactory { [RaisesException, Unforgeable] TrustedTypePolicy createPolicy(DOMString policyName, TrustedTypePolicyOptions policyOptions, optional boolean exposed = false); [Unforgeable] TrustedTypePolicy getExposedPolicy(DOMString policyName);
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc b/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc index f7c2d1a6..ef62ef5 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc +++ b/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc
@@ -203,26 +203,33 @@ origin_trials::TrustedDOMTypesEnabled(doc)); DCHECK(!string_or_trusted_html.IsNull()); - bool require_trusted_type = doc && doc->RequireTrustedTypes(); - if (!require_trusted_type && string_or_trusted_html.IsString()) { - return string_or_trusted_html.GetAsString(); - } - if (string_or_trusted_html.IsTrustedHTML()) { return string_or_trusted_html.GetAsTrustedHTML()->toString(); } + return GetStringFromTrustedHTML(string_or_trusted_html.GetAsString(), doc, + exception_state); +} + +String GetStringFromTrustedHTML(const String& string, + const Document* doc, + ExceptionState& exception_state) { + bool require_trusted_type = doc && doc->RequireTrustedTypes(); + if (!require_trusted_type) { + return string; + } + TrustedTypePolicy* default_policy = doc->ExecutingWindow()->trustedTypes()->getExposedPolicy("default"); if (!default_policy) { if (TrustedTypeFail(kTrustedHTMLAssignment, doc, exception_state)) { return g_empty_string; } - return string_or_trusted_html.GetAsString(); + return string; } - TrustedHTML* result = default_policy->CreateHTML( - doc->GetIsolate(), string_or_trusted_html.GetAsString(), exception_state); + TrustedHTML* result = + default_policy->CreateHTML(doc->GetIsolate(), string, exception_state); if (exception_state.HadException()) { exception_state.ClearException(); TrustedTypeFail(kTrustedHTMLAssignmentAndDefaultPolicyFailed, doc, @@ -371,4 +378,5 @@ return result->toString(); } + } // namespace blink
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h b/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h index 5adb8cc..4e0b60d 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h +++ b/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h
@@ -43,6 +43,10 @@ const Document*, ExceptionState&); +String GetStringFromTrustedHTML(const String&, + const Document*, + ExceptionState&); + String CORE_EXPORT GetStringFromTrustedScript(StringOrTrustedScript, const Document*, ExceptionState&);
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_url.idl b/third_party/blink/renderer/core/trustedtypes/trusted_url.idl index d11a566..b611563 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_url.idl +++ b/third_party/blink/renderer/core/trustedtypes/trusted_url.idl
@@ -8,7 +8,7 @@ [ Exposed=Window, - OriginTrialEnabled=TrustedDOMTypes + RuntimeEnabled=TrustedDOMTypes ] interface TrustedURL { stringifier; };
diff --git a/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc b/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc index cd8cf29..ef2b7527 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc
@@ -184,34 +184,6 @@ return false; } -// |layout_object| and |node| correspond to an AXLayoutObject. |alt_text| is an -// output parameter that will be populated if the AXLayoutObject is for a pseudo -// element and contained the alternative text -base::Optional<String> GetCSSAltText(Node* node) { - if (node && node->GetComputedStyle() && - node->GetComputedStyle()->GetContentData()) { - const ComputedStyle* style = node->GetComputedStyle(); - // If the content property is used on a non-pseudo element, match the - // behaviour of LayoutObject::CreateObject and only honour the style if - // there is exactly one piece of content, which is an image. - if (node->IsPseudoElement()) { - for (const ContentData* content_data = style->GetContentData(); - content_data; content_data = content_data->Next()) { - if (content_data->IsAltText()) - return To<AltTextContentData>(content_data)->GetText(); - } - return base::nullopt; - } - - const ContentData* content_data = style->GetContentData(); - if (content_data && content_data->IsImage() && content_data->Next() && - content_data->Next()->IsAltText()) { - return To<AltTextContentData>(content_data->Next())->GetText(); - } - } - return base::nullopt; -} - ax::mojom::Role AXLayoutObject::NativeRoleIgnoringAria() const { Node* node = layout_object_->GetNode(); LayoutBoxModelObject* css_box = GetLayoutBoxModelObject(); @@ -554,9 +526,6 @@ AXObjectInclusion AXLayoutObject::DefaultObjectInclusion( IgnoredReasons* ignored_reasons) const { - // The following cases can apply to any element that's a subclass of - // AXLayoutObject. - if (!layout_object_) { if (ignored_reasons) ignored_reasons->push_back(IgnoredReason(kAXNotRendered)); @@ -577,20 +546,6 @@ return AXObject::DefaultObjectInclusion(ignored_reasons); } -bool HasAriaAttribute(Element* element) { - if (!element) - return false; - - AttributeCollection attributes = element->AttributesWithoutUpdate(); - for (const Attribute& attr : attributes) { - // Attributes cache their uppercase names. - if (attr.GetName().LocalNameUpper().StartsWith("ARIA-")) - return true; - } - - return false; -} - static bool HasLineBox(const LayoutBlockFlow& block_flow) { if (!block_flow.IsLayoutNGMixin()) return block_flow.FirstLineBox(); @@ -630,58 +585,40 @@ DCHECK(initialized_); #endif - if (!layout_object_) - return true; - - // Check first if any of the common reasons cause this element to be ignored. - // Then process other use cases that need to be applied to all the various - // roles that AXLayoutObjects take on. - AXObjectInclusion decision = DefaultObjectInclusion(ignored_reasons); - if (decision == kIncludeObject) - return false; - if (decision == kIgnoreObject) - return true; - - if (layout_object_->IsAnonymousBlock() && !IsEditable()) - return true; - - // Ignore continuations, since those are essentially duplicate copies - // of inline nodes with blocks inside. - if (layout_object_->IsElementContinuation()) - return true; - - // If this element is within a parent that cannot have children, it should not - // be exposed. - if (IsDescendantOfLeafNode()) { - if (ignored_reasons) { - ignored_reasons->push_back( - IgnoredReason(kAXAncestorIsLeafNode, LeafNodeAncestor())); - } + if (!layout_object_) { + if (ignored_reasons) + ignored_reasons->push_back(IgnoredReason(kAXNotRendered)); return true; } - if (RoleValue() == ax::mojom::Role::kIgnored) { + // Check first if any of the common reasons cause this element to be ignored. + AXObjectInclusion default_inclusion = DefaultObjectInclusion(ignored_reasons); + if (default_inclusion == kIncludeObject) + return false; + if (default_inclusion == kIgnoreObject) + return true; + + AXObjectInclusion semantic_inclusion = + ShouldIncludeBasedOnSemantics(ignored_reasons); + if (semantic_inclusion == kIncludeObject) + return false; + if (semantic_inclusion == kIgnoreObject) + return true; + + if (layout_object_->IsAnonymousBlock() && !IsEditable()) { if (ignored_reasons) ignored_reasons->push_back(IgnoredReason(kAXUninteresting)); return true; } - if (HasInheritedPresentationalRole()) { - if (ignored_reasons) { - const AXObject* inherits_from = InheritsPresentationalRoleFrom(); - if (inherits_from == this) { - ignored_reasons->push_back(IgnoredReason(kAXPresentational)); - } else { - ignored_reasons->push_back( - IgnoredReason(kAXInheritsPresentation, inherits_from)); - } - } + // Ignore continuations, since those are essentially duplicate copies + // of inline nodes with blocks inside. + if (layout_object_->IsElementContinuation()) { + if (ignored_reasons) + ignored_reasons->push_back(IgnoredReason(kAXUninteresting)); return true; } - if (IsTableLikeRole() || IsTableRowLikeRole() || IsTableCellLikeRole()) - return false; - // A LayoutEmbeddedContent is an iframe element or embedded object element or // something like that. We don't want to ignore those. if (layout_object_->IsLayoutEmbeddedContent()) @@ -702,147 +639,11 @@ return false; } - // Find out if this element is inside of a label element. If so, it may be - // ignored because it's the label for a checkbox or radio button. - AXObject* control_object = CorrespondingControlForLabelElement(); - HTMLLabelElement* label = LabelElementContainer(); - if (control_object && control_object->IsCheckboxOrRadio() && - control_object->NameFromLabelElement() && - AccessibleNode::GetPropertyOrARIAAttribute( - label, AOMStringProperty::kRole) == g_null_atom) { - if (ignored_reasons) { - if (label && label != GetNode()) { - AXObject* label_ax_object = AXObjectCache().GetOrCreate(label); - ignored_reasons->push_back( - IgnoredReason(kAXLabelContainer, label_ax_object)); - } - - ignored_reasons->push_back(IgnoredReason(kAXLabelFor, control_object)); - } - return true; - } - - if (layout_object_->IsBR()) - return false; - - if (CanSetFocusAttribute() && GetNode() && !IsHTMLBodyElement(GetNode())) - return false; - - if (IsLink()) - return false; - - if (IsInPageLinkTarget()) - return false; - - // A click handler might be placed on an otherwise ignored non-empty block - // element, e.g. a div. We shouldn't ignore such elements because if an AT - // sees the |ax::mojom::DefaultActionVerb::kClickAncestor|, it will look for - // the clickable ancestor and it expects to find one. - if (IsClickable()) - return false; - - if (layout_object_->IsText()) { - if (CanIgnoreTextAsEmpty()) { - if (ignored_reasons) - ignored_reasons->push_back(IgnoredReason(kAXEmptyText)); - return true; - } - return false; - } - - if (IsHeading()) - return false; - - if (IsLandmarkRelated()) - return false; - - // Header and footer tags may also be exposed as landmark roles but not - // always. - if (GetNode() && - (GetNode()->HasTagName(kHeaderTag) || GetNode()->HasTagName(kFooterTag))) - return false; - - // all controls are accessible - if (IsControl()) - return false; - - if (AriaRoleAttribute() != ax::mojom::Role::kUnknown) - return false; - - // don't ignore labels, because they serve as TitleUIElements - Node* node = layout_object_->GetNode(); - if (IsHTMLLabelElement(node)) - return false; - - // Anything that is content editable should not be ignored. - // However, one cannot just call node->hasEditableStyle() since that will ask - // if its parents are also editable. Only the top level content editable - // region should be exposed. - if (HasContentEditableAttributeSet()) - return false; - - if (RoleValue() == ax::mojom::Role::kAbbr) - return false; - - // List items play an important role in defining the structure of lists. They - // should not be ignored. - if (RoleValue() == ax::mojom::Role::kListItem) - return false; - - if (RoleValue() == ax::mojom::Role::kBlockquote) - return false; - - if (RoleValue() == ax::mojom::Role::kDialog) - return false; - - if (RoleValue() == ax::mojom::Role::kFigcaption) - return false; - - if (RoleValue() == ax::mojom::Role::kFigure) - return false; - - if (RoleValue() == ax::mojom::Role::kContentDeletion) - return false; - - if (RoleValue() == ax::mojom::Role::kContentInsertion) - return false; - - if (RoleValue() == ax::mojom::Role::kDetails) - return false; - - if (RoleValue() == ax::mojom::Role::kMark) - return false; - - if (RoleValue() == ax::mojom::Role::kMath) - return false; - - if (RoleValue() == ax::mojom::Role::kMeter) - return false; - - if (RoleValue() == ax::mojom::Role::kRuby) - return false; - - if (RoleValue() == ax::mojom::Role::kSplitter) - return false; - - if (RoleValue() == ax::mojom::Role::kTime) - return false; - - if (RoleValue() == ax::mojom::Role::kProgressIndicator) - return false; - - // if this element has aria attributes on it, it should not be ignored. - if (HasGlobalARIAAttribute()) - return false; - - if (IsImage()) - return false; - if (IsCanvas()) { if (CanvasHasFallbackContent()) return false; - const auto* canvas = ToLayoutHTMLCanvasOrNull(layout_object_); + const auto* canvas = ToLayoutHTMLCanvasOrNull(GetLayoutObject()); if (canvas && (canvas->Size().Height() <= 1 || canvas->Size().Width() <= 1)) { if (ignored_reasons) @@ -854,33 +655,25 @@ // to decide. } - if (IsWebArea() || layout_object_->IsListMarkerIncludingNG()) + if (layout_object_->IsBR()) return false; - // Using the title or accessibility description (so we - // check if there's some kind of accessible name for the element) - // to decide an element's visibility is not as definitive as - // previous checks, so this should remain as one of the last. - // - // These checks are simplified in the interest of execution speed; - // for example, any element having an alt attribute will make it - // not ignored, rather than just images. - if (HasAriaAttribute(GetElement()) || !GetAttribute(kAltAttr).IsEmpty() || - !GetAttribute(kTitleAttr).IsEmpty()) + if (layout_object_->IsText()) { + if (CanIgnoreTextAsEmpty()) { + if (ignored_reasons) + ignored_reasons->push_back(IgnoredReason(kAXEmptyText)); + return true; + } return false; + } + // FIXME(aboxhall): may need to move? base::Optional<String> alt_text = GetCSSAltText(GetNode()); if (alt_text) return alt_text->IsEmpty(); - // <span> tags are inline tags and not meant to convey information if they - // have no other ARIA information on them. If we don't ignore them, they may - // emit signals expected to come from their parent. - if (IsHTMLSpanElement(node)) { - if (ignored_reasons) - ignored_reasons->push_back(IgnoredReason(kAXUninteresting)); - return true; - } + if (IsWebArea() || layout_object_->IsListMarkerIncludingNG()) + return false; // Positioned elements and scrollable containers are important for // determining bounding boxes.
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc index c63fd43b..5ff005e 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -34,6 +34,7 @@ #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/flat_tree_traversal.h" #include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h" +#include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/dom/node_traversal.h" #include "third_party/blink/renderer/core/dom/qualified_name.h" #include "third_party/blink/renderer/core/dom/shadow_root.h" @@ -127,23 +128,53 @@ return ax_descendant; } -bool AXNodeObject::ComputeAccessibilityIsIgnored( - IgnoredReasons* ignored_reasons) const { -#if DCHECK_IS_ON() - // Double-check that an AXObject is never accessed before - // it's been initialized. - DCHECK(initialized_); -#endif +bool HasAriaAttribute(Element* element) { + if (!element) + return false; + AttributeCollection attributes = element->AttributesWithoutUpdate(); + for (const Attribute& attr : attributes) { + // Attributes cache their uppercase names. + if (attr.GetName().LocalNameUpper().StartsWith("ARIA-")) + return true; + } + + return false; +} + +AXObjectInclusion AXNodeObject::ShouldIncludeBasedOnSemantics( + IgnoredReasons* ignored_reasons) const { // If this element is within a parent that cannot have children, it should not // be exposed. if (IsDescendantOfLeafNode()) { if (ignored_reasons) ignored_reasons->push_back( IgnoredReason(kAXAncestorIsLeafNode, LeafNodeAncestor())); - return true; + return kIgnoreObject; } + if (RoleValue() == ax::mojom::Role::kIgnored) { + if (ignored_reasons) + ignored_reasons->push_back(IgnoredReason(kAXUninteresting)); + return kIgnoreObject; + } + + if (HasInheritedPresentationalRole()) { + if (ignored_reasons) { + const AXObject* inherits_from = InheritsPresentationalRoleFrom(); + if (inherits_from == this) { + ignored_reasons->push_back(IgnoredReason(kAXPresentational)); + } else { + ignored_reasons->push_back( + IgnoredReason(kAXInheritsPresentation, inherits_from)); + } + } + return kIgnoreObject; + } + + if (IsTableLikeRole() || IsTableRowLikeRole() || IsTableCellLikeRole()) + return kIncludeObject; + // Ignore labels that are already referenced by a control. AXObject* control_object = CorrespondingControlForLabelElement(); HTMLLabelElement* label = LabelElementContainer(); @@ -160,24 +191,175 @@ ignored_reasons->push_back(IgnoredReason(kAXLabelFor, control_object)); } - return true; + return kIgnoreObject; + } + + if (CanSetFocusAttribute() && GetNode() && !IsHTMLBodyElement(GetNode())) + return kIncludeObject; + + if (IsLink() || IsInPageLinkTarget()) + return kIncludeObject; + + // A click handler might be placed on an otherwise ignored non-empty block + // element, e.g. a div. We shouldn't ignore such elements because if an AT + // sees the |ax::mojom::DefaultActionVerb::kClickAncestor|, it will look for + // the clickable ancestor and it expects to find one. + if (IsClickable()) + return kIncludeObject; + + if (IsHeading() || IsLandmarkRelated()) + return kIncludeObject; + + // Header and footer tags may also be exposed as landmark roles but not + // always. + if (GetNode() && + (GetNode()->HasTagName(kHeaderTag) || GetNode()->HasTagName(kFooterTag))) + return kIncludeObject; + + // All controls are accessible. + if (IsControl()) + return kIncludeObject; + + // Anything with an explicit ARIA role should be included. + if (AriaRoleAttribute() != ax::mojom::Role::kUnknown) + return kIncludeObject; + + // Anything with CSS alt should be included. + // Note: this is duplicated from AXLayoutObject because CSS alt text may apply + // to both Elements and pseudo-elements. + base::Optional<String> alt_text = GetCSSAltText(GetNode()); + if (alt_text && !alt_text->IsEmpty()) + return kIncludeObject; + + // Don't ignore labels, because they serve as TitleUIElements. + Node* node = GetNode(); + if (IsHTMLLabelElement(node)) + return kIncludeObject; + + // Anything that is content editable should not be ignored. + // However, one cannot just call node->hasEditableStyle() since that will ask + // if its parents are also editable. Only the top level content editable + // region should be exposed. + if (HasContentEditableAttributeSet()) + return kIncludeObject; + + static const std::set<ax::mojom::Role> always_included_computed_roles = { + ax::mojom::Role::kAbbr, + ax::mojom::Role::kBlockquote, + ax::mojom::Role::kContentDeletion, + ax::mojom::Role::kContentInsertion, + ax::mojom::Role::kDetails, + ax::mojom::Role::kDialog, + ax::mojom::Role::kFigcaption, + ax::mojom::Role::kFigure, + ax::mojom::Role::kListItem, + ax::mojom::Role::kMark, + ax::mojom::Role::kMath, + ax::mojom::Role::kMeter, + ax::mojom::Role::kProgressIndicator, + ax::mojom::Role::kRuby, + ax::mojom::Role::kSplitter, + ax::mojom::Role::kTime, + }; + + if (always_included_computed_roles.find(RoleValue()) != + always_included_computed_roles.end()) + return kIncludeObject; + + // If this element has aria attributes on it, it should not be ignored. + if (HasGlobalARIAAttribute()) + return kIncludeObject; + + if (IsImage()) + return kIncludeObject; + + // Using the title or accessibility description (so we + // check if there's some kind of accessible name for the element) + // to decide an element's visibility is not as definitive as + // previous checks, so this should remain as one of the last. + // + // These checks are simplified in the interest of execution speed; + // for example, any element having an alt attribute will make it + // not ignored, rather than just images. + if (HasAriaAttribute(GetElement()) || !GetAttribute(kAltAttr).IsEmpty() || + !GetAttribute(kTitleAttr).IsEmpty()) + return kIncludeObject; + + // <span> tags are inline tags and not meant to convey information if they + // have no other ARIA information on them. If we don't ignore them, they may + // emit signals expected to come from their parent. + if (node && IsHTMLSpanElement(node)) { + if (ignored_reasons) + ignored_reasons->push_back(IgnoredReason(kAXUninteresting)); + return kIgnoreObject; + } + + return kDefaultBehavior; +} + +base::Optional<String> AXNodeObject::GetCSSAltText(Node* node) { + if (!node || !node->GetComputedStyle() || + !node->GetComputedStyle()->GetContentData()) { + return base::nullopt; + } + + const ComputedStyle* style = node->GetComputedStyle(); + if (node->IsPseudoElement()) { + for (const ContentData* content_data = style->GetContentData(); + content_data; content_data = content_data->Next()) { + if (content_data->IsAltText()) + return To<AltTextContentData>(content_data)->GetText(); + } + return base::nullopt; + } + + // If the content property is used on a non-pseudo element, match the + // behaviour of LayoutObject::CreateObject and only honour the style if + // there is exactly one piece of content, which is an image. + const ContentData* content_data = style->GetContentData(); + if (content_data && content_data->IsImage() && content_data->Next() && + content_data->Next()->IsAltText()) { + return To<AltTextContentData>(content_data->Next())->GetText(); + } + + return base::nullopt; +} + +bool AXNodeObject::ComputeAccessibilityIsIgnored( + IgnoredReasons* ignored_reasons) const { +#if DCHECK_IS_ON() + // Double-check that an AXObject is never accessed before + // it's been initialized. + DCHECK(initialized_); +#endif + if (GetLayoutObject()) { + if (role_ == ax::mojom::Role::kUnknown) { + if (ignored_reasons) + ignored_reasons->push_back(IgnoredReason(kAXUninteresting)); + return true; + } + return false; } Element* element = GetNode()->IsElementNode() ? ToElement(GetNode()) : GetNode()->parentElement(); - if (!GetLayoutObject() && (!element || !element->IsInCanvasSubtree()) && - !AOMPropertyOrARIAAttributeIsFalse(AOMBooleanProperty::kHidden)) { - if (ignored_reasons) - ignored_reasons->push_back(IgnoredReason(kAXNotRendered)); + if (!element) return true; + + if (element->IsInCanvasSubtree()) + return ShouldIncludeBasedOnSemantics(ignored_reasons) == kIgnoreObject; + + if (AOMPropertyOrARIAAttributeIsFalse(AOMBooleanProperty::kHidden)) + return false; + + if (element->HasDisplayContentsStyle()) { + if (ShouldIncludeBasedOnSemantics(ignored_reasons) == kIncludeObject) + return false; } - if (role_ == ax::mojom::Role::kUnknown) { - if (ignored_reasons) - ignored_reasons->push_back(IgnoredReason(kAXUninteresting)); - return true; - } - return false; + if (ignored_reasons) + ignored_reasons->push_back(IgnoredReason(kAXNotRendered)); + return true; } static bool IsListElement(Node* node) { @@ -2035,9 +2217,12 @@ } } - // If it's in a canvas but doesn't have an explicit rect, get the bounding - // rect of its children. - if (GetNode()->parentElement()->IsInCanvasSubtree()) { + Element* element = GetElement(); + // If it's in a canvas but doesn't have an explicit rect, or has display: + // contents set, get the bounding rect of its children. + if ((GetNode()->parentElement() && + GetNode()->parentElement()->IsInCanvasSubtree()) || + (element && element->HasDisplayContentsStyle())) { Vector<FloatRect> rects; for (Node& child : NodeTraversal::ChildrenOf(*GetNode())) { if (child.IsHTMLElement()) {
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.h b/third_party/blink/renderer/modules/accessibility/ax_node_object.h index b25675f..79e03b2 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.h
@@ -54,6 +54,9 @@ // The accessibility role, not taking ARIA into account. ax::mojom::Role native_role_; + static base::Optional<String> GetCSSAltText(Node*); + AXObjectInclusion ShouldIncludeBasedOnSemantics( + IgnoredReasons* = nullptr) const; bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const override; const AXObject* InheritsPresentationalRoleFrom() const override; ax::mojom::Role DetermineAccessibilityRole() override;
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc index f34adac..e382ab4 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
@@ -1169,8 +1169,12 @@ DCHECK(!node->GetDocument().NeedsLayoutTreeUpdateForNode(*node)); + AXObject* obj = Get(node); + if (!obj && IsHTMLSelectElement(node)) + obj = GetOrCreate(node); + // Invalidate the current object and make the parent reconsider its children. - if (AXObject* obj = Get(node)) { + if (obj) { // Save parent for later use. AXObject* parent = obj->ParentObject();
diff --git a/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.idl b/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.idl index 08be78f2..c24290f 100644 --- a/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.idl +++ b/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.idl
@@ -7,7 +7,7 @@ [ Exposed=AnimationWorklet, Global=(Worklet,AnimationWorklet), - OriginTrialEnabled=AnimationWorklet + RuntimeEnabled=AnimationWorklet ] interface AnimationWorkletGlobalScope : WorkletGlobalScope { [MeasureAs=AnimationWorkletRegisterAnimator, RaisesException] void registerAnimator(DOMString name, AnimatorConstructor animatorCtor); };
diff --git a/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.idl b/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.idl index 55c092ab..e128733 100644 --- a/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.idl +++ b/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.idl
@@ -4,7 +4,7 @@ [ ImplementedAs=CSSAnimationWorklet, - OriginTrialEnabled=AnimationWorklet, + RuntimeEnabled=AnimationWorklet, SecureContext ] partial interface CSS { [CallWith=ScriptState] static readonly attribute Worklet animationWorklet;
diff --git a/third_party/blink/renderer/modules/animationworklet/effect_proxy.idl b/third_party/blink/renderer/modules/animationworklet/effect_proxy.idl index 9afe3a2..7761bb1 100644 --- a/third_party/blink/renderer/modules/animationworklet/effect_proxy.idl +++ b/third_party/blink/renderer/modules/animationworklet/effect_proxy.idl
@@ -6,7 +6,7 @@ // TODO(majidvp): Get rid of this in favor using KeyframeEffect interface directly. [ Exposed=AnimationWorklet, - OriginTrialEnabled=AnimationWorklet + RuntimeEnabled=AnimationWorklet ] interface EffectProxy { attribute unrestricted double? localTime; }; \ No newline at end of file
diff --git a/third_party/blink/renderer/modules/animationworklet/worklet_animation.idl b/third_party/blink/renderer/modules/animationworklet/worklet_animation.idl index 289899d..76a7624 100644 --- a/third_party/blink/renderer/modules/animationworklet/worklet_animation.idl +++ b/third_party/blink/renderer/modules/animationworklet/worklet_animation.idl
@@ -14,7 +14,7 @@ RaisesException=Constructor, ConstructorCallWith=ScriptState, MeasureAs=WorkletAnimationConstructor, - OriginTrialEnabled=AnimationWorklet + RuntimeEnabled=AnimationWorklet ] interface WorkletAnimation { readonly attribute AnimationEffect? effect; readonly attribute AnimationTimeline? timeline;
diff --git a/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.idl b/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.idl index b2fd1ed..eb2deb0b 100644 --- a/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.idl +++ b/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.idl
@@ -3,7 +3,7 @@ // found in the LICENSE file. [ Exposed=AnimationWorklet, - OriginTrialEnabled=AnimationWorklet + RuntimeEnabled=AnimationWorklet ] interface WorkletGroupEffectProxy { sequence<EffectProxy> getChildren(); };
diff --git a/third_party/blink/renderer/modules/badging/experimental_badge.idl b/third_party/blink/renderer/modules/badging/experimental_badge.idl index 35ccd0ae..e9a38529 100644 --- a/third_party/blink/renderer/modules/badging/experimental_badge.idl +++ b/third_party/blink/renderer/modules/badging/experimental_badge.idl
@@ -6,7 +6,7 @@ // https://github.com/WICG/badging/blob/master/explainer.md [ - OriginTrialEnabled=Badging, + RuntimeEnabled=Badging, // TODO(estevenson): Expose the Badge interface to Worker. Exposed=Window, ImplementedAs=Badge
diff --git a/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.idl b/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.idl index 1ecfc00..3c5a244b 100644 --- a/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.idl +++ b/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.idl
@@ -55,5 +55,5 @@ boolean preserveDrawingBuffer = false; CanvasPowerPreference powerPreference = "default"; boolean failIfMajorPerformanceCaveat = false; - [OriginTrialEnabled=WebXR] boolean xrCompatible = false; + [RuntimeEnabled=WebXR] boolean xrCompatible = false; };
diff --git a/third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl b/third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl index be86b92..73ac590 100644 --- a/third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl +++ b/third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl
@@ -7,7 +7,7 @@ [ Exposed=Window, SecureContext, - OriginTrialEnabled=ContactsManager + RuntimeEnabled=ContactsManager ] interface ContactsManager { [CallWith=ScriptState] Promise<sequence<ContactInfo>> select(ContactsSelectOptions options); };
diff --git a/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.idl b/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.idl index cfc26d1..bb47e9c 100644 --- a/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.idl +++ b/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.idl
@@ -8,5 +8,5 @@ Exposed=Window, ImplementedAs=NavigatorContacts ] partial interface Navigator { - [SecureContext, OriginTrialEnabled=ContactsManager] readonly attribute ContactsManager contacts; + [SecureContext, RuntimeEnabled=ContactsManager] readonly attribute ContactsManager contacts; };
diff --git a/third_party/blink/renderer/modules/cookie_store/cookie_change_event.idl b/third_party/blink/renderer/modules/cookie_store/cookie_change_event.idl index bb51c96..4024c9a61c 100644 --- a/third_party/blink/renderer/modules/cookie_store/cookie_change_event.idl +++ b/third_party/blink/renderer/modules/cookie_store/cookie_change_event.idl
@@ -10,7 +10,7 @@ [ Exposed=Window, - OriginTrialEnabled=CookieStore, + RuntimeEnabled=CookieStore, SecureContext, Constructor(DOMString type, optional CookieChangeEventInit eventInitDict) ] interface CookieChangeEvent : Event {
diff --git a/third_party/blink/renderer/modules/cookie_store/cookie_store.idl b/third_party/blink/renderer/modules/cookie_store/cookie_store.idl index 74dbdd47..7f2a1d9 100644 --- a/third_party/blink/renderer/modules/cookie_store/cookie_store.idl +++ b/third_party/blink/renderer/modules/cookie_store/cookie_store.idl
@@ -6,7 +6,7 @@ [ Exposed=(ServiceWorker,Window), - OriginTrialEnabled=CookieStore, + RuntimeEnabled=CookieStore, SecureContext ] interface CookieStore : EventTarget { // https://wicg.github.io/cookie-store/explainer.html#the-query-api
diff --git a/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.idl b/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.idl index f5bbba15..3c8d1b0 100644 --- a/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.idl +++ b/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.idl
@@ -9,7 +9,7 @@ [ Exposed=ServiceWorker, - OriginTrialEnabled=CookieStore, + RuntimeEnabled=CookieStore, Constructor(DOMString type, optional ExtendableCookieChangeEventInit eventInitDict) ] interface ExtendableCookieChangeEvent : ExtendableEvent { [MeasureAs=CookieStoreAPI] readonly attribute CookieList changed;
diff --git a/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.idl b/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.idl index c19ad6e..5f24bab 100644 --- a/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.idl +++ b/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.idl
@@ -5,7 +5,7 @@ // https://github.com/WICG/async-cookies-api/blob/gh-pages/explainer.md [ - OriginTrialEnabled=CookieStore, + RuntimeEnabled=CookieStore, ImplementedAs=ServiceWorkerGlobalScopeCookieStore ] partial interface ServiceWorkerGlobalScope { [Replaceable, SameObject] readonly attribute CookieStore cookieStore;
diff --git a/third_party/blink/renderer/modules/cookie_store/window_cookie_store.idl b/third_party/blink/renderer/modules/cookie_store/window_cookie_store.idl index 254a9c4..53466a5 100644 --- a/third_party/blink/renderer/modules/cookie_store/window_cookie_store.idl +++ b/third_party/blink/renderer/modules/cookie_store/window_cookie_store.idl
@@ -5,7 +5,7 @@ // https://github.com/WICG/async-cookies-api/blob/gh-pages/explainer.md [ - OriginTrialEnabled=CookieStore, + RuntimeEnabled=CookieStore, ImplementedAs=WindowCookieStore, SecureContext ] partial interface Window {
diff --git a/third_party/blink/renderer/modules/gamepad/gamepad.idl b/third_party/blink/renderer/modules/gamepad/gamepad.idl index 980596b..0e5a36c 100644 --- a/third_party/blink/renderer/modules/gamepad/gamepad.idl +++ b/third_party/blink/renderer/modules/gamepad/gamepad.idl
@@ -25,7 +25,7 @@ // https://w3c.github.io/gamepad/extensions.html#gamepadhand-enum [ - OriginTrialEnabled=WebVR + RuntimeEnabled=WebVR ] enum GamepadHand { "left", "right" @@ -45,9 +45,9 @@ // https://github.com/w3c/gamepad/pull/68 [MeasureAs=GamepadVibrationActuator] readonly attribute GamepadHapticActuator? vibrationActuator; - [OriginTrialEnabled=WebVR, MeasureAs=GamepadPose] readonly attribute GamepadPose? pose; - [OriginTrialEnabled=WebVR, MeasureAs=GamepadHand] readonly attribute GamepadHand hand; + [RuntimeEnabled=WebVR, MeasureAs=GamepadPose] readonly attribute GamepadPose? pose; + [RuntimeEnabled=WebVR, MeasureAs=GamepadHand] readonly attribute GamepadHand hand; // https://w3c.github.io/webvr/#interface-gamepad - [OriginTrialEnabled=WebVR, MeasureAs=GamepadDisplayId] readonly attribute unsigned long displayId; + [RuntimeEnabled=WebVR, MeasureAs=GamepadDisplayId] readonly attribute unsigned long displayId; };
diff --git a/third_party/blink/renderer/modules/gamepad/gamepad_pose.idl b/third_party/blink/renderer/modules/gamepad/gamepad_pose.idl index a60ecd9..61fe24ff 100644 --- a/third_party/blink/renderer/modules/gamepad/gamepad_pose.idl +++ b/third_party/blink/renderer/modules/gamepad/gamepad_pose.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/gamepad/extensions.html#gamepadpose-interface [ - OriginTrialEnabled=WebVR + RuntimeEnabled=WebVR ] interface GamepadPose { [MeasureAs=GamepadPoseHasOrientation] readonly attribute boolean hasOrientation; [MeasureAs=GamepadPoseHasPosition] readonly attribute boolean hasPosition;
diff --git a/third_party/blink/renderer/modules/installedapp/navigator_installed_app.idl b/third_party/blink/renderer/modules/installedapp/navigator_installed_app.idl index 11b223fe..81bba3f 100644 --- a/third_party/blink/renderer/modules/installedapp/navigator_installed_app.idl +++ b/third_party/blink/renderer/modules/installedapp/navigator_installed_app.idl
@@ -7,7 +7,7 @@ [ ImplementedAs=NavigatorInstalledApp, - OriginTrialEnabled=InstalledApp + RuntimeEnabled=InstalledApp ] partial interface Navigator { [CallWith=ScriptState, Measure, SecureContext] Promise<RelatedApplication> getInstalledRelatedApps(); };
diff --git a/third_party/blink/renderer/modules/installedapp/related_application.idl b/third_party/blink/renderer/modules/installedapp/related_application.idl index 80fe74a90..c55b7f6f 100644 --- a/third_party/blink/renderer/modules/installedapp/related_application.idl +++ b/third_party/blink/renderer/modules/installedapp/related_application.idl
@@ -10,7 +10,7 @@ // https://crbug.com/687444. [ NoInterfaceObject, - OriginTrialEnabled=InstalledApp + RuntimeEnabled=InstalledApp ] interface RelatedApplication { readonly attribute DOMString platform; readonly attribute DOMString url;
diff --git a/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl b/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl index 3cbe88a..55d1fa4 100644 --- a/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl +++ b/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl
@@ -11,7 +11,7 @@ sequence<DOMString> resizeMode; sequence<boolean> echoCancellation; // See http://crbug.com/846270. - [OriginTrialEnabled=ExperimentalHardwareEchoCancellation] sequence<DOMString> echoCancellationType; + [RuntimeEnabled=ExperimentalHardwareEchoCancellation] sequence<DOMString> echoCancellationType; sequence<boolean> autoGainControl; sequence<boolean> noiseSuppression; LongRange sampleSize;
diff --git a/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl b/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl index 2c995f4..e09bbe3d 100644 --- a/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl +++ b/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl
@@ -22,7 +22,7 @@ ConstrainLong sampleSize; ConstrainBoolean echoCancellation; // See http://crbug.com/846270. - [OriginTrialEnabled=ExperimentalHardwareEchoCancellation] ConstrainDOMString echoCancellationType; + [RuntimeEnabled=ExperimentalHardwareEchoCancellation] ConstrainDOMString echoCancellationType; ConstrainBoolean autoGainControl; ConstrainBoolean noiseSuppression; ConstrainDouble latency;
diff --git a/third_party/blink/renderer/modules/mediastream/media_track_settings.idl b/third_party/blink/renderer/modules/mediastream/media_track_settings.idl index 5964c04..774e38f 100644 --- a/third_party/blink/renderer/modules/mediastream/media_track_settings.idl +++ b/third_party/blink/renderer/modules/mediastream/media_track_settings.idl
@@ -21,7 +21,7 @@ long channelCount; DOMString deviceId; DOMString groupId; - [OriginTrialEnabled=ExperimentalHardwareEchoCancellation] DOMString echoCancellationType; + [RuntimeEnabled=ExperimentalHardwareEchoCancellation] DOMString echoCancellationType; // Media Capture Depth Stream Extensions // https://w3c.github.io/mediacapture-depth/#mediatracksettings-dictionary // TODO(riju): videoKind attribute should be declared as partial
diff --git a/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl b/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl index 7b02b8c6..5651fd5 100644 --- a/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl +++ b/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl
@@ -19,7 +19,7 @@ boolean sampleSize = true; boolean echoCancellation = true; // See http://crbug.com/846270. - [OriginTrialEnabled=ExperimentalHardwareEchoCancellation] boolean echoCancellationType = true; + [RuntimeEnabled=ExperimentalHardwareEchoCancellation] boolean echoCancellationType = true; boolean autoGainControl = true; boolean noiseSuppression = true; boolean latency = true;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl b/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl index b339ece..662fb9a 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl
@@ -51,8 +51,8 @@ // Nonstandard, added for backward compatibility reasons during a // transitional phase. https://crbug.com/908377 boolean offerExtmapAllowMixed; - [OriginTrialEnabled=RtcAudioJitterBufferMaxPackets] long rtcAudioJitterBufferMaxPackets; - [OriginTrialEnabled=RtcAudioJitterBufferMaxPackets] boolean rtcAudioJitterBufferFastAccelerate; - [OriginTrialEnabled=RtcAudioJitterBufferMaxPackets] long rtcAudioJitterBufferMinDelayMs; + [RuntimeEnabled=RtcAudioJitterBufferMaxPackets] long rtcAudioJitterBufferMaxPackets; + [RuntimeEnabled=RtcAudioJitterBufferMaxPackets] boolean rtcAudioJitterBufferFastAccelerate; + [RuntimeEnabled=RtcAudioJitterBufferMaxPackets] long rtcAudioJitterBufferMinDelayMs; };
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.idl b/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.idl index cef48a9..ce8f51f 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.idl
@@ -34,7 +34,7 @@ ConstructorCallWith=ExecutionContext, Exposed=Window, Measure, - OriginTrialEnabled=RTCIceTransportExtension, + RuntimeEnabled=RTCIceTransportExtension, SecureContext ] interface RTCIceTransport : EventTarget { // TODO(github.com/w3c/webrtc-ice/issues/4): role is non-null in the
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl b/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl index 92404fba..8e793d4 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl
@@ -14,7 +14,7 @@ // https://w3c.github.io/webrtc-quic/#quicstream* [ Exposed=Window, - OriginTrialEnabled=RTCQuicTransport, + RuntimeEnabled=RTCQuicTransport, SecureContext ] interface RTCQuicStream : EventTarget { [Measure] readonly attribute RTCQuicTransport transport;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.idl b/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.idl index d3770982..ced237c 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/webrtc-quic/#rtcquicstreamevent [ - OriginTrialEnabled=RTCQuicTransport, + RuntimeEnabled=RTCQuicTransport, Constructor(DOMString type, optional RTCQuicStreamEventInit eventInitDict), Exposed=Window ] interface RTCQuicStreamEvent : Event {
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl b/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl index d45489f..7062aacc0 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl
@@ -18,7 +18,7 @@ RaisesException=Constructor, Exposed=Window, Measure, - OriginTrialEnabled=RTCQuicTransport, + RuntimeEnabled=RTCQuicTransport, SecureContext ] interface RTCQuicTransport : EventTarget { [Measure] readonly attribute RTCIceTransport transport;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.idl b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.idl index 8ff7202..01827c26 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.idl
@@ -8,7 +8,7 @@ readonly attribute MediaStreamTrack track; [RuntimeEnabled=RTCDtlsTransport] readonly attribute RTCDtlsTransport? transport; [RuntimeEnabled=RTCDtlsTransport] readonly attribute RTCDtlsTransport? rtcp_transport; - [RaisesException, OriginTrialEnabled=RtcJitterBufferDelayHint] attribute double? jitterBufferDelayHint; + [RaisesException, RuntimeEnabled=RtcJitterBufferDelayHint] attribute double? jitterBufferDelayHint; static RTCRtpCapabilities? getCapabilities(DOMString kind); RTCRtpReceiveParameters getParameters(); sequence<RTCRtpSynchronizationSource> getSynchronizationSources();
diff --git a/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.idl b/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.idl index a64f0f3d..015f00b 100644 --- a/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.idl +++ b/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.idl
@@ -12,6 +12,6 @@ [RuntimeEnabled=PictureInPictureAPI] attribute EventHandler onenterpictureinpicture; [RuntimeEnabled=PictureInPictureAPI] attribute EventHandler onleavepictureinpicture; - [OriginTrialEnabled=AutoPictureInPicture, CEReactions, Measure, Reflect] attribute boolean autoPictureInPicture; + [RuntimeEnabled=AutoPictureInPicture, CEReactions, Measure, Reflect] attribute boolean autoPictureInPicture; [RuntimeEnabled=PictureInPictureAPI, CEReactions, Measure, Reflect] attribute boolean disablePictureInPicture; };
diff --git a/third_party/blink/renderer/modules/vr/navigator_vr.idl b/third_party/blink/renderer/modules/vr/navigator_vr.idl index 86ae2c92..6ec39bf 100644 --- a/third_party/blink/renderer/modules/vr/navigator_vr.idl +++ b/third_party/blink/renderer/modules/vr/navigator_vr.idl
@@ -7,8 +7,8 @@ ImplementedAs=NavigatorVR ] partial interface Navigator { // Latest API - [SecureContext, OriginTrialEnabled=WebXR, MeasureAs=NavigatorXR] readonly attribute XR xr; + [SecureContext, RuntimeEnabled=WebXR, MeasureAs=NavigatorXR] readonly attribute XR xr; // Legacy API - [OriginTrialEnabled=WebVR, CallWith=ScriptState] Promise<sequence<VRDisplay>> getVRDisplays(); + [RuntimeEnabled=WebVR, CallWith=ScriptState] Promise<sequence<VRDisplay>> getVRDisplays(); };
diff --git a/third_party/blink/renderer/modules/vr/vr_display.idl b/third_party/blink/renderer/modules/vr/vr_display.idl index 5f8be46..04e577ae 100644 --- a/third_party/blink/renderer/modules/vr/vr_display.idl +++ b/third_party/blink/renderer/modules/vr/vr_display.idl
@@ -10,7 +10,7 @@ // https://w3c.github.io/webvr/#interface-vrdisplay [ ActiveScriptWrappable, - OriginTrialEnabled=WebVR + RuntimeEnabled=WebVR ] interface VRDisplay : EventTarget { // An identifier for this device unique across VRDisplays. readonly attribute unsigned long displayId;
diff --git a/third_party/blink/renderer/modules/vr/vr_display_capabilities.idl b/third_party/blink/renderer/modules/vr/vr_display_capabilities.idl index 14d8265..78cd1f5 100644 --- a/third_party/blink/renderer/modules/vr/vr_display_capabilities.idl +++ b/third_party/blink/renderer/modules/vr/vr_display_capabilities.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/webvr/#interface-vrdisplaycapabilities [ - OriginTrialEnabled=WebVR + RuntimeEnabled=WebVR ] interface VRDisplayCapabilities { // Whether or not the VR display is capable of reporting user position. // If false position may still be reported using simulated values like
diff --git a/third_party/blink/renderer/modules/vr/vr_display_event.idl b/third_party/blink/renderer/modules/vr/vr_display_event.idl index ae9103a..5627279 100644 --- a/third_party/blink/renderer/modules/vr/vr_display_event.idl +++ b/third_party/blink/renderer/modules/vr/vr_display_event.idl
@@ -12,7 +12,7 @@ // https://w3c.github.io/webvr/#interface-vrdisplayevent [ - OriginTrialEnabled=WebVR, + RuntimeEnabled=WebVR, Constructor(DOMString type, optional VRDisplayEventInit eventInitDict) ] interface VRDisplayEvent : Event { readonly attribute VRDisplay display;
diff --git a/third_party/blink/renderer/modules/vr/vr_eye_parameters.idl b/third_party/blink/renderer/modules/vr/vr_eye_parameters.idl index 7b5b630..4da215c 100644 --- a/third_party/blink/renderer/modules/vr/vr_eye_parameters.idl +++ b/third_party/blink/renderer/modules/vr/vr_eye_parameters.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/webvr/#interface-vreyeparameters [ - OriginTrialEnabled=WebVR + RuntimeEnabled=WebVR ] interface VREyeParameters { /* These values will vary after a FOV has been set */ [DeprecateAs=VREyeParametersOffset] readonly attribute Float32Array offset;
diff --git a/third_party/blink/renderer/modules/vr/vr_frame_data.idl b/third_party/blink/renderer/modules/vr/vr_frame_data.idl index 5d1f348..9df122c 100644 --- a/third_party/blink/renderer/modules/vr/vr_frame_data.idl +++ b/third_party/blink/renderer/modules/vr/vr_frame_data.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/webvr/#interface-vrframedata [ - OriginTrialEnabled=WebVR, + RuntimeEnabled=WebVR, Constructor ] interface VRFrameData { readonly attribute Float32Array leftProjectionMatrix;
diff --git a/third_party/blink/renderer/modules/vr/vr_pose.idl b/third_party/blink/renderer/modules/vr/vr_pose.idl index e935c5f..e8dcd63 100644 --- a/third_party/blink/renderer/modules/vr/vr_pose.idl +++ b/third_party/blink/renderer/modules/vr/vr_pose.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/webvr/#interface-vrpose [ - OriginTrialEnabled=WebVR + RuntimeEnabled=WebVR ] interface VRPose { readonly attribute Float32Array? position; [MeasureAs=VRPoseLinearVelocity] readonly attribute Float32Array? linearVelocity;
diff --git a/third_party/blink/renderer/modules/vr/vr_stage_parameters.idl b/third_party/blink/renderer/modules/vr/vr_stage_parameters.idl index 458582f..562c9b5a 100644 --- a/third_party/blink/renderer/modules/vr/vr_stage_parameters.idl +++ b/third_party/blink/renderer/modules/vr/vr_stage_parameters.idl
@@ -4,7 +4,7 @@ // https://w3c.github.io/webvr/#interface-vrstageparameters [ - OriginTrialEnabled=WebVR + RuntimeEnabled=WebVR ] interface VRStageParameters { // A 16 element array containing the components of a 4x4 transform // matrix. This matrix transforms the sitting space position
diff --git a/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc b/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc index 6966c7a6..3952278 100644 --- a/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc +++ b/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc
@@ -36,10 +36,25 @@ #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/cross_thread_functional.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" -#include "third_party/blink/renderer/platform/wtf/locker.h" namespace blink { +class MediaElementAudioSourceHandlerLocker final { + STACK_ALLOCATED(); + + public: + MediaElementAudioSourceHandlerLocker(MediaElementAudioSourceHandler& lockable) + : lockable_(lockable) { + lockable_.lock(); + } + ~MediaElementAudioSourceHandlerLocker() { lockable_.unlock(); } + + private: + MediaElementAudioSourceHandler& lockable_; + + DISALLOW_COPY_AND_ASSIGN(MediaElementAudioSourceHandlerLocker); +}; + MediaElementAudioSourceHandler::MediaElementAudioSourceHandler( AudioNode& node, HTMLMediaElement& media_element) @@ -100,7 +115,7 @@ DLOG(ERROR) << "setFormat(" << number_of_channels << ", " << source_sample_rate << ") - unhandled format change"; // Synchronize with process(). - Locker<MediaElementAudioSourceHandler> locker(*this); + MediaElementAudioSourceHandlerLocker locker(*this); source_number_of_channels_ = 0; source_sample_rate_ = 0; is_origin_tainted_ = is_tainted; @@ -110,7 +125,7 @@ // Synchronize with process() to protect |source_number_of_channels_|, // |source_sample_rate_|, |multi_channel_resampler_|. and // |is_origin_tainted_|. - Locker<MediaElementAudioSourceHandler> locker(*this); + MediaElementAudioSourceHandlerLocker locker(*this); is_origin_tainted_ = is_tainted; source_number_of_channels_ = number_of_channels;
diff --git a/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc b/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc index 8276797..0338f1d8 100644 --- a/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc +++ b/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc
@@ -35,7 +35,6 @@ #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/mediastream/media_stream_center.h" #include "third_party/blink/renderer/platform/uuid.h" -#include "third_party/blink/renderer/platform/wtf/locker.h" namespace blink {
diff --git a/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc b/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc index b22626c..4f2929d 100644 --- a/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc +++ b/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc
@@ -30,7 +30,6 @@ #include "third_party/blink/renderer/modules/webaudio/audio_node_output.h" #include "third_party/blink/renderer/modules/webaudio/media_stream_audio_source_options.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" -#include "third_party/blink/renderer/platform/wtf/locker.h" namespace blink {
diff --git a/third_party/blink/renderer/modules/webgl/webgl_context_attributes.idl b/third_party/blink/renderer/modules/webgl/webgl_context_attributes.idl index d148ac9..bb593cd 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_context_attributes.idl +++ b/third_party/blink/renderer/modules/webgl/webgl_context_attributes.idl
@@ -41,6 +41,6 @@ boolean preserveDrawingBuffer = false; WebGLPowerPreference powerPreference = "default"; boolean failIfMajorPerformanceCaveat = false; - [OriginTrialEnabled=WebXR] boolean xrCompatible = false; + [RuntimeEnabled=WebXR] boolean xrCompatible = false; boolean desynchronized = false; };
diff --git a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl index b825f7e..60824477 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl +++ b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl
@@ -709,5 +709,5 @@ [RuntimeEnabled=OffscreenCanvasCommit] void commit(); // WebXR Device API support - [OriginTrialEnabled=WebXR, SecureContext, CallWith=ScriptState] Promise<void> makeXRCompatible(); + [RuntimeEnabled=WebXR, SecureContext, CallWith=ScriptState] Promise<void> makeXRCompatible(); };
diff --git a/third_party/blink/renderer/modules/xr/xr.idl b/third_party/blink/renderer/modules/xr/xr.idl index 1337c09..3301a0e8 100644 --- a/third_party/blink/renderer/modules/xr/xr.idl +++ b/third_party/blink/renderer/modules/xr/xr.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XR : EventTarget { attribute EventHandler ondevicechange; [CallWith=ScriptState, MeasureAs=XRSupportsSession] Promise<void> supportsSessionMode(XRSessionMode mode);
diff --git a/third_party/blink/renderer/modules/xr/xr_bounded_reference_space.idl b/third_party/blink/renderer/modules/xr/xr_bounded_reference_space.idl index ea8d30b..928eac0 100644 --- a/third_party/blink/renderer/modules/xr/xr_bounded_reference_space.idl +++ b/third_party/blink/renderer/modules/xr/xr_bounded_reference_space.idl
@@ -7,7 +7,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRBoundedReferenceSpace : XRReferenceSpace { readonly attribute FrozenArray<DOMPointReadOnly> boundsGeometry; };
diff --git a/third_party/blink/renderer/modules/xr/xr_frame.idl b/third_party/blink/renderer/modules/xr/xr_frame.idl index 50bb9dc..a39ce1b 100644 --- a/third_party/blink/renderer/modules/xr/xr_frame.idl +++ b/third_party/blink/renderer/modules/xr/xr_frame.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRFrame { readonly attribute XRSession session;
diff --git a/third_party/blink/renderer/modules/xr/xr_input_source.idl b/third_party/blink/renderer/modules/xr/xr_input_source.idl index 3f30bcc..908e163a 100644 --- a/third_party/blink/renderer/modules/xr/xr_input_source.idl +++ b/third_party/blink/renderer/modules/xr/xr_input_source.idl
@@ -17,7 +17,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRInputSource { readonly attribute XRHandedness handedness; readonly attribute XRTargetRayMode targetRayMode;
diff --git a/third_party/blink/renderer/modules/xr/xr_input_source_event.idl b/third_party/blink/renderer/modules/xr/xr_input_source_event.idl index bca79e7..293379b0 100644 --- a/third_party/blink/renderer/modules/xr/xr_input_source_event.idl +++ b/third_party/blink/renderer/modules/xr/xr_input_source_event.idl
@@ -5,7 +5,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR, + RuntimeEnabled=WebXR, Constructor(DOMString type, XRInputSourceEventInit eventInitDict) ] interface XRInputSourceEvent : Event { readonly attribute XRFrame frame;
diff --git a/third_party/blink/renderer/modules/xr/xr_layer.idl b/third_party/blink/renderer/modules/xr/xr_layer.idl index 26ceefed..6c1c187 100644 --- a/third_party/blink/renderer/modules/xr/xr_layer.idl +++ b/third_party/blink/renderer/modules/xr/xr_layer.idl
@@ -6,5 +6,5 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRLayer {};
diff --git a/third_party/blink/renderer/modules/xr/xr_pose.idl b/third_party/blink/renderer/modules/xr/xr_pose.idl index 3827098..9a28215 100644 --- a/third_party/blink/renderer/modules/xr/xr_pose.idl +++ b/third_party/blink/renderer/modules/xr/xr_pose.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRPose { readonly attribute XRRigidTransform transform; readonly attribute boolean emulatedPosition;
diff --git a/third_party/blink/renderer/modules/xr/xr_presentation_context.idl b/third_party/blink/renderer/modules/xr/xr_presentation_context.idl index 2ecd316..4d507e9e 100644 --- a/third_party/blink/renderer/modules/xr/xr_presentation_context.idl +++ b/third_party/blink/renderer/modules/xr/xr_presentation_context.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRPresentationContext { // back-reference to the canvas readonly attribute HTMLCanvasElement canvas;
diff --git a/third_party/blink/renderer/modules/xr/xr_ray.idl b/third_party/blink/renderer/modules/xr/xr_ray.idl index ef41463d..68d261a 100644 --- a/third_party/blink/renderer/modules/xr/xr_ray.idl +++ b/third_party/blink/renderer/modules/xr/xr_ray.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR, + RuntimeEnabled=WebXR, Constructor(), Constructor(DOMPointInit origin), Constructor(DOMPointInit origin, DOMPointInit direction),
diff --git a/third_party/blink/renderer/modules/xr/xr_reference_space.idl b/third_party/blink/renderer/modules/xr/xr_reference_space.idl index da6d5c46..037a4c7 100644 --- a/third_party/blink/renderer/modules/xr/xr_reference_space.idl +++ b/third_party/blink/renderer/modules/xr/xr_reference_space.idl
@@ -14,7 +14,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRReferenceSpace : XRSpace { attribute XRRigidTransform originOffset; attribute EventHandler onreset;
diff --git a/third_party/blink/renderer/modules/xr/xr_render_state.idl b/third_party/blink/renderer/modules/xr/xr_render_state.idl index 0eea405..e79af752 100644 --- a/third_party/blink/renderer/modules/xr/xr_render_state.idl +++ b/third_party/blink/renderer/modules/xr/xr_render_state.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRRenderState { readonly attribute double depthNear; readonly attribute double depthFar;
diff --git a/third_party/blink/renderer/modules/xr/xr_rigid_transform.idl b/third_party/blink/renderer/modules/xr/xr_rigid_transform.idl index 4d1000f5..4e26ca7 100644 --- a/third_party/blink/renderer/modules/xr/xr_rigid_transform.idl +++ b/third_party/blink/renderer/modules/xr/xr_rigid_transform.idl
@@ -7,7 +7,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR, + RuntimeEnabled=WebXR, Constructor(optional DOMPointInit position, optional DOMPointInit orientation) ] interface XRRigidTransform { readonly attribute DOMPointReadOnly position;
diff --git a/third_party/blink/renderer/modules/xr/xr_session.idl b/third_party/blink/renderer/modules/xr/xr_session.idl index 0b47826..518367a 100644 --- a/third_party/blink/renderer/modules/xr/xr_session.idl +++ b/third_party/blink/renderer/modules/xr/xr_session.idl
@@ -20,7 +20,7 @@ ActiveScriptWrappable, SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRSession : EventTarget { readonly attribute XRSessionMode mode; readonly attribute XREnvironmentBlendMode environmentBlendMode;
diff --git a/third_party/blink/renderer/modules/xr/xr_session_event.idl b/third_party/blink/renderer/modules/xr/xr_session_event.idl index 7bf08de..46ef20f 100644 --- a/third_party/blink/renderer/modules/xr/xr_session_event.idl +++ b/third_party/blink/renderer/modules/xr/xr_session_event.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR, + RuntimeEnabled=WebXR, Constructor(DOMString type, XRSessionEventInit eventInitDict) ] interface XRSessionEvent : Event { readonly attribute XRSession session;
diff --git a/third_party/blink/renderer/modules/xr/xr_space.idl b/third_party/blink/renderer/modules/xr/xr_space.idl index 0e8df5a..583725d 100644 --- a/third_party/blink/renderer/modules/xr/xr_space.idl +++ b/third_party/blink/renderer/modules/xr/xr_space.idl
@@ -6,5 +6,5 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRSpace : EventTarget {};
diff --git a/third_party/blink/renderer/modules/xr/xr_stage_bounds.idl b/third_party/blink/renderer/modules/xr/xr_stage_bounds.idl index 95e0fad..86c6fd9 100644 --- a/third_party/blink/renderer/modules/xr/xr_stage_bounds.idl +++ b/third_party/blink/renderer/modules/xr/xr_stage_bounds.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRStageBounds { readonly attribute FrozenArray<DOMPointReadOnly> geometry; };
diff --git a/third_party/blink/renderer/modules/xr/xr_stationary_reference_space.idl b/third_party/blink/renderer/modules/xr/xr_stationary_reference_space.idl index ac30cc8e..544e865 100644 --- a/third_party/blink/renderer/modules/xr/xr_stationary_reference_space.idl +++ b/third_party/blink/renderer/modules/xr/xr_stationary_reference_space.idl
@@ -13,7 +13,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRStationaryReferenceSpace : XRReferenceSpace { readonly attribute XRStationaryReferenceSpaceSubtype subtype; };
diff --git a/third_party/blink/renderer/modules/xr/xr_unbounded_reference_space.idl b/third_party/blink/renderer/modules/xr/xr_unbounded_reference_space.idl index 4826c55..a3cf8ddb 100644 --- a/third_party/blink/renderer/modules/xr/xr_unbounded_reference_space.idl +++ b/third_party/blink/renderer/modules/xr/xr_unbounded_reference_space.idl
@@ -7,6 +7,6 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRUnboundedReferenceSpace : XRReferenceSpace { };
diff --git a/third_party/blink/renderer/modules/xr/xr_view.idl b/third_party/blink/renderer/modules/xr/xr_view.idl index 3bd730f..aa17b8b 100644 --- a/third_party/blink/renderer/modules/xr/xr_view.idl +++ b/third_party/blink/renderer/modules/xr/xr_view.idl
@@ -11,7 +11,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRView { readonly attribute XREye eye; readonly attribute Float32Array projectionMatrix;
diff --git a/third_party/blink/renderer/modules/xr/xr_viewer_pose.idl b/third_party/blink/renderer/modules/xr/xr_viewer_pose.idl index 15fad3a..4265678 100644 --- a/third_party/blink/renderer/modules/xr/xr_viewer_pose.idl +++ b/third_party/blink/renderer/modules/xr/xr_viewer_pose.idl
@@ -7,7 +7,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRViewerPose : XRPose { readonly attribute FrozenArray<XRView> views; };
diff --git a/third_party/blink/renderer/modules/xr/xr_viewport.idl b/third_party/blink/renderer/modules/xr/xr_viewport.idl index 8c51f30..6e21159 100644 --- a/third_party/blink/renderer/modules/xr/xr_viewport.idl +++ b/third_party/blink/renderer/modules/xr/xr_viewport.idl
@@ -6,7 +6,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR + RuntimeEnabled=WebXR ] interface XRViewport { readonly attribute long x; readonly attribute long y;
diff --git a/third_party/blink/renderer/modules/xr/xr_webgl_layer.idl b/third_party/blink/renderer/modules/xr/xr_webgl_layer.idl index 0b7495c..9174a5d 100644 --- a/third_party/blink/renderer/modules/xr/xr_webgl_layer.idl +++ b/third_party/blink/renderer/modules/xr/xr_webgl_layer.idl
@@ -8,7 +8,7 @@ [ SecureContext, Exposed=Window, - OriginTrialEnabled=WebXR, + RuntimeEnabled=WebXR, Constructor(XRSession session, XRWebGLRenderingContext context, optional XRWebGLLayerInit layerInit), RaisesException=Constructor ] interface XRWebGLLayer : XRLayer {
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 4bb9e4a25..b59d09e 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -39,10 +39,12 @@ "../build/scripts/templates/runtime_enabled_features_test_helpers.h.tmpl", ] + build_scripts_output_dir = "$blink_platform_output_dir/../build/scripts" outputs = [ "$blink_platform_output_dir/runtime_enabled_features.cc", "$blink_platform_output_dir/runtime_enabled_features.h", "$blink_platform_output_dir/testing/runtime_enabled_features_test_helpers.h", + "$build_scripts_output_dir/runtime_enabled_features.pickle", ] args = [ @@ -50,6 +52,11 @@ "--output_dir", rebase_path(blink_platform_output_dir, root_build_dir), ] + + visibility += [ + "//third_party/blink/renderer/bindings/core:interfaces_info_individual_core", + "//third_party/blink/renderer/bindings/modules:interfaces_info_individual_modules", + ] } blink_python_runner("color_data") {
diff --git a/third_party/blink/renderer/platform/exported/web_runtime_features.cc b/third_party/blink/renderer/platform/exported/web_runtime_features.cc index ff0881a..e7ad1eb 100644 --- a/third_party/blink/renderer/platform/exported/web_runtime_features.cc +++ b/third_party/blink/renderer/platform/exported/web_runtime_features.cc
@@ -519,8 +519,12 @@ RuntimeEnabledFeatures::SetScrollAnchorSerializationEnabled(enable); } -void WebRuntimeFeatures::EnableSecMetadata(bool enable) { - RuntimeEnabledFeatures::SetSecMetadataEnabled(enable); +void WebRuntimeFeatures::EnableFetchMetadata(bool enable) { + RuntimeEnabledFeatures::SetFetchMetadataEnabled(enable); +} + +void WebRuntimeFeatures::EnableFetchMetadataDestination(bool enable) { + RuntimeEnabledFeatures::SetFetchMetadataDestinationEnabled(enable); } void WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(bool enable) {
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 16afbeb..1880fa5 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -550,6 +550,14 @@ name: "FeaturePolicyVibrateFeature" }, { + name: "FetchMetadata", + status: "experimental" + }, + { + name: "FetchMetadataDestination", + status: "experimental" + }, + { name: "FileSystem", status: "stable", }, @@ -1269,10 +1277,6 @@ status: "stable", }, { - name: "SecMetadata", - status: "experimental" - }, - { name: "SendBeaconThrowForBlobWithNonSimpleType", status: "stable", },
diff --git a/third_party/blink/renderer/platform/wtf/BUILD.gn b/third_party/blink/renderer/platform/wtf/BUILD.gn index 403ac928..af23c6e0 100644 --- a/third_party/blink/renderer/platform/wtf/BUILD.gn +++ b/third_party/blink/renderer/platform/wtf/BUILD.gn
@@ -92,7 +92,6 @@ "leak_annotations.h", "linked_hash_set.h", "list_hash_set.h", - "locker.h", "math_extras.h", "pod_arena.h", "pod_free_list_arena.h",
diff --git a/third_party/blink/renderer/platform/wtf/date_math.h b/third_party/blink/renderer/platform/wtf/date_math.h index 069a557..123b6331 100644 --- a/third_party/blink/renderer/platform/wtf/date_math.h +++ b/third_party/blink/renderer/platform/wtf/date_math.h
@@ -53,6 +53,11 @@ // Not really math related, but this is currently the only shared place to put // these. +// +// TODO(tkent): Only blink::ParseDate() uses this function to parse HTTP +// header values. net::HTTPResponseHeaders::GetTimeValuedHeader() uses +// base::Time::FromUTCString() for the same purpose. We should consider +// switching to base::Time::FromUTCString() for consistency. WTF_EXPORT double ParseDateFromNullTerminatedCharacters( const char* date_string);
diff --git a/third_party/blink/renderer/platform/wtf/locker.h b/third_party/blink/renderer/platform/wtf/locker.h deleted file mode 100644 index b594e45..0000000 --- a/third_party/blink/renderer/platform/wtf/locker.h +++ /dev/null
@@ -1,54 +0,0 @@ -/* - * Copyright (C) 2008 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_LOCKER_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_LOCKER_H_ - -#include "base/macros.h" -#include "third_party/blink/renderer/platform/wtf/allocator.h" - -namespace WTF { - -template <typename T> -class Locker final { - STACK_ALLOCATED(); - - public: - Locker(T& lockable) : lockable_(lockable) { lockable_.lock(); } - ~Locker() { lockable_.unlock(); } - - private: - T& lockable_; - - DISALLOW_COPY_AND_ASSIGN(Locker); -}; - -} // namespace WTF - -using WTF::Locker; - -#endif
diff --git a/third_party/blink/renderer/platform/wtf/threading_primitives.h b/third_party/blink/renderer/platform/wtf/threading_primitives.h index 2d6f3065..819ba7a 100644 --- a/third_party/blink/renderer/platform/wtf/threading_primitives.h +++ b/third_party/blink/renderer/platform/wtf/threading_primitives.h
@@ -36,7 +36,6 @@ #include "build/build_config.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" -#include "third_party/blink/renderer/platform/wtf/locker.h" #include "third_party/blink/renderer/platform/wtf/wtf_export.h" #if defined(OS_WIN) @@ -125,8 +124,6 @@ DISALLOW_COPY_AND_ASSIGN(MutexLocker); }; -using RecursiveMutexLocker = Locker<RecursiveMutex>; - class MutexTryLocker final { STACK_ALLOCATED(); @@ -171,7 +168,6 @@ using WTF::RecursiveMutex; using WTF::MutexLocker; using WTF::MutexTryLocker; -using WTF::RecursiveMutexLocker; using WTF::ThreadCondition; #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_THREADING_PRIMITIVES_H_
diff --git a/third_party/blink/tools/blinkpy/bindings/bindings_tests.py b/third_party/blink/tools/blinkpy/bindings/bindings_tests.py index 6edb9ba3..6db448d8 100644 --- a/third_party/blink/tools/blinkpy/bindings/bindings_tests.py +++ b/third_party/blink/tools/blinkpy/bindings/bindings_tests.py
@@ -34,6 +34,7 @@ from blinkpy.common import path_finder path_finder.add_bindings_scripts_dir_to_sys_path() +path_finder.add_build_scripts_dir_to_sys_path() from code_generator_v8 import CodeGeneratorDictionaryImpl from code_generator_v8 import CodeGeneratorV8 @@ -47,6 +48,7 @@ generate_union_type_containers, generate_dictionary_impl, generate_callback_function_impl) +from json5_generator import Json5File from utilities import ComponentInfoProviderCore from utilities import ComponentInfoProviderModules from utilities import get_file_contents @@ -103,7 +105,7 @@ shutil.rmtree(name) -def generate_interface_dependencies(): +def generate_interface_dependencies(runtime_enabled_features): def idl_paths_recursive(directory): # This is slow, especially on Windows, due to os.walk making # excess stat() calls. Faster versions may appear in Python 3.5 or @@ -137,7 +139,7 @@ # To avoid this issue, we need to clear relative_dir here. for value in info['interfaces_info'].itervalues(): value['relative_dir'] = '' - component_info = info_collector.get_component_info_as_dict() + component_info = info_collector.get_component_info_as_dict(runtime_enabled_features) return info, component_info # We compute interfaces info for *all* IDL files, not just test IDL @@ -275,8 +277,18 @@ return False return True + def make_runtime_features_dict(): + input_filename = os.path.join(TEST_INPUT_DIRECTORY, 'runtime_enabled_features.json5') + json5_file = Json5File.load_from_files([input_filename]) + features_map = {} + for feature in json5_file.name_dictionaries: + features_map[str(feature['name'])] = { + 'in_origin_trial': feature['in_origin_trial'] + } + return features_map + try: - generate_interface_dependencies() + generate_interface_dependencies(make_runtime_features_dict()) for component in COMPONENT_DIRECTORY: output_dir = os.path.join(output_directory, component) if not os.path.exists(output_dir):
diff --git a/third_party/blink/tools/blinkpy/common/path_finder.py b/third_party/blink/tools/blinkpy/common/path_finder.py index 0813c1b..c829a09ba 100644 --- a/third_party/blink/tools/blinkpy/common/path_finder.py +++ b/third_party/blink/tools/blinkpy/common/path_finder.py
@@ -44,6 +44,12 @@ sys.path.insert(0, path_to_bindings_scripts) +def add_build_scripts_dir_to_sys_path(): + path_to_build_scripts = os.path.join(get_source_dir(), 'build', 'scripts') + if path_to_build_scripts not in sys.path: + sys.path.insert(0, path_to_build_scripts) + + def add_blinkpy_thirdparty_dir_to_sys_path(): path = get_blinkpy_thirdparty_dir() if path not in sys.path:
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index aeded0bc..3ea264aa 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -6066,6 +6066,7 @@ crbug.com/915352 [ Mac10.10 Mac10.11 ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-with-scroll-timeline.https.html [ Pass Failure ] crbug.com/915352 [ Mac10.10 Mac10.11 ] virtual/threaded/external/wpt/animation-worklet/worklet-animation-with-scroll-timeline-and-display-none.https.html [ Pass Failure ] +crbug.com/951753 virtual/threaded/external/wpt/animation-worklet/worklet-animation-duration.https.html [ Pass Failure ] # Sheriff 2019-03-01 crbug.com/937170 [ Linux Win7 ] external/wpt/IndexedDB/interleaved-cursors-large.html [ Pass Timeout Crash ]
diff --git a/third_party/blink/web_tests/accessibility/display-contents.html b/third_party/blink/web_tests/accessibility/display-contents.html new file mode 100644 index 0000000..c5975e5 --- /dev/null +++ b/third_party/blink/web_tests/accessibility/display-contents.html
@@ -0,0 +1,64 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<template id="template"> + <slot role="note" name="one"></slot> + <slot name="two"></slot> +</template> + +<div class="container"> + <div style="display: contents" id="div">Boring old div</div> + <div style="display: contents" role="heading" id="role-heading">Heading</div> + <button style="display: contents" id="button">Clear form</button> + <a href="#" style="display: contents" id="link">Click here</a> + <div id="shadow-host"> + <div slot="one">Hello</div> + <div slot="two">Goodbye</div> + </div> +</div> + +<script> + let shadowHost = document.getElementById('shadow-host'); + let shadowRoot = shadowHost.attachShadow({mode: 'open'}); + let template = document.getElementById('template'); + shadowRoot.appendChild(template.content.cloneNode(true)); +</script> + +<script> +test(function(t) +{ + let axDiv = accessibilityController.accessibleElementById('div'); + assert_not_equals(axDiv, undefined); + assert_equals(axDiv.role, 'AXRole: AXGenericContainer'); +}, 'Elements with display: contents should appear in the accessibility tree.'); + +test(function(t) +{ + let axHeading = accessibilityController.accessibleElementById('role-heading'); + assert_not_equals(axHeading, undefined); + assert_equals(axHeading.role, 'AXRole: AXHeading'); +}, 'Elements with display: contents should have ARIA roles respected.'); + +test(function(t) +{ + let axButton = accessibilityController.accessibleElementById('button'); + assert_not_equals(axButton, undefined); + assert_equals(axButton.role, 'AXRole: AXButton'); + let axLink = accessibilityController.accessibleElementById('link'); + assert_not_equals(axLink, undefined); + assert_equals(axLink.role, 'AXRole: AXLink'); +}, 'Elements with display: contents should have native roles respected.'); + +test(function(t) +{ + let axShadowHost = accessibilityController.accessibleElementById('shadow-host'); + assert_equals(axShadowHost.childrenCount, 2); + + let axSlotWithRole = axShadowHost.childAtIndex(0); + assert_equals(axSlotWithRole.role, 'AXRole: AXNote'); + + let axSlotWithoutRole = axShadowHost.childAtIndex(1); + assert_equals(axSlotWithoutRole.role, 'AXRole: AXGenericContainer'); +}, '<slot> elements should appear in the accessibility tree, and have ARIA roles respected'); +</script>
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json index a2b53c33..c0623e4d 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json
@@ -109477,6 +109477,18 @@ {} ] ], + "html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001.html": [ + [ + "/html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001.html", + [ + [ + "/html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001-ref.html", + "==" + ] + ], + {} + ] + ], "infrastructure/assumptions/ahem.html": [ [ "/infrastructure/assumptions/ahem.html", @@ -114762,18 +114774,6 @@ ], {} ] - ], - "xhtml/adopt-while-parsing-001.html": [ - [ - "/xhtml/adopt-while-parsing-001.html", - [ - [ - "/xhtml/adopt-while-parsing-001-ref.html", - "==" - ] - ], - {} - ] ] }, "reftest_node": { @@ -159898,6 +159898,11 @@ {} ] ], + "dom/events/Event-dispatch-handlers-changed-expected.txt": [ + [ + {} + ] + ], "dom/events/Event-dispatch-listener-order.window-expected.txt": [ [ {} @@ -176643,6 +176648,16 @@ {} ] ], + "html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001-ref.html": [ + [ + {} + ] + ], + "html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing.xhtml": [ + [ + {} + ] + ], "html/the-xhtml-syntax/parsing-xhtml-documents/xhtml-mathml-dtd-entity-support.htm": [ [ {} @@ -188613,11 +188628,21 @@ {} ] ], + "service-workers/service-worker/resources/import-scripts-diff-resource-map-worker.js": [ + [ + {} + ] + ], "service-workers/service-worker/resources/import-scripts-echo.py": [ [ {} ] ], + "service-workers/service-worker/resources/import-scripts-get.py": [ + [ + {} + ] + ], "service-workers/service-worker/resources/import-scripts-mime-types-worker.js": [ [ {} @@ -204822,16 +204847,6 @@ [ {} ] - ], - "xhtml/adopt-while-parsing-001-ref.html": [ - [ - {} - ] - ], - "xhtml/adopt-while-parsing.xhtml": [ - [ - {} - ] ] }, "testharness": { @@ -407871,8 +407886,12 @@ "76ea3d78ba74e027c7a9148257f437b52b73250a", "testharness" ], + "dom/events/Event-dispatch-handlers-changed-expected.txt": [ + "c3c943786a4bfe3b851351a71f93f44aa522521d", + "support" + ], "dom/events/Event-dispatch-handlers-changed.html": [ - "b325d5c5dc6b62cfb434a89e99004257c6982a57", + "24e6fd70cb4ec4d44905ba8624280a526ef888c6", "testharness" ], "dom/events/Event-dispatch-listener-order.window-expected.txt": [ @@ -434919,6 +434938,18 @@ "870ff58a34277ed367f3f9a9d58f6abcb44293c3", "support" ], + "html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001-ref.html": [ + "5b512e72f5a1f3780c9c38be79968b095c277a39", + "support" + ], + "html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001.html": [ + "74018b4ad0f342aa5b38ad337ce9329e6d92545d", + "reftest" + ], + "html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing.xhtml": [ + "2d85d21558b1778e17376d12424f81c703c0c262", + "support" + ], "html/the-xhtml-syntax/parsing-xhtml-documents/xhtml-mathml-dtd-entity-1.htm": [ "4025e2a477fde1dbeb170e7248032e221efdb62f", "testharness" @@ -464372,7 +464403,7 @@ "testharness" ], "service-workers/service-worker/import-scripts-resource-map.https.html": [ - "a5e26785fac4aa1267762ff58c48969dc8acb017", + "4742bd01268360477bf6061f8505fe9a3b7cadb7", "testharness" ], "service-workers/service-worker/import-scripts-updated-flag.https.html": [ @@ -465287,10 +465318,18 @@ "063a62d03143a32f44365bf1e7b08d283ae52895", "support" ], + "service-workers/service-worker/resources/import-scripts-diff-resource-map-worker.js": [ + "0fdcb0fcf80ad7f0dffa284c5b77178bdad95ef6", + "support" + ], "service-workers/service-worker/resources/import-scripts-echo.py": [ "7d92794e31b6b1270db26779f63644ac42a3d3d6", "support" ], + "service-workers/service-worker/resources/import-scripts-get.py": [ + "9e376bc092889f1b231628ec7c17339674d284f4", + "support" + ], "service-workers/service-worker/resources/import-scripts-mime-types-worker.js": [ "2c585ac1060a88c4f3eeac6b6a81bbb4e0c30280", "support" @@ -489494,18 +489533,6 @@ "xhr/xmlhttprequest-unsent.htm": [ "eb52d63eef971895f69f1b0151baa457250dd452", "testharness" - ], - "xhtml/adopt-while-parsing-001-ref.html": [ - "5b512e72f5a1f3780c9c38be79968b095c277a39", - "support" - ], - "xhtml/adopt-while-parsing-001.html": [ - "74018b4ad0f342aa5b38ad337ce9329e6d92545d", - "reftest" - ], - "xhtml/adopt-while-parsing.xhtml": [ - "2d85d21558b1778e17376d12424f81c703c0c262", - "support" ] }, "url_base": "/",
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/Event-dispatch-handlers-changed-expected.txt b/third_party/blink/web_tests/external/wpt/dom/events/Event-dispatch-handlers-changed-expected.txt new file mode 100644 index 0000000..c3c943786 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/dom/events/Event-dispatch-handlers-changed-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Dispatch additional events inside an event listener assert_array_equals: actual_targets lengths differ, expected 17 got 16 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/dom/events/Event-dispatch-handlers-changed.html b/third_party/blink/web_tests/external/wpt/dom/events/Event-dispatch-handlers-changed.html index b325d5c..24e6fd70 100644 --- a/third_party/blink/web_tests/external/wpt/dom/events/Event-dispatch-handlers-changed.html +++ b/third_party/blink/web_tests/external/wpt/dom/events/Event-dispatch-handlers-changed.html
@@ -20,7 +20,7 @@ </table> <script> -async_test(function() { +test(function() { var event_type = "bar"; var target = document.getElementById("target"); var parent = document.getElementById("parent"); @@ -39,6 +39,7 @@ parent, target, target, + target, // The additional listener for target runs as we copy its listeners twice parent, tbody, table, @@ -47,7 +48,7 @@ document, window ]; - var expected_listeners = [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]; + var expected_listeners = [0,0,0,0,0,0,0,0,1,3,1,1,1,1,1,1,1]; var actual_targets = [], actual_listeners = []; var test_event_function = function(i) { @@ -86,7 +87,5 @@ assert_array_equals(actual_targets, expected_targets, "actual_targets"); assert_array_equals(actual_listeners, expected_listeners, "actual_listeners"); - - this.done(); }); </script>
diff --git a/third_party/blink/web_tests/external/wpt/xhtml/adopt-while-parsing-001-ref.html b/third_party/blink/web_tests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001-ref.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/xhtml/adopt-while-parsing-001-ref.html rename to third_party/blink/web_tests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001-ref.html
diff --git a/third_party/blink/web_tests/external/wpt/xhtml/adopt-while-parsing-001.html b/third_party/blink/web_tests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/xhtml/adopt-while-parsing-001.html rename to third_party/blink/web_tests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing-001.html
diff --git a/third_party/blink/web_tests/external/wpt/xhtml/adopt-while-parsing.xhtml b/third_party/blink/web_tests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing.xhtml similarity index 100% rename from third_party/blink/web_tests/external/wpt/xhtml/adopt-while-parsing.xhtml rename to third_party/blink/web_tests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/adopt-while-parsing.xhtml
diff --git a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/import-scripts-resource-map.https.html b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/import-scripts-resource-map.https.html index a5e2678..4742bd01 100644 --- a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/import-scripts-resource-map.https.html +++ b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/import-scripts-resource-map.https.html
@@ -1,23 +1,34 @@ <!DOCTYPE html> -<meta charset="utf-8"> +<meta charset="utf-8" /> <title>Tests for importScripts: script resource map</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="resources/test-helpers.sub.js"></script> <body> -<script> -// This test registers a worker that imports a script multiple times. The -// script should be stored on the first import and thereafter that stored -// script should be loaded. The worker asserts that the stored script was -// loaded; if the assert fails then registration fails. -promise_test(t => { - const scope = 'resources/import-scripts-resource-map'; - return service_worker_unregister(t, scope) - .then(() => { - return navigator.serviceWorker.register( - 'resources/import-scripts-resource-map-worker.js', {scope: scope}); - }) - .then(r => r.unregister()); - }, 'import the same script URL multiple times'); -</script> + <script> + // This test registers a worker that imports a script multiple times. The + // script should be stored on the first import and thereafter that stored + // script should be loaded. The worker asserts that the stored script was + // loaded; if the assert fails then registration fails. + + promise_test(async t => { + const SCOPE = "resources/import-scripts-resource-map"; + const SCRIPT = "resources/import-scripts-resource-map-worker.js"; + await service_worker_unregister(t, SCOPE); + const registration = await navigator.serviceWorker.register(SCRIPT, { + scope: SCOPE + }); + await registration.unregister(); + }, "import the same script URL multiple times"); + + promise_test(async t => { + const SCOPE = "resources/import-scripts-diff-resource-map"; + const SCRIPT = "resources/import-scripts-diff-resource-map-worker.js"; + await service_worker_unregister(t, SCOPE); + const registration = await navigator.serviceWorker.register(SCRIPT, { + scope: SCOPE + }); + await registration.unregister(); + }, "call importScripts() with multiple arguments"); + </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/import-scripts-diff-resource-map-worker.js b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/import-scripts-diff-resource-map-worker.js new file mode 100644 index 0000000..0fdcb0f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/import-scripts-diff-resource-map-worker.js
@@ -0,0 +1,10 @@ +importScripts('/resources/testharness.js'); + +let echo1 = null; +let echo2 = null; +let arg1 = 'import-scripts-get.py?output=echo1&msg=test1'; +let arg2 = 'import-scripts-get.py?output=echo2&msg=test2'; + +importScripts(arg1, arg2); +assert_equals(echo1, 'test1'); +assert_equals(echo2, 'test2');
diff --git a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/import-scripts-get.py b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/import-scripts-get.py new file mode 100644 index 0000000..9e376bc --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/import-scripts-get.py
@@ -0,0 +1,6 @@ +def main(req, res): + return ([ + ('Cache-Control', 'no-cache, must-revalidate'), + ('Pragma', 'no-cache'), + ('Content-Type', 'application/javascript')], + '%s = "%s";\n' % (req.GET['output'], req.GET['msg']))
diff --git a/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-Document-write.tentative.html b/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-Document-write.tentative.html index 5fa0b19..845df47 100644 --- a/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-Document-write.tentative.html +++ b/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-Document-write.tentative.html
@@ -10,14 +10,22 @@ <body> <script> // TrustedURL assignments do not throw. + let p = createHTML_policy(window, 1); test(t => { document.body.innerText = ''; - let p = createHTML_policy(window, 1); let html = p.createHTML(INPUTS.HTML); document.write(html); assert_equals(document.body.innerText, RESULTS.HTML); }, "document.write with html assigned via policy (successful URL transformation)."); + // TrustedURL assignments do not throw. (Now for writeln.) + test(t => { + document.body.innerText = ''; + let html = p.createHTML(INPUTS.HTML); + document.writeln(html); + assert_equals(document.body.innerText, RESULTS.HTML); + }, "document.writeln with html assigned via policy (successful URL transformation)."); + // String assignments throw. test(t => { const old = document.body.innerText; @@ -27,6 +35,15 @@ assert_equals(document.body.innerText, old); }, "`document.write(string)` throws"); + // String assignments throw. (Now for writeln.) + test(t => { + const old = document.body.innerText; + assert_throws(new TypeError(), _ => { + document.writeln('A string'); + }); + assert_equals(document.body.innerText, old); + }, "`document.writeln(string)` throws"); + // Null assignment throws. test(t => { const old = document.body.innerText; @@ -35,4 +52,30 @@ }); assert_equals(document.body.innerText, old); }, "`document.write(null)` throws"); + + // Null assignment throws. (Now for writeln.) + test(t => { + const old = document.body.innerText; + assert_throws(new TypeError(), _ => { + document.writeln(null); + }); + assert_equals(document.body.innerText, old); + }, "`document.writeln(null)` throws"); + + let default_policy = TrustedTypes.createPolicy('default', + { createHTML: createHTMLJS }, true ); + + // Default policy works. + test(t => { + document.body.innerText = ''; + document.write(INPUTS.HTML); + assert_equals(document.body.innerText, RESULTS.HTML); + }, "`document.write(string)` observes default policy"); + + // Default policy works. (Now for writeln.) + test(t => { + document.body.innerText = ''; + document.writeln(INPUTS.HTML); + assert_equals(document.body.innerText, RESULTS.HTML); + }, "`document.writeln(string)` observes default policy"); </script>
diff --git a/third_party/blink/web_tests/inspector-protocol/accessibility/accessibility-ignoredNodes-expected.txt b/third_party/blink/web_tests/inspector-protocol/accessibility/accessibility-ignoredNodes-expected.txt index a616f48..115af994 100644 --- a/third_party/blink/web_tests/inspector-protocol/accessibility/accessibility-ignoredNodes-expected.txt +++ b/third_party/blink/web_tests/inspector-protocol/accessibility/accessibility-ignoredNodes-expected.txt
@@ -1,6 +1,27 @@ Tests accessibility values of ignored nodes. WebArea + *Ignored +{ + "nodeId": "<string>", + "ignored": true, + "ignoredReasons": [ + { + "name": "uninteresting", + "value": { + "type": "boolean", + "value": true + } + } + ], + "role": { + "type": "internalRole", + "value": "Ignored" + }, + "domNode": "html" +} + +WebArea img *Ignored { @@ -155,6 +176,9 @@ button "aria-hidden false button" GenericContainer combobox + GenericContainer "span with ARIA label" + text "div with display contents - should be ignored, but text should be included" + GenericContainer { "nodeId": "<string>", "ignored": false, @@ -345,6 +369,9 @@ menuitem "Options should be" menuitem "sent down even though" menuitem "they are grandchildren" + GenericContainer "span with ARIA label" + text "div with display contents - should be ignored, but text should be included" + GenericContainer { "nodeId": "<string>", "ignored": false, @@ -504,3 +531,123 @@ "domNode": "button" } +WebArea + GenericContainer + img + button "Buttons are leaf nodes" + text "List item also presentational" + GenericContainer + checkbox "Content within label refers to label container" + button "aria-hidden false button" + GenericContainer + combobox + *GenericContainer "span with ARIA label" + text "should not be ignored" + text "div with display contents - should be ignored, but text should be included" + GenericContainer +{ + "nodeId": "<string>", + "ignored": false, + "role": { + "type": "internalRole", + "value": "GenericContainer" + }, + "name": { + "type": "computedString", + "value": "span with ARIA label", + "sources": [ + { + "type": "relatedElement", + "attribute": "aria-labelledby" + }, + { + "type": "attribute", + "value": { + "type": "computedString", + "value": "span with ARIA label" + }, + "attribute": "aria-label", + "attributeValue": { + "type": "string", + "value": "span with ARIA label" + } + }, + { + "type": "attribute", + "attribute": "title", + "superseded": true + } + ] + }, + "properties": [], + "domNode": "span" +} + +WebArea + *Ignored +{ + "nodeId": "<string>", + "ignored": true, + "ignoredReasons": [ + { + "name": "notRendered", + "value": { + "type": "boolean", + "value": true + } + } + ], + "role": { + "type": "internalRole", + "value": "Ignored" + }, + "domNode": "div" +} + +WebArea + GenericContainer + img + button "Buttons are leaf nodes" + text "List item also presentational" + GenericContainer + checkbox "Content within label refers to label container" + button "aria-hidden false button" + GenericContainer + combobox + GenericContainer "span with ARIA label" + text "div with display contents - should be ignored, but text should be included" + *GenericContainer + text "summary element without details parent is ignored" +{ + "nodeId": "<string>", + "ignored": false, + "role": { + "type": "internalRole", + "value": "GenericContainer" + }, + "name": { + "type": "computedString", + "value": "", + "sources": [ + { + "type": "relatedElement", + "attribute": "aria-labelledby" + }, + { + "type": "attribute", + "attribute": "aria-label" + }, + { + "type": "attribute", + "attribute": "title" + } + ] + }, + "description": { + "type": "computedString", + "value": "summary element without details parent is ignored" + }, + "properties": [], + "domNode": "summary" +} +
diff --git a/third_party/blink/web_tests/inspector-protocol/accessibility/accessibility-ignoredNodes.js b/third_party/blink/web_tests/inspector-protocol/accessibility/accessibility-ignoredNodes.js index 175c365c..6fc3cbb 100644 --- a/third_party/blink/web_tests/inspector-protocol/accessibility/accessibility-ignoredNodes.js +++ b/third_party/blink/web_tests/inspector-protocol/accessibility/accessibility-ignoredNodes.js
@@ -1,45 +1,53 @@ (async function(testRunner) { var {page, session, dp} = await testRunner.startHTML(` + <html data-dump><!-- HTML nodes are ignored --> <div>Non-hidden div for comparison</div> - <div role='img'> - <svg data-dump> - <!-- Children of img role are presentational --> - <circle xmlns:svg='http://www.w3.org/2000/svg' cx='150px' cy='100px' r='50px' fill='#ff0000' stroke='#000000' stroke-width='5px'/> - </svg> - </div> - <button> - <span data-dump>Buttons are leaf nodes</span> - </button> - <div data-dump aria-hidden='true'> - <div data-dump>Descendant of aria-hidden node</div> - </div> - <ol role='none' data-dump><!-- list is presentational --> - <li data-dump>List item also presentational</li> - <div data-dump>Div in list isn't presentational</div> - </ol> + <div role='img'> + <svg data-dump> + <!-- Children of img role are presentational --> + <circle xmlns:svg='http://www.w3.org/2000/svg' cx='150px' cy='100px' r='50px' fill='#ff0000' stroke='#000000' stroke-width='5px'/> + </svg> + </div> + <button> + <span data-dump>Buttons are leaf nodes</span> + </button> + <div data-dump aria-hidden='true'> + <div data-dump>Descendant of aria-hidden node</div> + </div> + <ol role='none' data-dump><!-- list is presentational --> + <li data-dump>List item also presentational</li> + <div data-dump>Div in list isn't presentational</div> + </ol> - <label for='checkbox' data-dump><span data-dump>Content within label refers to label container</span></label> - <input type='checkbox' id='checkbox'> - <div style='display: none' data-dump> - Non-rendered div - <span data-dump>Span within non-rendered div</span> - <button aria-hidden='false'>aria-hidden false button</button> - </div> + <label for='checkbox' data-dump><span data-dump>Content within label refers to label container</span></label> + <input type='checkbox' id='checkbox'> + <div style='display: none' data-dump> + Non-rendered div + <span data-dump>Span within non-rendered div</span> + <button aria-hidden='false'>aria-hidden false button</button> + </div> - <canvas style='height: 1px; width: 1px;' data-dump></canvas> + <canvas style='height: 1px; width: 1px;' data-dump></canvas> - <canvas role='presentation' data-dump><div>Canvas fallback content</div></canvas> + <canvas role='presentation' data-dump><div>Canvas fallback content</div></canvas> - <select data-dump> - <option data-dump>Options should be</option> - <option>sent down even though</option> - <option>they are grandchildren</option> - </select> + <select data-dump> + <option data-dump>Options should be</option> + <option>sent down even though</option> + <option>they are grandchildren</option> + </select> - <button inert data-dump>inert button</button> - <div id='inert-root' inert> - <button data-dump>button in inert subtree</button> - </div> + <button inert data-dump>inert button</button> + <div id='inert-root' inert> + <button data-dump>button in inert subtree</button> + </div> + + <span data-dump aria-label="span with ARIA label">should not be ignored</span> + + <div data-dump style="display: contents">div with display contents - should be ignored, but text should be included</div> + + <summary data-dump>summary element without details parent is ignored</summary> + </html> `, 'Tests accessibility values of ignored nodes.'); var dumpAccessibilityNodesBySelectorAndCompleteTest =
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 3bffbe7..c0ab3bc 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -2449,6 +2449,7 @@ <int value="15" label="App started by left-clicking on link"/> <int value="16" label="App started from link context menu"/> <int value="17" label="App started from Smart Text Selection context menu"/> + <int value="18" label="App started from Kiosk Next Home"/> </enum> <enum name="ArcVideoDecodeAcceleratorResult"> @@ -10445,6 +10446,7 @@ <int value="1" label="Failed"/> <int value="2" label="Failed VM Stopped"/> <int value="3" label="Failed VM Started"/> + <int value="4" label="Failed Architecture mismatch"/> </enum> <enum name="CrostiniSetupResult"> @@ -36958,6 +36960,105 @@ <int value="5" label="~2160 or higher"/> </enum> +<enum name="MegaConfusionMatrix"> + <int value="0" label="True Negative (Bucket 0)"/> + <int value="1" label="False Negative (Bucket 0)"/> + <int value="2" label="False Positive (Bucket 0)"/> + <int value="3" label="True Positive (Bucket 0)"/> + <int value="4" label="No-prediction Negative (Bucket 0)"/> + <int value="5" label="No-prediction Positive (Bucket 0)"/> + <int value="10" label="True Negative (Bucket 1)"/> + <int value="11" label="False Negative (Bucket 1)"/> + <int value="12" label="False Positive (Bucket 1)"/> + <int value="13" label="True Positive (Bucket 1)"/> + <int value="14" label="No-prediction Negative (Bucket 1)"/> + <int value="15" label="No-prediction Positive (Bucket 1)"/> + <int value="20" label="True Negative (Bucket 2)"/> + <int value="21" label="False Negative (Bucket 2)"/> + <int value="22" label="False Positive (Bucket 2)"/> + <int value="23" label="True Positive (Bucket 2)"/> + <int value="24" label="No-prediction Negative (Bucket 2)"/> + <int value="25" label="No-prediction Positive (Bucket 2)"/> + <int value="30" label="True Negative (Bucket 3)"/> + <int value="31" label="False Negative (Bucket 3)"/> + <int value="32" label="False Positive (Bucket 3)"/> + <int value="33" label="True Positive (Bucket 3)"/> + <int value="34" label="No-prediction Negative (Bucket 3)"/> + <int value="35" label="No-prediction Positive (Bucket 3)"/> + <int value="40" label="True Negative (Bucket 4)"/> + <int value="41" label="False Negative (Bucket 4)"/> + <int value="42" label="False Positive (Bucket 4)"/> + <int value="43" label="True Positive (Bucket 4)"/> + <int value="44" label="No-prediction Negative (Bucket 4)"/> + <int value="45" label="No-prediction Positive (Bucket 4)"/> + <int value="50" label="True Negative (Bucket 5)"/> + <int value="51" label="False Negative (Bucket 5)"/> + <int value="52" label="False Positive (Bucket 5)"/> + <int value="53" label="True Positive (Bucket 5)"/> + <int value="54" label="No-prediction Negative (Bucket 5)"/> + <int value="55" label="No-prediction Positive (Bucket 5)"/> + <int value="60" label="True Negative (Bucket 6)"/> + <int value="61" label="False Negative (Bucket 6)"/> + <int value="62" label="False Positive (Bucket 6)"/> + <int value="63" label="True Positive (Bucket 6)"/> + <int value="64" label="No-prediction Negative (Bucket 6)"/> + <int value="65" label="No-prediction Positive (Bucket 6)"/> + <int value="70" label="True Negative (Bucket 7)"/> + <int value="71" label="False Negative (Bucket 7)"/> + <int value="72" label="False Positive (Bucket 7)"/> + <int value="73" label="True Positive (Bucket 7)"/> + <int value="74" label="No-prediction Negative (Bucket 7)"/> + <int value="75" label="No-prediction Positive (Bucket 7)"/> + <int value="80" label="True Negative (Bucket 8)"/> + <int value="81" label="False Negative (Bucket 8)"/> + <int value="82" label="False Positive (Bucket 8)"/> + <int value="83" label="True Positive (Bucket 8)"/> + <int value="84" label="No-prediction Negative (Bucket 8)"/> + <int value="85" label="No-prediction Positive (Bucket 8)"/> + <int value="90" label="True Negative (Bucket 9)"/> + <int value="91" label="False Negative (Bucket 9)"/> + <int value="92" label="False Positive (Bucket 9)"/> + <int value="93" label="True Positive (Bucket 9)"/> + <int value="94" label="No-prediction Negative (Bucket 9)"/> + <int value="95" label="No-prediction Positive (Bucket 9)"/> + <int value="100" label="True Negative (Bucket 10)"/> + <int value="101" label="False Negative (Bucket 10)"/> + <int value="102" label="False Positive (Bucket 10)"/> + <int value="103" label="True Positive (Bucket 10)"/> + <int value="104" label="No-prediction Negative (Bucket 10)"/> + <int value="105" label="No-prediction Positive (Bucket 10)"/> + <int value="110" label="True Negative (Bucket 11)"/> + <int value="111" label="False Negative (Bucket 11)"/> + <int value="112" label="False Positive (Bucket 11)"/> + <int value="113" label="True Positive (Bucket 11)"/> + <int value="114" label="No-prediction Negative (Bucket 11)"/> + <int value="115" label="No-prediction Positive (Bucket 11)"/> + <int value="120" label="True Negative (Bucket 12)"/> + <int value="121" label="False Negative (Bucket 12)"/> + <int value="122" label="False Positive (Bucket 12)"/> + <int value="123" label="True Positive (Bucket 12)"/> + <int value="124" label="No-prediction Negative (Bucket 12)"/> + <int value="125" label="No-prediction Positive (Bucket 12)"/> + <int value="130" label="True Negative (Bucket 13)"/> + <int value="131" label="False Negative (Bucket 13)"/> + <int value="132" label="False Positive (Bucket 13)"/> + <int value="133" label="True Positive (Bucket 13)"/> + <int value="134" label="No-prediction Negative (Bucket 13)"/> + <int value="135" label="No-prediction Positive (Bucket 13)"/> + <int value="140" label="True Negative (Bucket 14)"/> + <int value="141" label="False Negative (Bucket 14)"/> + <int value="142" label="False Positive (Bucket 14)"/> + <int value="143" label="True Positive (Bucket 14)"/> + <int value="144" label="No-prediction Negative (Bucket 14)"/> + <int value="145" label="No-prediction Positive (Bucket 14)"/> + <int value="150" label="True Negative (Bucket 15)"/> + <int value="151" label="False Negative (Bucket 15)"/> + <int value="152" label="False Positive (Bucket 15)"/> + <int value="153" label="True Positive (Bucket 15)"/> + <int value="154" label="No-prediction Negative (Bucket 15)"/> + <int value="155" label="No-prediction Positive (Bucket 15)"/> +</enum> + <enum name="MemCacheWriteResult"> <int value="0" label="Success"/> <int value="1" label="Invalid Argument"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index e7ed23b..c898909 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -52284,9 +52284,86 @@ </summary> </histogram> +<histogram base="true" name="Media.Learning.BinaryThreshold.Aggregate" + enum="ConfusionMatrix" expires_after="2019-06-30"> +<!-- Name completed by histogram_suffixes + name="Media.Learning.BinaryThreshold" --> + + <owner>liberato@chromium.org</owner> + <owner>chcunningham@chromium.org</owner> + <summary> + Confusion matrix for UMA-reported regresssion tasks for media local learning + experiments. Each bucket is interpreted as follows: + + TrueNegative - prediction was negative, observation was negative. + FalseNegative - prediction was negative, observation was positive. + FalsePositive - prediction was positive, observation was negative. + TruePositive - prediction was positive, observation was positive. + + For those observations for which we could not make a prediction due to data + sparsity, the "no-prediction" buckets indicate whether the + observation was positive or negative. + </summary> +</histogram> + +<histogram base="true" name="Media.Learning.BinaryThreshold.ByFeature" + enum="MegaConfusionMatrix" expires_after="2019-06-30"> +<!-- Name completed by histogram_suffixes + name="Media.Learning.BinaryThreshold" --> + + <owner>liberato@chromium.org</owner> + <owner>chcunningham@chromium.org</owner> + <summary> + Confusion matrices, split out by the feature index used to train the model. + Each confusion matrix has 6 entries: + + TrueNegative - prediction was negative, observation was negative. + FalseNegative - prediction was negative, observation was positive. + FalsePositive - prediction was positive, observation was negative. + TruePositive - prediction was positive, observation was positive. + No-prediction Negative - no prediction made, observation was negative. + No-prediction Positive - no prediction made, observation was positive. + + The confusion matrix entry will also be labelled with a bucket number, which + for this histogram represents the index of the feature that was used. The + feature index matches |LearningTask::feature_descriptions| for the + appropriate task. + </summary> +</histogram> + +<histogram base="true" name="Media.Learning.BinaryThreshold.ByTrainingWeight" + enum="MegaConfusionMatrix" expires_after="2019-06-30"> +<!-- Name completed by histogram_suffixes + name="Media.Learning.BinaryThreshold" --> + + <owner>liberato@chromium.org</owner> + <owner>chcunningham@chromium.org</owner> + <summary> + Confusion matrices, split out by the total amount of training data used to + train the model. Each confusion matrix has 6 entries: + + TrueNegative - prediction was negative, observation was negative. + FalseNegative - prediction was negative, observation was positive. + FalsePositive - prediction was positive, observation was negative. + TruePositive - prediction was positive, observation was positive. + No-prediction Negative - no prediction made, observation was negative. + No-prediction Positive - no prediction made, observation was positive. + + The bucket number mentioned in the enum label indicates how much weight the + training set had. To convert from bucket number to an actual weight range, + one must know the particular settings in the corresponding LearningTask. + + Please see |LearningTask::max_reporting_weight| and + |LearningTask::num_reporting_weight_buckets| for the the appropriate task. + </summary> +</histogram> + <histogram base="true" name="Media.Learning.MediaCapabilities.DroppedFrameRatioTask" - units="ConfusionMatrix" expires_after="2019-06-30"> + enum="ConfusionMatrix" expires_after="2019-06-30"> + <obsolete> + Deprecated in favor of Media.Learning.BinaryThreshold.Aggregate.* + </obsolete> <!-- Name completed by histogram_suffixes name="MediaLearningDroppedFrameRatioTask" --> <owner>liberato@chromium.org</owner> @@ -146279,6 +146356,19 @@ <affected-histogram name="Manifest.HasProperty"/> </histogram_suffixes> +<histogram_suffixes name="Media.Learning.BinaryThreshold" separator="."> + <suffix name="BaseTable" label="Basic features, lookup table model"/> + <suffix name="BaseTree" label="Basic feaetures, ExtraTrees model"/> + <suffix name="BinarySmoothnessTree" + label="Basic+extra features, pre-thresholded ExtraTrees model"/> + <suffix name="EnhancedTree" label="Basic+extra features, ExtraTrees model"/> + <suffix name="EnhancedUnweightedTree" + label="Basic+extra features, unweighted ExtraTrees model"/> + <affected-histogram name="Media.Learning.BinaryThreshold.Aggregate"/> + <affected-histogram name="Media.Learning.BinaryThreshold.ByFeature"/> + <affected-histogram name="Media.Learning.BinaryThreshold.ByTrainingWeight"/> +</histogram_suffixes> + <histogram_suffixes name="MediaAudioInputControllerTime" separator="."> <suffix name="CloseTime" label="Measures the time taken for DoClose()."/> <suffix name="CreateTime" label="Measures the time taken for DoCreate()."/>
diff --git a/tools/traffic_annotation/bin/README.md b/tools/traffic_annotation/bin/README.md index c0ed42b..95563af0 100644 --- a/tools/traffic_annotation/bin/README.md +++ b/tools/traffic_annotation/bin/README.md
@@ -75,4 +75,4 @@ README should be committed along with the updated .sha1 checksums. CLANG_REVISION = '357692' -LASTCHANGE=4e7b710eaec0d246a3a16cc3d5594c169a34f0be-refs/heads/master@{#648669} \ No newline at end of file +LASTCHANGE=4e7b710eaec0d246a3a16cc3d5594c169a34f0be-refs/heads/master@{#648669}
diff --git a/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 b/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 index 1f4868f..3af4147f8 100644 --- a/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 +++ b/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1
@@ -1 +1 @@ -b0ad62b575576e1b786be9e488052a395d7f20a0 \ No newline at end of file +d9314aa2e3fab7ef7eb3fb38a392b40877cf5826 \ No newline at end of file
diff --git a/tools/traffic_annotation/bin/linux64/traffic_annotation_extractor.sha1 b/tools/traffic_annotation/bin/linux64/traffic_annotation_extractor.sha1 index 9c65b15..e0f5492 100644 --- a/tools/traffic_annotation/bin/linux64/traffic_annotation_extractor.sha1 +++ b/tools/traffic_annotation/bin/linux64/traffic_annotation_extractor.sha1
@@ -1 +1 @@ -2c8407d57939e5a05587a8c51612d43c2a91db0d \ No newline at end of file +cb73626ecd59e93627a0b151923012e22e459a47 \ No newline at end of file
diff --git a/ui/file_manager/image_loader/piex/tests.html b/ui/file_manager/image_loader/piex/tests.html index e9ed990..6394b97c 100644 --- a/ui/file_manager/image_loader/piex/tests.html +++ b/ui/file_manager/image_loader/piex/tests.html
@@ -154,7 +154,7 @@ return (string || '').replace(/\0/g, ''); } - self.Module = { + window.Module = { onRuntimeInitialized: piexModuleReady, };
diff --git a/ui/views/controls/native/native_view_host.cc b/ui/views/controls/native/native_view_host.cc index 2e46742..3ec401e 100644 --- a/ui/views/controls/native/native_view_host.cc +++ b/ui/views/controls/native/native_view_host.cc
@@ -97,7 +97,24 @@ if (!native_view_ || !native_wrapper_.get()) return; - if (IsDrawn() && !bounds().IsEmpty()) { + gfx::Rect vis_bounds = GetVisibleBounds(); + bool visible = !vis_bounds.IsEmpty(); + + if (visible && !fast_resize_) { + if (vis_bounds.size() != size()) { + // Only a portion of the Widget is really visible. + int x = vis_bounds.x(); + int y = vis_bounds.y(); + native_wrapper_->InstallClip(x, y, vis_bounds.width(), + vis_bounds.height()); + } else if (native_wrapper_->HasInstalledClip()) { + // The whole widget is visible but we installed a clip on the widget, + // uninstall it. + native_wrapper_->UninstallClip(); + } + } + + if (visible) { // Since widgets know nothing about the View hierarchy (they are direct // children of the Widget that hosts our View hierarchy) they need to be // positioned in the coordinate system of the Widget, not the current @@ -113,6 +130,7 @@ } else { native_wrapper_->HideWidget(); } + fast_resize_at_last_layout_ = visible && fast_resize_; } void NativeViewHost::OnPaint(gfx::Canvas* canvas) {
diff --git a/ui/views/controls/native/native_view_host.h b/ui/views/controls/native/native_view_host.h index c643413..1a4bcee2 100644 --- a/ui/views/controls/native/native_view_host.h +++ b/ui/views/controls/native/native_view_host.h
@@ -86,6 +86,11 @@ void set_fast_resize(bool fast_resize) { fast_resize_ = fast_resize; } bool fast_resize() const { return fast_resize_; } + // Value of fast_resize() the last time Layout() was invoked. + bool fast_resize_at_last_layout() const { + return fast_resize_at_last_layout_; + } + gfx::NativeView native_view() const { return native_view_; } void NativeViewDestroyed(); @@ -133,6 +138,9 @@ // in the setter/accessor above. bool fast_resize_ = false; + // Value of |fast_resize_| during the last call to Layout. + bool fast_resize_at_last_layout_ = false; + DISALLOW_COPY_AND_ASSIGN(NativeViewHost); };
diff --git a/ui/views/controls/native/native_view_host_aura.cc b/ui/views/controls/native/native_view_host_aura.cc index 978a0fb..c15db47 100644 --- a/ui/views/controls/native/native_view_host_aura.cc +++ b/ui/views/controls/native/native_view_host_aura.cc
@@ -183,12 +183,21 @@ UpdateInsets(); } +void NativeViewHostAura::InstallClip(int x, int y, int w, int h) { + clip_rect_ = std::make_unique<gfx::Rect>( + host_->ConvertRectToWidget(gfx::Rect(x, y, w, h))); +} + int NativeViewHostAura::GetHitTestTopInset() const { return top_inset_; } bool NativeViewHostAura::HasInstalledClip() { - return clip_rect_.has_value(); + return !!clip_rect_; +} + +void NativeViewHostAura::UninstallClip() { + clip_rect_.reset(); } void NativeViewHostAura::ShowWidget(int x, @@ -198,11 +207,12 @@ int native_w, int native_h) { if (host_->fast_resize()) { - clip_rect_ = gfx::Rect(x, y, w, h); + gfx::Point origin(x, y); + views::View::ConvertPointFromWidget(host_, &origin); + InstallClip(origin.x(), origin.y(), w, h); native_w = host_->native_view()->bounds().width(); native_h = host_->native_view()->bounds().height(); } else { - clip_rect_.reset(); gfx::Transform transform = original_transform_; if (w > 0 && h > 0 && native_w > 0 && native_h > 0) { transform.Scale(static_cast<SkMScalar>(w) / native_w, @@ -215,7 +225,7 @@ } } - clipping_window_->SetBounds(clip_rect_.value_or(gfx::Rect(x, y, w, h))); + clipping_window_->SetBounds(clip_rect_ ? *clip_rect_ : gfx::Rect(x, y, w, h)); gfx::Point clip_offset = clipping_window_->bounds().origin(); host_->native_view()->SetBounds( gfx::Rect(x - clip_offset.x(), y - clip_offset.y(), native_w, native_h)); @@ -224,7 +234,6 @@ } void NativeViewHostAura::HideWidget() { - clip_rect_.reset(); host_->native_view()->Hide(); clipping_window_->Hide(); }
diff --git a/ui/views/controls/native/native_view_host_aura.h b/ui/views/controls/native/native_view_host_aura.h index 2e3d8872..26381af 100644 --- a/ui/views/controls/native/native_view_host_aura.h +++ b/ui/views/controls/native/native_view_host_aura.h
@@ -7,7 +7,6 @@ #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/optional.h" #include "ui/aura/window_observer.h" #include "ui/compositor/layer_owner.h" #include "ui/gfx/transform.h" @@ -37,7 +36,9 @@ bool SetCustomMask(std::unique_ptr<ui::LayerOwner> mask) override; void SetHitTestTopInset(int top_inset) override; int GetHitTestTopInset() const override; + void InstallClip(int x, int y, int w, int h) override; bool HasInstalledClip() override; + void UninstallClip() override; void ShowWidget(int x, int y, int w, int h, int native_w, int native_h) override; void HideWidget() override; @@ -88,7 +89,7 @@ // clipping to occur. This is positioned in the coordinate space of // host_->GetWidget(). std::unique_ptr<aura::Window> clipping_window_; - base::Optional<gfx::Rect> clip_rect_; + std::unique_ptr<gfx::Rect> clip_rect_; // This mask exists for the sake of SetCornerRadius(). std::unique_ptr<ui::LayerOwner> mask_;
diff --git a/ui/views/controls/native/native_view_host_aura_unittest.cc b/ui/views/controls/native/native_view_host_aura_unittest.cc index 121b709..2587ff5 100644 --- a/ui/views/controls/native/native_view_host_aura_unittest.cc +++ b/ui/views/controls/native/native_view_host_aura_unittest.cc
@@ -278,6 +278,48 @@ DestroyHost(); } +// Test installing and uninstalling a clip. +TEST_F(NativeViewHostAuraTest, InstallClip) { + CreateHost(); + toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); + + // Without a clip, the clipping window should always be positioned at the + // requested coordinates with the native view positioned at the origin of the + // clipping window. + native_host()->ShowWidget(10, 20, 100, 100, 100, 100); + EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), + host()->native_view()->bounds().ToString()); + EXPECT_EQ(gfx::Rect(10, 20, 100, 100).ToString(), + clipping_window()->bounds().ToString()); + + // Clip to the bottom right quarter of the native view. + native_host()->InstallClip(60, 70, 50, 50); + native_host()->ShowWidget(10, 20, 100, 100, 100, 100); + EXPECT_EQ(gfx::Rect(-50, -50, 100, 100).ToString(), + host()->native_view()->bounds().ToString()); + EXPECT_EQ(gfx::Rect(60, 70, 50, 50).ToString(), + clipping_window()->bounds().ToString()); + + // Clip to the center of the native view. + native_host()->InstallClip(35, 45, 50, 50); + native_host()->ShowWidget(10, 20, 100, 100, 100, 100); + EXPECT_EQ(gfx::Rect(-25, -25, 100, 100).ToString(), + host()->native_view()->bounds().ToString()); + EXPECT_EQ(gfx::Rect(35, 45, 50, 50).ToString(), + clipping_window()->bounds().ToString()); + + // Uninstalling the clip should make the clipping window match the native view + // again. + native_host()->UninstallClip(); + native_host()->ShowWidget(10, 20, 100, 100, 100, 100); + EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), + host()->native_view()->bounds().ToString()); + EXPECT_EQ(gfx::Rect(10, 20, 100, 100).ToString(), + clipping_window()->bounds().ToString()); + + DestroyHost(); +} + // Ensure native view is parented to the root window after detaching. This is // a regression test for http://crbug.com/389261. TEST_F(NativeViewHostAuraTest, ParentAfterDetach) {
diff --git a/ui/views/controls/native/native_view_host_mac.h b/ui/views/controls/native/native_view_host_mac.h index e9b01b7..d163c51e 100644 --- a/ui/views/controls/native/native_view_host_mac.h +++ b/ui/views/controls/native/native_view_host_mac.h
@@ -42,7 +42,9 @@ bool SetCustomMask(std::unique_ptr<ui::LayerOwner> mask) override; void SetHitTestTopInset(int top_inset) override; int GetHitTestTopInset() const override; + void InstallClip(int x, int y, int w, int h) override; bool HasInstalledClip() override; + void UninstallClip() override; void ShowWidget(int x, int y, int w, int h, int native_w, int native_h) override; void HideWidget() override;
diff --git a/ui/views/controls/native/native_view_host_mac.mm b/ui/views/controls/native/native_view_host_mac.mm index 85fab5c..d68efa0 100644 --- a/ui/views/controls/native/native_view_host_mac.mm +++ b/ui/views/controls/native/native_view_host_mac.mm
@@ -169,10 +169,18 @@ return 0; } +void NativeViewHostMac::InstallClip(int x, int y, int w, int h) { + NOTIMPLEMENTED(); +} + bool NativeViewHostMac::HasInstalledClip() { return false; } +void NativeViewHostMac::UninstallClip() { + NOTIMPLEMENTED(); +} + void NativeViewHostMac::ShowWidget(int x, int y, int w,
diff --git a/ui/views/controls/native/native_view_host_wrapper.h b/ui/views/controls/native/native_view_host_wrapper.h index 378c311..8381997 100644 --- a/ui/views/controls/native/native_view_host_wrapper.h +++ b/ui/views/controls/native/native_view_host_wrapper.h
@@ -51,10 +51,20 @@ virtual void SetHitTestTopInset(int top_inset) = 0; virtual int GetHitTestTopInset() const = 0; + // Installs a clip on the gfx::NativeView. These values are in the coordinate + // space of the Widget, so if this method is called from ShowWidget + // then the values need to be translated. + virtual void InstallClip(int x, int y, int w, int h) = 0; + // Whether or not a clip has been installed on the wrapped gfx::NativeView. - // A clip is only installed during fast-resize. virtual bool HasInstalledClip() = 0; + // Removes the clip installed on the gfx::NativeView by way of InstallClip. A + // following call to ShowWidget should occur after calling this method to + // position the gfx::NativeView correctly, since the clipping process may have + // adjusted its position. + virtual void UninstallClip() = 0; + // Shows the gfx::NativeView within the specified region (relative to the // parent native view) and with the given native size. The content will // appear scaled if the |native_w| or |native_h| are different from |w| or