diff --git a/DEPS b/DEPS index f368057..4b3f592 100644 --- a/DEPS +++ b/DEPS
@@ -283,11 +283,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'ee023e6af4ea32e22c9f19cfa0d1041dc9fbb5f1', + 'angle_revision': '9ea3967d3e8b97b7d70d193560ef388d953421ce', # 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': 'e885694aca94c508e94ac7f67289f85298536966', + 'swiftshader_revision': 'd070309f7d154d6764cbd514b1a5c8bfcef61d06', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -302,7 +302,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Fuchsia sdk # and whatever else without interference from each other. - 'fuchsia_version': 'version:8.20220527.1.1', + 'fuchsia_version': 'version:8.20220527.2.1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling google-toolbox-for-mac # and whatever else without interference from each other. @@ -354,7 +354,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '86bffd656c2f064aa110a85235804e2c521f3b35', + 'devtools_frontend_revision': '50a0b94bcb16130284a3a954757646cc8b7f950f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -390,7 +390,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': '15691360729d9f97abfa4b4f1422540ce5567d55', + 'dawn_revision': '2cefd07454df24d6dc71f9e986d86b64228913ee', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -920,7 +920,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': '-hRN0Qsp6Ws7bGPZknnK_7B0x4p6WN_9TxKHkmarWUIC', + 'version': 'fG_1zE_32JdLLyVDr2e60nsfHYDu7bylpMV_MZtZxvMC', }, ], 'condition': 'checkout_android', @@ -1113,7 +1113,7 @@ # Tools used when building Chrome for Chrome OS. This affects both the Simple # Chrome workflow, as well as the chromeos-chrome ebuild. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'ea9cc82778106bd6f698f17ffdc29d5797e9319d', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '3f862120bceef5b6d7b2c0e4750282f8539b24a1', 'condition': 'checkout_chromeos', }, @@ -1136,7 +1136,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'b6083facb676c7580b27e2bb83a0e96c0b65dec9', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '10a8286824639fe34a8c14e8d4075cdf56c5a69d', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1669,7 +1669,7 @@ 'condition': 'checkout_android', }, - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@74d505bc504e88cb5f009998ee47b5b5696342b7', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@2f94e7e4c5bbf83e526fbab8af36bd43c4dba896', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + 'ebe84bec02c041d28f902da0214bf442743fc907', @@ -1708,7 +1708,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '70091fdb8d3d037b8f2919eb63e5a2bf6444deb7', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '2d133637d17d3128a71fa2f1a2c0f0cf871c207d', + Var('webrtc_git') + '/src.git' + '@' + 'a93260b2f418f00cc93b10ae8470a7ff08b31f3d', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1781,7 +1781,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@183012d61fa28504af86c09b89eb9117202f1c46', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@ab8cc2ad9ed1c2e6573970ea6e00893c6885622d', 'condition': 'checkout_src_internal', }, @@ -1822,7 +1822,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/media_app/app', - 'version': '4L_DbWJIyg10ZsAIKDeLYL_oscHR4vP9NGv05HRZ0xUC', + 'version': 'X95M0P0NjefqU8YMT7tK-d1uP-BXtEvqDKNG-S1mQgAC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/ash/app_list/views/assistant/assistant_page_view_unittest.cc b/ash/app_list/views/assistant/assistant_page_view_unittest.cc index 9448a98e..aa2acca7 100644 --- a/ash/app_list/views/assistant/assistant_page_view_unittest.cc +++ b/ash/app_list/views/assistant/assistant_page_view_unittest.cc
@@ -814,8 +814,9 @@ EXPECT_HAS_FOCUS(input_text_field()); } +// TODO(b/234164113): Test is flaky. TEST_P(AssistantPageClamshellTest, - ShouldFocusMicWhenSubmittingSuggestionChipInVoiceMode) { + DISABLED_ShouldFocusMicWhenSubmittingSuggestionChipInVoiceMode) { ShowAssistantUi(); ash::SuggestionChipView* suggestion_chip = CreateAndGetSuggestionChip("<suggestion chip query>");
diff --git a/ash/assistant/assistant_interaction_controller_impl.cc b/ash/assistant/assistant_interaction_controller_impl.cc index ca08814f..8761285 100644 --- a/ash/assistant/assistant_interaction_controller_impl.cc +++ b/ash/assistant/assistant_interaction_controller_impl.cc
@@ -139,8 +139,6 @@ AssistantQuerySource query_source) { DCHECK(assistant_); - StopActiveInteraction(false); - model_.SetPendingQuery( std::make_unique<AssistantTextQuery>(text, query_source)); @@ -184,7 +182,6 @@ const absl::optional<std::string>& client_id = GetDeepLinkParam(params, DeepLinkParam::kClientId); if (client_id && !client_id.value().empty()) { - StopActiveInteraction(false); model_.SetPendingQuery(std::make_unique<AssistantTextQuery>( l10n_util::GetStringUTF8(IDS_ASSISTANT_EDIT_REMINDER_QUERY), /*query_source=*/AssistantQuerySource::kDeepLink)); @@ -814,8 +811,6 @@ } void AssistantInteractionControllerImpl::StartVoiceInteraction() { - StopActiveInteraction(false); - model_.SetPendingQuery(std::make_unique<AssistantVoiceQuery>()); assistant_->StartVoiceInteraction();
diff --git a/ash/assistant/test/test_assistant_service.cc b/ash/assistant/test/test_assistant_service.cc index cebd255..50f6735e 100644 --- a/ash/assistant/test/test_assistant_service.cc +++ b/ash/assistant/test/test_assistant_service.cc
@@ -8,6 +8,8 @@ #include <utility> #include <vector> +#include "base/threading/sequenced_task_runner_handle.h" +#include "base/time/time.h" #include "base/unguessable_token.h" #include "chromeos/services/assistant/public/cpp/assistant_service.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -225,14 +227,10 @@ chromeos::assistant::AssistantQuerySource source, bool allow_tts) { StartInteraction(AssistantInteractionType::kText, source, query); - if (interaction_response_) - SendInteractionResponse(); } void TestAssistantService::StartVoiceInteraction() { StartInteraction(AssistantInteractionType::kVoice); - if (interaction_response_) - SendInteractionResponse(); } void TestAssistantService::StopActiveInteraction(bool cancel_conversation) { @@ -292,12 +290,30 @@ chromeos::assistant::AssistantInteractionType type, chromeos::assistant::AssistantQuerySource source, const std::string& query) { + if (running_active_interaction_) { + StopActiveInteraction(/*cancel_conversation=*/false); + } + + // Pretend to respond asynchronously. + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&TestAssistantService::InteractionStarted, + weak_factory_.GetWeakPtr(), type, source, query)); +} + +void TestAssistantService::InteractionStarted( + chromeos::assistant::AssistantInteractionType type, + chromeos::assistant::AssistantQuerySource source, + const std::string& query) { DCHECK(!running_active_interaction_); AssistantInteractionMetadata metadata{type, source, query}; for (auto& subscriber : interaction_subscribers_) { subscriber.OnInteractionStarted(metadata); } running_active_interaction_ = true; + + if (interaction_response_) + SendInteractionResponse(); } void TestAssistantService::SendInteractionResponse() {
diff --git a/ash/assistant/test/test_assistant_service.h b/ash/assistant/test/test_assistant_service.h index be60488..41a826b 100644 --- a/ash/assistant/test/test_assistant_service.h +++ b/ash/assistant/test/test_assistant_service.h
@@ -9,6 +9,7 @@ #include <string> #include <vector> +#include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/timer/timer.h" #include "chromeos/services/assistant/public/cpp/assistant_service.h" @@ -125,6 +126,9 @@ chromeos::assistant::AssistantQuerySource source = chromeos::assistant::AssistantQuerySource::kUnspecified, const std::string& query = std::string()); + void InteractionStarted(chromeos::assistant::AssistantInteractionType type, + chromeos::assistant::AssistantQuerySource source, + const std::string& query); void SendInteractionResponse(); std::unique_ptr<LibassistantContractChecker> libassistant_contract_checker_; @@ -136,6 +140,8 @@ base::ObserverList<chromeos::assistant::AssistantInteractionSubscriber> interaction_subscribers_; bool running_active_interaction_ = false; + + base::WeakPtrFactory<TestAssistantService> weak_factory_{this}; }; } // namespace ash
diff --git a/ash/components/proximity_auth/unlock_manager_impl.cc b/ash/components/proximity_auth/unlock_manager_impl.cc index 6c799ea..b21b77ef 100644 --- a/ash/components/proximity_auth/unlock_manager_impl.cc +++ b/ash/components/proximity_auth/unlock_manager_impl.cc
@@ -189,6 +189,37 @@ kMaxExtendedDuration /* max */, kNumDurationMetricBuckets /* buckets */); } +bool HasCommunicatedWithPhone(SmartLockState state) { + switch (state) { + case SmartLockState::kDisabled: + [[fallthrough]]; + case SmartLockState::kInactive: + [[fallthrough]]; + case SmartLockState::kBluetoothDisabled: + [[fallthrough]]; + case SmartLockState::kPhoneNotFound: + [[fallthrough]]; + case SmartLockState::kConnectingToPhone: + [[fallthrough]]; + case SmartLockState::kPasswordReentryRequired: + return false; + case SmartLockState::kPhoneNotLockable: + [[fallthrough]]; + case SmartLockState::kPhoneNotAuthenticated: + [[fallthrough]]; + case SmartLockState::kPhoneFoundLockedAndDistant: + [[fallthrough]]; + case SmartLockState::kPhoneFoundLockedAndProximate: + [[fallthrough]]; + case SmartLockState::kPhoneFoundUnlockedAndDistant: + [[fallthrough]]; + case SmartLockState::kPhoneAuthenticated: + [[fallthrough]]; + case SmartLockState::kPrimaryUserAbsent: + return true; + } +} + } // namespace UnlockManagerImpl::UnlockManagerImpl( @@ -945,10 +976,6 @@ base::UmaHistogramEnumeration("SmartLock.FirstStatusToUser", first_status.value()); - const std::string histogram_status_suffix = GetHistogramStatusSuffix( - /*unlockable=*/(first_status == - FirstSmartLockStatus::kPhoneAuthenticated)); - base::Time now = base::DefaultClock::GetInstance()->Now(); base::TimeDelta show_lock_screen_to_show_first_status_to_user_duration = now - show_lock_screen_time_; @@ -958,11 +985,23 @@ "SmartLock.Performance.ShowLockScreenToShowFirstStatusToUserDuration." "Unlock", show_lock_screen_to_show_first_status_to_user_duration); - RecordExtendedDurationTimerMetric( - "SmartLock.Performance.ShowLockScreenToShowFirstStatusToUserDuration." - "Unlock." + - histogram_status_suffix, - show_lock_screen_to_show_first_status_to_user_duration); + + if (new_state == SmartLockState::kPhoneAuthenticated) { + RecordExtendedDurationTimerMetric( + "SmartLock.Performance.ShowLockScreenToShowFirstStatusToUserDuration." + "Unlock.Unlockable", + show_lock_screen_to_show_first_status_to_user_duration); + } else if (HasCommunicatedWithPhone(new_state)) { + // Only log to Unlock.Other if we aren't in an unlockable state since + // that's covered by the other metric, and only if we are in a state that + // indicates we were able to communicate with the phone over Bluetooth + // since in all other cases the time to show the first status is highly + // deterministic. + RecordExtendedDurationTimerMetric( + "SmartLock.Performance.ShowLockScreenToShowFirstStatusToUserDuration." + "Unlock.Other", + show_lock_screen_to_show_first_status_to_user_duration); + } } }
diff --git a/ash/system/time/calendar_event_list_item_view.cc b/ash/system/time/calendar_event_list_item_view.cc index f368de5..4cfc6d4 100644 --- a/ash/system/time/calendar_event_list_item_view.cc +++ b/ash/system/time/calendar_event_list_item_view.cc
@@ -34,9 +34,6 @@ namespace ash { namespace { -// The meeting title is too long, it is truncated in this length. -constexpr int kTruncatedTitleLength = 20; - // Paddings in this view. constexpr int kEntryHorizontalPadding = 20; @@ -56,10 +53,12 @@ {"9", "5484ed"}, {"10", "51b749"}, {"11", "dc2127"}}; // Sets up the event label. -void SetUpLabel(views::Label* label) { - label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_CENTER); +void SetUpLabel(views::Label* label, + gfx::ElideBehavior elide_behavior, + gfx::HorizontalAlignment horizontal_alignment) { + label->SetHorizontalAlignment(horizontal_alignment); label->SetAutoColorReadabilityEnabled(false); - label->SetElideBehavior(gfx::NO_ELIDE); + label->SetElideBehavior(elide_behavior); label->SetSubpixelRenderingEnabled(false); label->SetTextContext(CONTEXT_CALENDAR_DATE); } @@ -109,9 +108,28 @@ time_range_(new views::Label()), event_url_(event.html_link()) { SetLayoutManager(std::make_unique<views::FillLayout>()); + DCHECK(calendar_view_controller_->selected_date().has_value()); - const base::Time start_time = event.start_time().date_time(); - const base::Time end_time = event.end_time().date_time(); + const base::Time event_start_time = event.start_time().date_time(); + const base::Time event_end_time = event.end_time().date_time(); + + const base::TimeDelta time_difference = calendar_utils::GetTimeDifference( + calendar_view_controller_->selected_date().value()); + + const base::Time selected_midnight = + calendar_view_controller_->selected_date_midnight(); + const base::Time selected_midnight_utc = + calendar_view_controller_->selected_date_midnight_utc(); + const base::Time selected_last_minute = + calendar_utils::GetNextDayMidnight(selected_midnight) - base::Minutes(1); + const base::Time selected_last_minute_utc = + selected_last_minute - time_difference; + + base::Time start_time = + calendar_utils::GetMaxTime(event_start_time, selected_midnight_utc); + base::Time end_time = + calendar_utils::GetMinTime(event_end_time, selected_last_minute_utc); + bool use_12_hour_clock = Shell::Get()->system_tray_model()->clock()->hour_clock_type() == base::k12HourClock; @@ -131,10 +149,10 @@ summary_->SetText(event.summary().empty() ? l10n_util::GetStringUTF16(IDS_ASH_CALENDAR_NO_TITLE) : base::UTF8ToUTF16(event.summary())); - SetUpLabel(summary_); - summary_->SetTruncateLength(kTruncatedTitleLength); - summary_->SetBorder(views::CreateEmptyBorder( - gfx::Insets::TLBR(0, kEntryHorizontalPadding, 0, 0))); + SetUpLabel(summary_, gfx::ElideBehavior::ELIDE_TAIL, + gfx::HorizontalAlignment::ALIGN_LEFT); + summary_->SetBorder( + views::CreateEmptyBorder(gfx::Insets::VH(0, kEntryHorizontalPadding))); // When using AM/PM time format and the start time and end time are in the // same meridiem, remove the first one and the space before it, which are the @@ -148,15 +166,20 @@ auto time_range = start_time_string + u" - " + end_time_string; time_range_->SetText(time_range); - SetUpLabel(time_range_); + SetUpLabel(time_range_, gfx::NO_ELIDE, + gfx::HorizontalAlignment::ALIGN_CENTER); - // Creates a `TriView` which carries the `color_dot` and `summary_` at the - // entry start and the `time_range_` at the entry end. + // Creates a `TriView` which carries the `color_dot`, `summary_` and + // `time_range_`. TriView* tri_view = TrayPopupUtils::CreateDefaultRowView(); + tri_view->SetMinSize( + TriView::Container::START, + gfx::Size(kColorDotViewSize, + tri_view->GetMinSize(TriView::Container::START).height())); tri_view->AddView(TriView::Container::START, AddChildView(std::make_unique<CalendarEventListItemDot>( event.color_id()))); - tri_view->AddView(TriView::Container::START, summary_); + tri_view->AddView(TriView::Container::CENTER, summary_); tri_view->AddView(TriView::Container::END, time_range_); auto tooltip_text = l10n_util::GetStringFUTF16(
diff --git a/ash/system/time/calendar_event_list_view_unittest.cc b/ash/system/time/calendar_event_list_view_unittest.cc index 8753d9c..778a467 100644 --- a/ash/system/time/calendar_event_list_view_unittest.cc +++ b/ash/system/time/calendar_event_list_view_unittest.cc
@@ -193,16 +193,26 @@ TEST_F(CalendarViewEventListViewTest, CheckTimeFormat) { ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID(u"GMT"); + // Date of first day which holds a normal event and a multi-day event. base::Time date; ASSERT_TRUE(base::Time::FromString("22 Nov 2021 10:00 GMT", &date)); + // Date of the second day which holds the second day of the multi-day event. + base::Time date_2; + ASSERT_TRUE(base::Time::FromString("23 Nov 2021 10:00 GMT", &date_2)); + // Set the time in AM/PM format. Shell::Get()->system_tray_model()->SetUse24HourClock(false); CreateEventListView(date); + SetSelectedDate(date); EXPECT_EQ(u"8:30 - 9:30 PM", GetTimeRange(0)->GetText()); - EXPECT_EQ(u"11:30 PM - 12:30 AM", GetTimeRange(1)->GetText()); + EXPECT_EQ(u"11:30 - 11:59 PM", GetTimeRange(1)->GetText()); + + // Select the second day of the multi-day event. + SetSelectedDate(date_2); + EXPECT_EQ(u"12:00 - 12:30 AM", GetTimeRange(0)->GetText()); // Set the time in 24 hour format. Shell::Get()->system_tray_model()->SetUse24HourClock(true); @@ -210,8 +220,12 @@ // Regenerate the event list to refresh events time range. CreateEventListView(date); + SetSelectedDate(date); EXPECT_EQ(u"20:30 - 21:30", GetTimeRange(0)->GetText()); - EXPECT_EQ(u"23:30 - 00:30", GetTimeRange(1)->GetText()); + EXPECT_EQ(u"23:30 - 23:59", GetTimeRange(1)->GetText()); + + SetSelectedDate(date_2); + EXPECT_EQ(u"00:00 - 00:30", GetTimeRange(0)->GetText()); } } // namespace ash
diff --git a/ash/system/time/calendar_model.cc b/ash/system/time/calendar_model.cc index fa66fa3..6d859b7c 100644 --- a/ash/system/time/calendar_model.cc +++ b/ash/system/time/calendar_model.cc
@@ -305,7 +305,18 @@ PromoteMonth(start_of_month); } else { // Store the incoming events. - InsertEvents(events); + for (const auto& event : events->items()) { + if (IsMultiDayEvent(event.get())) + InsertMultiDayEvent(event.get(), start_of_month); + else { + base::Time start_time_midnight = + GetStartTimeMidnightAdjusted(event.get()); + InsertEventInMonth( + event.get(), + calendar_utils::GetStartOfMonthUTC(start_time_midnight), + start_time_midnight); + } + } } // Notify observers. @@ -352,12 +363,62 @@ event->self_response_status()); } -void CalendarModel::InsertEvent( - const google_apis::calendar::CalendarEvent* event) { +bool CalendarModel::IsMultiDayEvent( + google_apis::calendar::CalendarEvent* event) const { + DCHECK(event); + return (GetStartTimeMidnightAdjusted(event) < + GetEndTimeMidnightAdjusted(event)); +} + +void CalendarModel::InsertMultiDayEvent( + const google_apis::calendar::CalendarEvent* event, + const base::Time start_of_month) { DCHECK(event); - base::Time start_of_month = - calendar_utils::GetStartOfMonthUTC(GetStartTimeMidnightAdjusted(event)); + base::Time start_time_midnight = GetStartTimeMidnightAdjusted(event); + base::Time end_time_midnight = GetEndTimeMidnightAdjusted(event); + base::Time end_time = GetEndTimeAdjusted(event); + + base::Time current_day_midnight = + calendar_utils::GetMaxTime(start_of_month, start_time_midnight) + .UTCMidnight(); + base::Time start_of_next_month = + calendar_utils::GetStartOfNextMonthUTC(current_day_midnight); + base::Time last_day_midnight = + calendar_utils::GetMinTime(start_of_next_month, end_time_midnight) + .UTCMidnight(); + + // If the event ends at midnight we don't add it to that last day. + if (end_time == end_time_midnight) + last_day_midnight = + (last_day_midnight - calendar_utils::kDurationForGettingPreviousDay) + .UTCMidnight(); + + if (ash::features::IsCalendarModelDebugModeEnabled()) { + VLOG(1) << __FUNCTION__ + << " current_day_midnight: " << current_day_midnight; + VLOG(1) << __FUNCTION__ << " last_day_midnight: " << last_day_midnight; + } + + while (current_day_midnight <= last_day_midnight) { + InsertEventInMonth(event, start_of_month, current_day_midnight); + current_day_midnight = + calendar_utils::GetNextDayMidnight(current_day_midnight); + } +} + +void CalendarModel::InsertEventInMonth( + const google_apis::calendar::CalendarEvent* event, + const base::Time start_of_month, + const base::Time start_time_midnight) { + DCHECK(event); + + // Check the event is in the month we're trying to insert it into. + if (start_of_month != calendar_utils::GetStartOfMonthUTC(start_time_midnight)) + return; + + // Month is now the most-recently-used. + PromoteMonth(start_of_month); if (ash::features::IsCalendarModelDebugModeEnabled()) { VLOG(1) << __FUNCTION__ << " start_of_month " << start_of_month; @@ -368,26 +429,23 @@ if (it == event_months_.end()) { // No events for this month, so add a map for it and insert. SingleMonthEventMap month; - InsertEventInMonth(month, event); + InsertEventInMonthEventList(month, event, start_time_midnight); event_months_.emplace(start_of_month, month); } else { // Insert in a pre-existing month. SingleMonthEventMap& month = it->second; - InsertEventInMonth(month, event); + InsertEventInMonthEventList(month, event, start_time_midnight); } - - // Month is now the most-recently-used. - PromoteMonth(start_of_month); } -void CalendarModel::InsertEventInMonth( +void CalendarModel::InsertEventInMonthEventList( SingleMonthEventMap& month, - const google_apis::calendar::CalendarEvent* event) { + const google_apis::calendar::CalendarEvent* event, + const base::Time start_time_midnight) { + DCHECK(event); if (!ShouldInsertEvent(event)) return; - base::Time start_time_midnight = GetStartTimeMidnightAdjusted(event); - auto it = month.find(start_time_midnight); if (it == month.end()) { // No events stored for this day, so create a new list, add the event to @@ -419,15 +477,13 @@ return GetStartTimeAdjusted(event).UTCMidnight(); } -void CalendarModel::InsertEvents( - const google_apis::calendar::EventList* events) { - if (!events) - return; - - for (const auto& event : events->items()) - InsertEvent(event.get()); +base::Time CalendarModel::GetEndTimeMidnightAdjusted( + const google_apis::calendar::CalendarEvent* event) const { + return GetEndTimeAdjusted(event).UTCMidnight(); } +// TODO(crbug/1330004): Remove function in favor of calling `OnEventsFetched` +// directly from tests. void CalendarModel::InsertEventsForTesting( const google_apis::calendar::EventList* events) { if (!events) @@ -439,10 +495,25 @@ // Insert, and collect the set of months inserted. std::set<base::Time> months_inserted; for (const auto& event : events->items()) { - base::Time month = - calendar_utils::GetStartOfMonthUTC(event->start_time().date_time()); - months_inserted.emplace(month); - InsertEvent(event.get()); + base::Time start_time_midnight = GetStartTimeMidnightAdjusted(event.get()); + base::Time start_of_month = + calendar_utils::GetStartOfMonthUTC(start_time_midnight); + if (IsMultiDayEvent(event.get())) { + const base::Time end_time_midnight = + GetEndTimeMidnightAdjusted(event.get()); + // If we have multi-day events, we insert the event to every month map the + // event exists in. This to reproduce Google Calendar API requests, which + // are fetched by month, so multi-day events get inserted for every month + // they are active. + while (end_time_midnight >= start_of_month) { + InsertMultiDayEvent(event.get(), start_of_month); + start_of_month = calendar_utils::GetStartOfNextMonthUTC(start_of_month); + months_inserted.emplace(start_of_month); + } + } else { + InsertEventInMonth(event.get(), start_of_month, start_time_midnight); + months_inserted.emplace(start_of_month); + } } } @@ -586,11 +657,14 @@ } } - // Clear out the entire event store, freshly insert the redistrubted events. + // Clear out the entire event store, freshly insert the redistributed events. event_months_.clear(); for (const google_apis::calendar::CalendarEvent& event : to_be_redistributed_events) { - InsertEvent(&event); + base::Time start_time_midnight = GetStartTimeMidnightAdjusted(&event); + InsertEventInMonth(&event, + calendar_utils::GetStartOfMonthUTC(start_time_midnight), + start_time_midnight); } }
diff --git a/ash/system/time/calendar_model.h b/ash/system/time/calendar_model.h index 08964325..d7b9dd25f 100644 --- a/ash/system/time/calendar_model.h +++ b/ash/system/time/calendar_model.h
@@ -114,11 +114,6 @@ // time difference. This method is only called when there's a timezone change. void RedistributeEvents(); - // Updates the time difference in minutes. - void set_time_difference_minutes(int minutes) { - time_difference_minutes_ = minutes; - } - protected: // Fetch events for `start_of_month`. virtual void MaybeFetchMonth(base::Time start_of_month); @@ -146,31 +141,43 @@ bool ShouldInsertEvent( const google_apis::calendar::CalendarEvent* event) const; - // Inserts a single `event` in the EventCache. - void InsertEvent(const google_apis::calendar::CalendarEvent* event); + // Checks if the event spans more than one day. + bool IsMultiDayEvent(google_apis::calendar::CalendarEvent* event) const; - // Inserts a single `event` in the EventMap for the month that contains its - // start date. - void InsertEventInMonth(SingleMonthEventMap& month, - const google_apis::calendar::CalendarEvent* event); + // Inserts a single `event` that spans more than one day in the EventCache. + void InsertMultiDayEvent(const google_apis::calendar::CalendarEvent* event, + const base::Time start_of_month); - // Returns the `start_time` of `event` adjusted by - // `time_difference_minutes_`, to ensure that each event is stored by its - // local time, e.g. an event that starts at 2022-05-31 22:00:00.000 PST - // (2022-06-01 05:00:00.000 UTC) is stored in the map for 05-2022. + // Finds or creates a new SingleMonthEventMap to then insert the `event` into + // an event list of that month. + void InsertEventInMonth(const google_apis::calendar::CalendarEvent* event, + const base::Time start_of_month, + const base::Time start_time_midnight); + + // Inserts a single `event` in a SingleDayEventList of a SingleMonthEventMap. + void InsertEventInMonthEventList( + SingleMonthEventMap& month, + const google_apis::calendar::CalendarEvent* event, + const base::Time start_time_midnight); + + // Returns the `start_time` of `event` adjusted by time difference, to ensure + // that each event is stored by its local time, e.g. an event that starts at + // 2022-05-31 22:00:00.000 PST (2022-06-01 05:00:00.000 UTC) is stored in the + // map for 05-2022. base::Time GetStartTimeAdjusted( const google_apis::calendar::CalendarEvent* event) const; - // Returns the `end_time` of `event` adjusted by `time_difference_minutes_`. + // Returns the `end_time` of `event` adjusted by time difference. base::Time GetEndTimeAdjusted( const google_apis::calendar::CalendarEvent* event) const; - // Returns midnight on the day of the state time of `event`. + // Returns midnight on the day of the start time of `event`. base::Time GetStartTimeMidnightAdjusted( const google_apis::calendar::CalendarEvent* event) const; - // Inserts EventList `events` in the EventCache. - void InsertEvents(const google_apis::calendar::EventList* events); + // Returns midnight on the day of the end time of `event`. + base::Time GetEndTimeMidnightAdjusted( + const google_apis::calendar::CalendarEvent* event) const; // Inserts EventList `events` in the EventCache. For testing only, it clears // out the entire cache and inserts the `events`. @@ -221,9 +228,6 @@ // All fetch requests that are still in-progress. std::map<base::Time, std::unique_ptr<CalendarEventFetch>> pending_fetches_; - // Time difference between the UTC time and the local time in minutes. - absl::optional<int> time_difference_minutes_; - // The first on-screen month to have been displayed when the calendar was // opened. base::Time first_on_screen_month_;
diff --git a/ash/system/time/calendar_model_unittest.cc b/ash/system/time/calendar_model_unittest.cc index 541f9ee..4d984be 100644 --- a/ash/system/time/calendar_model_unittest.cc +++ b/ash/system/time/calendar_model_unittest.cc
@@ -297,6 +297,10 @@ AshTestBase::TearDown(); } + void InsertEvents(const google_apis::calendar::EventList* events) { + calendar_model_->InsertEventsForTesting(events); + } + int EventsNumberOfDay(const char* day, SingleDayEventList* events) { base::Time day_base = calendar_test_utils::GetTimeFromString(day); @@ -328,10 +332,6 @@ return calendar_model_->GetStartTimeMidnightAdjusted(event); } - void set_time_difference_minutes(int minutes) { - calendar_model_->set_time_difference_minutes(minutes); - } - bool IsEventPresent(const char* event_id, SingleDayEventList& events) { const auto it = std::find_if(events.begin(), events.end(), @@ -453,6 +453,23 @@ SetFakeNowFromTime(current_date); } + void TestMultiDayEvent(SingleDayEventList events, + const char* start_date_str, + const char* end_date_str) { + base::Time start_time_midnight = + calendar_test_utils::GetTimeFromString(start_date_str).UTCMidnight(); + base::Time end_time_midnight = + calendar_test_utils::GetTimeFromString(end_date_str).UTCMidnight(); + + // Each day inside the event's time range should have an event. + while (start_time_midnight <= end_time_midnight) { + EXPECT_EQ(1, EventsNumberOfDay(start_time_midnight, &events)); + // Add more than 24 hours to consider daylight savings. + start_time_midnight = + (start_time_midnight + base::Hours(30)).UTCMidnight(); + } + } + static void SetFakeNow(base::Time fake_now) { fake_time_ = fake_now; } static base::Time FakeTimeNow() { return fake_time_; } static base::Time fake_time_; @@ -1225,6 +1242,62 @@ EXPECT_TRUE(next_month_map->second.empty()); } +TEST_F(CalendarModelTest, MultiDayEvents) { + // Generic event id and summary. + const char* kId = "id"; + const char* kSummary = "summary"; + + // Multi-day event ranges in the two surrounding months. + const char* kMultiDayStartTime = "20 Nov 2022 22:00 GMT"; + const char* kMultiDayEndTime = "25 Nov 2022 10:00 GMT"; + const char* kMultiMonthStartTime = "10 Sep 2022 22:00 GMT"; + const char* kMultiMonthEndTime = "2 Nov 2022 10:00 GMT"; + const char* kMultiYearStartTime = "10 Dec 2022 22:00 GMT"; + const char* kMultiYearEndTime = "10 Jan 2023 10:00 GMT"; + + // Set timezone and fake now. + const char* kNow = "10 Nov 2022 13:00 GMT"; + ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID(u"GMT"); + SetFakeNowFromStr(kNow); + + // Get ready to inject events. + calendar_model_ = std::make_unique<TestableCalendarModel>(); + std::unique_ptr<google_apis::calendar::EventList> event_list = + std::make_unique<google_apis::calendar::EventList>(); + SingleDayEventList events; + + // Create multi-day events. + std::unique_ptr<google_apis::calendar::CalendarEvent> multi_day_event = + calendar_test_utils::CreateEvent(kId, kSummary, kMultiDayStartTime, + kMultiDayEndTime); + std::unique_ptr<google_apis::calendar::CalendarEvent> multi_month_event = + calendar_test_utils::CreateEvent(kId, kSummary, kMultiMonthStartTime, + kMultiMonthEndTime); + std::unique_ptr<google_apis::calendar::CalendarEvent> multi_year_event = + calendar_test_utils::CreateEvent(kId, kSummary, kMultiYearStartTime, + kMultiYearEndTime); + + // Haven't injected anything yet, so no events on the start times. + EXPECT_EQ(0, EventsNumberOfDay(kMultiDayStartTime, &events)); + EXPECT_EQ(0, EventsNumberOfDay(kMultiMonthStartTime, &events)); + EXPECT_EQ(0, EventsNumberOfDay(kMultiYearStartTime, &events)); + + // Inject events. + event_list->InjectItemForTesting(std::move(multi_day_event)); + event_list->InjectItemForTesting(std::move(multi_month_event)); + event_list->InjectItemForTesting(std::move(multi_year_event)); + InsertEvents(event_list.get()); + + // Test a multi-day event whose start and end are in the same month. + TestMultiDayEvent(events, kMultiDayStartTime, kMultiDayEndTime); + + // Test a multi-day event whose start and end are in different months. + TestMultiDayEvent(events, kMultiMonthStartTime, kMultiMonthEndTime); + + // Test a multi-day event whose start and end are in different years. + TestMultiDayEvent(events, kMultiYearStartTime, kMultiYearEndTime); +} + // A mock `CalendarClient`. This mock client's `GetEventList` waits for a short // duration to mock the fetching process. class CalendarClientTestImpl : public CalendarClient {
diff --git a/ash/system/time/calendar_month_view.cc b/ash/system/time/calendar_month_view.cc index 3a7ab68..28f9e177 100644 --- a/ash/system/time/calendar_month_view.cc +++ b/ash/system/time/calendar_month_view.cc
@@ -74,18 +74,19 @@ CalendarDateCellView::CalendarDateCellView( CalendarViewController* calendar_view_controller, base::Time date, + base::TimeDelta time_difference, bool is_grayed_out_date, int row_index) : views::LabelButton( views::Button::PressedCallback( base::BindRepeating(&CalendarDateCellView::OnDateCellActivated, base::Unretained(this))), - calendar_utils::GetDayIntOfMonth( - date + calendar_view_controller->time_difference_minutes()), + calendar_utils::GetDayIntOfMonth(date + time_difference), CONTEXT_CALENDAR_DATE), date_(date), grayed_out_(is_grayed_out_date), row_index_(row_index), + time_difference_(time_difference), calendar_view_controller_(calendar_view_controller) { SetHorizontalAlignment(gfx::ALIGN_CENTER); SetBorder(views::CreateEmptyBorder(calendar_utils::kDateCellInsets)); @@ -169,8 +170,7 @@ } // Sets accessible label. E.g. Calendar, week of July 16th 2021, [selected // date] is currently selected. - base::Time local_date = - date_ + calendar_view_controller_->time_difference_minutes(); + base::Time local_date = date_ + time_difference_; base::Time::Exploded date_exploded = calendar_utils::GetExplodedUTC(local_date); base::Time first_day_of_week = @@ -334,7 +334,6 @@ base::Time current_date = calendar_utils::GetFirstDayOfWeekLocalMidnight(first_day_of_month); base::Time current_date_local = current_date + time_difference; - base::Time::Exploded current_date_exploded = calendar_utils::GetExplodedUTC(current_date_local); @@ -439,6 +438,7 @@ layout_manager->AddRows(1, views::TableLayout::kFixedSize); return AddChildView(std::make_unique<CalendarDateCellView>( calendar_view_controller_, current_date, + calendar_utils::GetTimeDifference(current_date), /*is_grayed_out_date=*/!is_in_current_month, /*row_index=*/row_index)); }
diff --git a/ash/system/time/calendar_month_view.h b/ash/system/time/calendar_month_view.h index f854cfc..0296f39c 100644 --- a/ash/system/time/calendar_month_view.h +++ b/ash/system/time/calendar_month_view.h
@@ -28,6 +28,7 @@ CalendarDateCellView(CalendarViewController* calendar_view_controller, base::Time date, + base::TimeDelta time_difference, bool is_grayed_out_date, int row_index); CalendarDateCellView(const CalendarDateCellView& other) = delete; @@ -99,6 +100,9 @@ // After the events date is back, show date and event numbers. std::u16string tool_tip_; + // The time difference from UTC time based on `date_`; + base::TimeDelta time_difference_; + // Owned by UnifiedCalendarViewController. CalendarViewController* const calendar_view_controller_;
diff --git a/ash/system/time/calendar_month_view_unittest.cc b/ash/system/time/calendar_month_view_unittest.cc index de286934..ecbff79e 100644 --- a/ash/system/time/calendar_month_view_unittest.cc +++ b/ash/system/time/calendar_month_view_unittest.cc
@@ -39,7 +39,7 @@ event_list->InjectItemForTesting(calendar_test_utils::CreateEvent( "id_5", "summary_5", "2 Sep 2021 10:30 GMT", "21 Nov 2021 11:30 GMT")); event_list->InjectItemForTesting(calendar_test_utils::CreateEvent( - "id_6", "summary_6", "10 Aug 2021 4:30 GMT", "10 Aug 2021 8:30 GMT")); + "id_6", "summary_6", "10 Aug 2021 4:30 GMT", "10 Aug 2021 5:30 GMT")); event_list->InjectItemForTesting(calendar_test_utils::CreateEvent( "id_7", "summary_7", "10 Aug 2021 7:30 GMT", "10 Aug 2021 9:30 GMT")); event_list->InjectItemForTesting(calendar_test_utils::CreateEvent( @@ -333,10 +333,6 @@ month_view()->SchedulePaintChildren(); TriggerPaint(); - // August is before the daylight saving, time difference between UTC and PST - // should be 7 hours. - EXPECT_EQ(base::Minutes(-420), controller()->time_difference_minutes()); - EXPECT_EQ(u"18", static_cast<CalendarDateCellView*>(month_view()->children()[17]) ->GetText());
diff --git a/ash/system/time/calendar_utils.cc b/ash/system/time/calendar_utils.cc index 911d34d..7797da8 100644 --- a/ash/system/time/calendar_utils.cc +++ b/ash/system/time/calendar_utils.cc
@@ -157,6 +157,14 @@ (end_exp.month - start_exp.month) % 12; } +base::Time GetMaxTime(const base::Time d1, const base::Time d2) { + return (d1 > d2) ? d1 : d2; +} + +base::Time GetMinTime(const base::Time d1, const base::Time d2) { + return (d1 < d2) ? d1 : d2; +} + SkColor GetPrimaryTextColor() { const ash::AshColorProvider* color_provider = ash::AshColorProvider::Get(); return color_provider->GetContentLayerColor( @@ -196,6 +204,11 @@ .UTCMidnight(); } +base::Time GetNextDayMidnight(base::Time date) { + return (date.UTCMidnight() + base::Days(1) + kDurationForAdjustingDST) + .UTCMidnight(); +} + ASH_EXPORT base::Time GetStartOfPreviousMonthUTC(base::Time date) { return GetStartOfMonthUTC(GetStartOfMonthUTC(date) - base::Days(1)); }
diff --git a/ash/system/time/calendar_utils.h b/ash/system/time/calendar_utils.h index 7f2dc27..5762b37 100644 --- a/ash/system/time/calendar_utils.h +++ b/ash/system/time/calendar_utils.h
@@ -63,6 +63,10 @@ // expected date. constexpr base::TimeDelta kDurationForAdjustingDST = base::Hours(5); +// Duration subtracted from an existing midnight in UTC to get the +// previous day. It is less than 24 hours to consider daylight savings. +constexpr base::TimeDelta kDurationForGettingPreviousDay = base::Hours(20); + // Event fetch will terminate if we don't receive a response sooner than this. constexpr base::TimeDelta kEventFetchTimeout = base::Seconds(10); @@ -149,6 +153,12 @@ ASH_EXPORT int GetMonthsBetween(const base::Time& start_date, const base::Time& end_date); +// Gets date with greater value between `d1` and `d2`. +ASH_EXPORT base::Time GetMaxTime(const base::Time d1, const base::Time d2); + +// Gets date with lesser value between `d1` and `d2`. +ASH_EXPORT base::Time GetMinTime(const base::Time d1, const base::Time d2); + // Colors. SkColor GetPrimaryTextColor(); SkColor GetSecondaryTextColor(); @@ -174,6 +184,9 @@ // |date|. base::Time GetStartOfNextMonthUTC(base::Time date); +// Returns UTC midnight of `date`'s next day without adjusting time difference. +ASH_EXPORT base::Time GetNextDayMidnight(base::Time date); + // Returns true if it's a regular user or the user session is not blocked. bool IsActiveUser();
diff --git a/ash/system/time/calendar_utils_unittest.cc b/ash/system/time/calendar_utils_unittest.cc index 6ce3ec3..f52956c 100644 --- a/ash/system/time/calendar_utils_unittest.cc +++ b/ash/system/time/calendar_utils_unittest.cc
@@ -206,4 +206,19 @@ EXPECT_EQ(fetch.second, expected_end); } +TEST_F(CalendarUtilsUnittest, MinMaxTime) { + base::Time date_1; + base::Time date_2; + base::Time date_3; + base::Time date_4; + ASSERT_TRUE(base::Time::FromString("01 Apr 2022 00:00 GMT", &date_1)); + ASSERT_TRUE(base::Time::FromString("01 Apr 2023 00:00 GMT", &date_2)); + ASSERT_TRUE(base::Time::FromString("01 Apr 2022 20:00 GMT", &date_3)); + ASSERT_TRUE(base::Time::FromString("31 Mar 2022 00:00 GMT", &date_4)); + + EXPECT_EQ(date_2, calendar_utils::GetMaxTime(date_1, date_2)); + EXPECT_EQ(date_3, calendar_utils::GetMaxTime(date_1, date_3)); + EXPECT_EQ(date_4, calendar_utils::GetMinTime(date_1, date_4)); +} + } // namespace ash
diff --git a/ash/system/time/calendar_view_controller.cc b/ash/system/time/calendar_view_controller.cc index 4ab0f88..0fb5c163 100644 --- a/ash/system/time/calendar_view_controller.cc +++ b/ash/system/time/calendar_view_controller.cc
@@ -34,11 +34,10 @@ CalendarViewController::CalendarViewController() : currently_shown_date_(base::Time::Now()), calendar_open_time_(base::TimeTicks::Now()), - month_dwell_time_(base::TimeTicks::Now()), - time_difference_minutes_( - calendar_utils::GetTimeDifference(currently_shown_date_)) { + month_dwell_time_(base::TimeTicks::Now()) { std::set<base::Time> months = calendar_utils::GetSurroundingMonthsUTC( - base::Time::Now() + time_difference_minutes_, + base::Time::Now() + + calendar_utils::GetTimeDifference(currently_shown_date_), calendar_utils::kNumSurroundingMonthsCached); Shell::Get()->system_tray_model()->calendar_model()->AddNonPrunableMonths( months); @@ -182,6 +181,11 @@ selected_date_row_index_ = row_index; expanded_row_index_ = row_index; + base::TimeDelta time_difference = + calendar_utils::GetTimeDifference(selected_date); + selected_date_midnight_ = (selected_date + time_difference).UTCMidnight(); + selected_date_midnight_utc_ = selected_date_midnight_ - time_difference; + // Notify observers. for (auto& observer : observers_) observer.OnSelectedDateUpdated();
diff --git a/ash/system/time/calendar_view_controller.h b/ash/system/time/calendar_view_controller.h index 0d985dd..9f65674 100644 --- a/ash/system/time/calendar_view_controller.h +++ b/ash/system/time/calendar_view_controller.h
@@ -81,6 +81,14 @@ // The currently selected date to show the event list. absl::optional<base::Time> selected_date() { return selected_date_; } + // The midnight of the currently selected date adjusted to the local timezone. + base::Time selected_date_midnight() { return selected_date_midnight_; }; + + // The midnight of the selected date in UTC time. + base::Time selected_date_midnight_utc() { + return selected_date_midnight_utc_; + }; + // The row index of the currently selected date. This is used for auto // scrolling to this row when the event list is expanded. int selected_date_row_index() { return selected_date_row_index_; } @@ -102,10 +110,6 @@ int row_height() const { return row_height_; } void set_row_height(int height) { row_height_ = height; } - base::TimeDelta time_difference_minutes() const { - return time_difference_minutes_; - } - // Getters of the today's row position, top and bottom. int GetTodayRowTopHeight() const; int GetTodayRowBottomHeight() const; @@ -144,7 +148,7 @@ friend class CalendarViewTest; friend class CalendarViewAnimationTest; - // Adds the `time_difference_minutes_` and returns the adjusted time. + // Adds the time difference and returns the adjusted time. base::Time ApplyTimeDifference(base::Time date); // The currently shown date, which can be today or the first day of the @@ -176,15 +180,18 @@ // The currently selected date. absl::optional<base::Time> selected_date_; + // The midnight of the currently selected date adjusted to the local timezone. + base::Time selected_date_midnight_; + + // The midnight of the selected date in UTC time. + base::Time selected_date_midnight_utc_; + // The row index of the currently selected date. int selected_date_row_index_ = 0; // The current row index when the event list view is shown. int expanded_row_index_ = 0; - // The time difference between UTC and local time. - const base::TimeDelta time_difference_minutes_; - base::ObserverList<Observer> observers_; base::WeakPtrFactory<CalendarViewController> weak_factory_{this};
diff --git a/ash/system/time/calendar_view_unittest.cc b/ash/system/time/calendar_view_unittest.cc index 510af54..69cbbf5 100644 --- a/ash/system/time/calendar_view_unittest.cc +++ b/ash/system/time/calendar_view_unittest.cc
@@ -266,8 +266,7 @@ } // Test the init view of the `CalendarView` starting with December. -// TODO(crbug.com/1329028): Re-enable this test -TEST_F(CalendarViewTest, DISABLED_InitDec) { +TEST_F(CalendarViewTest, InitDec) { base::Time dec_date; ASSERT_TRUE(base::Time::FromString("24 Dec 2021 10:00 GMT", &dec_date));
diff --git a/ash/webui/os_feedback_ui/resources/share_data_page.js b/ash/webui/os_feedback_ui/resources/share_data_page.js index 4d50e16..98c6f3d5 100644 --- a/ash/webui/os_feedback_ui/resources/share_data_page.js +++ b/ash/webui/os_feedback_ui/resources/share_data_page.js
@@ -81,9 +81,10 @@ * @protected */ handleSendButtonClicked_(e) { + this.getElement_('#buttonSend').disabled = true; + e.stopPropagation(); - // TODO(xiangdongkong): Disable the button to prevent sending the same - // report again. + this.dispatchEvent(new CustomEvent('continue-click', { composed: true, bubbles: true,
diff --git a/ash/webui/personalization_app/resources/trusted/wallpaper/wallpaper_images_element.html b/ash/webui/personalization_app/resources/trusted/wallpaper/wallpaper_images_element.html index 0394843..33e64c26 100644 --- a/ash/webui/personalization_app/resources/trusted/wallpaper/wallpaper_images_element.html +++ b/ash/webui/personalization_app/resources/trusted/wallpaper/wallpaper_images_element.html
@@ -2,7 +2,7 @@ <main id="main" tabindex="-1" aria-label$="[[getMainAriaLabel_(collectionId, collections_)]]"> <iron-media-query query="(prefers-color-scheme: dark)" - query-matches="{{isDarkModeActive_}}"> + query-matches="{{isDarkModeActive}}"> </iron-media-query> <images-grid id="imagesGrid"></images-grid> </main>
diff --git a/ash/webui/personalization_app/resources/trusted/wallpaper/wallpaper_images_element.ts b/ash/webui/personalization_app/resources/trusted/wallpaper/wallpaper_images_element.ts index 4680203..09f579f 100644 --- a/ash/webui/personalization_app/resources/trusted/wallpaper/wallpaper_images_element.ts +++ b/ash/webui/personalization_app/resources/trusted/wallpaper/wallpaper_images_element.ts
@@ -116,6 +116,14 @@ }, /** + * Whether dark mode is the active preferred color scheme. + */ + isDarkModeActive: { + type: Boolean, + value: false, + }, + + /** * The current collection id to display. */ collectionId: String, @@ -163,19 +171,12 @@ type: Boolean, computed: 'computeHasImages_(images_, imagesLoading_, collectionId)', }, - - /** - * Whether dark mode is the active preferred color scheme. - */ - isDarkModeActive_: { - type: Boolean, - value: false, - }, }; } override hidden: boolean; collectionId: string; + isDarkModeActive: boolean; private collections_: WallpaperCollection[]|null; private collectionsLoading_: boolean; private images_: Record<string, WallpaperImage[]|null>; @@ -184,11 +185,10 @@ private pendingSelected_: DisplayableImage|null; private hasError_: boolean; private hasImages_: boolean; - private isDarkModeActive_: boolean; static get observers() { return [ - 'onImagesUpdated_(hasImages_, hasError_, collectionId, isDarkModeActive_)', + 'onImagesUpdated_(hasImages_, hasError_, collectionId, isDarkModeActive)', ]; }
diff --git a/ash/wm/desks/templates/saved_desk_item_view.cc b/ash/wm/desks/templates/saved_desk_item_view.cc index 3d138c07..4e0b44f 100644 --- a/ash/wm/desks/templates/saved_desk_item_view.cc +++ b/ash/wm/desks/templates/saved_desk_item_view.cc
@@ -401,6 +401,10 @@ return; DCHECK_EQ(observed_view, name_view_); + + // Make sure the current desk item view is fully visible. + ScrollViewToVisible(); + is_template_name_being_modified_ = true; // Assume we should commit the name change unless `HandleKeyEvent` detects the
diff --git a/ash/wm/desks/templates/saved_desk_unittest.cc b/ash/wm/desks/templates/saved_desk_unittest.cc index 59dfbed..fb42a00 100644 --- a/ash/wm/desks/templates/saved_desk_unittest.cc +++ b/ash/wm/desks/templates/saved_desk_unittest.cc
@@ -3834,6 +3834,38 @@ } } +// Tests that the save desk item view is fully visible when it gains focus. +TEST_F(SavedDeskTest, FocusedDeskItemFullyVisible) { + // Set up a small display, so that the new saved desk may fall completely + // outside the display. + UpdateDisplay("800x500"); + + // Add 6 `kTemplate` entries. + for (size_t i = 1; i <= 6; i++) { + AddEntry(base::GUID::GenerateRandomV4(), + "desk_template " + base::NumberToString(i), base::Time::Now(), + DeskTemplateType::kTemplate); + } + + // Create a window then save the current desk for later. + CreateAppWindow().release(); + ToggleOverview(); + WaitForDesksTemplatesUI(); + auto* save_desk_button = + GetSaveDeskForLaterButtonForRoot(Shell::Get()->GetPrimaryRootWindow()); + ClickOnView(save_desk_button); + WaitForDesksTemplatesUI(); + + // The newly saved desk item should be fully visible. + SavedDeskItemView* item_view = GetItemViewFromTemplatesGrid(6); + ASSERT_EQ(u"Desk 1", item_view->name_view()->GetText()); + ASSERT_TRUE(item_view->name_view()->HasFocus()); + EXPECT_EQ(item_view->name_view()->GetPreferredSize(), + item_view->name_view()->GetVisibleBounds().size()); + EXPECT_EQ(item_view->GetPreferredSize(), + item_view->GetVisibleBounds().size()); +} + using DeskSaveAndRecallTest = SavedDeskTest; TEST_F(DeskSaveAndRecallTest, SaveDeskForLater) {
diff --git a/ash/wm/window_cycle/window_cycle_controller_unittest.cc b/ash/wm/window_cycle/window_cycle_controller_unittest.cc index 4539597..fd4894b 100644 --- a/ash/wm/window_cycle/window_cycle_controller_unittest.cc +++ b/ash/wm/window_cycle/window_cycle_controller_unittest.cc
@@ -30,6 +30,7 @@ #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" +#include "ash/system/unified/unified_system_tray.h" #include "ash/test/ash_test_base.h" #include "ash/test_shell_delegate.h" #include "ash/wm/desks/desk.h" @@ -1019,6 +1020,34 @@ EXPECT_FALSE(base::Contains(currently_pressed_keys, ui::VKEY_MENU)); } +// Tests that system tray will be closed when alt-tab cycling starts. Also tests +// releasing the alt key will end the alt-tab cycling successfully. +TEST_F(WindowCycleControllerTest, AltKeyReleaseOnSystemTrayOpen) { + std::unique_ptr<Window> window0(CreateTestWindowInShellWithId(0)); + std::unique_ptr<Window> window1(CreateTestWindowInShellWithId(1)); + + WindowCycleController* controller = Shell::Get()->window_cycle_controller(); + ui::test::EventGenerator* event_generator = GetEventGenerator(); + + // Open system tray. + auto* system_tray = GetPrimaryUnifiedSystemTray(); + event_generator->MoveMouseTo(system_tray->GetBoundsInScreen().CenterPoint()); + event_generator->ClickLeftButton(); + EXPECT_TRUE(system_tray->IsBubbleShown()); + + // Start window cycling by press Alt + Tab key. + WindowState::Get(window0.get())->Activate(); + event_generator->PressKey(ui::VKEY_MENU, ui::EF_NONE); + event_generator->PressKey(ui::VKEY_TAB, ui::EF_ALT_DOWN); + EXPECT_TRUE(controller->IsCycling()); + // Verify the system tray is closed after the alt-tab cycling starts. + EXPECT_FALSE(system_tray->IsBubbleShown()); + + // Release Alt key, verify alt-tab cycling is ended. + event_generator->ReleaseKey(ui::VKEY_MENU, ui::EF_NONE); + EXPECT_FALSE(controller->IsCycling()); +} + // Test alt-tab will be shown on the display where the cursor is located // when there are 2 displays, TEST_F(WindowCycleControllerTest, AltTabMultiDisplay) {
diff --git a/ash/wm/window_cycle/window_cycle_list.cc b/ash/wm/window_cycle/window_cycle_list.cc index 3ff161d..8240406 100644 --- a/ash/wm/window_cycle/window_cycle_list.cc +++ b/ash/wm/window_cycle/window_cycle_list.cc
@@ -10,8 +10,10 @@ #include "ash/frame_throttler/frame_throttling_controller.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" +#include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/shell_delegate.h" +#include "ash/system/unified/unified_system_tray.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/window_cycle/window_cycle_controller.h" @@ -331,6 +333,14 @@ if (cycle_view_) return; aura::Window* root_window = GetRootWindowForCycleView(); + + // Close the system quick settings tray before creating the cycle view. + UnifiedSystemTray* tray = RootWindowController::ForWindow(root_window) + ->GetStatusAreaWidget() + ->unified_system_tray(); + if (tray->IsBubbleShown()) + tray->CloseBubble(); + cycle_view_ = new WindowCycleView(root_window, windows_); const bool is_interactive_alt_tab_mode_allowed = Shell::Get()->window_cycle_controller()->IsInteractiveAltTabModeAllowed();
diff --git a/base/containers/checked_range.h b/base/containers/checked_range.h index 1dae907..9ded412 100644 --- a/base/containers/checked_range.h +++ b/base/containers/checked_range.h
@@ -11,6 +11,7 @@ #include <type_traits> #include <utility> +#include "base/check.h" #include "base/containers/checked_iterators.h" #include "base/template_util.h" @@ -127,7 +128,8 @@ constexpr reference back() const noexcept { return *(end() - 1); } constexpr reference operator[](size_type idx) const noexcept { - return *(begin() + idx); + CHECK(idx < size()); + return *(begin() + static_cast<difference_type>(idx)); } constexpr pointer data() const noexcept {
diff --git a/base/containers/circular_deque.h b/base/containers/circular_deque.h index 372e1e6..dd2bf625 100644 --- a/base/containers/circular_deque.h +++ b/base/containers/circular_deque.h
@@ -13,7 +13,6 @@ #include "base/as_const.h" #include "base/check.h" -#include "base/check_op.h" #include "base/containers/vector_buffer.h" #include "base/dcheck_is_on.h" #include "base/memory/raw_ptr_exclusion.h" @@ -300,16 +299,16 @@ // Since circular_deque doesn't guarantee stability, any attempt to // dereference this iterator after a mutation (i.e. the generation doesn't // match the original) in the container is illegal. - DCHECK_EQ(created_generation_, parent_deque_->generation_) + DCHECK(created_generation_ == parent_deque_->generation_) << "circular_deque iterator dereferenced after mutation."; } void CheckComparable(const circular_deque_const_iterator& other) const { - DCHECK_EQ(parent_deque_, other.parent_deque_); + DCHECK(parent_deque_ == other.parent_deque_); // Since circular_deque doesn't guarantee stability, two iterators that // are compared must have been generated without mutating the container. // If this fires, the container was mutated between generating the two // iterators being compared. - DCHECK_EQ(created_generation_, other.created_generation_); + DCHECK(created_generation_ == other.created_generation_); } #else inline void CheckUnstableUsage() const {} @@ -721,9 +720,12 @@ insert(const_iterator pos, InputIterator first, InputIterator last) { ValidateIterator(pos); - size_t inserted_items = std::distance(first, last); - if (inserted_items == 0) + const difference_type inserted_items_signed = std::distance(first, last); + if (inserted_items_signed == 0) return; // Can divide by 0 when doing modulo below, so return early. + CHECK(inserted_items_signed > 0); + const size_type inserted_items = + static_cast<size_type>(inserted_items_signed); // Make a hole to copy the items into. iterator insert_cur;
diff --git a/base/containers/cxx20_erase_vector.h b/base/containers/cxx20_erase_vector.h index 6f06f7d..200e3702 100644 --- a/base/containers/cxx20_erase_vector.h +++ b/base/containers/cxx20_erase_vector.h
@@ -23,7 +23,7 @@ template <class T, class Allocator, class Value> size_t Erase(std::vector<T, Allocator>& container, const Value& value) { auto it = std::remove(container.begin(), container.end(), value); - size_t removed = std::distance(it, container.end()); + size_t removed = static_cast<size_t>(std::distance(it, container.end())); container.erase(it, container.end()); return removed; } @@ -31,7 +31,7 @@ template <class T, class Allocator, class Predicate> size_t EraseIf(std::vector<T, Allocator>& container, Predicate pred) { auto it = std::remove_if(container.begin(), container.end(), pred); - size_t removed = std::distance(it, container.end()); + size_t removed = static_cast<size_t>(std::distance(it, container.end())); container.erase(it, container.end()); return removed; }
diff --git a/base/containers/flat_tree.h b/base/containers/flat_tree.h index 01594755..55f8969 100644 --- a/base/containers/flat_tree.h +++ b/base/containers/flat_tree.h
@@ -825,10 +825,12 @@ // Provide a convenience lambda to obtain an iterator pointing past the last // old element. This needs to be dymanic due to possible re-allocations. - auto middle = [this, size = size()] { return std::next(begin(), size); }; + auto middle = [this, size = size()] { + return std::next(begin(), static_cast<difference_type>(size)); + }; // For batch updates initialize the first insertion point. - difference_type pos_first_new = size(); + auto pos_first_new = static_cast<difference_type>(size()); // Loop over the input range while appending new values and overwriting // existing ones, if applicable. Keep track of the first insertion point. @@ -904,7 +906,8 @@ auto flat_tree<Key, GetKeyFromValue, KeyCompare, Container>::erase(const K& val) -> size_type { auto eq_range = equal_range(val); - auto res = std::distance(eq_range.first, eq_range.second); + auto res = + static_cast<size_type>(std::distance(eq_range.first, eq_range.second)); erase(eq_range.first, eq_range.second); return res; } @@ -941,7 +944,7 @@ auto flat_tree<Key, GetKeyFromValue, KeyCompare, Container>::count( const K& key) const -> size_type { auto eq_range = equal_range(key); - return std::distance(eq_range.first, eq_range.second); + return static_cast<size_type>(std::distance(eq_range.first, eq_range.second)); } template <class Key, class GetKeyFromValue, class KeyCompare, class Container>
diff --git a/base/containers/intrusive_heap.h b/base/containers/intrusive_heap.h index 2a12d10..4d69785 100644 --- a/base/containers/intrusive_heap.h +++ b/base/containers/intrusive_heap.h
@@ -422,8 +422,8 @@ [&](const auto& element) { return !predicate(element); }); // Clear the heap handle of every element that will be erased. - for (size_t i = erase_start - impl_.heap_.begin(); i < impl_.heap_.size(); - ++i) { + for (size_t i = static_cast<size_t>(erase_start - impl_.heap_.begin()); + i < impl_.heap_.size(); ++i) { ClearHeapHandle(i); } @@ -1083,8 +1083,8 @@ // MoveHoleUpAndFill can tolerate the initial hole being in a slot that // doesn't yet exist. It will be created by MoveHole by copy/move, thus // removing the need for a default constructor. - size_t i = MoveHoleUpAndFill(size(), std::move_if_noexcept(element)); - return cbegin() + i; + size_type i = MoveHoleUpAndFill(size(), std::move_if_noexcept(element)); + return cbegin() + static_cast<difference_type>(i); } template <typename T, typename Compare, typename HeapHandleAccessor> @@ -1101,7 +1101,7 @@ } else { i = MoveHoleDownAndFill<WithElement>(pos, std::move_if_noexcept(element)); } - return cbegin() + i; + return cbegin() + static_cast<difference_type>(i); } template <typename T, typename Compare, typename HeapHandleAccessor> @@ -1111,7 +1111,7 @@ MakeHole(0u); size_type i = MoveHoleDownAndFill<WithElement>(0u, std::move_if_noexcept(element)); - return cbegin() + i; + return cbegin() + static_cast<difference_type>(i); } ////////////////////////////////////////////////////////////////////////////////
diff --git a/base/containers/small_map.h b/base/containers/small_map.h index 071f87c1..2e2b61f 100644 --- a/base/containers/small_map.h +++ b/base/containers/small_map.h
@@ -487,7 +487,7 @@ return iterator(map_.erase(position.map_iter_)); } - size_t i = position.array_iter_ - array_; + size_t i = static_cast<size_t>(position.array_iter_ - array_); // TODO(crbug.com/817982): When we have a checked iterator, this CHECK might // not be necessary. CHECK_LE(i, size_);
diff --git a/base/containers/span.h b/base/containers/span.h index 4a66026..61465634 100644 --- a/base/containers/span.h +++ b/base/containers/span.h
@@ -469,10 +469,19 @@ } // Type-deducing helpers for constructing a span. -template <int&... ExplicitArgumentBarrier, typename It, typename EndOrSize> -constexpr auto make_span(It it, EndOrSize end_or_size) noexcept { +template <int&... ExplicitArgumentBarrier, typename It> +constexpr auto make_span(It it, size_t size) noexcept { using T = std::remove_reference_t<iter_reference_t<It>>; - return span<T>(it, end_or_size); + return span<T>(it, size); +} + +template <int&... ExplicitArgumentBarrier, + typename It, + typename End, + typename = std::enable_if_t<!std::is_convertible_v<End, size_t>>> +constexpr auto make_span(It it, End end) noexcept { + using T = std::remove_reference_t<iter_reference_t<It>>; + return span<T>(it, end); } // make_span utility function that deduces both the span's value_type and extent @@ -487,7 +496,7 @@ return span<T, Extent::value>(std::forward<Container>(container)); } -// make_span utility function that allows callers to explicit specify the span's +// make_span utility functions that allow callers to explicit specify the span's // extent, the value_type is deduced automatically. This is useful when passing // a dynamically sized container to a method expecting static spans, when the // container is known to have the correct size. @@ -495,13 +504,20 @@ // Note: This will CHECK that N indeed matches size(container). // // Usage: auto static_span = base::make_span<N>(...); +template <size_t N, int&... ExplicitArgumentBarrier, typename It> +constexpr auto make_span(It it, size_t size) noexcept { + using T = std::remove_reference_t<iter_reference_t<It>>; + return span<T, N>(it, size); +} + template <size_t N, int&... ExplicitArgumentBarrier, typename It, - typename EndOrSize> -constexpr auto make_span(It it, EndOrSize end_or_size) noexcept { + typename End, + typename = std::enable_if_t<!std::is_convertible_v<End, size_t>>> +constexpr auto make_span(It it, End end) noexcept { using T = std::remove_reference_t<iter_reference_t<It>>; - return span<T, N>(it, end_or_size); + return span<T, N>(it, end); } template <size_t N, int&... ExplicitArgumentBarrier, typename Container>
diff --git a/base/debug/gdi_debug_util_win.cc b/base/debug/gdi_debug_util_win.cc index 960adbd..28ab2f2 100644 --- a/base/debug/gdi_debug_util_win.cc +++ b/base/debug/gdi_debug_util_win.cc
@@ -378,20 +378,20 @@ int total_process_count = 0; base::debug::Alias(&total_process_count); - int total_peak_gdi_count = 0; + DWORD total_peak_gdi_count = 0; base::debug::Alias(&total_peak_gdi_count); - int total_gdi_count = 0; + DWORD total_gdi_count = 0; base::debug::Alias(&total_gdi_count); - int total_user_count = 0; + DWORD total_user_count = 0; base::debug::Alias(&total_user_count); int child_count = 0; base::debug::Alias(&child_count); - int peak_gdi_count = 0; + DWORD peak_gdi_count = 0; base::debug::Alias(&peak_gdi_count); - int sum_gdi_count = 0; + DWORD sum_gdi_count = 0; base::debug::Alias(&sum_gdi_count); - int sum_user_count = 0; + DWORD sum_user_count = 0; base::debug::Alias(&sum_user_count); PROCESSENTRY32 proc_entry = {}; @@ -405,8 +405,8 @@ if (!process.is_valid()) continue; - int num_gdi_handles = GetGuiResources(process.get(), GR_GDIOBJECTS); - int num_user_handles = GetGuiResources(process.get(), GR_USEROBJECTS); + DWORD num_gdi_handles = GetGuiResources(process.get(), GR_GDIOBJECTS); + DWORD num_user_handles = GetGuiResources(process.get(), GR_USEROBJECTS); // Compute sum and peak counts for all processes. ++total_process_count;
diff --git a/base/debug/stack_trace_win.cc b/base/debug/stack_trace_win.cc index d21fe40..383a220 100644 --- a/base/debug/stack_trace_win.cc +++ b/base/debug/stack_trace_win.cc
@@ -328,17 +328,17 @@ STACKFRAME64 stack_frame; memset(&stack_frame, 0, sizeof(stack_frame)); #if defined(ARCH_CPU_X86_64) - int machine_type = IMAGE_FILE_MACHINE_AMD64; + DWORD machine_type = IMAGE_FILE_MACHINE_AMD64; stack_frame.AddrPC.Offset = context_record->Rip; stack_frame.AddrFrame.Offset = context_record->Rbp; stack_frame.AddrStack.Offset = context_record->Rsp; #elif defined(ARCH_CPU_ARM64) - int machine_type = IMAGE_FILE_MACHINE_ARM64; + DWORD machine_type = IMAGE_FILE_MACHINE_ARM64; stack_frame.AddrPC.Offset = context_record->Pc; stack_frame.AddrFrame.Offset = context_record->Fp; stack_frame.AddrStack.Offset = context_record->Sp; #elif defined(ARCH_CPU_X86) - int machine_type = IMAGE_FILE_MACHINE_I386; + DWORD machine_type = IMAGE_FILE_MACHINE_I386; stack_frame.AddrPC.Offset = context_record->Eip; stack_frame.AddrFrame.Offset = context_record->Ebp; stack_frame.AddrStack.Offset = context_record->Esp;
diff --git a/base/time/time_win.cc b/base/time/time_win.cc index 014dd169..56cba84 100644 --- a/base/time/time_win.cc +++ b/base/time/time_win.cc
@@ -163,7 +163,7 @@ } // Returns the current value of the performance counter. -uint64_t QPCNowRaw() { +int64_t QPCNowRaw() { LARGE_INTEGER perf_counter_now = {}; // According to the MSDN documentation for QueryPerformanceCounter(), this // will never fail on systems that run XP or later. @@ -760,12 +760,12 @@ // TSC and the performance counter. static const uint64_t tsc_initial = __rdtsc(); - static const uint64_t perf_counter_initial = QPCNowRaw(); + static const int64_t perf_counter_initial = QPCNowRaw(); // Make a another reading of the TSC and the performance counter every time // that this function is called. const uint64_t tsc_now = __rdtsc(); - const uint64_t perf_counter_now = QPCNowRaw(); + const int64_t perf_counter_now = QPCNowRaw(); // Reset the thread priority. ::SetThreadPriority(::GetCurrentThread(), previous_priority); @@ -782,7 +782,7 @@ LARGE_INTEGER perf_counter_frequency = {}; ::QueryPerformanceFrequency(&perf_counter_frequency); DCHECK_GE(perf_counter_now, perf_counter_initial); - const uint64_t perf_counter_ticks = perf_counter_now - perf_counter_initial; + const int64_t perf_counter_ticks = perf_counter_now - perf_counter_initial; const double elapsed_time_seconds = perf_counter_ticks / static_cast<double>(perf_counter_frequency.QuadPart);
diff --git a/base/win/pe_image.cc b/base/win/pe_image.cc index 817e5c57..6d1c038 100644 --- a/base/win/pe_image.cc +++ b/base/win/pe_image.cc
@@ -144,22 +144,22 @@ PIMAGE_SECTION_HEADER PEImage::GetImageSectionHeaderByName( LPCSTR section_name) const { - if (nullptr == section_name) + if (section_name == nullptr) return nullptr; - PIMAGE_SECTION_HEADER ret = nullptr; int num_sections = GetNumSections(); + if (num_sections <= 0) + return nullptr; - for (int i = 0; i < num_sections; i++) { + for (UINT i = 0; i < static_cast<UINT>(num_sections); ++i) { PIMAGE_SECTION_HEADER section = GetSectionHeader(i); if (_strnicmp(reinterpret_cast<LPCSTR>(section->Name), section_name, sizeof(section->Name)) == 0) { - ret = section; - break; + return section; } } - return ret; + return nullptr; } bool PEImage::GetDebugId(LPGUID guid, @@ -199,7 +199,9 @@ for (const char* const end = pdb_info->PdbFileName + length_max; eos < end && *eos; ++eos) ; - *pdb_filename_length = eos - pdb_info->PdbFileName; + // This static_cast is safe because the loop above only increments eos, + // and ensures it won't wrap. + *pdb_filename_length = static_cast<size_t>(eos - pdb_info->PdbFileName); *pdb_filename = pdb_info->PdbFileName; } return true;
diff --git a/base/win/scoped_safearray.h b/base/win/scoped_safearray.h index 11ab451..3808eec 100644 --- a/base/win/scoped_safearray.h +++ b/base/win/scoped_safearray.h
@@ -74,8 +74,8 @@ pointer data() { return array_; } const_pointer data() const { return array_; } - reference operator[](int index) { return at(index); } - const_reference operator[](int index) const { return at(index); } + reference operator[](size_t index) { return at(index); } + const_reference operator[](size_t index) const { return at(index); } reference at(size_t index) { DCHECK_NE(array_, nullptr); @@ -202,7 +202,10 @@ DCHECK(SUCCEEDED(hr)); hr = SafeArrayGetUBound(safearray_, dimension + 1, &upper); DCHECK(SUCCEEDED(hr)); - return (upper - lower + 1); + LONG count = upper - lower + 1; + // SafeArrays may have negative lower bounds, so check for wraparound. + DCHECK_GT(count, 0); + return static_cast<size_t>(count); } // Returns the internal pointer.
diff --git a/build/fuchsia/linux_internal.sdk.sha1 b/build/fuchsia/linux_internal.sdk.sha1 index 7fa9f89..7fa1c4da 100644 --- a/build/fuchsia/linux_internal.sdk.sha1 +++ b/build/fuchsia/linux_internal.sdk.sha1
@@ -1 +1 @@ -8.20220527.2.1 +8.20220527.3.1
diff --git a/cc/layers/solid_color_scrollbar_layer_impl.cc b/cc/layers/solid_color_scrollbar_layer_impl.cc index 8a3f3a2..f1b8b88 100644 --- a/cc/layers/solid_color_scrollbar_layer_impl.cc +++ b/cc/layers/solid_color_scrollbar_layer_impl.cc
@@ -50,7 +50,9 @@ /*is_overlay*/ true), thumb_thickness_(thumb_thickness), track_start_(track_start), - color_(tree_impl->settings().solid_color_scrollbar_color) {} + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + color_(SkColor4f::FromColor( + tree_impl->settings().solid_color_scrollbar_color)) {} void SolidColorScrollbarLayerImpl::PushPropertiesTo(LayerImpl* layer) { ScrollbarLayerImplBase::PushPropertiesTo(layer); @@ -106,8 +108,9 @@ return; auto* quad = render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>(); - quad->SetNew( - shared_quad_state, thumb_quad_rect, visible_quad_rect, color_, false); + // TODO(crbug/1308932): Remove toSkColor and make all SkColor4f. + quad->SetNew(shared_quad_state, thumb_quad_rect, visible_quad_rect, + color_.toSkColor(), false); } const char* SolidColorScrollbarLayerImpl::LayerTypeAsString() const {
diff --git a/cc/layers/solid_color_scrollbar_layer_impl.h b/cc/layers/solid_color_scrollbar_layer_impl.h index 6aff854..2c688ed 100644 --- a/cc/layers/solid_color_scrollbar_layer_impl.h +++ b/cc/layers/solid_color_scrollbar_layer_impl.h
@@ -52,7 +52,7 @@ int thumb_thickness_; int track_start_; - SkColor color_; + SkColor4f color_; }; } // namespace cc
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/ScrollingStripStacker.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/ScrollingStripStacker.java index fd65ebb..185de18 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/ScrollingStripStacker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/ScrollingStripStacker.java
@@ -28,16 +28,16 @@ } @Override - public float computeNewTabButtonOffset(StripLayoutTab[] indexOrderedTabs, - float tabOverlapWidth, float stripLeftMargin, float stripRightMargin, float stripWidth, - float newTabButtonWidth) { + public float computeNewTabButtonOffset(StripLayoutTab[] indexOrderedTabs, float tabOverlapWidth, + float stripLeftMargin, float stripRightMargin, float stripWidth, float buttonWidth, + float touchTargetOffset) { if (CachedFeatureFlags.isEnabled(ChromeFeatureList.TAB_STRIP_IMPROVEMENTS)) { return super.computeNewTabButtonOffset(indexOrderedTabs, tabOverlapWidth, - stripLeftMargin, stripRightMargin, stripWidth, newTabButtonWidth); + stripLeftMargin, stripRightMargin, stripWidth, buttonWidth, touchTargetOffset); } return LocalizationUtils.isLayoutRtl() ? computeNewTabButtonOffsetRtl(indexOrderedTabs, tabOverlapWidth, stripRightMargin, - stripWidth, newTabButtonWidth) + stripWidth, buttonWidth) : computeNewTabButtonOffsetLtr(indexOrderedTabs, tabOverlapWidth, stripLeftMargin); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java index 0d83c26..ca533d35 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java
@@ -99,7 +99,8 @@ private static final float NEW_TAB_BUTTON_CLICK_SLOP_DP = 12.f; private static final float NEW_TAB_BUTTON_WIDTH_DP = 24.f; private static final float NEW_TAB_BUTTON_HEIGHT_DP = 24.f; - private static final float NEW_TAB_BUTTON_PADDING_DP = 12.f; + private static final float NEW_TAB_BUTTON_PADDING_DP = 24.f; + private static final float NEW_TAB_BUTTON_TOUCH_TARGET_OFFSET = 12.f; static final float FADE_FULL_OPACITY_THRESHOLD_DP = 24.f; private static final float TAB_WIDTH_SMALL = 108.f; @@ -296,6 +297,14 @@ } /** + * @return The touch target offset to be applied to the new tab button. + */ + public float getNewTabButtonTouchTargetOffset() { + boolean isRtl = LocalizationUtils.isLayoutRtl(); + return isRtl ? NEW_TAB_BUTTON_TOUCH_TARGET_OFFSET : -NEW_TAB_BUTTON_TOUCH_TARGET_OFFSET; + } + + /** * @return The brightness of background tabs in the tabstrip. */ public float getBackgroundTabBrightness() { @@ -1396,8 +1405,9 @@ } // 1. Get offset from strip stacker. - float offset = mStripStacker.computeNewTabButtonOffset(mStripTabs, - mTabOverlapWidth, mLeftMargin, mRightMargin, mWidth, mNewTabButtonWidth); + float offset = mStripStacker.computeNewTabButtonOffset(mStripTabs, mTabOverlapWidth, + mLeftMargin, mRightMargin, mWidth, mNewTabButtonWidth, + NEW_TAB_BUTTON_TOUCH_TARGET_OFFSET); // 2. Hide the new tab button if it's not visible on the screen. boolean isRtl = LocalizationUtils.isLayoutRtl();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java index 20cc65ffc..2888c6a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java
@@ -423,6 +423,13 @@ return getActiveStripLayoutHelper().getNewTabButton(); } + /** + * @return The touch target offset to be applied to the new tab button. + */ + public float getNewTabBtnTouchTargetOffset() { + return getActiveStripLayoutHelper().getNewTabButtonTouchTargetOffset(); + } + public CompositorButton getModelSelectorButton() { return mModelSelectorButton; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java index 00c550e..aa486a35 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java
@@ -25,6 +25,8 @@ import org.chromium.chrome.browser.compositor.layouts.components.CompositorButton.CompositorOnClickHandler; import org.chromium.chrome.browser.compositor.layouts.components.TintedCompositorButton; import org.chromium.chrome.browser.compositor.overlays.strip.TabLoadTracker.TabLoadTrackerCallback; +import org.chromium.chrome.browser.flags.CachedFeatureFlags; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.layouts.animation.CompositorAnimator; import org.chromium.chrome.browser.layouts.animation.FloatProperty; import org.chromium.chrome.browser.layouts.components.VirtualView; @@ -119,6 +121,7 @@ // Close button width private static final int CLOSE_BUTTON_WIDTH_DP = 36; + private static final int CLOSE_BUTTON_WIDTH_SCROLLING_STRIP_DP = 48; private int mId = Tab.INVALID_TAB_ID; @@ -613,26 +616,32 @@ } private RectF getCloseRect() { + boolean tabStripImprovementsEnabled = + CachedFeatureFlags.isEnabled(ChromeFeatureList.TAB_STRIP_IMPROVEMENTS); + int closeButtonWidth = tabStripImprovementsEnabled ? CLOSE_BUTTON_WIDTH_SCROLLING_STRIP_DP + : CLOSE_BUTTON_WIDTH_DP; if (!LocalizationUtils.isLayoutRtl()) { - mClosePlacement.left = getWidth() - CLOSE_BUTTON_WIDTH_DP; - mClosePlacement.right = mClosePlacement.left + CLOSE_BUTTON_WIDTH_DP; + mClosePlacement.left = getWidth() - closeButtonWidth; + mClosePlacement.right = mClosePlacement.left + closeButtonWidth; } else { mClosePlacement.left = 0; - mClosePlacement.right = CLOSE_BUTTON_WIDTH_DP; + mClosePlacement.right = closeButtonWidth; } mClosePlacement.top = 0; mClosePlacement.bottom = getHeight(); float xOffset = 0; - ResourceManager manager = mRenderHost.getResourceManager(); - if (manager != null) { - LayoutResource resource = - manager.getResource(AndroidResourceType.STATIC, getResourceId()); - if (resource != null) { - xOffset = LocalizationUtils.isLayoutRtl() - ? resource.getPadding().left - : -(resource.getBitmapSize().width() - resource.getPadding().right); + if (!tabStripImprovementsEnabled) { + ResourceManager manager = mRenderHost.getResourceManager(); + if (manager != null) { + LayoutResource resource = + manager.getResource(AndroidResourceType.STATIC, getResourceId()); + if (resource != null) { + xOffset = LocalizationUtils.isLayoutRtl() + ? resource.getPadding().left + : -(resource.getBitmapSize().width() - resource.getPadding().right); + } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripStacker.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripStacker.java index 63c54a59..50a1b78 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripStacker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripStacker.java
@@ -74,22 +74,23 @@ * @param stripLeftMargin The left margin of the tab strip. * @param stripRightMargin The right margin of the tab strip. * @param stripWidth The width of the tab strip. - * @param mNewTabButtonWidth The width of the new tab button. + * @param buttonWidth The width of the new tab button. + * @param touchTargetOffset Touch target offset applied to the button position. * @return The x offset for the new tab button. */ public float computeNewTabButtonOffset(StripLayoutTab[] indexOrderedTabs, float tabOverlapWidth, - float stripLeftMargin, float stripRightMargin, float stripWidth, - float mNewTabButtonWidth) { + float stripLeftMargin, float stripRightMargin, float stripWidth, float buttonWidth, + float touchTargetOffset) { return LocalizationUtils.isLayoutRtl() ? computeNewTabButtonOffsetRtl(indexOrderedTabs, stripLeftMargin, stripRightMargin, - stripWidth, mNewTabButtonWidth) + stripWidth, buttonWidth, touchTargetOffset) : computeNewTabButtonOffsetLtr(indexOrderedTabs, tabOverlapWidth, stripLeftMargin, - stripRightMargin, stripWidth); + stripRightMargin, stripWidth, touchTargetOffset); } private float computeNewTabButtonOffsetLtr(StripLayoutTab[] indexOrderedTabs, - float tabOverlapWidth, float stripLeftMargin, float stripRightMargin, - float stripWidth) { + float tabOverlapWidth, float stripLeftMargin, float stripRightMargin, float stripWidth, + float touchTargetOffset) { float rightEdge = stripLeftMargin; for (StripLayoutTab tab : indexOrderedTabs) { @@ -99,13 +100,16 @@ rightEdge = Math.min(rightEdge + tabOverlapWidth, stripWidth - stripRightMargin); + // Adjust the new tab button to be away from the tabs to account for the touch target skew. + rightEdge += touchTargetOffset; + // The draw X position for the new tab button is the rightEdge of the tab strip. return rightEdge; } private float computeNewTabButtonOffsetRtl(StripLayoutTab[] indexOrderedTabs, float stripLeftMargin, float stripRightMargin, float stripWidth, - float newTabButtonWidth) { + float newTabButtonWidth, float touchTargetOffset) { float leftEdge = stripWidth - stripRightMargin; for (StripLayoutTab tab : indexOrderedTabs) { @@ -114,6 +118,9 @@ leftEdge = Math.max(leftEdge, stripLeftMargin); + // Adjust the new tab button to be away from the tabs to account for the touch target skew. + leftEdge -= touchTargetOffset; + // The draw X position for the new tab button is the left edge of the tab strip minus // the new tab button width. return leftEdge - newTabButtonWidth;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java index c0f8dc3..46eb178 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java
@@ -128,8 +128,9 @@ TabStripSceneLayerJni.get().updateNewTabButton(mNativePtr, TabStripSceneLayer.this, newTabButton.getResourceId(), newTabButton.getX() * mDpToPx, newTabButton.getY() * mDpToPx, newTabButton.getWidth() * mDpToPx, - newTabButton.getHeight() * mDpToPx, newTabButtonVisible, newTabButton.getTint(), - newTabButton.getOpacity(), resourceManager); + newTabButton.getHeight() * mDpToPx, + layoutHelper.getNewTabBtnTouchTargetOffset() * mDpToPx, newTabButtonVisible, + newTabButton.getTint(), newTabButton.getOpacity(), resourceManager); TabStripSceneLayerJni.get().updateModelSelectorButton(mNativePtr, TabStripSceneLayer.this, modelSelectorButton.getResourceId(), modelSelectorButton.getX() * mDpToPx, @@ -208,8 +209,9 @@ void updateStripScrim(long nativeTabStripSceneLayer, TabStripSceneLayer caller, float x, float y, float width, float height, int color, float alpha); void updateNewTabButton(long nativeTabStripSceneLayer, TabStripSceneLayer caller, - int resourceId, float x, float y, float width, float height, boolean visible, - int tint, float buttonAlpha, ResourceManager resourceManager); + int resourceId, float x, float y, float width, float height, + float touchTargetOffset, boolean visible, int tint, float buttonAlpha, + ResourceManager resourceManager); void updateModelSelectorButton(long nativeTabStripSceneLayer, TabStripSceneLayer caller, int resourceId, float x, float y, float width, float height, boolean incognito, boolean visible, ResourceManager resourceManager);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/identity_disc/IdentityDiscController.java b/chrome/android/java/src/org/chromium/chrome/browser/identity_disc/IdentityDiscController.java index 0bb56898..a4d8b7b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/identity_disc/IdentityDiscController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/identity_disc/IdentityDiscController.java
@@ -29,6 +29,7 @@ import org.chromium.chrome.browser.toolbar.ButtonData.ButtonSpec; import org.chromium.chrome.browser.toolbar.ButtonDataImpl; import org.chromium.chrome.browser.toolbar.ButtonDataProvider; +import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.user_education.IPHCommandBuilder; import org.chromium.chrome.features.start_surface.StartSurfaceState; import org.chromium.components.browser_ui.settings.SettingsLauncher; @@ -113,7 +114,7 @@ new IPHCommandBuilder(mContext.getResources(), FeatureConstants.IDENTITY_DISC_FEATURE, R.string.iph_identity_disc_text, R.string.iph_identity_disc_accessibility_text), - /*isEnabled=*/true); + /*isEnabled=*/true, AdaptiveToolbarButtonVariant.UNKNOWN); } /** @@ -182,8 +183,9 @@ private static ButtonSpec buttonSpecWithDrawable(ButtonSpec buttonSpec, Drawable drawable) { if (buttonSpec.getDrawable() == drawable) return buttonSpec; return new ButtonSpec(drawable, buttonSpec.getOnClickListener(), - buttonSpec.getContentDescriptionResId(), buttonSpec.getSupportsTinting(), - buttonSpec.getIPHCommandBuilder()); + /*onLongClickListener=*/null, buttonSpec.getContentDescriptionResId(), + buttonSpec.getSupportsTinting(), buttonSpec.getIPHCommandBuilder(), + AdaptiveToolbarButtonVariant.UNKNOWN); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java b/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java index 4b190b6..846b257 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java
@@ -241,13 +241,6 @@ /* stringId = */ R.string.adaptive_toolbar_button_share_iph, /* accessibilityStringId = */ R.string.adaptive_toolbar_button_share_iph) .setHighlightParams(params); - - ButtonData.ButtonSpec currentSpec = mButtonData.getButtonSpec(); - ButtonData.ButtonSpec newSpec = new ButtonData.ButtonSpec(currentSpec.getDrawable(), - currentSpec.getOnClickListener(), currentSpec.getContentDescriptionResId(), - currentSpec.getSupportsTinting(), iphCommandBuilder, - currentSpec.getButtonVariant()); - - mButtonData.setButtonSpec(newSpec); + mButtonData.updateIPHCommandBuilder(iphCommandBuilder); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchInstrumentationBase.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchInstrumentationBase.java index ff1cc1d..7bc4878 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchInstrumentationBase.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchInstrumentationBase.java
@@ -280,7 +280,7 @@ /** * Parameter provider for enabling/disabling triggering-related Features. */ - public static class BaseFeatureParamProvider implements ParameterProvider { + public static class FeatureParamProvider implements ParameterProvider { @Override public Iterable<ParameterSet> getParameters() { return Arrays.asList(new ParameterSet().value(EnabledFeature.NONE).name("default"), @@ -325,21 +325,14 @@ /** This represents the current fully-launched configuration, with no other Features. */ protected static final ImmutableMap<String, Boolean> ENABLE_NONE = ImmutableMap.of(); - /** This is the Translations Feature addition. */ - private static final ImmutableMap<String, Boolean> ENABLE_TRANSLATIONS = - ImmutableMap.of(ChromeFeatureList.CONTEXTUAL_SEARCH_TRANSLATIONS, true); - - /** This is the privacy-neutral-engagement feature set. */ - private static final ImmutableMap<String, Boolean> ENABLE_PRIVACY_NEUTRAL = + /** This is the helper-test Feature. */ + private static final ImmutableMap<String, Boolean> ENABLE_FORCE_CAPTION = ImmutableMap.of(ChromeFeatureList.CONTEXTUAL_SEARCH_FORCE_CAPTION, true); - /** This is the privacy-neutral-engagement feature set, plus Related Searches. */ - private static final ImmutableMap<String, Boolean> - ENABLE_PRIVACY_NEUTRAL_WITH_RELATED_SEARCHES = - ImmutableMap.of(ChromeFeatureList.CONTEXTUAL_SEARCH_FORCE_CAPTION, true, - ChromeFeatureList.RELATED_SEARCHES, true, - ChromeFeatureList.RELATED_SEARCHES_IN_BAR, true, - ChromeFeatureList.RELATED_SEARCHES_UI, true); + /** This is the Related Searches Feature in the MVP configuration. */ + private static final ImmutableMap<String, Boolean> ENABLE_RELATED_SEARCHES = ImmutableMap.of( + ChromeFeatureList.RELATED_SEARCHES, true, ChromeFeatureList.RELATED_SEARCHES_IN_BAR, + true, ChromeFeatureList.RELATED_SEARCHES_UI, true); /** This is the contextual triggers feature set that alters tap to show selection handles. */ private static final ImmutableMap<String, Boolean> ENABLE_CONTEXTUAL_TRIGGERS = @@ -357,9 +350,7 @@ // Feature maps that we use for individual tests. //-------------------------------------------------------------------------------------------- protected static final ImmutableMap<String, Boolean> ENABLE_RELATED_SEARCHES_IN_BAR = - ImmutableMap.of(ChromeFeatureList.RELATED_SEARCHES, true, - ChromeFeatureList.RELATED_SEARCHES_UI, true, - ChromeFeatureList.RELATED_SEARCHES_IN_BAR, true); + ENABLE_RELATED_SEARCHES; protected ContextualSearchManager mManager; protected ContextualSearchPolicy mPolicy; @@ -399,7 +390,7 @@ // Tracks whether a long-press triggering experiment is active. private @EnabledFeature int mEnabledFeature; - @ParameterAnnotations.UseMethodParameterBefore(BaseFeatureParamProvider.class) + @ParameterAnnotations.UseMethodParameterBefore(FeatureParamProvider.class) public void setFeatureParameterForTest(@EnabledFeature int enabledFeature) { mEnabledFeature = enabledFeature; } @@ -468,14 +459,11 @@ case EnabledFeature.NONE: whichFeature = ENABLE_NONE; break; - case EnabledFeature.TRANSLATIONS: - whichFeature = ENABLE_TRANSLATIONS; - break; case EnabledFeature.PRIVACY_NEUTRAL: - whichFeature = ENABLE_PRIVACY_NEUTRAL; + whichFeature = ENABLE_FORCE_CAPTION; break; case EnabledFeature.PRIVACY_NEUTRAL_WITH_RELATED_SEARCHES: - whichFeature = ENABLE_PRIVACY_NEUTRAL_WITH_RELATED_SEARCHES; + whichFeature = ENABLE_RELATED_SEARCHES; break; case EnabledFeature.CONTEXTUAL_TRIGGERS: whichFeature = ENABLE_CONTEXTUAL_TRIGGERS;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchInstrumentationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchInstrumentationTest.java index 045e9587..d152237 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchInstrumentationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchInstrumentationTest.java
@@ -14,8 +14,6 @@ import org.junit.runner.RunWith; import org.chromium.base.test.params.ParameterAnnotations; -import org.chromium.base.test.params.ParameterProvider; -import org.chromium.base.test.params.ParameterSet; import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CommandLineFlags; @@ -27,8 +25,6 @@ import org.chromium.chrome.test.ChromeJUnit4RunnerDelegate; import org.chromium.ui.test.util.UiRestriction; -import java.util.Arrays; - /** * Tests the Contextual Search Manager using instrumentation tests. */ @@ -42,33 +38,6 @@ @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) @Batch(Batch.PER_CLASS) public class ContextualSearchInstrumentationTest extends ContextualSearchInstrumentationBase { - /** - * Parameter provider for enabling/disabling Features under development. - */ - public static class FeatureParamProvider implements ParameterProvider { - @Override - public Iterable<ParameterSet> getParameters() { - return Arrays.asList(new ParameterSet().value(EnabledFeature.NONE).name("default"), - new ParameterSet() - .value(EnabledFeature.TRANSLATIONS) - .name("enableTranslations"), - new ParameterSet() - .value(EnabledFeature.CONTEXTUAL_TRIGGERS) - .name("enableContextualTriggers"), - new ParameterSet() - .value(EnabledFeature.CONTEXTUAL_TRIGGERS_MENU) - .name("enableContextualTriggersMenu"), - new ParameterSet() - .value(EnabledFeature.PRIVACY_NEUTRAL) - .name("enablePrivacyNeutralEngagement"), - new ParameterSet() - .value(EnabledFeature.PRIVACY_NEUTRAL_WITH_RELATED_SEARCHES) - .name("enablePrivacyNeutralWithRelatedSearches")); - } - } - - // @ParameterAnnotations.UseMethodParameterBefore(BaseFeatureParamProvider.class) - @Override @Before public void setUp() throws Exception {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java index 0905989..29701ec 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java
@@ -34,8 +34,6 @@ import org.chromium.base.FeatureList; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.test.params.ParameterAnnotations; -import org.chromium.base.test.params.ParameterProvider; -import org.chromium.base.test.params.ParameterSet; import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.ApplicationTestUtils; import org.chromium.base.test.util.Batch; @@ -86,7 +84,6 @@ import org.chromium.ui.test.util.UiRestriction; import org.chromium.url.GURL; -import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -107,17 +104,6 @@ @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) @Batch(Batch.PER_CLASS) public class ContextualSearchManagerTest extends ContextualSearchInstrumentationBase { - /** Parameter provider for enabling/disabling triggering-related Features. */ - public static class FeatureParamProvider implements ParameterProvider { - @Override - public Iterable<ParameterSet> getParameters() { - return Arrays.asList(new ParameterSet().value(EnabledFeature.NONE).name("default"), - new ParameterSet() - .value(EnabledFeature.TRANSLATIONS) - .name("enableTranslations")); - } - } - // DOM element IDs in our test page based on what functions they trigger. // TODO(donnd): add more, and also the associated Search Term, or build a similar mapping. /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchObserverTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchObserverTest.java index fe2f7785..771bc4f 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchObserverTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchObserverTest.java
@@ -15,8 +15,6 @@ import org.junit.runner.RunWith; import org.chromium.base.test.params.ParameterAnnotations; -import org.chromium.base.test.params.ParameterProvider; -import org.chromium.base.test.params.ParameterSet; import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CommandLineFlags; @@ -29,8 +27,6 @@ import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.test.util.UiRestriction; -import java.util.Arrays; - /** * Tests system and application interaction with Contextual Search using instrumentation tests. */ @@ -44,31 +40,6 @@ @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) @Batch(Batch.PER_CLASS) public class ContextualSearchObserverTest extends ContextualSearchInstrumentationBase { - /** - * Parameter provider for enabling/disabling Features under development. - */ - public static class FeatureParamProvider implements ParameterProvider { - @Override - public Iterable<ParameterSet> getParameters() { - return Arrays.asList(new ParameterSet().value(EnabledFeature.NONE).name("default"), - new ParameterSet() - .value(EnabledFeature.TRANSLATIONS) - .name("enableTranslations"), - new ParameterSet() - .value(EnabledFeature.CONTEXTUAL_TRIGGERS) - .name("enableContextualTriggers"), - new ParameterSet() - .value(EnabledFeature.CONTEXTUAL_TRIGGERS_MENU) - .name("enableContextualTriggersMenu"), - new ParameterSet() - .value(EnabledFeature.PRIVACY_NEUTRAL) - .name("enablePrivacyNeutralEngagement"), - new ParameterSet() - .value(EnabledFeature.PRIVACY_NEUTRAL_WITH_RELATED_SEARCHES) - .name("enablePrivacyNeutralWithRelatedSearches")); - } - } - @Override @Before public void setUp() throws Exception { @@ -169,7 +140,7 @@ @Test @SmallTest @Feature({"ContextualSearch"}) - @ParameterAnnotations.UseMethodParameter(ContextualSearchManagerTest.FeatureParamProvider.class) + @ParameterAnnotations.UseMethodParameter(FeatureParamProvider.class) @Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) // Previously flaky and disabled 4/2021. https://crbug.com/1180304 public void testNotifyObserversAfterLongPressWithoutSurroundings(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSystemTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSystemTest.java index 8520e19..b9d38a91 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSystemTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSystemTest.java
@@ -19,8 +19,6 @@ import org.chromium.base.task.PostTask; import org.chromium.base.test.params.ParameterAnnotations; -import org.chromium.base.test.params.ParameterProvider; -import org.chromium.base.test.params.ParameterSet; import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CommandLineFlags; @@ -42,8 +40,6 @@ import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.test.util.UiRestriction; -import java.util.Arrays; - /** * Tests system and application interaction with Contextual Search using instrumentation tests. */ @@ -57,31 +53,6 @@ @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) @Batch(Batch.PER_CLASS) public class ContextualSearchSystemTest extends ContextualSearchInstrumentationBase { - /** - * Parameter provider for enabling/disabling Features under development. - */ - public static class FeatureParamProvider implements ParameterProvider { - @Override - public Iterable<ParameterSet> getParameters() { - return Arrays.asList(new ParameterSet().value(EnabledFeature.NONE).name("default"), - new ParameterSet() - .value(EnabledFeature.TRANSLATIONS) - .name("enableTranslations"), - new ParameterSet() - .value(EnabledFeature.CONTEXTUAL_TRIGGERS) - .name("enableContextualTriggers"), - new ParameterSet() - .value(EnabledFeature.CONTEXTUAL_TRIGGERS_MENU) - .name("enableContextualTriggersMenu"), - new ParameterSet() - .value(EnabledFeature.PRIVACY_NEUTRAL) - .name("enablePrivacyNeutralEngagement"), - new ParameterSet() - .value(EnabledFeature.PRIVACY_NEUTRAL_WITH_RELATED_SEARCHES) - .name("enablePrivacyNeutralWithRelatedSearches")); - } - } - @Override @Before public void setUp() throws Exception {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/OmniboxPedalsRenderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/OmniboxPedalsRenderTest.java index 40afa9c..bc5550d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/OmniboxPedalsRenderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/OmniboxPedalsRenderTest.java
@@ -52,8 +52,7 @@ * Tests of the Omnibox Pedals feature. */ @RunWith(ParameterizedRunner.class) -@CommandLineFlags. -Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, "enable-features=OmniboxPedalsAndroidBatch1"}) +@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @ParameterAnnotations.UseRunnerDelegate(ChromeJUnit4RunnerDelegate.class) @EnableFeatures(ChromeFeatureList.ENABLE_IPH) public class OmniboxPedalsRenderTest {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhoneTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhoneTest.java index a6ae829..a77e3e2 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhoneTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhoneTest.java
@@ -41,6 +41,7 @@ import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.theme.ThemeColorProvider; import org.chromium.chrome.browser.toolbar.ButtonDataImpl; +import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.toolbar.menu_button.MenuButton; import org.chromium.chrome.browser.toolbar.menu_button.MenuButtonCoordinator; import org.chromium.chrome.browser.ui.appmenu.AppMenuCoordinator; @@ -124,8 +125,8 @@ // When menu is hidden, optional button should have no padding. doReturn(false).when(mMenuButtonCoordinator).isVisible(); TestThreadUtils.runOnUiThreadBlocking(() -> { - mToolbar.updateOptionalButton( - new ButtonDataImpl(false, drawable, null, R.string.share, false, null, false)); + mToolbar.updateOptionalButton(new ButtonDataImpl(false, drawable, null, R.string.share, + false, null, false, AdaptiveToolbarButtonVariant.UNKNOWN)); mToolbar.updateButtonVisibility(); }); @@ -166,8 +167,8 @@ () -> null, () -> {}, org.chromium.chrome.R.id.menu_button_wrapper); // clang-format on mToolbar.setMenuButtonCoordinatorForTesting(realMenuButtonCoordinator); - mToolbar.updateOptionalButton( - new ButtonDataImpl(false, drawable, null, R.string.share, false, null, false)); + mToolbar.updateOptionalButton(new ButtonDataImpl(false, drawable, null, R.string.share, + false, null, false, AdaptiveToolbarButtonVariant.UNKNOWN)); // Make sure the button is visible in the beginning of the test. assertEquals(realMenuButtonCoordinator.isVisible(), true);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/top/StartSurfaceToolbarMediatorUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/top/StartSurfaceToolbarMediatorUnitTest.java index e0d74c5..f691b55 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/top/StartSurfaceToolbarMediatorUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/top/StartSurfaceToolbarMediatorUnitTest.java
@@ -65,6 +65,7 @@ import org.chromium.chrome.browser.tabmodel.TabModelSelectorObserver; import org.chromium.chrome.browser.toolbar.ButtonData.ButtonSpec; import org.chromium.chrome.browser.toolbar.ButtonDataImpl; +import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.toolbar.menu_button.MenuButtonCoordinator; import org.chromium.chrome.browser.user_education.IPHCommandBuilder; import org.chromium.chrome.browser.user_education.UserEducationHelper; @@ -146,9 +147,10 @@ .with(StartSurfaceToolbarProperties.NEW_TAB_VIEW_AT_START, false) .with(StartSurfaceToolbarProperties.NEW_TAB_VIEW_TEXT_IS_VISIBLE, false) .build(); - mButtonData = new ButtonDataImpl(false, mDrawable, mOnClickListener, 0, false, null, true); - ButtonDataImpl disabledButtonData = - new ButtonDataImpl(false, null, null, 0, false, null, true); + mButtonData = new ButtonDataImpl(false, mDrawable, mOnClickListener, 0, false, null, true, + AdaptiveToolbarButtonVariant.UNKNOWN); + ButtonDataImpl disabledButtonData = new ButtonDataImpl( + false, null, null, 0, false, null, true, AdaptiveToolbarButtonVariant.UNKNOWN); mIdentityDiscStateSupplier = new ObservableSupplierImpl<>(); mStartSurfaceAsHomepageSupplier = new ObservableSupplierImpl<>(); mStartSurfaceAsHomepageSupplier.set(true); @@ -367,9 +369,10 @@ mMediator.onStartSurfaceStateChanged(StartSurfaceState.SHOWN_HOMEPAGE, true); assertFalse(mPropertyModel.get(IDENTITY_DISC_IS_VISIBLE)); - mButtonData.setButtonSpec( - new ButtonSpec(mDrawable, mOnClickListener, /*contentDescriptionResId=*/5, - /*supportsTinting=*/false, /*iphCommandBuilder=*/null)); + mButtonData.setButtonSpec(new ButtonSpec(mDrawable, mOnClickListener, + /*onLongClickListener*/ null, /*contentDescriptionResId=*/5, + /*supportsTinting=*/false, /*iphCommandBuilder=*/null, + AdaptiveToolbarButtonVariant.UNKNOWN)); mButtonData.setCanShow(true); mMediator.updateIdentityDisc(mButtonData); assertTrue(mPropertyModel.get(IDENTITY_DISC_IS_VISIBLE)); @@ -380,9 +383,10 @@ Drawable testDrawable2 = mock(Drawable.class); doReturn(mMockConstantState).when(testDrawable2).getConstantState(); doReturn(testDrawable2).when(mMockConstantState).newDrawable(); - mButtonData.setButtonSpec( - new ButtonSpec(testDrawable2, mOnClickListener, /*contentDescriptionResId=*/5, - /*supportsTinting=*/false, /*iphCommandBuilder=*/null)); + mButtonData.setButtonSpec(new ButtonSpec(testDrawable2, mOnClickListener, + /*onLongClickListener*/ null, /*contentDescriptionResId=*/5, + /*supportsTinting=*/false, /*iphCommandBuilder=*/null, + AdaptiveToolbarButtonVariant.UNKNOWN)); mMediator.updateIdentityDisc(mButtonData); assertEquals(testDrawable2, mPropertyModel.get(IDENTITY_DISC_IMAGE)); @@ -419,9 +423,10 @@ IPHCommandBuilder iphCommandBuilder = new IPHCommandBuilder(mMockResources, "IdentityDisc", 0, 0) .setOnDismissCallback(mDismissedCallback); - mButtonData.setButtonSpec( - new ButtonSpec(mDrawable, mOnClickListener, /*contentDescriptionResId=*/0, - /*supportsTinting=*/false, /*iphCommandBuilder=*/iphCommandBuilder)); + mButtonData.setButtonSpec(new ButtonSpec(mDrawable, mOnClickListener, + /*onLongClickListener*/ null, /*contentDescriptionResId=*/0, + /*supportsTinting=*/false, /*iphCommandBuilder=*/iphCommandBuilder, + AdaptiveToolbarButtonVariant.UNKNOWN)); mMediator.updateIdentityDisc(mButtonData); assertTrue(mPropertyModel.get(IDENTITY_DISC_IS_VISIBLE)); @@ -499,9 +504,10 @@ // Identity disc should be shown at start on homepage. assertFalse(mPropertyModel.get(IDENTITY_DISC_IS_VISIBLE)); mButtonData.setCanShow(true); - mButtonData.setButtonSpec( - new ButtonSpec(mDrawable, mOnClickListener, /*contentDescriptionResId=*/5, - /*supportsTinting=*/false, /*iphCommandBuilder=*/null)); + mButtonData.setButtonSpec(new ButtonSpec(mDrawable, mOnClickListener, + /*onLongClickListener*/ null, /*contentDescriptionResId=*/5, + /*supportsTinting=*/false, /*iphCommandBuilder=*/null, + AdaptiveToolbarButtonVariant.UNKNOWN)); mMediator.updateIdentityDisc(mButtonData); assertTrue(mPropertyModel.get(IDENTITY_DISC_IS_VISIBLE)); assertTrue(mPropertyModel.get(IDENTITY_DISC_AT_START));
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index f403161..56d7b5e 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -5254,6 +5254,10 @@ "chromeos/app_mode/startup_app_launcher_update_checker.h", "chromeos/extensions/echo_private/echo_private_api.cc", "chromeos/extensions/echo_private/echo_private_api.h", + "chromeos/extensions/file_system_provider/file_system_provider_api.cc", + "chromeos/extensions/file_system_provider/file_system_provider_api.h", + "chromeos/extensions/file_system_provider/provider_function.cc", + "chromeos/extensions/file_system_provider/provider_function.h", "chromeos/extensions/info_private_api.cc", "chromeos/extensions/info_private_api.h", "chromeos/extensions/public_session_permission_helper.cc", @@ -5446,6 +5450,7 @@ deps += [ ":dlp_policy_event_proto", "//chrome/browser/chromeos/extensions/login_screen", + "//chrome/common/chromeos/extensions", "//chromeos/crosapi/cpp", "//chromeos/crosapi/cpp:crosapi_constants", "//chromeos/crosapi/mojom",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 4152141a7b..4e2f334 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -5046,10 +5046,6 @@ flag_descriptions::kOmniboxMostVisitedTilesName, flag_descriptions::kOmniboxMostVisitedTilesDescription, kOsAndroid, FEATURE_VALUE_TYPE(omnibox::kMostVisitedTiles)}, - {"omnibox-pedals-android-batch1", - flag_descriptions::kOmniboxPedalsAndroidBatch1Name, - flag_descriptions::kOmniboxPedalsAndroidBatch1Description, kOsAndroid, - FEATURE_VALUE_TYPE(omnibox::kOmniboxPedalsAndroidBatch1)}, #endif // BUILDFLAG(IS_ANDROID) {"omnibox-on-focus-suggestions-contextual-web",
diff --git a/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.cc b/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.cc index 267274e..27870f8 100644 --- a/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.cc +++ b/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.cc
@@ -180,6 +180,7 @@ jfloat y, jfloat width, jfloat height, + jfloat touch_target_offset, jboolean visible, jint tint, jfloat button_alpha, @@ -192,6 +193,10 @@ new_tab_button_->SetUIResourceId(button_resource->ui_resource()->id()); float left_offset = (width - button_resource->size().width()) / 2; float top_offset = (height - button_resource->size().height()) / 2; + // The touch target for the new tab button is skewed towards the end of the + // strip. This ensures that the view itself is correctly aligned without + // adjusting the touch target. + left_offset += touch_target_offset; new_tab_button_->SetPosition(gfx::PointF(x + left_offset, y + top_offset)); new_tab_button_->SetBounds(button_resource->size()); new_tab_button_->SetHideLayerAndSubtree(!visible);
diff --git a/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.h b/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.h index 50bfdbb8..d99a882 100644 --- a/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.h +++ b/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.h
@@ -74,6 +74,7 @@ jfloat y, jfloat width, jfloat height, + jfloat touch_target_offset, jboolean visible, jint tint, jfloat button_alpha,
diff --git a/chrome/browser/apps/platform_apps/api/BUILD.gn b/chrome/browser/apps/platform_apps/api/BUILD.gn index 4faa6e2..faf1ff5c 100644 --- a/chrome/browser/apps/platform_apps/api/BUILD.gn +++ b/chrome/browser/apps/platform_apps/api/BUILD.gn
@@ -29,6 +29,8 @@ "browser/browser_api.h", "browser_context_keyed_service_factories.cc", "browser_context_keyed_service_factories.h", + "deprecation_features.cc", + "deprecation_features.h", "media_galleries/blob_data_source_factory.cc", "media_galleries/blob_data_source_factory.h", "media_galleries/media_galleries_api.cc",
diff --git a/chrome/browser/apps/platform_apps/api/deprecation_features.cc b/chrome/browser/apps/platform_apps/api/deprecation_features.cc new file mode 100644 index 0000000..4b75381 --- /dev/null +++ b/chrome/browser/apps/platform_apps/api/deprecation_features.cc
@@ -0,0 +1,13 @@ +// Copyright 2022 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/apps/platform_apps/api/deprecation_features.h" + +namespace chrome_apps::features { + +// Deprecates the Media Galleries Chrome App APIs. +const base::Feature kDeprecateMediaGalleriesApis = { + "DeprecateMediaGalleriesApis", base::FEATURE_DISABLED_BY_DEFAULT}; + +} // namespace chrome_apps::features
diff --git a/chrome/browser/apps/platform_apps/api/deprecation_features.h b/chrome/browser/apps/platform_apps/api/deprecation_features.h new file mode 100644 index 0000000..3e265ed --- /dev/null +++ b/chrome/browser/apps/platform_apps/api/deprecation_features.h
@@ -0,0 +1,16 @@ +// Copyright 2022 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_APPS_PLATFORM_APPS_API_DEPRECATION_FEATURES_H_ +#define CHROME_BROWSER_APPS_PLATFORM_APPS_API_DEPRECATION_FEATURES_H_ + +#include "base/feature_list.h" + +namespace chrome_apps::features { + +extern const base::Feature kDeprecateMediaGalleriesApis; + +} // namespace chrome_apps::features + +#endif // CHROME_BROWSER_APPS_PLATFORM_APPS_API_DEPRECATION_FEATURES_H_
diff --git a/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_api.cc b/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_api.cc index 510fe42..4388e99 100644 --- a/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_api.cc +++ b/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_api.cc
@@ -24,6 +24,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "chrome/browser/apps/platform_apps/api/deprecation_features.h" #include "chrome/browser/apps/platform_apps/api/media_galleries/blob_data_source_factory.h" #include "chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_api_util.h" #include "chrome/browser/browser_process.h" @@ -99,6 +100,8 @@ const char kInvalidGalleryId[] = "-1"; +const char kDeprecatedError[] = + "Media Galleries API is deprecated on this platform."; const char kNoRenderFrameOrRenderProcessError[] = "No render frame or render process."; const char kNoWebContentsError[] = "Could not find web contents."; @@ -394,6 +397,10 @@ ExtensionFunction::ResponseAction MediaGalleriesGetMediaFileSystemsFunction::Run() { ::media_galleries::UsageCount(::media_galleries::GET_MEDIA_FILE_SYSTEMS); + + if (base::FeatureList::IsEnabled(features::kDeprecateMediaGalleriesApis)) + return RespondNow(Error(kDeprecatedError)); + std::unique_ptr<GetMediaFileSystems::Params> params( GetMediaFileSystems::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); @@ -513,6 +520,10 @@ ExtensionFunction::ResponseAction MediaGalleriesAddUserSelectedFolderFunction::Run() { ::media_galleries::UsageCount(::media_galleries::ADD_USER_SELECTED_FOLDER); + + if (base::FeatureList::IsEnabled(features::kDeprecateMediaGalleriesApis)) + return RespondNow(Error(kDeprecatedError)); + std::string error; const bool result = Setup(Profile::FromBrowserContext(browser_context()), &error, @@ -622,6 +633,10 @@ ExtensionFunction::ResponseAction MediaGalleriesGetMetadataFunction::Run() { ::media_galleries::UsageCount(::media_galleries::GET_METADATA); + + if (base::FeatureList::IsEnabled(features::kDeprecateMediaGalleriesApis)) + return RespondNow(Error(kDeprecatedError)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 1); EXTENSION_FUNCTION_VALIDATE(args()[0].is_string()); const std::string& blob_uuid = args()[0].GetString(); @@ -809,8 +824,13 @@ ExtensionFunction::ResponseAction MediaGalleriesAddGalleryWatchFunction::Run() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + if (base::FeatureList::IsEnabled(features::kDeprecateMediaGalleriesApis)) + return RespondNow(Error(kDeprecatedError)); + Profile* profile = Profile::FromBrowserContext(browser_context()); DCHECK(profile); + if (!render_frame_host() || !render_frame_host()->GetProcess()) return RespondNow(Error(kNoRenderFrameOrRenderProcessError)); @@ -884,6 +904,10 @@ ExtensionFunction::ResponseAction MediaGalleriesRemoveGalleryWatchFunction::Run() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + if (base::FeatureList::IsEnabled(features::kDeprecateMediaGalleriesApis)) + return RespondNow(Error(kDeprecatedError)); + if (!render_frame_host() || !render_frame_host()->GetProcess()) return RespondNow(Error(kNoRenderFrameOrRenderProcessError));
diff --git a/chrome/browser/ash/crosapi/crosapi_util.cc b/chrome/browser/ash/crosapi/crosapi_util.cc index eff44879..fb3fbebf 100644 --- a/chrome/browser/ash/crosapi/crosapi_util.cc +++ b/chrome/browser/ash/crosapi/crosapi_util.cc
@@ -120,6 +120,8 @@ // Capability to support reloading the lacros browser on receiving a // notification that the browser component was successfully updated. constexpr char kBrowserManagerReloadBrowserCapability[] = "crbug/1237235"; +// Capability to support shared_storage in prefs. +constexpr char kSharedStoragePrefsCapability[] = "b/231890240"; // Returns the vector containing policy data of the device account. In case of // an error, returns nullopt. @@ -460,7 +462,8 @@ ash::features:: IsHoldingSpaceInProgressDownloadsNotificationSuppressionEnabled(); - params->ash_capabilities = {{kBrowserManagerReloadBrowserCapability}}; + params->ash_capabilities = { + {kBrowserManagerReloadBrowserCapability, kSharedStoragePrefsCapability}}; params->is_device_enterprised_managed = ash::InstallAttributes::Get()->IsEnterpriseManaged();
diff --git a/chrome/browser/ash/crosapi/file_system_provider_service_ash.cc b/chrome/browser/ash/crosapi/file_system_provider_service_ash.cc index 4c21d73..a912487 100644 --- a/chrome/browser/ash/crosapi/file_system_provider_service_ash.cc +++ b/chrome/browser/ash/crosapi/file_system_provider_service_ash.cc
@@ -252,6 +252,52 @@ ProfileManager::GetPrimaryUserProfile()); } +void FileSystemProviderServiceAsh::ExtensionLoaded( + bool configurable, + bool watchable, + bool multiple_mounts, + mojom::FileSystemSource source, + const std::string& name, + const std::string& id) { + Service* const service = + Service::Get(ProfileManager::GetPrimaryUserProfile()); + DCHECK(service); + + ProviderId provider_id = ProviderId::CreateFromExtensionId(id); + extensions::FileSystemProviderSource extension_source; + switch (source) { + case crosapi::mojom::FileSystemSource::kFile: + extension_source = extensions::FileSystemProviderSource::SOURCE_FILE; + break; + case crosapi::mojom::FileSystemSource::kNetwork: + extension_source = extensions::FileSystemProviderSource::SOURCE_NETWORK; + break; + case crosapi::mojom::FileSystemSource::kDevice: + extension_source = extensions::FileSystemProviderSource::SOURCE_DEVICE; + break; + } + ash::file_system_provider::Capabilities capabilities{ + configurable, watchable, multiple_mounts, extension_source}; + auto provider = + std::make_unique<ash::file_system_provider::ExtensionProvider>( + ProfileManager::GetPrimaryUserProfile(), std::move(provider_id), + std::move(capabilities), name); + service->RegisterProvider(std::move(provider)); +} + +void FileSystemProviderServiceAsh::ExtensionUnloaded(const std::string& id, + bool due_to_shutdown) { + Service* const service = + Service::Get(ProfileManager::GetPrimaryUserProfile()); + DCHECK(service); + ProviderId provider_id = ProviderId::CreateFromExtensionId(id); + service->UnregisterProvider( + provider_id, + due_to_shutdown + ? ash::file_system_provider::Service::UNMOUNT_REASON_SHUTDOWN + : ash::file_system_provider::Service::UNMOUNT_REASON_USER); +} + void FileSystemProviderServiceAsh::MountWithProfile( mojom::FileSystemMetadataPtr metadata, bool persistent,
diff --git a/chrome/browser/ash/crosapi/file_system_provider_service_ash.h b/chrome/browser/ash/crosapi/file_system_provider_service_ash.h index 6069d7a..74f97dd 100644 --- a/chrome/browser/ash/crosapi/file_system_provider_service_ash.h +++ b/chrome/browser/ash/crosapi/file_system_provider_service_ash.h
@@ -50,6 +50,13 @@ int64_t request_id, std::vector<base::Value> args, OperationFinishedCallback callback) override; + void ExtensionLoaded(bool configurable, + bool watchable, + bool multiple_mounts, + mojom::FileSystemSource source, + const std::string& name, + const std::string& id) override; + void ExtensionUnloaded(const std::string& id, bool due_to_shutdown) override; // In order to support multi-login in ash, a legacy feature that is going // away in Lacros, all methods above are redirected to a variation that
diff --git a/chrome/browser/ash/crosapi/prefs_ash.cc b/chrome/browser/ash/crosapi/prefs_ash.cc index 5ddec3b..ceb9d5e 100644 --- a/chrome/browser/ash/crosapi/prefs_ash.cc +++ b/chrome/browser/ash/crosapi/prefs_ash.cc
@@ -29,27 +29,29 @@ // corresponding paths in the prefstore. Initialized on first use. const std::string& GetProfilePrefNameForPref(mojom::PrefPath path) { static base::NoDestructor<std::map<mojom::PrefPath, std::string>> - profile_prefpath_to_name( - {{mojom::PrefPath::kAccessibilitySpokenFeedbackEnabled, - ash::prefs::kAccessibilitySpokenFeedbackEnabled}, - {mojom::PrefPath::kQuickAnswersEnabled, - quick_answers::prefs::kQuickAnswersEnabled}, - {mojom::PrefPath::kQuickAnswersConsentStatus, - quick_answers::prefs::kQuickAnswersConsentStatus}, - {mojom::PrefPath::kQuickAnswersDefinitionEnabled, - quick_answers::prefs::kQuickAnswersDefinitionEnabled}, - {mojom::PrefPath::kQuickAnswersTranslationEnabled, - quick_answers::prefs::kQuickAnswersTranslationEnabled}, - {mojom::PrefPath::kQuickAnswersUnitConversionEnabled, - quick_answers::prefs::kQuickAnswersUnitConversionEnabled}, - {mojom::PrefPath::kQuickAnswersNoticeImpressionCount, - quick_answers::prefs::kQuickAnswersNoticeImpressionCount}, - {mojom::PrefPath::kQuickAnswersNoticeImpressionDuration, - quick_answers::prefs::kQuickAnswersNoticeImpressionDuration}, - {mojom::PrefPath::kPreferredLanguages, - language::prefs::kPreferredLanguages}, - {mojom::PrefPath::kApplicationLocale, - language::prefs::kApplicationLocale}}); + profile_prefpath_to_name({ + {mojom::PrefPath::kAccessibilitySpokenFeedbackEnabled, + ash::prefs::kAccessibilitySpokenFeedbackEnabled}, + {mojom::PrefPath::kQuickAnswersEnabled, + quick_answers::prefs::kQuickAnswersEnabled}, + {mojom::PrefPath::kQuickAnswersConsentStatus, + quick_answers::prefs::kQuickAnswersConsentStatus}, + {mojom::PrefPath::kQuickAnswersDefinitionEnabled, + quick_answers::prefs::kQuickAnswersDefinitionEnabled}, + {mojom::PrefPath::kQuickAnswersTranslationEnabled, + quick_answers::prefs::kQuickAnswersTranslationEnabled}, + {mojom::PrefPath::kQuickAnswersUnitConversionEnabled, + quick_answers::prefs::kQuickAnswersUnitConversionEnabled}, + {mojom::PrefPath::kQuickAnswersNoticeImpressionCount, + quick_answers::prefs::kQuickAnswersNoticeImpressionCount}, + {mojom::PrefPath::kQuickAnswersNoticeImpressionDuration, + quick_answers::prefs::kQuickAnswersNoticeImpressionDuration}, + {mojom::PrefPath::kPreferredLanguages, + language::prefs::kPreferredLanguages}, + {mojom::PrefPath::kApplicationLocale, + language::prefs::kApplicationLocale}, + {mojom::PrefPath::kSharedStorage, prefs::kSharedStorage}, + }); auto pref_name = profile_prefpath_to_name->find(path); DCHECK(pref_name != profile_prefpath_to_name->end()); return pref_name->second; @@ -252,6 +254,9 @@ absl::optional<PrefsAsh::State> PrefsAsh::GetState(mojom::PrefPath path) { switch (path) { + case mojom::PrefPath::kUnknown: + LOG(WARNING) << "Unknown pref path: " << path; + return absl::nullopt; case mojom::PrefPath::kMetricsReportingEnabled: return State{local_state_, &local_state_registrar_, false, metrics::prefs::kMetricsReportingEnabled}; @@ -264,7 +269,8 @@ case mojom::PrefPath::kQuickAnswersNoticeImpressionCount: case mojom::PrefPath::kQuickAnswersNoticeImpressionDuration: case mojom::PrefPath::kPreferredLanguages: - case mojom::PrefPath::kApplicationLocale: { + case mojom::PrefPath::kApplicationLocale: + case mojom::PrefPath::kSharedStorage: { if (!profile_prefs_registrar_) { LOG(WARNING) << "Primary profile is not yet initialized"; return absl::nullopt; @@ -304,9 +310,6 @@ std::string pref_name = GetExtensionPrefNameForPref(path); return State{profile_prefs_registrar_->prefs(), nullptr, true, pref_name}; } - default: - LOG(WARNING) << "Unknown pref path: " << path; - return absl::nullopt; } }
diff --git a/chrome/browser/ash/file_system_provider/extension_provider.cc b/chrome/browser/ash/file_system_provider/extension_provider.cc index 6163e6ce..41d8c8d 100644 --- a/chrome/browser/ash/file_system_provider/extension_provider.cc +++ b/chrome/browser/ash/file_system_provider/extension_provider.cc
@@ -126,7 +126,22 @@ capabilities_.multiple_mounts = info.capabilities.multiple_mounts(); capabilities_.source = info.capabilities.source(); name_ = info.name; + ObserveAppServiceForIcons(profile); +} +ExtensionProvider::ExtensionProvider(Profile* profile, + ProviderId id, + Capabilities capabilities, + std::string name) + : provider_id_(std::move(id)), + capabilities_(std::move(capabilities)), + name_(std::move(name)) { + ObserveAppServiceForIcons(profile); +} + +ExtensionProvider::~ExtensionProvider() = default; + +void ExtensionProvider::ObserveAppServiceForIcons(Profile* profile) { if (apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)) { auto* AppServiceProxy = apps::AppServiceProxyFactory::GetForProfile(profile); @@ -156,8 +171,6 @@ provider_id_.GetExtensionId() + "/32/1")); } -ExtensionProvider::~ExtensionProvider() = default; - void ExtensionProvider::OnAppUpdate(const apps::AppUpdate& update) { if (update.AppId() != provider_id_.GetExtensionId() || !update.IconKeyChanged()) {
diff --git a/chrome/browser/ash/file_system_provider/extension_provider.h b/chrome/browser/ash/file_system_provider/extension_provider.h index 70cf0d9..3a66a5b13 100644 --- a/chrome/browser/ash/file_system_provider/extension_provider.h +++ b/chrome/browser/ash/file_system_provider/extension_provider.h
@@ -40,6 +40,11 @@ ExtensionProvider(Profile* profile, const extensions::ExtensionId& extension_id, const ProvidingExtensionInfo& info); + ExtensionProvider(Profile* profile, + ProviderId id, + Capabilities capabilities, + std::string name); + ~ExtensionProvider() override; // Returns a provider instance for the specified extension. If the extension @@ -59,6 +64,10 @@ bool RequestMount(Profile* profile) override; private: + // This method is only partially functional since non-app extensions are not + // registered with the app service. + void ObserveAppServiceForIcons(Profile* profile); + // apps::AppRegistryCache::Observer overrides: void OnAppUpdate(const apps::AppUpdate& update) override; void OnAppRegistryCacheWillBeDestroyed(
diff --git a/chrome/browser/ash/file_system_provider/operations/operation.cc b/chrome/browser/ash/file_system_provider/operations/operation.cc index 45dbe3c..69f7572f 100644 --- a/chrome/browser/ash/file_system_provider/operations/operation.cc +++ b/chrome/browser/ash/file_system_provider/operations/operation.cc
@@ -11,6 +11,8 @@ #include "chrome/browser/ash/crosapi/crosapi_manager.h" #include "chrome/browser/ash/crosapi/file_system_provider_service_ash.h" #include "chrome/browser/ash/file_system_provider/provided_file_system_info.h" +#include "chrome/browser/ash/file_system_provider/service.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chromeos/crosapi/mojom/file_system_provider.mojom.h" #include "extensions/browser/event_router.h" #include "extensions/common/extension_id.h" @@ -20,10 +22,36 @@ namespace operations { namespace { +// This method is only used when Lacros is enabled. It's a callback from Lacros +// indicating whether the operation was successfully forwarded. If the operation +// could not be forwarded then the file system request manager must be informed. +void OperationForwarded(ash::file_system_provider::ProviderId provider_id, + const std::string& file_system_id, + int request_id, + bool delivery_failure) { + using ash::file_system_provider::Service; + // Successful deliveries will go through the FileSystemProvider mojom path. + if (!delivery_failure) + return; + // When Lacros is enabled the primary profile is the only profile. + Service* const service = + Service::Get(ProfileManager::GetPrimaryUserProfile()); + DCHECK(service); + ProvidedFileSystemInterface* const file_system = + service->GetProvidedFileSystem(provider_id, file_system_id); + if (!file_system) + return; + file_system->GetRequestManager()->DestroyRequest(request_id); +} + // Default implementation for dispatching an event. Can be replaced for unit // tests by Operation::SetDispatchEventImplForTest(). bool DispatchEventImpl(extensions::EventRouter* event_router, const extensions::ExtensionId& extension_id, + ProviderId provider_id, + const std::string& file_system_id, + int request_id, + extensions::events::HistogramValue histogram_value, const std::string& event_name, std::vector<base::Value> event_args) { @@ -36,15 +64,19 @@ return true; } - // If there are any Lacros remotes, forward the message. + // If there are any Lacros remotes, forward the message to the first one. This + // does not support multiple remotes. auto& remotes = crosapi::CrosapiManager::Get() ->crosapi_ash() ->file_system_provider_service_ash() ->remotes(); - for (auto& remote : remotes) { - remote->ForwardOperation(extension_id, - static_cast<int32_t>(histogram_value), event_name, - std::move(event_args)); + if (!remotes.empty()) { + auto remote = remotes.begin(); + auto callback = base::BindOnce(&OperationForwarded, provider_id, + file_system_id, request_id); + (*remote)->ForwardOperation( + extension_id, static_cast<int32_t>(histogram_value), event_name, + std::move(event_args), std::move(callback)); } return !remotes.empty(); } @@ -65,7 +97,8 @@ void Operation::SetDispatchEventImplForTesting( const DispatchEventImplCallback& callback) { auto wrapped_callback = base::BindRepeating( - [](const DispatchEventImplCallback& callback, + [](const DispatchEventImplCallback& callback, ProviderId provider_id, + const std::string& file_system_id, int request_id, extensions::events::HistogramValue histogram_value, const std::string& event_name, std::vector<base::Value> event_args) { auto event = std::make_unique<extensions::Event>( @@ -80,8 +113,9 @@ extensions::events::HistogramValue histogram_value, const std::string& event_name, std::vector<base::Value> event_args) { - return dispatch_event_impl_.Run(histogram_value, event_name, - std::move(event_args)); + return dispatch_event_impl_.Run( + file_system_info_.provider_id(), file_system_info_.file_system_id(), + request_id, histogram_value, event_name, std::move(event_args)); } } // namespace operations
diff --git a/chrome/browser/ash/file_system_provider/operations/operation.h b/chrome/browser/ash/file_system_provider/operations/operation.h index ac1fc72..95ab7a0 100644 --- a/chrome/browser/ash/file_system_provider/operations/operation.h +++ b/chrome/browser/ash/file_system_provider/operations/operation.h
@@ -64,7 +64,10 @@ private: using DispatchEventInternalCallback = - base::RepeatingCallback<bool(extensions::events::HistogramValue, + base::RepeatingCallback<bool(ProviderId provider_id, + const std::string& file_system_id, + int request_id, + extensions::events::HistogramValue, const std::string&, std::vector<base::Value>)>; DispatchEventInternalCallback dispatch_event_impl_;
diff --git a/chrome/browser/ash/file_system_provider/request_manager.h b/chrome/browser/ash/file_system_provider/request_manager.h index 2853e2a..3cade52 100644 --- a/chrome/browser/ash/file_system_provider/request_manager.h +++ b/chrome/browser/ash/file_system_provider/request_manager.h
@@ -148,6 +148,9 @@ void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); + // Destroys the request with the passed |request_id|. + void DestroyRequest(int request_id); + private: struct Request { Request(); @@ -164,9 +167,6 @@ std::unique_ptr<HandlerInterface> handler; }; - // Destroys the request with the passed |request_id|. - void DestroyRequest(int request_id); - // Called when a request with |request_id| timeouts. void OnRequestTimeout(int request_id);
diff --git a/chrome/browser/ash/wallpaper_handlers/mock_wallpaper_handlers.cc b/chrome/browser/ash/wallpaper_handlers/mock_wallpaper_handlers.cc index 262a4a6..8b6feed 100644 --- a/chrome/browser/ash/wallpaper_handlers/mock_wallpaper_handlers.cc +++ b/chrome/browser/ash/wallpaper_handlers/mock_wallpaper_handlers.cc
@@ -77,7 +77,7 @@ .WillByDefault( [](const absl::optional<std::string>& item_id, const absl::optional<std::string>& album_id, - const absl::optional<std::string>& resume_token, + const absl::optional<std::string>& resume_token, bool shuffle, base::OnceCallback<void(GooglePhotosPhotosCbkArgs)> callback) { auto response = FetchGooglePhotosPhotosResponse::New( std::vector<GooglePhotosPhotoPtr>(), absl::nullopt);
diff --git a/chrome/browser/ash/wallpaper_handlers/mock_wallpaper_handlers.h b/chrome/browser/ash/wallpaper_handlers/mock_wallpaper_handlers.h index fc26d910..535451f6 100644 --- a/chrome/browser/ash/wallpaper_handlers/mock_wallpaper_handlers.h +++ b/chrome/browser/ash/wallpaper_handlers/mock_wallpaper_handlers.h
@@ -89,6 +89,7 @@ (const absl::optional<std::string>& item_id, const absl::optional<std::string>& album_id, const absl::optional<std::string>& resume_token, + bool shuffle, base::OnceCallback<void(GooglePhotosPhotosCbkArgs)> callback), (override));
diff --git a/chrome/browser/ash/wallpaper_handlers/wallpaper_handlers.cc b/chrome/browser/ash/wallpaper_handlers/wallpaper_handlers.cc index 157788f0..67f9502 100644 --- a/chrome/browser/ash/wallpaper_handlers/wallpaper_handlers.cc +++ b/chrome/browser/ash/wallpaper_handlers/wallpaper_handlers.cc
@@ -79,6 +79,11 @@ "https://photosfirstparty-pa.googleapis.com/v1/chromeos/" "collectionById:read"; +// The collectionById endpoint accepts a "return_order" parameter that +// determines what order the photos are returned in, using these values. +constexpr char kGooglePhotosAlbumCollectionOrder[] = "1"; +constexpr char kGooglePhotosAlbumShuffledOrder[] = "2"; + // The URL to download the albums in a user's Google Photos library. constexpr char kGooglePhotosAlbumsUrl[] = "https://photosfirstparty-pa.googleapis.com/v1/chromeos/" @@ -831,16 +836,22 @@ const absl::optional<std::string>& item_id, const absl::optional<std::string>& album_id, const absl::optional<std::string>& resume_token, + bool shuffle, base::OnceCallback<void(GooglePhotosPhotosCbkArgs)> callback) { GURL service_url; if (item_id.has_value()) { - DCHECK(!album_id.has_value() && !resume_token.has_value()); + DCHECK(!album_id.has_value() && !resume_token.has_value() && !shuffle); service_url = net::AppendQueryParameter(GURL(kGooglePhotosPhotoUrl), "item_id", item_id.value()); } else if (album_id.has_value()) { service_url = net::AppendQueryParameter(GURL(kGooglePhotosAlbumUrl), "collection_id", album_id.value()); + service_url = + net::AppendQueryParameter(service_url, "return_order", + shuffle ? kGooglePhotosAlbumShuffledOrder + : kGooglePhotosAlbumCollectionOrder); } else { + DCHECK(!shuffle); service_url = GURL(kGooglePhotosPhotosUrl); }
diff --git a/chrome/browser/ash/wallpaper_handlers/wallpaper_handlers.h b/chrome/browser/ash/wallpaper_handlers/wallpaper_handlers.h index da67df1..e0ee879c 100644 --- a/chrome/browser/ash/wallpaper_handlers/wallpaper_handlers.h +++ b/chrome/browser/ash/wallpaper_handlers/wallpaper_handlers.h
@@ -283,6 +283,7 @@ const absl::optional<std::string>& item_id, const absl::optional<std::string>& album_id, const absl::optional<std::string>& resume_token, + bool shuffle, base::OnceCallback<void(GooglePhotosPhotosCbkArgs)> callback); protected:
diff --git a/chrome/browser/ash/web_applications/personalization_app/personalization_app_wallpaper_provider_impl.cc b/chrome/browser/ash/web_applications/personalization_app/personalization_app_wallpaper_provider_impl.cc index cd7b9b9..8cf3ca2 100644 --- a/chrome/browser/ash/web_applications/personalization_app/personalization_app_wallpaper_provider_impl.cc +++ b/chrome/browser/ash/web_applications/personalization_app/personalization_app_wallpaper_provider_impl.cc
@@ -281,7 +281,7 @@ profile_); } google_photos_photos_fetcher_->AddRequestAndStartIfNecessary( - item_id, album_id, resume_token, std::move(callback)); + item_id, album_id, resume_token, /*shuffle=*/false, std::move(callback)); } void PersonalizationAppWallpaperProviderImpl::GetDefaultImageThumbnail(
diff --git a/chrome/browser/ash/web_applications/personalization_app/personalization_app_wallpaper_provider_impl_unittest.cc b/chrome/browser/ash/web_applications/personalization_app/personalization_app_wallpaper_provider_impl_unittest.cc index 0001146..9f3e473b 100644 --- a/chrome/browser/ash/web_applications/personalization_app/personalization_app_wallpaper_provider_impl_unittest.cc +++ b/chrome/browser/ash/web_applications/personalization_app/personalization_app_wallpaper_provider_impl_unittest.cc
@@ -593,7 +593,7 @@ EXPECT_CALL(*google_photos_photos_fetcher, AddRequestAndStartIfNecessary( absl::make_optional(item_id), absl::make_optional(album_id), - absl::make_optional(kResumeToken), ::testing::_)) + absl::make_optional(kResumeToken), false, ::testing::_)) .Times(GooglePhotosEnabled() ? kNumFetches : 0); // Test fetching Google Photos photos before fetching the enterprise setting.
diff --git a/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.cc b/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.cc index 13221a8..2f0a109 100644 --- a/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.cc +++ b/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.cc
@@ -40,6 +40,8 @@ namespace extensions { namespace { +constexpr const char kInterfaceUnavailable[] = "interface unavailable"; + api::file_system_provider::FileSystemInfo ConvertFileSystemInfoMojomToExtension( crosapi::mojom::FileSystemInfoPtr info) { using api::file_system_provider::OpenedFile; @@ -126,6 +128,22 @@ } } +#if BUILDFLAG(IS_CHROMEOS_LACROS) +bool FileSystemProviderBase::InterfaceAvailable() { + auto* service = chromeos::LacrosService::Get(); + return service->GetInterfaceVersion( + crosapi::mojom::FileSystemProviderService::Uuid_) >= + int{crosapi::mojom::FileSystemProviderService::MethodMinVersions:: + kOperationFinishedMinVersion}; +} + +mojo::Remote<crosapi::mojom::FileSystemProviderService>& +FileSystemProviderBase::GetRemote() { + auto* service = chromeos::LacrosService::Get(); + return service->GetRemote<crosapi::mojom::FileSystemProviderService>(); +} +#endif + ExtensionFunction::ResponseAction FileSystemProviderMountFunction::Run() { using api::file_system_provider::Mount::Params; const std::unique_ptr<Params> params(Params::Create(args())); @@ -169,11 +187,18 @@ auto callback = base::BindOnce(&FileSystemProviderMountFunction::RespondWithError, this); +#if BUILDFLAG(IS_CHROMEOS_ASH) crosapi::CrosapiManager::Get() ->crosapi_ash() ->file_system_provider_service_ash() ->MountWithProfile(std::move(metadata), persistent, std::move(callback), Profile::FromBrowserContext(browser_context())); +#else + if (!InterfaceAvailable()) + return RespondNow(Error(kInterfaceUnavailable)); + GetRemote()->Mount(std::move(metadata), persistent, std::move(callback)); + +#endif return RespondLater(); } @@ -187,22 +212,34 @@ id->id = params->options.file_system_id; auto callback = base::BindOnce( &FileSystemProviderUnmountFunction::RespondWithError, this); +#if BUILDFLAG(IS_CHROMEOS_ASH) crosapi::CrosapiManager::Get() ->crosapi_ash() ->file_system_provider_service_ash() ->UnmountWithProfile(std::move(id), std::move(callback), Profile::FromBrowserContext(browser_context())); +#else + if (!InterfaceAvailable()) + return RespondNow(Error(kInterfaceUnavailable)); + GetRemote()->Unmount(std::move(id), std::move(callback)); +#endif return RespondLater(); } ExtensionFunction::ResponseAction FileSystemProviderGetAllFunction::Run() { auto callback = base::BindOnce(&FileSystemProviderGetAllFunction::RespondWithInfos, this); +#if BUILDFLAG(IS_CHROMEOS_ASH) crosapi::CrosapiManager::Get() ->crosapi_ash() ->file_system_provider_service_ash() ->GetAllWithProfile(extension_id(), std::move(callback), Profile::FromBrowserContext(browser_context())); +#else + if (!InterfaceAvailable()) + return RespondNow(Error(kInterfaceUnavailable)); + GetRemote()->GetAll(extension_id(), std::move(callback)); +#endif return RespondLater(); } @@ -227,11 +264,17 @@ id->id = params->file_system_id; auto callback = base::BindOnce(&FileSystemProviderGetFunction::RespondWithInfo, this); +#if BUILDFLAG(IS_CHROMEOS_ASH) crosapi::CrosapiManager::Get() ->crosapi_ash() ->file_system_provider_service_ash() ->GetWithProfile(std::move(id), std::move(callback), Profile::FromBrowserContext(browser_context())); +#else + if (!InterfaceAvailable()) + return RespondNow(Error(kInterfaceUnavailable)); + GetRemote()->Get(std::move(id), std::move(callback)); +#endif return RespondLater(); } @@ -270,12 +313,19 @@ changes = ParseChanges(*params->options.changes); } +#if BUILDFLAG(IS_CHROMEOS_ASH) crosapi::CrosapiManager::Get() ->crosapi_ash() ->file_system_provider_service_ash() ->NotifyWithProfile(std::move(id), std::move(watcher), type, std::move(changes), std::move(callback), Profile::FromBrowserContext(browser_context())); +#else + if (!InterfaceAvailable()) + return RespondNow(Error(kInterfaceUnavailable)); + GetRemote()->Notify(std::move(id), std::move(watcher), type, + std::move(changes), std::move(callback)); +#endif return RespondLater(); } @@ -295,8 +345,11 @@ std::unique_ptr<Params> params(Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); - ForwardOperationResult(params, mutable_args(), - crosapi::mojom::FSPOperationResponse::kUnmountSuccess); + bool result = ForwardOperationResult( + params, mutable_args(), + crosapi::mojom::FSPOperationResponse::kUnmountSuccess); + if (!result) + Respond(Error(kInterfaceUnavailable)); return RespondLater(); } @@ -306,9 +359,11 @@ std::unique_ptr<Params> params(Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); - ForwardOperationResult( + bool result = ForwardOperationResult( params, mutable_args(), crosapi::mojom::FSPOperationResponse::kGetEntryMetadataSuccess); + if (!result) + return RespondNow(Error(kInterfaceUnavailable)); return RespondLater(); } @@ -317,9 +372,11 @@ using api::file_system_provider_internal::GetActionsRequestedSuccess::Params; std::unique_ptr<Params> params(Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); - ForwardOperationResult( + bool result = ForwardOperationResult( params, mutable_args(), crosapi::mojom::FSPOperationResponse::kGetActionsSuccess); + if (!result) + return RespondNow(Error(kInterfaceUnavailable)); return RespondLater(); } @@ -329,9 +386,11 @@ Params; std::unique_ptr<Params> params(Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); - ForwardOperationResult( + bool result = ForwardOperationResult( params, mutable_args(), crosapi::mojom::FSPOperationResponse::kReadDirectorySuccess); + if (!result) + return RespondNow(Error(kInterfaceUnavailable)); return RespondLater(); } @@ -343,9 +402,11 @@ // TODO(https://crbug.com/1314397): Improve performance by removing copy. std::unique_ptr<Params> params(Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); - ForwardOperationResult( + bool result = ForwardOperationResult( params, mutable_args(), crosapi::mojom::FSPOperationResponse::kReadFileSuccess); + if (!result) + return RespondNow(Error(kInterfaceUnavailable)); return RespondLater(); } @@ -355,8 +416,11 @@ std::unique_ptr<Params> params(Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); - ForwardOperationResult(params, mutable_args(), - crosapi::mojom::FSPOperationResponse::kGenericSuccess); + bool result = ForwardOperationResult( + params, mutable_args(), + crosapi::mojom::FSPOperationResponse::kGenericSuccess); + if (!result) + return RespondNow(Error(kInterfaceUnavailable)); return RespondLater(); } @@ -371,8 +435,11 @@ return ValidationFailure(this); } - ForwardOperationResult(params, mutable_args(), - crosapi::mojom::FSPOperationResponse::kGenericFailure); + bool result = ForwardOperationResult( + params, mutable_args(), + crosapi::mojom::FSPOperationResponse::kGenericFailure); + if (!result) + return RespondNow(Error(kInterfaceUnavailable)); return RespondLater(); }
diff --git a/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.h b/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.h index c47272a..66bd9bb 100644 --- a/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.h +++ b/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.h
@@ -5,20 +5,38 @@ #ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_SYSTEM_PROVIDER_FILE_SYSTEM_PROVIDER_API_H_ #define CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_SYSTEM_PROVIDER_FILE_SYSTEM_PROVIDER_API_H_ -#include "chrome/browser/ash/crosapi/crosapi_ash.h" -#include "chrome/browser/ash/crosapi/crosapi_manager.h" -#include "chrome/browser/ash/crosapi/file_system_provider_service_ash.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/chromeos/extensions/file_system_provider/provider_function.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/crosapi/mojom/file_system_provider.mojom.h" #include "extensions/browser/extension_function.h" +#if BUILDFLAG(IS_CHROMEOS_ASH) +#include "chrome/browser/ash/crosapi/crosapi_ash.h" +#include "chrome/browser/ash/crosapi/crosapi_manager.h" +#include "chrome/browser/ash/crosapi/file_system_provider_service_ash.h" +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + +#if BUILDFLAG(IS_CHROMEOS_LACROS) +#include "chromeos/lacros/lacros_service.h" +#include "mojo/public/cpp/bindings/remote.h" +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) + namespace extensions { class FileSystemProviderBase : public ExtensionFunction { protected: ~FileSystemProviderBase() override {} void RespondWithError(const std::string& error); + +#if BUILDFLAG(IS_CHROMEOS_LACROS) + // Whether ash supports the FileSystemProviderService interface. + bool InterfaceAvailable(); + + // A helper function that returns a reference to a functional remote. Should + // only be called if InterfaceAvailable is true. + mojo::Remote<crosapi::mojom::FileSystemProviderService>& GetRemote(); +#endif }; class FileSystemProviderMountFunction : public FileSystemProviderBase { @@ -41,7 +59,7 @@ ResponseAction Run() override; }; -class FileSystemProviderGetAllFunction : public ExtensionFunction { +class FileSystemProviderGetAllFunction : public FileSystemProviderBase { public: DECLARE_EXTENSION_FUNCTION("fileSystemProvider.getAll", FILESYSTEMPROVIDER_GETALL) @@ -52,7 +70,7 @@ ResponseAction Run() override; }; -class FileSystemProviderGetFunction : public ExtensionFunction { +class FileSystemProviderGetFunction : public FileSystemProviderBase { public: DECLARE_EXTENSION_FUNCTION("fileSystemProvider.get", FILESYSTEMPROVIDER_GET) @@ -93,8 +111,9 @@ } // Forwards the result of the operation to the file system provider service. + // Returns false if the forwarding failed. template <typename Params> - void ForwardOperationResult(const Params& params, + bool ForwardOperationResult(const Params& params, std::vector<base::Value>& args, crosapi::mojom::FSPOperationResponse response) { crosapi::mojom::FileSystemIdPtr file_system_id; @@ -102,6 +121,7 @@ GetOperationMetadata(params, &file_system_id, &request_id); auto callback = base::BindOnce(&FileSystemProviderInternal::RespondWithError, this); +#if BUILDFLAG(IS_CHROMEOS_ASH) crosapi::CrosapiManager::Get() ->crosapi_ash() ->file_system_provider_service_ash() @@ -109,6 +129,15 @@ response, std::move(file_system_id), request_id, std::move(args), std::move(callback), Profile::FromBrowserContext(browser_context())); + return true; +#else + if (!InterfaceAvailable()) + return false; + GetRemote()->OperationFinished(response, std::move(file_system_id), + request_id, std::move(args), + std::move(callback)); + return true; +#endif } };
diff --git a/chrome/browser/download/mixed_content_download_blocking.cc b/chrome/browser/download/mixed_content_download_blocking.cc index 0b7a690e..b0d255c3 100644 --- a/chrome/browser/download/mixed_content_download_blocking.cc +++ b/chrome/browser/download/mixed_content_download_blocking.cc
@@ -293,7 +293,7 @@ base::SplitStringPiece(extension_list, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { DCHECK_EQ(base::ToLowerASCII(item), item); - if (base::LowerCaseEqualsASCII(extension, item)) + if (base::EqualsCaseInsensitiveASCII(extension, item)) return true; }
diff --git a/chrome/browser/enterprise/connectors/common.cc b/chrome/browser/enterprise/connectors/common.cc index e9f012b..186df52 100644 --- a/chrome/browser/enterprise/connectors/common.cc +++ b/chrome/browser/enterprise/connectors/common.cc
@@ -6,6 +6,9 @@ #include "base/notreached.h" #include "build/chromeos_buildflags.h" +#include "chrome/browser/enterprise/connectors/analysis/content_analysis_delegate_base.h" +#include "chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h" +#include "chrome/browser/enterprise/connectors/analysis/content_analysis_downloads_delegate.h" #include "chrome/browser/enterprise/connectors/connectors_prefs.h" #include "chrome/browser/enterprise/connectors/connectors_service.h" #include "chrome/browser/profiles/profile.h" @@ -212,17 +215,64 @@ if (danger_type == download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING || danger_type == download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_BLOCK) { return ConnectorsServiceFactory::GetForBrowserContext(profile) - ->HasCustomInfoToDisplay( - enterprise_connectors::AnalysisConnector::FILE_DOWNLOADED, kDlpTag); + ->HasCustomInfoToDisplay(AnalysisConnector::FILE_DOWNLOADED, kDlpTag); } else if (danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL || danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT) { return ConnectorsServiceFactory::GetForBrowserContext(profile) - ->HasCustomInfoToDisplay( - enterprise_connectors::AnalysisConnector::FILE_DOWNLOADED, - kMalwareTag); + ->HasCustomInfoToDisplay(AnalysisConnector::FILE_DOWNLOADED, + kMalwareTag); } return false; } +void ShowDownloadReviewDialog(const std::u16string& filename, + Profile* profile, + download::DownloadItem* download_item, + content::WebContents* web_contents, + download::DownloadDangerType danger_type, + base::OnceClosure keep_closure, + base::OnceClosure discard_closure) { + auto state = FinalContentAnalysisResult::FAILURE; + if (danger_type == download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING) { + state = FinalContentAnalysisResult::WARNING; + } + + const char* tag = + (danger_type == + download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING || + danger_type == + download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_BLOCK + ? kDlpTag + : kMalwareTag); + + auto* connectors_service = + ConnectorsServiceFactory::GetForBrowserContext(profile); + + std::u16string custom_message = + connectors_service + ->GetCustomMessage(AnalysisConnector::FILE_DOWNLOADED, tag) + .value_or(u""); + GURL learn_more_url = + connectors_service + ->GetLearnMoreUrl(AnalysisConnector::FILE_DOWNLOADED, tag) + .value_or(GURL()); + + bool bypass_justification_required = + connectors_service + ->GetBypassJustificationRequired(AnalysisConnector::FILE_DOWNLOADED, + tag) + .value_or(false); + + // This dialog opens itself, and is thereafter owned by constrained window + // code. + new ContentAnalysisDialog( + std::make_unique<ContentAnalysisDownloadsDelegate>( + filename, custom_message, learn_more_url, + bypass_justification_required, std::move(keep_closure), + std::move(discard_closure), download_item), + web_contents, safe_browsing::DeepScanAccessPoint::DOWNLOAD, + /* file_count */ 1, state, download_item); +} + } // namespace enterprise_connectors
diff --git a/chrome/browser/enterprise/connectors/common.h b/chrome/browser/enterprise/connectors/common.h index 5ca3bf7..0cf6d6d 100644 --- a/chrome/browser/enterprise/connectors/common.h +++ b/chrome/browser/enterprise/connectors/common.h
@@ -10,6 +10,7 @@ #include <string> #include <vector> +#include "base/callback_forward.h" #include "base/supports_user_data.h" #include "components/download/public/common/download_danger_type.h" #include "components/enterprise/common/proto/connectors.pb.h" @@ -18,6 +19,14 @@ class Profile; +namespace content { +class WebContents; +} // namespace content + +namespace download { +class DownloadItem; +} // namespace download + namespace enterprise_connectors { // Alias to reduce verbosity when using TriggeredRule::Actions. @@ -242,6 +251,16 @@ bool ShouldPromptReviewForDownload(Profile* profile, download::DownloadDangerType danger_type); +// Shows the review dialog after a user has clicked the "Review" button +// corresponding to a download. +void ShowDownloadReviewDialog(const std::u16string& filename, + Profile* profile, + download::DownloadItem* download_item, + content::WebContents* web_contents, + download::DownloadDangerType danger_type, + base::OnceClosure keep_closure, + base::OnceClosure discard_closure); + } // namespace enterprise_connectors #endif // CHROME_BROWSER_ENTERPRISE_CONNECTORS_COMMON_H_
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 10b2f06..69d8725 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -978,6 +978,7 @@ "api/platform_keys/verify_trust_api.h", "api/printing/print_job_controller.cc", "api/printing/print_job_controller.h", + "api/shared_storage/shared_storage_private_api.h", "clipboard_extension_helper_chromeos.cc", "clipboard_extension_helper_chromeos.h", "system_display/system_display_serialization.cc", @@ -1003,9 +1004,9 @@ deps += [ "//chrome/browser/chromeos/extensions:constants", "//chrome/browser/chromeos/extensions/login_screen", - "//chromeos/constants", "//chromeos/components/disks:prefs", "//chromeos/components/quick_answers/public/cpp:prefs", + "//chromeos/constants", "//chromeos/crosapi/cpp", "//chromeos/crosapi/mojom", "//chromeos/dbus/missive:missive", @@ -1078,6 +1079,7 @@ "api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.h", "api/settings_private/generated_time_zone_pref_base.cc", "api/settings_private/generated_time_zone_pref_base.h", + "api/shared_storage/shared_storage_private_api_ash.cc", "api/terminal/crostini_startup_status.cc", "api/terminal/crostini_startup_status.h", "api/terminal/terminal_private_api.cc", @@ -1191,6 +1193,7 @@ "api/messaging/native_message_host_lacros.cc", "api/quick_unlock_private/quick_unlock_private_api_lacros.cc", "api/quick_unlock_private/quick_unlock_private_api_lacros.h", + "api/shared_storage/shared_storage_private_api_lacros.cc", "chrome_kiosk_delegate.cc", "preinstalled_apps.cc", "preinstalled_apps.h",
diff --git a/chrome/browser/extensions/api/shared_storage/OWNERS b/chrome/browser/extensions/api/shared_storage/OWNERS new file mode 100644 index 0000000..702fa2d --- /dev/null +++ b/chrome/browser/extensions/api/shared_storage/OWNERS
@@ -0,0 +1,3 @@ +erikchen@chromium.org +joelhockey@chromium.org +lxj@google.com
diff --git a/chrome/browser/extensions/api/shared_storage/shared_storage_private_api.h b/chrome/browser/extensions/api/shared_storage/shared_storage_private_api.h new file mode 100644 index 0000000..4bebb8c7 --- /dev/null +++ b/chrome/browser/extensions/api/shared_storage/shared_storage_private_api.h
@@ -0,0 +1,104 @@ +// Copyright 2022 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_EXTENSIONS_API_SHARED_STORAGE_SHARED_STORAGE_PRIVATE_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_SHARED_STORAGE_SHARED_STORAGE_PRIVATE_API_H_ + +#include <string> +#include <vector> + +#include "base/values.h" +#include "build/buildflag.h" +#include "build/chromeos_buildflags.h" +#include "extensions/browser/extension_function.h" + +#if BUILDFLAG(IS_CHROMEOS_LACROS) +#include "third_party/abseil-cpp/absl/types/optional.h" +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) + +#if BUILDFLAG(IS_CHROMEOS_ASH) +class PrefRegistrySimple; +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + +namespace extensions { +#if BUILDFLAG(IS_CHROMEOS_ASH) +namespace shared_storage { +void RegisterProfilePrefs(PrefRegistrySimple* registry); +} // namespace shared_storage +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + +// Used by gnubbyd in ash and lacros. Stores small amounts of data in ash prefs +// which is shared by ash and lacros versions of the extension. +// TODO(b/231890240): Once Terminal SWA runs in lacros rather than ash, we can +// migrate gnubbyd back to using chrome.storage.local and remove this private +// API. +class SharedStoragePrivateGetFunction : public ExtensionFunction { + public: + SharedStoragePrivateGetFunction(); + SharedStoragePrivateGetFunction(const SharedStoragePrivateGetFunction&) = + delete; + SharedStoragePrivateGetFunction& operator=( + const SharedStoragePrivateGetFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("sharedStoragePrivate.get", + SHAREDSTORAGEPRIVATE_GET) + + protected: + ~SharedStoragePrivateGetFunction() override; + + // ExtensionFunction: + ResponseAction Run() override; +#if BUILDFLAG(IS_CHROMEOS_LACROS) + void OnGet(absl::optional<base::Value> storage); +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) +}; + +class SharedStoragePrivateSetFunction : public ExtensionFunction { + public: + SharedStoragePrivateSetFunction(); + SharedStoragePrivateSetFunction(const SharedStoragePrivateSetFunction&) = + delete; + SharedStoragePrivateSetFunction& operator=( + const SharedStoragePrivateSetFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("sharedStoragePrivate.set", + SHAREDSTORAGEPRIVATE_SET) + + protected: + ~SharedStoragePrivateSetFunction() override; + + // ExtensionFunction: + ResponseAction Run() override; +#if BUILDFLAG(IS_CHROMEOS_LACROS) + void OnGet(base::DictionaryValue to_add, absl::optional<base::Value> items); + void OnSet(); +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) +}; + +class SharedStoragePrivateRemoveFunction : public ExtensionFunction { + public: + SharedStoragePrivateRemoveFunction(); + SharedStoragePrivateRemoveFunction( + const SharedStoragePrivateRemoveFunction&) = delete; + SharedStoragePrivateRemoveFunction& operator=( + const SharedStoragePrivateRemoveFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("sharedStoragePrivate.remove", + SHAREDSTORAGEPRIVATE_REMOVE) + + protected: + ~SharedStoragePrivateRemoveFunction() override; + + // ExtensionFunction: + ResponseAction Run() override; +#if BUILDFLAG(IS_CHROMEOS_LACROS) + void OnGet(std::vector<std::string> keys, + absl::optional<base::Value> storage); + void OnSet(); +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) +}; + +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_SHARED_STORAGE_SHARED_STORAGE_PRIVATE_API_H_
diff --git a/chrome/browser/extensions/api/shared_storage/shared_storage_private_api_ash.cc b/chrome/browser/extensions/api/shared_storage/shared_storage_private_api_ash.cc new file mode 100644 index 0000000..7db25c1 --- /dev/null +++ b/chrome/browser/extensions/api/shared_storage/shared_storage_private_api_ash.cc
@@ -0,0 +1,70 @@ +// Copyright 2022 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/extensions/api/shared_storage/shared_storage_private_api.h" + +#include "base/values.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/extensions/api/shared_storage_private.h" +#include "chrome/common/pref_names.h" +#include "components/prefs/pref_registry_simple.h" +#include "components/prefs/pref_service.h" +#include "components/prefs/scoped_user_pref_update.h" + +// TODO(b/231890240): Once Terminal SWA runs in lacros rather than ash, we can +// migrate gnubbyd back to using chrome.storage.local and remove this private +// API. + +namespace shared_api = extensions::api::shared_storage_private; + +namespace extensions { +namespace shared_storage { +void RegisterProfilePrefs(PrefRegistrySimple* registry) { + registry->RegisterDictionaryPref(prefs::kSharedStorage); +} +} // namespace shared_storage + +SharedStoragePrivateGetFunction::SharedStoragePrivateGetFunction() = default; +SharedStoragePrivateGetFunction::~SharedStoragePrivateGetFunction() = default; + +ExtensionFunction::ResponseAction SharedStoragePrivateGetFunction::Run() { + PrefService* prefs = + Profile::FromBrowserContext(browser_context())->GetPrefs(); + return RespondNow(OneArgument(prefs->Get(prefs::kSharedStorage)->Clone())); +} + +SharedStoragePrivateSetFunction::SharedStoragePrivateSetFunction() = default; +SharedStoragePrivateSetFunction::~SharedStoragePrivateSetFunction() = default; + +ExtensionFunction::ResponseAction SharedStoragePrivateSetFunction::Run() { + std::unique_ptr<shared_api::Set::Params> params = + shared_api::Set::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params); + PrefService* prefs = + Profile::FromBrowserContext(browser_context())->GetPrefs(); + DictionaryPrefUpdate update(prefs, prefs::kSharedStorage); + update.Get()->MergeDictionary(¶ms->items.additional_properties); + return RespondNow(NoArguments()); +} + +SharedStoragePrivateRemoveFunction::SharedStoragePrivateRemoveFunction() = + default; +SharedStoragePrivateRemoveFunction::~SharedStoragePrivateRemoveFunction() = + default; + +ExtensionFunction::ResponseAction SharedStoragePrivateRemoveFunction::Run() { + std::unique_ptr<shared_api::Remove::Params> params = + shared_api::Remove::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params); + PrefService* prefs = + Profile::FromBrowserContext(browser_context())->GetPrefs(); + DictionaryPrefUpdate update(prefs, prefs::kSharedStorage); + base::Value* items = update.Get(); + for (const auto& key : params->keys) { + items->RemoveKey(key); + } + return RespondNow(NoArguments()); +} + +} // namespace extensions
diff --git a/chrome/browser/extensions/api/shared_storage/shared_storage_private_api_lacros.cc b/chrome/browser/extensions/api/shared_storage/shared_storage_private_api_lacros.cc new file mode 100644 index 0000000..b713759 --- /dev/null +++ b/chrome/browser/extensions/api/shared_storage/shared_storage_private_api_lacros.cc
@@ -0,0 +1,139 @@ +// Copyright 2022 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/extensions/api/shared_storage/shared_storage_private_api.h" + +#include "base/values.h" +#include "chrome/common/extensions/api/shared_storage_private.h" +#include "chromeos/crosapi/mojom/prefs.mojom.h" +#include "chromeos/lacros/lacros_service.h" + +// TODO(b/231890240): Once Terminal SWA runs in lacros rather than ash, we can +// migrate gnubbyd back to using chrome.storage.local and remove this private +// API. + +namespace shared_api = extensions::api::shared_storage_private; + +namespace extensions { +namespace { + +constexpr char kErrorNotAvailable[] = "crosapi: Prefs API not available"; +constexpr char kErrorFetching[] = "crosapi: Error fetching pref shared_storage"; + +} // namespace + +SharedStoragePrivateGetFunction::SharedStoragePrivateGetFunction() = default; +SharedStoragePrivateGetFunction::~SharedStoragePrivateGetFunction() = default; + +ExtensionFunction::ResponseAction SharedStoragePrivateGetFunction::Run() { + auto* lacros_service = chromeos::LacrosService::Get(); + if (!lacros_service || + !lacros_service->IsAvailable<crosapi::mojom::Prefs>()) { + LOG(ERROR) << kErrorNotAvailable; + return RespondNow(Error(kErrorNotAvailable)); + } + lacros_service->GetRemote<crosapi::mojom::Prefs>()->GetPref( + crosapi::mojom::PrefPath::kSharedStorage, + base::BindOnce(&SharedStoragePrivateGetFunction::OnGet, this)); + return RespondLater(); +} + +void SharedStoragePrivateGetFunction::OnGet(absl::optional<base::Value> items) { + if (!items) { + LOG(ERROR) << kErrorFetching; + return Respond(Error(kErrorFetching)); + } + Respond(OneArgument(std::move(*items))); +} + +SharedStoragePrivateSetFunction::SharedStoragePrivateSetFunction() = default; +SharedStoragePrivateSetFunction::~SharedStoragePrivateSetFunction() = default; + +ExtensionFunction::ResponseAction SharedStoragePrivateSetFunction::Run() { + std::unique_ptr<shared_api::Set::Params> params = + shared_api::Set::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params); + auto* lacros_service = chromeos::LacrosService::Get(); + if (!lacros_service || + !lacros_service->IsAvailable<crosapi::mojom::Prefs>()) { + LOG(ERROR) << kErrorNotAvailable; + return RespondNow(Error(kErrorNotAvailable)); + } + lacros_service->GetRemote<crosapi::mojom::Prefs>()->GetPref( + crosapi::mojom::PrefPath::kSharedStorage, + base::BindOnce(&SharedStoragePrivateSetFunction::OnGet, this, + std::move(params->items.additional_properties))); + return RespondLater(); +} + +void SharedStoragePrivateSetFunction::OnGet(base::DictionaryValue to_add, + absl::optional<base::Value> items) { + if (!items) { + LOG(ERROR) << kErrorFetching; + return Respond(Error(kErrorFetching)); + } + items->MergeDictionary(&to_add); + auto* lacros_service = chromeos::LacrosService::Get(); + if (!lacros_service || + !lacros_service->IsAvailable<crosapi::mojom::Prefs>()) { + LOG(ERROR) << kErrorNotAvailable; + return Respond(Error(kErrorNotAvailable)); + } + lacros_service->GetRemote<crosapi::mojom::Prefs>()->SetPref( + crosapi::mojom::PrefPath::kSharedStorage, std::move(*items), + base::BindOnce(&SharedStoragePrivateSetFunction::OnSet, this)); +} + +void SharedStoragePrivateSetFunction::OnSet() { + Respond(NoArguments()); +} + +SharedStoragePrivateRemoveFunction::SharedStoragePrivateRemoveFunction() = + default; +SharedStoragePrivateRemoveFunction::~SharedStoragePrivateRemoveFunction() = + default; + +ExtensionFunction::ResponseAction SharedStoragePrivateRemoveFunction::Run() { + std::unique_ptr<shared_api::Remove::Params> params = + shared_api::Remove::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params); + auto* lacros_service = chromeos::LacrosService::Get(); + if (!lacros_service || + !lacros_service->IsAvailable<crosapi::mojom::Prefs>()) { + LOG(ERROR) << kErrorNotAvailable; + return RespondNow(Error(kErrorNotAvailable)); + } + lacros_service->GetRemote<crosapi::mojom::Prefs>()->GetPref( + crosapi::mojom::PrefPath::kSharedStorage, + base::BindOnce(&SharedStoragePrivateRemoveFunction::OnGet, this, + std::move(params->keys))); + return RespondLater(); +} + +void SharedStoragePrivateRemoveFunction::OnGet( + std::vector<std::string> keys, + absl::optional<base::Value> items) { + if (!items) { + LOG(ERROR) << kErrorFetching; + return Respond(Error(kErrorFetching)); + } + for (const auto& key : keys) { + items->RemoveKey(key); + } + auto* lacros_service = chromeos::LacrosService::Get(); + if (!lacros_service || + !lacros_service->IsAvailable<crosapi::mojom::Prefs>()) { + LOG(ERROR) << kErrorNotAvailable; + return Respond(Error(kErrorNotAvailable)); + } + lacros_service->GetRemote<crosapi::mojom::Prefs>()->SetPref( + crosapi::mojom::PrefPath::kSharedStorage, std::move(*items), + base::BindOnce(&SharedStoragePrivateRemoveFunction::OnSet, this)); +} + +void SharedStoragePrivateRemoveFunction::OnSet() { + Respond(NoArguments()); +} + +} // namespace extensions
diff --git a/chrome/browser/extensions/api/shared_storage/shared_storage_private_apitest.cc b/chrome/browser/extensions/api/shared_storage/shared_storage_private_apitest.cc new file mode 100644 index 0000000..b92e8cee --- /dev/null +++ b/chrome/browser/extensions/api/shared_storage/shared_storage_private_apitest.cc
@@ -0,0 +1,31 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/values.h" +#include "build/buildflag.h" +#include "chrome/browser/extensions/extension_apitest.h" +#include "content/public/test/browser_test.h" + +#if BUILDFLAG(IS_CHROMEOS_LACROS) +#include "base/containers/contains.h" +#include "chromeos/startup/browser_init_params.h" +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) + +namespace extensions { + +using SharedStoragePrivateApiTest = ExtensionApiTest; + +IN_PROC_BROWSER_TEST_F(SharedStoragePrivateApiTest, Test) { +#if BUILDFLAG(IS_CHROMEOS_LACROS) + auto capabilities = chromeos::BrowserInitParams::Get()->ash_capabilities; + if (!capabilities || !base::Contains(*capabilities, "b/231890240")) { + LOG(WARNING) << "Unsupported ash version for shared storage."; + return; + } +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) + + ASSERT_TRUE(RunExtensionTest("shared_storage_private")) << message_; +} + +} // namespace extensions
diff --git a/chrome/browser/extensions/dynamic_origin_browsertest.cc b/chrome/browser/extensions/dynamic_origin_browsertest.cc new file mode 100644 index 0000000..f83a212 --- /dev/null +++ b/chrome/browser/extensions/dynamic_origin_browsertest.cc
@@ -0,0 +1,183 @@ +// Copyright 2022 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/extensions/chrome_test_extension_loader.h" +#include "chrome/browser/extensions/extension_browsertest.h" +#include "chrome/test/base/ui_test_utils.h" +#include "components/version_info/channel.h" +#include "content/public/common/referrer.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "content/public/test/test_navigation_observer.h" +#include "extensions/common/extension_features.h" +#include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/test_extension_dir.h" + +namespace extensions { + +namespace { + +class DynamicOriginBrowserTest : public ExtensionBrowserTest { + public: + DynamicOriginBrowserTest() { + feature_list_.InitAndEnableFeature( + extensions_features::kExtensionDynamicURLRedirection); + } + + void SetUpOnMainThread() override { + ExtensionBrowserTest::SetUpOnMainThread(); + InstallExtension(); + } + + protected: + const Extension* GetExtension() { return extension_; } + + content::WebContents* GetActiveWebContents() const { + return browser()->tab_strip_model()->GetActiveWebContents(); + } + + content::RenderFrameHost* GetMainFrame() const { + return GetActiveWebContents()->GetMainFrame(); + } + + private: + void InstallExtension() { + dir_.WriteManifest(R"({ + "name": "Extension", + "version": "1.0", + "manifest_version": 3, + "web_accessible_resources": [{ + "resources": ["web_accessible_resource.html", "ok.html"], + "matches": ["<all_urls>"] + }] + })"); + std::vector<std::string> files( + {"extension_resource.html", "web_accessible_resource.html", "ok.html"}); + for (const auto& filename : files) { + dir_.WriteFile(base::FilePath::FromASCII(filename).value(), filename); + } + extension_ = LoadExtension(dir_.UnpackedPath()); + DCHECK(extension_); + } + + const Extension* extension_ = nullptr; + TestExtensionDir dir_; + base::test::ScopedFeatureList feature_list_; + ScopedCurrentChannel current_channel_{version_info::Channel::CANARY}; +}; + +// Web Accessible Resources. +IN_PROC_BROWSER_TEST_F(DynamicOriginBrowserTest, DynamicUrl) { + auto* extension = GetExtension(); + + // Resource and extension origin should match. + { + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), extension->GetResourceURL("ok.html"))); + ASSERT_EQ(extension->origin(), GetMainFrame()->GetLastCommittedOrigin()); + } + + // Dynamic resource should resolve to static url. + { + GURL static_url = extension->url().Resolve("ok.html"); + GURL dynamic_url = extension->dynamic_url().Resolve("ok.html"); + ASSERT_NE(static_url, dynamic_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), dynamic_url)); + EXPECT_EQ(static_url, GetMainFrame()->GetLastCommittedURL()); + EXPECT_EQ(extension->origin(), GetMainFrame()->GetLastCommittedOrigin()); + } +} + +// Error accessing resource from random guid. +IN_PROC_BROWSER_TEST_F(DynamicOriginBrowserTest, + InvalidDynamicResourceFailsToLoad) { + auto* extension = GetExtension(); + + auto run = [&](const GURL& gurl, int status) { + content::WebContents* web_contents = GetActiveWebContents(); + content::TestNavigationObserver nav_observer(web_contents); + web_contents->GetController().LoadURL( + gurl, content::Referrer(), ui::PageTransition::PAGE_TRANSITION_TYPED, + std::string()); + nav_observer.Wait(); + EXPECT_EQ(status == net::OK, nav_observer.last_navigation_succeeded()); + EXPECT_EQ(status, nav_observer.last_net_error_code()); + }; + + auto random_guid = base::GUID::GenerateRandomV4().AsLowercaseString(); + GURL random_url = + Extension::GetBaseURLFromExtensionId(random_guid).Resolve("ok.html"); + GURL dynamic_url = extension->dynamic_url().Resolve("ok.html"); + run(random_url, net::ERR_BLOCKED_BY_CLIENT); + run(dynamic_url, net::OK); +} + +// Web Accessible Resources. +IN_PROC_BROWSER_TEST_F(DynamicOriginBrowserTest, FetchGuidFromFrame) { + auto* extension = GetExtension(); + + // Fetch url from frame to verify with expectations. + auto test_frame_with_fetch = [&](const GURL& frame_url, + const GURL& expected_frame_url, + const GURL& fetch_url, + const char* expected_fetch_url_contents) { + SCOPED_TRACE(testing::Message() << "test_frame_with_fetch" + << ": frame_url = " << frame_url + << "; fetch_url = " << fetch_url); + // Fetch and test resource. + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), frame_url)); + content::WebContents* web_contents = GetActiveWebContents(); + EXPECT_EQ(expected_frame_url, + web_contents->GetMainFrame()->GetLastCommittedURL()); + + std::string result; + constexpr char kFetchScriptTemplate[] = + R"( + fetch($1).then(result => { + return result.text(); + }).then(text => { + domAutomationController.send(text); + }).catch(err => { + domAutomationController.send(String(err)); + });)"; + EXPECT_TRUE(content::ExecuteScriptAndExtractString( + web_contents, + content::JsReplace(kFetchScriptTemplate, fetch_url.spec()), &result)); + EXPECT_EQ(expected_fetch_url_contents, result); + }; + + // clang-format off + struct { + const GURL& frame_url; + const GURL& expected_frame_url; + const GURL& fetch_url; + const char* expected_fetch_url_contents; + } test_cases[] = { + // Fetch web accessible resource from extension resource. + { + extension->url().Resolve("extension_resource.html"), + extension->url().Resolve("extension_resource.html"), + extension->url().Resolve("web_accessible_resource.html"), + "web_accessible_resource.html" + }, + // Fetch dynamic web accessible resource from extension resource. + { + extension->url().Resolve("extension_resource.html"), + extension->url().Resolve("extension_resource.html"), + extension->dynamic_url().Resolve("web_accessible_resource.html"), + "web_accessible_resource.html" + }, + }; + // clang-format on + + for (const auto& test_case : test_cases) { + test_frame_with_fetch(test_case.frame_url, test_case.expected_frame_url, + test_case.fetch_url, + test_case.expected_fetch_url_contents); + } +} + +} // namespace + +} // namespace extensions
diff --git a/chrome/browser/extensions/tab_helper.cc b/chrome/browser/extensions/tab_helper.cc index e1f6a40..f0698f5 100644 --- a/chrome/browser/extensions/tab_helper.cc +++ b/chrome/browser/extensions/tab_helper.cc
@@ -309,9 +309,8 @@ Browser* browser = chrome::FindBrowserWithWebContents(web_contents()); if (browser && (browser->is_type_app() || browser->is_type_app_popup())) { - const Extension* extension = registry->GetExtensionById( - web_app::GetAppIdFromApplicationName(browser->app_name()), - ExtensionRegistry::EVERYTHING); + const Extension* extension = registry->GetInstalledExtension( + web_app::GetAppIdFromApplicationName(browser->app_name())); if (extension && AppLaunchInfo::GetFullLaunchURL(extension).is_valid()) { DCHECK(extension->is_app()); SetExtensionApp(extension);
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index bc25d4e..0f78329 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -903,6 +903,11 @@ "expiry_milestone": 105 }, { + "name": "content-suggestions-ui-module-refresh", + "owners": [ "thegreenfrog@google.com", "bling-flags@google.com" ], + "expiry_milestone": 108 + }, + { "name": "content-suggestions-uiviewcontroller-migration", "owners": [ "thegreenfrog@google.com", "adamta@google.com" ], "expiry_milestone": 106 @@ -4558,11 +4563,6 @@ "expiry_milestone": 110 }, { - "name": "omnibox-pedals-android-batch1", - "owners": [ "gangwu", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 105 - }, - { "name": "omnibox-retain-suggestions-with-headers", "owners": [ "ender@google.com", "mahmadi@google.com", "chrome-omnibox-team@google.com" ], "expiry_milestone": 112
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index e52c5bbd..b3088d8 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -3718,10 +3718,6 @@ const char kWebNotesDynamicTemplatesDescription[] = "Allows templates to be modified remotely on short notice."; -const char kOmniboxPedalsAndroidBatch1Name[] = "Omnibox Pedals Android batch 1"; -const char kOmniboxPedalsAndroidBatch1Description[] = - "Enable the first batch of Omnibox Pedals on Android."; - const char kPasswordEditDialogWithDetailsName[] = "Password edit dialog with details UI"; const char kPasswordEditDialogWithDetailsDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index ba72d16..9cc988b 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -2114,9 +2114,6 @@ extern const char kWebNotesDynamicTemplatesName[]; extern const char kWebNotesDynamicTemplatesDescription[]; -extern const char kOmniboxPedalsAndroidBatch1Name[]; -extern const char kOmniboxPedalsAndroidBatch1Description[]; - extern const char kPasswordEditDialogWithDetailsName[]; extern const char kPasswordEditDialogWithDetailsDescription[];
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index a56e674..3f7ff1b 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -10,8 +10,11 @@ #include "base/android/jni_array.h" #include "base/android/jni_string.h" +#include "base/containers/flat_map.h" #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" +#include "base/no_destructor.h" +#include "base/strings/string_piece_forward.h" #include "chrome/browser/browser_features.h" #include "chrome/browser/feature_guide/notifications/feature_notification_guide_service.h" #include "chrome/browser/flags/android/chrome_session_state.h" @@ -383,10 +386,19 @@ }; const base::Feature* FindFeatureExposedToJava(const std::string& feature_name) { - for (const auto* feature : kFeaturesExposedToJava) { - if (feature->name == feature_name) - return feature; + static auto kFeaturesExposedToJavaMap = base::NoDestructor( + base::MakeFlatMap<base::StringPiece, const base::Feature*>( + kFeaturesExposedToJava, {}, + [](const base::Feature* a) + -> std::pair<base::StringPiece, const base::Feature*> { + return std::make_pair(a->name, a); + })); + + auto it = kFeaturesExposedToJavaMap->find(base::StringPiece(feature_name)); + if (it != kFeaturesExposedToJavaMap->end()) { + return it->second; } + NOTREACHED() << "Queried feature cannot be found in ChromeFeatureList: " << feature_name; return nullptr;
diff --git a/chrome/browser/lacros/lacros_file_system_provider.cc b/chrome/browser/lacros/lacros_file_system_provider.cc index b2fa6edc..8a13c80 100644 --- a/chrome/browser/lacros/lacros_file_system_provider.cc +++ b/chrome/browser/lacros/lacros_file_system_provider.cc
@@ -8,9 +8,13 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/common/extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.h" #include "chromeos/lacros/lacros_service.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_event_histogram_value.h" +#include "extensions/browser/unloaded_extension_reason.h" +#include "extensions/common/manifest_constants.h" +#include "extensions/common/permissions/permissions_data.h" namespace { @@ -31,23 +35,56 @@ return; service->GetRemote<crosapi::mojom::FileSystemProviderService>() ->RegisterFileSystemProvider(receiver_.BindNewPipeAndPassRemote()); + + Profile* main_profile = GetMainProfile(); + if (main_profile) { + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(main_profile); + extension_observation_.Observe(registry); + + // Initial conditions + for (const scoped_refptr<const extensions::Extension> extension : + registry->enabled_extensions()) { + OnExtensionLoaded(main_profile, extension.get()); + } + } } LacrosFileSystemProvider::~LacrosFileSystemProvider() = default; -void LacrosFileSystemProvider::ForwardOperation(const std::string& provider, - int32_t histogram_value, - const std::string& event_name, - std::vector<base::Value> args) { +void LacrosFileSystemProvider::DeprecatedForwardOperation( + const std::string& provider, + int32_t histogram_value, + const std::string& event_name, + std::vector<base::Value> args) { + ForwardOperation(provider, histogram_value, event_name, std::move(args), + base::DoNothing()); +} + +void LacrosFileSystemProvider::ForwardOperation( + const std::string& provider, + int32_t histogram_value, + const std::string& event_name, + std::vector<base::Value> args, + ForwardOperationCallback callback) { Profile* main_profile = GetMainProfile(); - if (!main_profile) + if (!main_profile) { + LOG(ERROR) << "Could not get main profile"; + std::move(callback).Run(/*delivery_failure=*/true); return; + } extensions::EventRouter* router = extensions::EventRouter::Get(main_profile); - if (!router) + if (!router) { + LOG(ERROR) << "Could not get event router"; + std::move(callback).Run(/*delivery_failure=*/true); return; + } - if (!router->ExtensionHasEventListener(provider, event_name)) + if (!router->ExtensionHasEventListener(provider, event_name)) { + LOG(ERROR) << "Could not get event listener"; + std::move(callback).Run(/*delivery_failure=*/true); return; + } // Conversions are safe since the enum is stable. See documentation. int32_t lowest_valid_enum = @@ -57,6 +94,8 @@ 1; if (histogram_value < lowest_valid_enum || histogram_value > highest_valid_enum) { + LOG(ERROR) << "Invalid histogram"; + std::move(callback).Run(/*delivery_failure=*/true); return; } extensions::events::HistogramValue histogram = @@ -65,4 +104,61 @@ auto event = std::make_unique<extensions::Event>(histogram, event_name, std::move(args)); router->DispatchEventToExtension(provider, std::move(event)); + std::move(callback).Run(/*delivery_failure=*/false); +} + +void LacrosFileSystemProvider::OnExtensionLoaded( + content::BrowserContext* browser_context, + const extensions::Extension* extension) { + if (!extension->permissions_data()->HasAPIPermission( + extensions::mojom::APIPermissionID::kFileSystemProvider)) { + return; + } + const extensions::FileSystemProviderCapabilities* const capabilities = + extensions::FileSystemProviderCapabilities::Get(extension); + if (!capabilities) + return; + + chromeos::LacrosService* service = chromeos::LacrosService::Get(); + if (service->GetInterfaceVersion( + crosapi::mojom::FileSystemProviderService::Uuid_) < + int{crosapi::mojom::FileSystemProviderService::MethodMinVersions:: + kExtensionLoadedMinVersion}) { + return; + } + + crosapi::mojom::FileSystemSource source; + switch (capabilities->source()) { + case extensions::FileSystemProviderSource::SOURCE_FILE: + source = crosapi::mojom::FileSystemSource::kFile; + break; + case extensions::FileSystemProviderSource::SOURCE_NETWORK: + source = crosapi::mojom::FileSystemSource::kNetwork; + break; + case extensions::FileSystemProviderSource::SOURCE_DEVICE: + source = crosapi::mojom::FileSystemSource::kDevice; + break; + } + + service->GetRemote<crosapi::mojom::FileSystemProviderService>() + ->ExtensionLoaded(capabilities->configurable(), capabilities->watchable(), + capabilities->multiple_mounts(), source, + extension->name(), extension->id()); +} + +void LacrosFileSystemProvider::OnExtensionUnloaded( + content::BrowserContext* browser_context, + const extensions::Extension* extension, + extensions::UnloadedExtensionReason reason) { + chromeos::LacrosService* service = chromeos::LacrosService::Get(); + if (service->GetInterfaceVersion( + crosapi::mojom::FileSystemProviderService::Uuid_) < + int{crosapi::mojom::FileSystemProviderService::MethodMinVersions:: + kExtensionUnloadedMinVersion}) { + return; + } + service->GetRemote<crosapi::mojom::FileSystemProviderService>() + ->ExtensionUnloaded( + extension->id(), + reason == extensions::UnloadedExtensionReason::PROFILE_SHUTDOWN); }
diff --git a/chrome/browser/lacros/lacros_file_system_provider.h b/chrome/browser/lacros/lacros_file_system_provider.h index 3d9e052..77759ba 100644 --- a/chrome/browser/lacros/lacros_file_system_provider.h +++ b/chrome/browser/lacros/lacros_file_system_provider.h
@@ -5,13 +5,19 @@ #ifndef CHROME_BROWSER_LACROS_LACROS_FILE_SYSTEM_PROVIDER_H_ #define CHROME_BROWSER_LACROS_LACROS_FILE_SYSTEM_PROVIDER_H_ +#include "base/scoped_observation.h" #include "chromeos/crosapi/mojom/file_system_provider.mojom.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/extension_registry_observer.h" #include "mojo/public/cpp/bindings/receiver.h" -// This class is responsible for receiving file system provider events from Ash. -// These are forwarded to the corresponding main profile file system provider -// extension. -class LacrosFileSystemProvider : public crosapi::mojom::FileSystemProvider { +// This class has two responsibilities: +// (1) It receives file system provider events from Ash. These are forwarded +// to the corresponding main profile file system provider extension. +// (2) It detects extension loading/unloading in the main profile and forwards +// events to ash. +class LacrosFileSystemProvider : public crosapi::mojom::FileSystemProvider, + public extensions::ExtensionRegistryObserver { public: LacrosFileSystemProvider(); ~LacrosFileSystemProvider() override; @@ -19,15 +25,31 @@ LacrosFileSystemProvider& operator=(const LacrosFileSystemProvider&) = delete; // crosapi::mojom::FileSystemProvider + void DeprecatedForwardOperation(const std::string& provider, + int32_t histogram_value, + const std::string& event_name, + std::vector<base::Value> args) override; void ForwardOperation(const std::string& provider, int32_t histogram_value, const std::string& event_name, - std::vector<base::Value> args) override; + std::vector<base::Value> args, + ForwardOperationCallback callback) override; + + // extensions::ExtensionRegistryObserver overrides. + void OnExtensionLoaded(content::BrowserContext* browser_context, + const extensions::Extension* extension) override; + void OnExtensionUnloaded(content::BrowserContext* browser_context, + const extensions::Extension* extension, + extensions::UnloadedExtensionReason reason) override; private: // Mojo endpoint that's responsible for receiving messages from Ash. mojo::Receiver<crosapi::mojom::FileSystemProvider> receiver_; + base::ScopedObservation<extensions::ExtensionRegistry, + extensions::ExtensionRegistryObserver> + extension_observation_{this}; + base::WeakPtrFactory<LacrosFileSystemProvider> weak_factory_{this}; };
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 8f3e3bc..336f8af 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -193,6 +193,7 @@ #include "chrome/browser/ash/settings/stats_reporting_controller.h" #include "chrome/browser/chromeos/extensions/extensions_permissions_tracker.h" #include "chrome/browser/component_updater/metadata_table_chromeos.h" +#include "chrome/browser/extensions/api/shared_storage/shared_storage_private_api.h" #include "chrome/browser/ui/ash/projector/projector_app_client_impl.h" #include "chrome/browser/ui/webui/chromeos/edu_coexistence/edu_coexistence_login_handler_chromeos.h" #include "chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h" @@ -1328,6 +1329,9 @@ extensions::AudioAPI::RegisterUserPrefs(registry); extensions::ExtensionPrefs::RegisterProfilePrefs(registry); extensions::ExtensionsUI::RegisterProfilePrefs(registry); +#if BUILDFLAG(IS_CHROMEOS_ASH) + extensions::shared_storage::RegisterProfilePrefs(registry); +#endif // BUILDFLAG(IS_CHROMEOS_ASH) extensions::PermissionsManager::RegisterProfilePrefs(registry); extensions::RuntimeAPI::RegisterPrefs(registry); // TODO(devlin): This would be more inline with the other calls here if it
diff --git a/chrome/browser/resources/about_nacl/about_nacl.html b/chrome/browser/resources/about_nacl/about_nacl.html index ebf03564..a5429c42 100644 --- a/chrome/browser/resources/about_nacl/about_nacl.html +++ b/chrome/browser/resources/about_nacl/about_nacl.html
@@ -13,14 +13,12 @@ </div> <dom-bind> <template> - <dom-repeat items="[[moduleListData.naclInfo]]"> - <template> - <div> - <span class="key">[[item.key]]</span> - <span class="value">[[item.value]]</span> - </div> - </template> - </dom-repeat> + <template is="dom-repeat" items="[[naclInfo]]"> + <div> + <span class="key">[[item.key]]</span> + <span class="value">[[item.value]]</span> + </div> + </template> </template> </dom-bind> </div>
diff --git a/chrome/browser/resources/about_nacl/about_nacl.ts b/chrome/browser/resources/about_nacl/about_nacl.ts index 2e82eb2..ee90571e 100644 --- a/chrome/browser/resources/about_nacl/about_nacl.ts +++ b/chrome/browser/resources/about_nacl/about_nacl.ts
@@ -8,29 +8,22 @@ import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; import {$} from 'chrome://resources/js/util.m.js'; -type ModuleListData = { - naclInfo: Array<{key: string, value: string}>, -}; +type NaclInfo = Array<{key: string, value: string}>; -type DomBindElement = HTMLElement&{moduleListData: ModuleListData}; +type DomBindElement = HTMLElement&{naclInfo: NaclInfo}; /** * Asks the C++ NaClDOMHandler to get details about the NaCl and * re-populates the page with the data. */ function initialize() { - sendWithPromise('requestNaClInfo').then((moduleListData: ModuleListData) => { + sendWithPromise('requestNaClInfo').then((response: {naclInfo: NaclInfo}) => { $('loading-message').hidden = true; $('body-container').hidden = false; - /** - * Takes the |moduleListData| input argument which represents data about - * the currently available modules and populates the HTML template - * with that data. - */ const bind = document.body.querySelector<DomBindElement>('dom-bind'); assert(bind); - bind.moduleListData = moduleListData; + bind.naclInfo = response.naclInfo; }); }
diff --git a/chrome/browser/resources/chromeos/accessibility/.eslintrc.js b/chrome/browser/resources/chromeos/accessibility/.eslintrc.js index 77fce40..14271ef 100644 --- a/chrome/browser/resources/chromeos/accessibility/.eslintrc.js +++ b/chrome/browser/resources/chromeos/accessibility/.eslintrc.js
@@ -3,13 +3,14 @@ // found in the LICENSE file. module.exports = { - 'rules': { - 'brace-style': ['error', '1tbs'], - 'curly': ['error', 'multi-line', 'consistent'], - 'eqeqeq': ['error', 'always', {'null': 'ignore'}], - 'no-console': 'off', - 'no-throw-literal': 'off', - 'object-shorthand': ['error', 'always'], - 'prefer-const': ['error', {'destructuring': 'all'}], + 'rules' : { + 'brace-style' : ['error', '1tbs'], + 'curly' : ['error', 'multi-line', 'consistent'], + 'eqeqeq' : ['error', 'always', {'null' : 'ignore'}], + 'no-console' : 'off', + 'no-throw-literal' : 'off', + 'object-shorthand' : ['error', 'always'], + 'prefer-arrow-callback' : ['error', {'allowNamedFunctions' : true}], + 'prefer-const' : ['error', {'destructuring' : 'all'}], }, };
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn index 6cc4f908..97b4fa36 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn
@@ -33,7 +33,6 @@ "background/braille/pan_strategy.js", "background/braille/spans.js", "background/chromevox.js", - "background/chromevox_state.js", "background/command_handler_interface.js", "background/event_source.js", "background/focus_bounds.js", @@ -90,8 +89,9 @@ "background/braille/cursor_dots.js", "background/braille/expanding_braille_translator.js", "background/braille/pan_strategy.js", - "background/color.js", + "background/chromevox_state.js", "background/classic_background.js", + "background/color.js", "background/command_handler.js", "background/console_tts.js", "background/desktop_automation_handler.js",
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/auto_scroll_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/auto_scroll_handler.js index a6413e8..9234e52 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/auto_scroll_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/auto_scroll_handler.js
@@ -5,6 +5,7 @@ /** * @fileoverview Handles auto scrolling on navigation. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; // setTimeout and its clean-up are referencing each other. So, we need to set // "ignoreReadBeforeAssign" in this file. ESLint doesn't support per-line rule
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/auto_scroll_handler_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/auto_scroll_handler_test.js index 301f602d..30f24a0 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/auto_scroll_handler_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/auto_scroll_handler_test.js
@@ -22,6 +22,8 @@ await super.setUpDeferred(); await importModule( 'AutoScrollHandler', '/chromevox/background/auto_scroll_handler.js'); + await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); } /** @return {chrome.automation.AutomationNode} */
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/background.js index 2c92cc5..6635b48 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/background.js
@@ -3,6 +3,7 @@ // found in the LICENSE file. import {BrailleCommandHandler} from '/chromevox/background/braille/braille_command_handler.js'; +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {ChromeVoxBackground} from '/chromevox/background/classic_background.js'; import {CommandHandler} from '/chromevox/background/command_handler.js'; import {DesktopAutomationHandler} from '/chromevox/background/desktop_automation_handler.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/background_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/background_test.js index 0ed3d12..7bf16040 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/background_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/background_test.js
@@ -33,6 +33,8 @@ await importModule( 'ChromeVoxBackground', '/chromevox/background/classic_background.js'); await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); + await importModule( 'CustomAutomationEvent', '/chromevox/common/custom_automation_event.js'); await importModule(
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/base_automation_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/base_automation_handler.js index 0250009..9cf6e47e 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/base_automation_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/base_automation_handler.js
@@ -6,6 +6,7 @@ * @fileoverview Basic facillities to handle events from a single automation * node. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {ChromeVoxEvent} from '/chromevox/common/custom_automation_event.js'; const ActionType = chrome.automation.ActionType;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_background.js index 0689d649f..9c3c37e 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_background.js
@@ -9,6 +9,7 @@ import {BrailleInputHandler} from '/chromevox/background/braille/braille_input_handler.js'; import {BrailleKeyEventRewriter} from '/chromevox/background/braille/braille_key_event_rewriter.js'; import {BrailleTranslatorManager} from '/chromevox/background/braille/braille_translator_manager.js'; +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; /** @implements {BrailleInterface} */ export class BrailleBackground {
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_command_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_command_handler.js index b584ebf..8dff763 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_command_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_command_handler.js
@@ -5,6 +5,7 @@ /** * @fileoverview ChromeVox braille commands. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {DesktopAutomationInterface} from '/chromevox/background/desktop_automation_interface.js'; import {BrailleCommandData} from '/chromevox/common/braille/braille_command_data.js'; import {EventGenerator} from '/common/event_generator.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/chromevox_state.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/chromevox_state.js index 2da4cb5..d8f36b8 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/chromevox_state.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/chromevox_state.js
@@ -8,29 +8,19 @@ * object and to facilitate mocking for tests. */ -goog.provide('ChromeVoxState'); -goog.provide('ChromeVoxStateObserver'); - -goog.require('cursors.Cursor'); -goog.require('cursors.Range'); -goog.require('BrailleKeyEvent'); -goog.require('BridgeHelper'); -goog.require('UserActionMonitor'); - /** - * An interface implemented by objects that want to observe ChromeVox state - * changes. + * An interface implemented by objects to observe ChromeVox state changes. * @interface */ -ChromeVoxStateObserver = class { +export class ChromeVoxStateObserver { /** * @param {cursors.Range} range The new range. * @param {boolean=} opt_fromEditing */ onCurrentRangeChanged(range, opt_fromEditing) {} -}; +} -ChromeVoxState = class { +export class ChromeVoxState { /** @param {ChromeVoxStateObserver} observer */ static addObserver(observer) { ChromeVoxState.observers.push(observer); @@ -142,7 +132,7 @@ * @abstract */ readNextClipboardDataChange() {} -}; +} /** @type {ChromeVoxState} */ ChromeVoxState.instance;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/classic_background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/classic_background.js index 91fdc68..04ad1bf 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/classic_background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/classic_background.js
@@ -7,6 +7,7 @@ */ import {BrailleBackground} from '/chromevox/background/braille/braille_background.js'; import {BrailleCaptionsBackground} from '/chromevox/background/braille/braille_captions_background.js'; +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {ConsoleTts} from '/chromevox/background/console_tts.js'; import {InjectedScriptLoader} from '/chromevox/background/injected_script_loader.js'; import {ChromeVoxPrefs} from '/chromevox/background/prefs.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/color.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/color.js index f07d17e..8667216 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/color.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/color.js
@@ -31,9 +31,7 @@ * @param {number} color An integer representation of a color. * @return {number} */ -Color.getOpacityPercentage = function(color) { - return Math.round(((color >>> 24) / 256) * 100); -}; +Color.getOpacityPercentage = color => Math.round(((color >>> 24) / 256) * 100); /** * Finds the most similar stored color given an rgb value. @@ -41,22 +39,19 @@ * @return {string} */ Color.findClosestMatchingColor = function(target) { - let bestMessageId; - let bestDistance = Number.MAX_VALUE; - - Color.ColorObjectArray.forEach(function(obj) { - const val = obj.value; - const distance = Color.findDistance(target, val); - if (distance < bestDistance) { - bestMessageId = obj.colorMessageId; - bestDistance = distance; + const bestMatch = Color.ColorObjectArray.reduce((closest, color) => { + const distance = Color.findDistance(target, color.value); + if (distance < closest.distance) { + return {color, distance}; } - }); + return closest; + }, {distance: Number.MAX_VALUE}); + // Do not report color if most similar color is too inaccurate. - if (bestDistance > Color.DISTANCE_THRESHOLD) { + if (bestMatch.distance > Color.DISTANCE_THRESHOLD) { return ''; } - return Msgs.getMsg(bestMessageId); + return Msgs.getMsg(bestMatch.color.colorMessageId); }; /**
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/command_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/command_handler.js index 50c55142..d4b127f 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/command_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/command_handler.js
@@ -8,6 +8,7 @@ import {AutoScrollHandler} from '/chromevox/background/auto_scroll_handler.js'; import {BrailleBackground} from '/chromevox/background/braille/braille_background.js'; import {BrailleCaptionsBackground} from '/chromevox/background/braille/braille_captions_background.js'; +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {ChromeVoxBackground} from '/chromevox/background/classic_background.js'; import {Color} from '/chromevox/background/color.js'; import {DesktopAutomationInterface} from '/chromevox/background/desktop_automation_interface.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/desktop_automation_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/desktop_automation_handler.js index f13dd257..d17035a 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/desktop_automation_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/desktop_automation_handler.js
@@ -7,6 +7,7 @@ */ import {AutoScrollHandler} from '/chromevox/background/auto_scroll_handler.js'; import {AutomationObjectConstructorInstaller} from '/chromevox/background/automation_object_constructor_installer.js'; +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {DesktopAutomationInterface} from '/chromevox/background/desktop_automation_interface.js'; import {TextEditHandler} from '/chromevox/background/editing/editing.js'; import {ChromeVoxEvent, CustomAutomationEvent} from '/chromevox/common/custom_automation_event.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/earcons.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/earcons.js index 3c3a834..3cc1ca2 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/earcons.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/earcons.js
@@ -7,6 +7,7 @@ * auditory cues. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {EarconEngine} from '/chromevox/background/earcon_engine.js'; export class Earcons extends AbstractEarcons {
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/editing/editing.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/editing/editing.js index 5a84f2ea..729a06bd 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/editing/editing.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/editing/editing.js
@@ -7,6 +7,7 @@ * appropriate spoken and braille feedback. */ import {BrailleBackground} from '/chromevox/background/braille/braille_background.js'; +import {ChromeVoxState, ChromeVoxStateObserver} from '/chromevox/background/chromevox_state.js'; import {Color} from '/chromevox/background/color.js'; import {EditableLine} from '/chromevox/background/editing/editable_line.js'; import {IntentHandler} from '/chromevox/background/editing/intent_handler.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/find_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/find_handler.js index e64f256..a33abd0 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/find_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/find_handler.js
@@ -5,6 +5,7 @@ /** * @fileoverview Handles output for Chrome's built-in find. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; const TreeChangeObserverFilter = chrome.automation.TreeChangeObserverFilter;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/focus_automation_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/focus_automation_handler.js index 4d2343f..f7c6105 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/focus_automation_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/focus_automation_handler.js
@@ -6,6 +6,7 @@ * @fileoverview Handles automation events on the currently focused node. */ import {BaseAutomationHandler} from '/chromevox/background/base_automation_handler.js'; +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {ChromeVoxEvent} from '/chromevox/common/custom_automation_event.js'; const AutomationEvent = chrome.automation.AutomationEvent;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/gesture_command_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/gesture_command_handler.js index bbaebbc..a0c49d6 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/gesture_command_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/gesture_command_handler.js
@@ -5,6 +5,7 @@ /** * @fileoverview Handles gesture-based commands. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {GestureInterface} from '/chromevox/background/gesture_interface.js'; import {PointerHandler} from '/chromevox/background/pointer_handler.js'; import {GestureCommandData, GestureGranularity} from '/chromevox/common/gesture_command_data.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/keyboard_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/keyboard_handler.js index d9fe0e7f..06718706 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/keyboard_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/keyboard_handler.js
@@ -5,6 +5,7 @@ /** * @fileoverview ChromeVox keyboard handler. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {MathHandler} from '/chromevox/background/math_handler.js'; import {ChromeVoxKbHandler} from '/chromevox/common/keyboard_handler.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/keyboard_handler_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/keyboard_handler_test.js index 110ae7ef..8b7fbaf8f 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/keyboard_handler_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/keyboard_handler_test.js
@@ -15,6 +15,8 @@ await importModule( 'BackgroundKeyboardHandler', '/chromevox/background/keyboard_handler.js'); + await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); window.keyboardHandler = new BackgroundKeyboardHandler(); } };
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/live_regions.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/live_regions.js index 39d2a3c..96b409f7b 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/live_regions.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/live_regions.js
@@ -5,6 +5,7 @@ /** * @fileoverview Implements support for live regions in ChromeVox Next. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; const AutomationNode = chrome.automation.AutomationNode; const RoleType = chrome.automation.RoleType;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/live_regions_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/live_regions_test.js index 9836c6b..85b8ffd 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/live_regions_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/live_regions_test.js
@@ -13,9 +13,11 @@ ChromeVoxLiveRegionsTest = class extends ChromeVoxNextE2ETest { async setUpDeferred() { await super.setUpDeferred(); + await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); + await importModule('LiveRegions', '/chromevox/background/live_regions.js'); window.TreeChangeType = chrome.automation.TreeChangeType; - await importModule('LiveRegions', '/chromevox/background/live_regions.js'); } /**
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/loader.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/loader.js index 9f36869..ea09be2 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/loader.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/loader.js
@@ -16,8 +16,6 @@ goog.require('BrailleKeyEvent'); goog.require('BridgeHelper'); goog.require('ChromeVox'); -goog.require('ChromeVoxState'); -goog.require('ChromeVoxStateObserver'); goog.require('CommandHandlerInterface'); goog.require('EventSourceState'); goog.require('ExtraCellsSpan'); @@ -44,6 +42,7 @@ goog.require('TreeDumper'); goog.require('TreePathRecoveryStrategy'); goog.require('TtsInterface'); +goog.require('UserActionMonitor'); goog.require('ValueSelectionSpan'); goog.require('ValueSpan');
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/logging/log_url_watcher.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/logging/log_url_watcher.js index 15695d1e..0f810a08 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/logging/log_url_watcher.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/logging/log_url_watcher.js
@@ -6,6 +6,7 @@ * @fileoverview Watches the currently focused URL to verify if logging should * occur. */ +import {ChromeVoxState, ChromeVoxStateObserver} from '/chromevox/background/chromevox_state.js'; /** @implements {ChromeVoxStateObserver} */ export class LogUrlWatcher {
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/page_load_sound_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/page_load_sound_handler.js index 6c97f80..89b4207 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/page_load_sound_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/page_load_sound_handler.js
@@ -6,6 +6,7 @@ * @fileoverview Handles page loading sounds based on automation events. */ import {BaseAutomationHandler} from '/chromevox/background/base_automation_handler.js'; +import {ChromeVoxState, ChromeVoxStateObserver} from '/chromevox/background/chromevox_state.js'; import {ChromeVoxEvent} from '/chromevox/common/custom_automation_event.js'; const ActionType = chrome.automation.ActionType;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/panel/panel_background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/panel/panel_background.js index 1791bb1..7c4acfb 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/panel/panel_background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/panel/panel_background.js
@@ -6,6 +6,7 @@ * @fileoverview Handles logic for the ChromeVox panel that requires state from * the background context. */ +import {ChromeVoxState, ChromeVoxStateObserver} from '/chromevox/background/chromevox_state.js'; import {ISearch} from '/chromevox/background/panel/i_search.js'; import {ISearchHandler} from '/chromevox/background/panel/i_search_handler.js'; import {PanelNodeMenuBackground} from '/chromevox/background/panel/panel_node_menu_background.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/panel/panel_node_menu_background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/panel/panel_node_menu_background.js index 92e7dce..dda0cac 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/panel/panel_node_menu_background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/panel/panel_node_menu_background.js
@@ -6,6 +6,7 @@ * @fileoverview Calculates the menu items for the node menus in the ChromeVox * panel. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; const AutomationNode = chrome.automation.AutomationNode;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/pointer_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/pointer_handler.js index 07c7326..7a15b57 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/pointer_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/pointer_handler.js
@@ -7,6 +7,7 @@ * either user touch or mouse input. */ import {BaseAutomationHandler} from '/chromevox/background/base_automation_handler.js'; +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {DesktopAutomationInterface} from '/chromevox/background/desktop_automation_interface.js'; import {CustomAutomationEvent} from '/chromevox/common/custom_automation_event.js'; import {EventGenerator} from '/common/event_generator.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/portals_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/portals_test.js index 64e3113..0a3f3d3 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/portals_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/portals_test.js
@@ -20,6 +20,13 @@ return {enabled: ['blink::features::kPortals']}; } + /** @override */ + async setUpDeferred() { + await super.setUpDeferred(); + await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); + } + get testServer() { return true; }
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/range_automation_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/range_automation_handler.js index 30cd5f1..a0779a7 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/range_automation_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/range_automation_handler.js
@@ -6,6 +6,7 @@ * @fileoverview Handles automation from ChromeVox's current range. */ import {BaseAutomationHandler} from '/chromevox/background/base_automation_handler.js'; +import {ChromeVoxState, ChromeVoxStateObserver} from '/chromevox/background/chromevox_state.js'; import {DesktopAutomationHandler} from '/chromevox/background/desktop_automation_handler.js'; import {ChromeVoxEvent, CustomAutomationEvent} from '/chromevox/common/custom_automation_event.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/smart_sticky_mode.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/smart_sticky_mode.js index 5dc9f4e..48e631907 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/smart_sticky_mode.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/smart_sticky_mode.js
@@ -7,6 +7,7 @@ * when the current range is over an editable; restores sticky mode when not on * an editable. */ +import {ChromeVoxState, ChromeVoxStateObserver} from '/chromevox/background/chromevox_state.js'; import {ChromeVoxBackground} from '/chromevox/background/classic_background.js'; /** @implements {ChromeVoxStateObserver} */
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/smart_sticky_mode_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/smart_sticky_mode_test.js index 1942fd1..db2eddcf 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/smart_sticky_mode_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/smart_sticky_mode_test.js
@@ -15,6 +15,8 @@ await importModule( 'ChromeVoxBackground', '/chromevox/background/classic_background.js'); await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); + await importModule( 'SmartStickyMode', '/chromevox/background/smart_sticky_mode.js'); this.ssm_ = new SmartStickyMode(); // Deregister from actual range changes.
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js index 5e30218..45697c7 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js
@@ -357,11 +357,9 @@ UserActionMonitor.instance; BridgeHelper.registerHandler( - BridgeConstants.UserActionMonitor.TARGET, - BridgeConstants.UserActionMonitor.Action.CREATE, + BridgeTargets.USER_ACTION_MONITOR, BridgeActions.CREATE, (actions) => new Promise(resolve => UserActionMonitor.create(actions, resolve))); BridgeHelper.registerHandler( - BridgeConstants.UserActionMonitor.TARGET, - BridgeConstants.UserActionMonitor.Action.DESTROY, + BridgeTargets.USER_ACTION_MONITOR, BridgeActions.DESTROY, () => UserActionMonitor.destroy());
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor_test.js index 1e31584c..e8826bab 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor_test.js
@@ -17,6 +17,8 @@ '/chromevox/background/keyboard_handler.js'); await importModule( 'ChromeVoxKbHandler', '/chromevox/common/keyboard_handler.js'); + await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); } /**
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/background_bridge.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/background_bridge.js index 2663f9d..0d04aa75 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/background_bridge.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/background_bridge.js
@@ -323,8 +323,7 @@ */ async create(actions) { return BridgeHelper.sendMessage( - BridgeConstants.UserActionMonitor.TARGET, - BridgeConstants.UserActionMonitor.Action.CREATE, actions); + BridgeTargets.USER_ACTION_MONITOR, BridgeActions.CREATE, actions); }, /** @@ -333,7 +332,6 @@ */ async destroy() { return BridgeHelper.sendMessage( - BridgeConstants.UserActionMonitor.TARGET, - BridgeConstants.UserActionMonitor.Action.DESTORY); + BridgeTargets.USER_ACTION_MONITOR, BridgeActions.DESTROY); }, };
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/bridge_constants.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/bridge_constants.js index 9f76ada..a020bb7 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/bridge_constants.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/bridge_constants.js
@@ -17,6 +17,7 @@ LOG_STORE: 'LogStore', PANEL: 'Panel', PANEL_BACKGROUND: 'PanelBackground', + USER_ACTION_MONITOR: 'UserActionMonitor', }; /** * The class that a message is being sent to. @@ -100,16 +101,6 @@ SET_ENABLED: 'setEnabled', }, }, - - UserActionMonitor: { - /** @public {BridgeTarget} */ - TARGET: 'UserActionMonitor', - /** @enum {string} */ - Action: { - CREATE: 'create', - DESTROY: 'destroy', - }, - }, }; /** @@ -118,8 +109,10 @@ BridgeActions = { ADD_MENU_ITEM: 'addMenuItem', CLEAR_LOG: 'clearLog', + CREATE: 'create', CREATE_ALL_NODE_MENU_BACKGROUNDS: 'createAllNodeMenuBackgrounds', CREATE_NEW_I_SEARCH: 'createNewISearch', + DESTROY: 'destroy', DESTROY_I_SEARCH: 'destroyISearch', FOCUS_TAB: 'focusTab', GET_ACTIONS_FOR_CURRENT_NODE: 'getActionsForCurrentNode', @@ -145,7 +138,6 @@ * BridgeConstants.ChromeVoxState.Action | * BridgeConstants.CommandHandler.Action | * BridgeConstants.EventSourceState.Action | - * BridgeConstants.GestureCommandHandler.Action | - * BridgeConstants.UserActionMonitor.Action} + * BridgeConstants.GestureCommandHandler.Action} */ BridgeAction;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/editable_text_base.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/editable_text_base.js index 0e7b9e32..e82b73a18 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/editable_text_base.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/editable_text_base.js
@@ -13,6 +13,7 @@ * extended to override methods that extract lines for multiline fields * or to provide other customizations. */ +import {ChromeVoxState} from '/chromevox/background/chromevox_state.js'; import {AbstractTts} from '/chromevox/common/abstract_tts.js'; /**
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/editable_text_base_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/editable_text_base_test.js index ee55ae2..37c2646 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/editable_text_base_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/editable_text_base_test.js
@@ -88,10 +88,12 @@ /** @override */ async setUpDeferred() { await super.setUpDeferred(); - await importModules('AbstractTts', '/chromevox/common/abstract_tts.js'); - await importModules( + await importModule('AbstractTts', '/chromevox/common/abstract_tts.js'); + await importModule( ['ChromeVoxEditableTextBase', 'TextChangedEvent', 'TypingEcho'], '/chromevox/common/editable_text_base.js'); + await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); // TODO: These tests are all assuming we used the IBeam cursor. // We need to add coverage for block cursor.
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_loader.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_loader.js index caddee6..0272ca6 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_loader.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_loader.js
@@ -10,6 +10,7 @@ goog.require('AutomationUtil'); goog.require('BackgroundBridge'); goog.require('BridgeHelper'); +goog.require('EarconDescription'); goog.require('EventSourceType'); goog.require('KeyCode'); goog.require('KeySequence'); @@ -21,6 +22,7 @@ goog.require('PanelNodeMenuData'); goog.require('QueueMode'); goog.require('UserActionMonitor'); + goog.require('constants'); goog.require('cursors.Cursor'); goog.require('cursors.Range');
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test.js index f06a41c0..0558a96 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test.js
@@ -9,6 +9,13 @@ * Test fixture for Panel. */ ChromeVoxPanelTest = class extends ChromeVoxPanelTestBase { + /** @override */ + async setUpDeferred() { + await super.setUpDeferred(); + await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); + } + fireMockEvent(key) { return function() { const obj = {};
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/tutorial_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/tutorial_test.js index 1407919..527fb4ef 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/tutorial_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/tutorial_test.js
@@ -10,6 +10,13 @@ * Test fixture for the interactive tutorial. */ ChromeVoxTutorialTest = class extends ChromeVoxPanelTestBase { + /** @override */ + async setUpDeferred() { + await super.setUpDeferred(); + await importModule( + 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); + } + assertActiveLessonIndex(expectedIndex) { assertEquals(expectedIndex, this.getTutorial().activeLessonIndex); }
diff --git a/chrome/browser/resources/conflicts/BUILD.gn b/chrome/browser/resources/conflicts/BUILD.gn index 0f12e84..0f1e454 100644 --- a/chrome/browser/resources/conflicts/BUILD.gn +++ b/chrome/browser/resources/conflicts/BUILD.gn
@@ -10,7 +10,6 @@ js_library("about_conflicts") { deps = [ - "//third_party/jstemplate:jstemplate", "//ui/webui/resources/js:cr.m", "//ui/webui/resources/js:util.m", ]
diff --git a/chrome/browser/resources/conflicts/about_conflicts.html b/chrome/browser/resources/conflicts/about_conflicts.html index 2723032fd..76a2ba2 100644 --- a/chrome/browser/resources/conflicts/about_conflicts.html +++ b/chrome/browser/resources/conflicts/about_conflicts.html
@@ -144,113 +144,112 @@ modules registered to load at a <a href="#None">later</a> point.</span> </div> - <div id="modulesTemplate"> - - <div id="third-party-conflicts-status"> - Third-Party Module Features Status - <div> - <span jscontent="thirdPartyFeatureStatus">STATUS</span> - </div> - </div> - - <div id="container" class="vbox-container"> - <div id="top" class="wbox"> - <div class="section-header"> - <span class="section-header-title" - jscontent="moduleCount">COUNT</span> modules + <dom-bind> + <template> + <div id="third-party-conflicts-status"> + Third-Party Module Features Status + <div> + <span>[[data.thirdPartyFeatureStatus]]</span> </div> </div> - </div> - <div class="content"> - <div class="module-name no-modules" - jsdisplay="moduleList.length === 0"> - <div>Unable to detect any modules loaded.</div> + <div id="container" class="vbox-container"> + <div id="top" class="wbox"> + <div class="section-header"> + <span class="section-header-title">[[data.moduleCount]]</span> + <span>modules</span> + </div> + </div> </div> - <div jsdisplay="moduleList.length > 0"> - <table width="100%" cellpadding="0" cellspacing="0"> - <tr class="module-loaded"> - <td valign="top"> - <table cellpadding="2" cellspacing="0" border="0"> - <tr> - <td class="datacell"> - <span dir="ltr">Software</span> - </td> - <td class="datacell"> - <span dir="ltr">Signed by</span> - </td> - <td class="datacell"> - <span dir="ltr">Version</span> - </td> - <td class="datacell"> - <span dir="ltr">Code Id</span> - </td> - <td class="datacell"> - <span dir="ltr">Process types</span> - </td> - <td class="datacell"> - <span dir="ltr">Location</span> - </td> - <td jsdisplay="thirdPartyFeatureEnabled" class="datacell"> - <span dir="ltr">Conflicts Status</span> - </td> - </tr> - <tr jsvalues="data-process:process_types.toLowerCase()" - jsselect="moduleList" class="module"> - <td valign="top" class="datacell"> - <span dir="ltr" - jsvalues=".textContent:description" - class="clearing nowrap"></span> - </td> - <td valign="top" class="datacell"> - <span dir="ltr" jscontent="digital_signer" class="nowrap"> - SIGNER - </span> - </td> - <td valign="top" class="datacell"> - <span dir="ltr" jscontent="version" class="nowrap">VERSION</span> - </td> - <td valign="top" class="datacell"> - <span dir="ltr" jscontent="code_id" class="nowrap">CODE_ID</span> - </td> - <td valign="top" class="datacell"> - <span dir="ltr" jscontent="process_types" class="nowrap"> - PROCESS_TYPES - </span> - </td> - <td valign="top" class="datacell"> - <span class="nowrap"> - <span dir="ltr" jscontent="location">LOCATION</span> - <strong> - <span dir="ltr" jscontent="name">NAME</span> - </strong> - <span dir="ltr" jsdisplay="type_description.length > 0"> - ( - <span dir="ltr" jscontent="type_description"> - MODULE_TYPE - </span> - ) - </span> - </span> - </td> - <span jsdisplay="third_party_module_status.length > 0"> - <td valign="top" class="datacell nowrap"> - <span jscontent="third_party_module_status"> - THIRD_PARTY_MODULE_STATUS - </span> + <div class="content"> + <div class="module-name no-modules" hidden$="[[data.hasModules]]"> + <div>Unable to detect any modules loaded.</div> + </div> + + <div hidden$="[[!data.hasModules]]"> + <table width="100%" cellpadding="0" cellspacing="0"> + <tr class="module-loaded"> + <td valign="top"> + <table cellpadding="2" cellspacing="0" border="0"> + <tr> + <td class="datacell"> + <span dir="ltr">Software</span> + </td> + <td class="datacell"> + <span dir="ltr">Signed by</span> + </td> + <td class="datacell"> + <span dir="ltr">Version</span> + </td> + <td class="datacell"> + <span dir="ltr">Code Id</span> + </td> + <td class="datacell"> + <span dir="ltr">Process types</span> + </td> + <td class="datacell"> + <span dir="ltr">Location</span> + </td> + <td hidden$="[[!data.thirdPartyFeatureEnabled]]" + class="datacell"> + <span dir="ltr">Conflicts Status</span> + </td> + </tr> + + <template is="dom-repeat" items="[[data.moduleList]]"> + <tr data-process$="[[item.process_types]]" + class="module"> + <td valign="top" class="datacell"> + <span dir="ltr" class="clearing nowrap"> + [[item.description]] + </span> + </td> + <td valign="top" class="datacell"> + <span dir="ltr" class="nowrap"> + [[item.digital_signer]] + </span> + </td> + <td valign="top" class="datacell"> + <span dir="ltr" class="nowrap">[[item.version]]</span> + </td> + <td valign="top" class="datacell"> + <span dir="ltr"class="nowrap">[[item.code_id]]</span> + </td> + <td valign="top" class="datacell"> + <span dir="ltr" class="nowrap"> + [[item.process_types]] + </span> + </td> + <td valign="top" class="datacell"> + <span class="nowrap"> + <span dir="ltr">[[item.location]]</span> + <strong> + <span dir="ltr">[[item.name]]</span> + </strong> + <span dir="ltr" + hidden$="[[!item.type_description.length]]"> + ( + <span dir="ltr">[[item.type_description]]</span> + ) + </span> + </span> + </td> + <td valign="top" class="datacell nowrap" + hidden$="[[!item.third_party_module_status.length]]"> + <span>[[item.third_party_module_status]]</span> + </td> + </tr> + </template> + </table> </td> - </span> - </tr> - </table> - </td> - </tr> - </table> - </div> - </div> - </div> + </tr> + </table> + </div> + </div> <!-- content --> + </template> + </dom-bind> </div> -<script src="chrome://resources/js/jstemplate_compiled.js"></script> <script type="module" src="chrome://conflicts/conflicts.js"></script> </body> </html>
diff --git a/chrome/browser/resources/conflicts/about_conflicts.js b/chrome/browser/resources/conflicts/about_conflicts.js index 0e43531..08df95c9 100644 --- a/chrome/browser/resources/conflicts/about_conflicts.js +++ b/chrome/browser/resources/conflicts/about_conflicts.js
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; import {$} from 'chrome://resources/js/util.m.js'; @@ -26,15 +28,15 @@ /** * Takes the |moduleListData| input argument which represents data about - * the currently available modules and populates the html jstemplate + * the currently available modules and populates the HTML template * with that data. It expects an object structure like the above. * @param {Object} moduleListData Information about available modules. */ function renderTemplate(moduleListData) { - // This is the javascript code that processes the template: - const input = new JsEvalContext(moduleListData); - const output = $('modulesTemplate'); - jstProcess(input, output); + const bind = document.body.querySelector('dom-bind'); + + moduleListData.hasModules = moduleListData.moduleList.length > 0; + bind.data = moduleListData; } /** @@ -57,7 +59,7 @@ // Loop through all modules, and hide all that don't match the filter. for (const module of modules) { module.style.display = - module.dataset['process'].includes(filter) ? '' : 'none'; + module.dataset['process'].toLowerCase().includes(filter) ? '' : 'none'; } }
diff --git a/chrome/browser/resources/settings/search_engines_page/search_engine_entry_css.ts b/chrome/browser/resources/settings/search_engines_page/search_engine_entry_css.ts deleted file mode 100644 index 633535f..0000000 --- a/chrome/browser/resources/settings/search_engines_page/search_engine_entry_css.ts +++ /dev/null
@@ -1,8 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -const styleMod = document.createElement('dom-module'); -styleMod.innerHTML = `{__html_template__}`; -styleMod.register('search-engine-entry'); -export {};
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/ButtonData.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/ButtonData.java index 693f64f..ca95779 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/ButtonData.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/ButtonData.java
@@ -63,21 +63,6 @@ mButtonVariant = buttonVariant; } - public ButtonSpec(@NonNull Drawable drawable, @NonNull View.OnClickListener onClickListener, - int contentDescriptionResId, boolean supportsTinting, - @Nullable IPHCommandBuilder iphCommandBuilder, - @AdaptiveToolbarButtonVariant int buttonVariant) { - this(drawable, onClickListener, /*onLongClickListener=*/null, contentDescriptionResId, - supportsTinting, iphCommandBuilder, buttonVariant); - } - - public ButtonSpec(Drawable drawable, View.OnClickListener onClickListener, - int contentDescriptionResId, boolean supportsTinting, - IPHCommandBuilder iphCommandBuilder) { - this(drawable, onClickListener, contentDescriptionResId, supportsTinting, - iphCommandBuilder, AdaptiveToolbarButtonVariant.UNKNOWN); - } - /** Returns the {@link Drawable} for the button icon. */ @NonNull public Drawable getDrawable() {
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/ButtonDataImpl.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/ButtonDataImpl.java index 0cf601e6..8b2f3ca 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/ButtonDataImpl.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/ButtonDataImpl.java
@@ -7,6 +7,9 @@ import android.graphics.drawable.Drawable; import android.view.View; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.user_education.IPHCommandBuilder; @@ -19,22 +22,14 @@ public ButtonDataImpl() {} - public ButtonDataImpl(boolean canShow, Drawable drawable, View.OnClickListener onClickListener, - int contentDescriptionResId, boolean supportsTinting, - IPHCommandBuilder iphCommandBuilder, boolean isEnabled, - @AdaptiveToolbarButtonVariant int buttonVariant) { + public ButtonDataImpl(boolean canShow, @NonNull Drawable drawable, + @NonNull View.OnClickListener onClickListener, int contentDescriptionResId, + boolean supportsTinting, @Nullable IPHCommandBuilder iphCommandBuilder, + boolean isEnabled, @AdaptiveToolbarButtonVariant int buttonVariant) { mCanShow = canShow; mIsEnabled = isEnabled; - mButtonSpec = new ButtonSpec(drawable, onClickListener, contentDescriptionResId, - supportsTinting, iphCommandBuilder, buttonVariant); - } - - // A convenience constructor, doesn't require callers to import AdaptiveToolbarButtonVariant - public ButtonDataImpl(boolean canShow, Drawable drawable, View.OnClickListener onClickListener, - int contentDescriptionResId, boolean supportsTinting, - IPHCommandBuilder iphCommandBuilder, boolean isEnabled) { - this(canShow, drawable, onClickListener, contentDescriptionResId, supportsTinting, - iphCommandBuilder, isEnabled, AdaptiveToolbarButtonVariant.UNKNOWN); + mButtonSpec = new ButtonSpec(drawable, onClickListener, /*onLongClickListener=*/null, + contentDescriptionResId, supportsTinting, iphCommandBuilder, buttonVariant); } @Override @@ -52,6 +47,10 @@ return mButtonSpec; } + public void setButtonSpec(ButtonSpec buttonSpec) { + mButtonSpec = buttonSpec; + } + public void setCanShow(boolean canShow) { mCanShow = canShow; } @@ -60,7 +59,13 @@ mIsEnabled = enabled; } - public void setButtonSpec(ButtonSpec buttonSpec) { - mButtonSpec = buttonSpec; + /** Convenience method to update the IPH command builder. */ + public void updateIPHCommandBuilder(@Nullable IPHCommandBuilder iphCommandBuilder) { + ButtonSpec currentSpec = getButtonSpec(); + ButtonSpec newSpec = new ButtonSpec(currentSpec.getDrawable(), + currentSpec.getOnClickListener(), currentSpec.getOnLongClickListener(), + currentSpec.getContentDescriptionResId(), currentSpec.getSupportsTinting(), + iphCommandBuilder, currentSpec.getButtonVariant()); + setButtonSpec(newSpec); } }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonController.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonController.java index 47aa6fa..13631ed 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonController.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/VoiceToolbarButtonController.java
@@ -198,13 +198,7 @@ return; } - ButtonData.ButtonSpec currentSpec = mButtonData.getButtonSpec(); - ButtonData.ButtonSpec newSpec = new ButtonData.ButtonSpec(currentSpec.getDrawable(), - currentSpec.getOnClickListener(), currentSpec.getContentDescriptionResId(), - currentSpec.getSupportsTinting(), iphCommandBuilder, - currentSpec.getButtonVariant()); - - mButtonData.setButtonSpec(newSpec); + mButtonData.updateIPHCommandBuilder(iphCommandBuilder); } private boolean shouldShowVoiceButton(Tab tab) {
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonControllerTest.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonControllerTest.java index b564a40..e877e095 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonControllerTest.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarButtonControllerTest.java
@@ -124,7 +124,8 @@ mButtonData = new ButtonDataImpl( /*canShow=*/true, /*drawable=*/null, mock(View.OnClickListener.class), /*contentDescriptionResId=*/0, /*supportsTinting=*/false, - /*iphCommandBuilder=*/null, /*isEnabled=*/true); + /*iphCommandBuilder=*/null, /*isEnabled=*/true, + AdaptiveToolbarButtonVariant.UNKNOWN); } @After @@ -500,6 +501,7 @@ private static ButtonSpec makeButtonSpec(@AdaptiveToolbarButtonVariant int variant) { return new ButtonSpec(/*drawable=*/null, mock(View.OnClickListener.class), + /*onLongClickListener=*/null, /*contentDescriptionResId=*/101, /*supportsTinting=*/false, /*iphCommandBuilder=*/null, variant); }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonController.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonController.java index 1a41007..5f2d976 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonController.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/OptionalNewTabButtonController.java
@@ -237,13 +237,6 @@ /* stringId = */ R.string.adaptive_toolbar_button_new_tab_iph, /* accessibilityStringId = */ R.string.adaptive_toolbar_button_new_tab_iph) .setHighlightParams(params); - - ButtonData.ButtonSpec currentSpec = mButtonData.getButtonSpec(); - ButtonData.ButtonSpec newSpec = new ButtonData.ButtonSpec(currentSpec.getDrawable(), - currentSpec.getOnClickListener(), currentSpec.getContentDescriptionResId(), - currentSpec.getSupportsTinting(), iphCommandBuilder, - currentSpec.getButtonVariant()); - - mButtonData.setButtonSpec(newSpec); + mButtonData.updateIPHCommandBuilder(iphCommandBuilder); } }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/OptionalBrowsingModeButtonControllerTest.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/OptionalBrowsingModeButtonControllerTest.java index 642aeee..489446a 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/OptionalBrowsingModeButtonControllerTest.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/top/OptionalBrowsingModeButtonControllerTest.java
@@ -23,6 +23,7 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.toolbar.ButtonDataImpl; import org.chromium.chrome.browser.toolbar.ButtonDataProvider; +import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures.AdaptiveToolbarButtonVariant; import org.chromium.chrome.browser.user_education.UserEducationHelper; import java.util.Arrays; @@ -209,6 +210,7 @@ return new ButtonDataImpl( /*canShow=*/true, /*drawable=*/null, /*onClickListener=*/null, /*contentDescriptionResId=*/0, /*supportsTinting=*/false, - /*iphCommandBuilder=*/null, /*isEnabled=*/true); + /*iphCommandBuilder=*/null, /*isEnabled=*/true, + AdaptiveToolbarButtonVariant.UNKNOWN); } }
diff --git a/chrome/browser/ui/ash/assistant/assistant_browsertest.cc b/chrome/browser/ui/ash/assistant/assistant_browsertest.cc index 2b67e3b58..a7854d4 100644 --- a/chrome/browser/ui/ash/assistant/assistant_browsertest.cc +++ b/chrome/browser/ui/ash/assistant/assistant_browsertest.cc
@@ -174,6 +174,23 @@ }); } +IN_PROC_BROWSER_TEST_F(AssistantBrowserTest, + ShouldDisplayTextResponseWithTwoContiniousQueries) { + tester()->StartAssistantAndWaitForReady(); + + ShowAssistantUi(); + + tester()->SendTextQuery("phone"); + tester()->SendTextQuery("test"); + tester()->ExpectAnyOfTheseTextResponses({ + "No one told me there would be a test", + "You're coming in loud and clear", + "debug OK", + "I can assure you, this thing's on", + "Is this thing on?", + }); +} + IN_PROC_BROWSER_TEST_F(AssistantBrowserTest, ShouldDisplayCardResponse) { tester()->StartAssistantAndWaitForReady();
diff --git a/chrome/browser/ui/ash/wallpaper_controller_client_impl.cc b/chrome/browser/ui/ash/wallpaper_controller_client_impl.cc index 12cf16f..18864f79 100644 --- a/chrome/browser/ui/ash/wallpaper_controller_client_impl.cc +++ b/chrome/browser/ui/ash/wallpaper_controller_client_impl.cc
@@ -786,7 +786,8 @@ weak_factory_.GetWeakPtr(), std::move(callback)); google_photos_photos_fetchers_[account_id]->AddRequestAndStartIfNecessary( id, /*album_id=*/absl::nullopt, - /*resume_token=*/absl::nullopt, std::move(fetched_callback)); + /*resume_token=*/absl::nullopt, /*shuffle=*/false, + std::move(fetched_callback)); } void WallpaperControllerClientImpl::FetchDailyGooglePhotosPhoto( @@ -806,7 +807,8 @@ weak_factory_.GetWeakPtr(), account_id, std::move(callback)); google_photos_photos_fetchers_[account_id]->AddRequestAndStartIfNecessary( /*item_id=*/absl::nullopt, album_id, - /*resume_token=*/absl::nullopt, std::move(fetched_callback)); + /*resume_token=*/absl::nullopt, /*shuffle=*/true, + std::move(fetched_callback)); } void WallpaperControllerClientImpl::FetchGooglePhotosAccessToken(
diff --git a/chrome/browser/ui/omnibox/omnibox_pedal_implementations.cc b/chrome/browser/ui/omnibox/omnibox_pedal_implementations.cc index f0033c3..f6d61c53e 100644 --- a/chrome/browser/ui/omnibox/omnibox_pedal_implementations.cc +++ b/chrome/browser/ui/omnibox/omnibox_pedal_implementations.cc
@@ -1630,20 +1630,18 @@ }; #if BUILDFLAG(IS_ANDROID) - if (testing || OmniboxFieldTrial::IsPedalsAndroidBatch1Enabled()) { - if (!incognito) { - add(new OmniboxPedalClearBrowsingData(incognito)); - } - add(new OmniboxPedalManagePasswords()); - add(new OmniboxPedalUpdateCreditCard()); - add(new OmniboxPedalLaunchIncognito()); - add(new OmniboxPedalRunChromeSafetyCheck()); - add(new OmniboxPedalPlayChromeDinoGame()); - add(new OmniboxPedalManageSiteSettings()); - add(new OmniboxPedalManageChromeSettings()); - add(new OmniboxPedalViewChromeHistory()); - add(new OmniboxPedalManageChromeAccessibility()); + if (!incognito) { + add(new OmniboxPedalClearBrowsingData(incognito)); } + add(new OmniboxPedalManagePasswords()); + add(new OmniboxPedalUpdateCreditCard()); + add(new OmniboxPedalLaunchIncognito()); + add(new OmniboxPedalRunChromeSafetyCheck()); + add(new OmniboxPedalPlayChromeDinoGame()); + add(new OmniboxPedalManageSiteSettings()); + add(new OmniboxPedalManageChromeSettings()); + add(new OmniboxPedalViewChromeHistory()); + add(new OmniboxPedalManageChromeAccessibility()); #else // BUILDFLAG(IS_ANDROID) add(new OmniboxPedalClearBrowsingData(incognito));
diff --git a/chrome/browser/ui/tabs/tab_strip_model.cc b/chrome/browser/ui/tabs/tab_strip_model.cc index 3c9c3c1..7bf38a3 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.cc +++ b/chrome/browser/ui/tabs/tab_strip_model.cc
@@ -2133,15 +2133,19 @@ GetTabGroupForTab(current_index); const int first_non_pinned_tab_index = IndexOfFirstNonPinnedTab(); - int first_valid_index = + const int first_valid_index = IsTabPinned(current_index) ? 0 : first_non_pinned_tab_index; - int last_valid_index = + const int last_valid_index = IsTabPinned(current_index) ? first_non_pinned_tab_index - 1 : count() - 1; int target_index = std::max( std::min(current_index + offset, last_valid_index), first_valid_index); - absl::optional<tab_groups::TabGroupId> target_group = - GetTabGroupForTab(target_index); + // If the target index is the same as the current index, then the tab is at a + // min/max boundary and being moved further in that direction. In that case, + // the tab could still be ungrouped to move one more slot. + const absl::optional<tab_groups::TabGroupId> target_group = + (target_index == current_index) ? absl::nullopt + : GetTabGroupForTab(target_index); // If the tab is at a group boundary and the group is expanded, instead of // actually moving the tab just change its group membership.
diff --git a/chrome/browser/ui/tabs/tab_strip_model_unittest.cc b/chrome/browser/ui/tabs/tab_strip_model_unittest.cc index b0a5a05..6f80a90 100644 --- a/chrome/browser/ui/tabs/tab_strip_model_unittest.cc +++ b/chrome/browser/ui/tabs/tab_strip_model_unittest.cc
@@ -2600,6 +2600,25 @@ strip.CloseAllTabs(); } +TEST_F(TabStripModelTest, MoveTabNext_GroupAtEnd) { + TestTabStripModelDelegate delegate; + TabStripModel strip(&delegate, profile()); + ASSERT_NO_FATAL_FAILURE(PrepareTabstripForSelectionTest(&strip, 2, 0, "0")); + EXPECT_EQ("0 1", GetTabStripStateString(strip)); + + tab_groups::TabGroupId group = strip.AddToNewGroup({0, 1}); + + strip.MoveTabNext(); + EXPECT_EQ("1 0", GetTabStripStateString(strip)); + EXPECT_EQ(strip.GetTabGroupForTab(1), group); + + strip.MoveTabNext(); + EXPECT_EQ("1 0", GetTabStripStateString(strip)); + EXPECT_EQ(strip.GetTabGroupForTab(1), absl::nullopt); + + strip.CloseAllTabs(); +} + TEST_F(TabStripModelTest, MoveTabNext_PinnedDoesNotGroup) { TestTabStripModelDelegate delegate; TabStripModel strip(&delegate, profile()); @@ -2680,6 +2699,25 @@ strip.CloseAllTabs(); } +TEST_F(TabStripModelTest, MoveTabPrevious_GroupAtEnd) { + TestTabStripModelDelegate delegate; + TabStripModel strip(&delegate, profile()); + ASSERT_NO_FATAL_FAILURE(PrepareTabstripForSelectionTest(&strip, 2, 0, "1")); + EXPECT_EQ("0 1", GetTabStripStateString(strip)); + + tab_groups::TabGroupId group = strip.AddToNewGroup({0, 1}); + + strip.MoveTabPrevious(); + EXPECT_EQ("1 0", GetTabStripStateString(strip)); + EXPECT_EQ(strip.GetTabGroupForTab(0), group); + + strip.MoveTabPrevious(); + EXPECT_EQ("1 0", GetTabStripStateString(strip)); + EXPECT_EQ(strip.GetTabGroupForTab(0), absl::nullopt); + + strip.CloseAllTabs(); +} + TEST_F(TabStripModelTest, MoveSelectedTabsTo) { struct TestData { // Number of tabs the tab strip should have.
diff --git a/chrome/browser/ui/views/download/download_item_view.cc b/chrome/browser/ui/views/download/download_item_view.cc index 4be1a04..afc774a 100644 --- a/chrome/browser/ui/views/download/download_item_view.cc +++ b/chrome/browser/ui/views/download/download_item_view.cc
@@ -33,8 +33,6 @@ #include "chrome/browser/download/chrome_download_manager_delegate.h" #include "chrome/browser/download/download_stats.h" #include "chrome/browser/download/drag_download_item.h" -#include "chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h" -#include "chrome/browser/enterprise/connectors/analysis/content_analysis_downloads_delegate.h" #include "chrome/browser/enterprise/connectors/common.h" #include "chrome/browser/enterprise/connectors/connectors_service.h" #include "chrome/browser/icon_manager.h" @@ -137,12 +135,6 @@ // This is only used when the text size is large. constexpr int kMinimumVerticalPadding = 2 + kTopBottomPadding; -// The analysis service tag for data loss prevention. -const char kDlpTag[] = "dlp"; - -// The analysis service tag for malware. -const char kMalwareTag[] = "malware"; - // A stub subclass of Button that has no visuals. class TransparentButton : public views::Button { public: @@ -1292,56 +1284,14 @@ review_button_->SetEnabled(false); dropdown_button_->SetEnabled(false); - auto danger_type = model_->GetDangerType(); - auto state = enterprise_connectors::FinalContentAnalysisResult::FAILURE; - if (danger_type == download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING) { - state = enterprise_connectors::FinalContentAnalysisResult::WARNING; - } - - const char* tag = - (danger_type == - download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING || - danger_type == - download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_BLOCK - ? kDlpTag - : kMalwareTag); - - auto* connectors_service = - enterprise_connectors::ConnectorsServiceFactory::GetForBrowserContext( - model_->profile()); - - const std::u16string filename = ElidedFilename(*file_name_label_); - std::u16string custom_message = - connectors_service - ->GetCustomMessage( - enterprise_connectors::AnalysisConnector::FILE_DOWNLOADED, tag) - .value_or(u""); - GURL learn_more_url = - connectors_service - ->GetLearnMoreUrl( - enterprise_connectors::AnalysisConnector::FILE_DOWNLOADED, tag) - .value_or(GURL()); - - bool bypass_justification_required = - connectors_service - ->GetBypassJustificationRequired( - enterprise_connectors::AnalysisConnector::FILE_DOWNLOADED, tag) - .value_or(false); - - // This dialog opens itself, and is thereafter owned by constrained window - // code. - new enterprise_connectors::ContentAnalysisDialog( - std::make_unique<enterprise_connectors::ContentAnalysisDownloadsDelegate>( - filename, custom_message, learn_more_url, - bypass_justification_required, - base::BindOnce(&DownloadItemView::ExecuteCommand, - base::Unretained(this), DownloadCommands::KEEP), - base::BindOnce(&DownloadItemView::ExecuteCommand, - base::Unretained(this), DownloadCommands::DISCARD), - model_->download()), + enterprise_connectors::ShowDownloadReviewDialog( + ElidedFilename(*file_name_label_), model_->profile(), model_->download(), shelf_->browser()->tab_strip_model()->GetActiveWebContents(), - safe_browsing::DeepScanAccessPoint::DOWNLOAD, /* file_count */ 1, state, - model_->download()); + model_->GetDangerType(), + base::BindOnce(&DownloadItemView::ExecuteCommand, base::Unretained(this), + DownloadCommands::KEEP), + base::BindOnce(&DownloadItemView::ExecuteCommand, base::Unretained(this), + DownloadCommands::DISCARD)); } void DownloadItemView::ShowOpenDialog(content::WebContents* web_contents) {
diff --git a/chrome/browser/ui/webui/conflicts/conflicts_ui.cc b/chrome/browser/ui/webui/conflicts/conflicts_ui.cc index 368b5b5..a673cdb 100644 --- a/chrome/browser/ui/webui/conflicts/conflicts_ui.cc +++ b/chrome/browser/ui/webui/conflicts/conflicts_ui.cc
@@ -11,10 +11,8 @@ #include "chrome/browser/ui/webui/conflicts/conflicts_handler.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" -#include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/theme_resources.h" -#include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui_data_source.h" #include "services/network/public/mojom/content_security_policy.mojom.h" #include "ui/base/resource/resource_bundle.h" @@ -26,10 +24,7 @@ content::WebUIDataSource::Create(chrome::kChromeUIConflictsHost); source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::ScriptSrc, - "script-src chrome://resources 'self' 'unsafe-eval';"); - source->OverrideContentSecurityPolicy( - network::mojom::CSPDirectiveName::TrustedTypes, - "trusted-types jstemplate;"); + "script-src chrome://resources 'self';"); source->AddResourcePath("conflicts.js", IDR_ABOUT_CONFLICTS_JS); source->AddResourcePath("warning.svg", IDR_ABOUT_CONFLICTS_WARNING_SVG);
diff --git a/chrome/browser/ui/webui/nacl_ui.cc b/chrome/browser/ui/webui/nacl_ui.cc index fbf9a94..92291be5 100644 --- a/chrome/browser/ui/webui/nacl_ui.cc +++ b/chrome/browser/ui/webui/nacl_ui.cc
@@ -60,10 +60,7 @@ content::WebUIDataSource::Create(chrome::kChromeUINaClHost); source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::ScriptSrc, - "script-src chrome://resources 'self' 'unsafe-eval';"); - source->OverrideContentSecurityPolicy( - network::mojom::CSPDirectiveName::TrustedTypes, - "trusted-types jstemplate;"); + "script-src chrome://resources 'self';"); source->UseStringsJs(); source->AddResourcePath("about_nacl.css", IDR_ABOUT_NACL_CSS); source->AddResourcePath("about_nacl.js", IDR_ABOUT_NACL_JS);
diff --git a/chrome/browser/ui/webui/policy/policy_ui.cc b/chrome/browser/ui/webui/policy/policy_ui.cc index b145691..6b26cb6 100644 --- a/chrome/browser/ui/webui/policy/policy_ui.cc +++ b/chrome/browser/ui/webui/policy/policy_ui.cc
@@ -14,6 +14,7 @@ #include "components/grit/dev_ui_components_resources.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui.h" +#include "services/network/public/mojom/content_security_policy.mojom.h" #include "ui/base/webui/web_ui_util.h" namespace { @@ -83,7 +84,18 @@ source->AddResourcePath("policy.css", IDR_POLICY_CSS); source->AddResourcePath("policy_base.js", IDR_POLICY_BASE_JS); source->AddResourcePath("policy.js", IDR_POLICY_JS); + source->AddResourcePath("policy_conflict.js", IDR_POLICY_POLICY_CONFLICT_JS); + source->AddResourcePath("policy_row.js", IDR_POLICY_POLICY_ROW_JS); + source->AddResourcePath("policy_precedence_row.js", + IDR_POLICY_POLICY_PRECEDENCE_ROW_JS); + source->AddResourcePath("policy_table.js", IDR_POLICY_POLICY_TABLE_JS); + source->AddResourcePath("status_box.js", IDR_POLICY_STATUS_BOX_JS); source->SetDefaultResource(IDR_POLICY_HTML); + + source->EnableReplaceI18nInJS(); + source->OverrideContentSecurityPolicy( + network::mojom::CSPDirectiveName::TrustedTypes, + "trusted-types static-types;"); return source; }
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index ac8964d..db6849e 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1653652279-b776df1ece98a9c774e9b0438b2b266676c895ce.profdata +chrome-mac-main-1653674373-ea5fe4c1bad0af9f9937b9344482cc6a8e01974d.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 1eabfb8..fcf91e8 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1653663221-586ad2636e97b2c092190f2c884a2a1942a84385.profdata +chrome-win32-main-1653674373-acea6486b590716fd115fd9b37b69c6003616bc8.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index ead3d01..91174da 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1653663221-1d7f02af064b740916358abe3db80ef6b8a36865.profdata +chrome-win64-main-1653682408-7e1dd82cfc97a287ee426e4efb8f4a3dc5bb5f1f.profdata
diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index d218489..de183da 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn
@@ -359,11 +359,17 @@ public_deps += [ ":app_mode_app_support" ] } - if (is_chromeos_ash) { + if (is_chromeos) { assert(enable_extensions) sources += [ "extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.cc", "extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.h", + ] + deps += [ "//chrome/common/chromeos/extensions" ] + } + if (is_chromeos_ash) { + assert(enable_extensions) + sources += [ "extensions/api/input_ime/input_components_handler.cc", "extensions/api/input_ime/input_components_handler.h", ]
diff --git a/chrome/common/extensions/api/_api_features.json b/chrome/common/extensions/api/_api_features.json index 27c353e..ecea20d0 100644 --- a/chrome/common/extensions/api/_api_features.json +++ b/chrome/common/extensions/api/_api_features.json
@@ -533,6 +533,10 @@ "dependencies": ["permission:gcm"], "contexts": ["blessed_extension"] }, + "sharedStoragePrivate": { + "dependencies": ["permission:sharedStoragePrivate"], + "contexts": ["blessed_extension"] + }, "history": { "dependencies": ["permission:history"], "contexts": ["blessed_extension"]
diff --git a/chrome/common/extensions/api/_manifest_features.json b/chrome/common/extensions/api/_manifest_features.json index f4a879e..0791093d 100644 --- a/chrome/common/extensions/api/_manifest_features.json +++ b/chrome/common/extensions/api/_manifest_features.json
@@ -140,7 +140,7 @@ }, { "channel": "stable", "extension_types": ["legacy_packaged_app"], - "platforms": ["chromeos"], + "platforms": ["chromeos", "lacros"], "allowlist": [ "0EA6B717932AD64C469C1CCB6911457733295907", // http://crbug.com/673004 "58B0C2968C335964D5433E89CA4D86628A0E3D4B" // http://crbug.com/673004
diff --git a/chrome/common/extensions/api/_permission_features.json b/chrome/common/extensions/api/_permission_features.json index 355e870..e0868db1 100644 --- a/chrome/common/extensions/api/_permission_features.json +++ b/chrome/common/extensions/api/_permission_features.json
@@ -371,11 +371,11 @@ "fileSystemProvider": [{ "channel": "stable", "extension_types": ["extension", "platform_app"], - "platforms": ["chromeos"] + "platforms": ["chromeos", "lacros"] }, { "channel": "stable", "extension_types": ["legacy_packaged_app"], - "platforms": ["chromeos"], + "platforms": ["chromeos", "lacros"], "allowlist": [ "0EA6B717932AD64C469C1CCB6911457733295907", // http://crbug.com/673004 "58B0C2968C335964D5433E89CA4D86628A0E3D4B" // http://crbug.com/673004 @@ -395,6 +395,22 @@ "extension", "legacy_packaged_app", "hosted_app", "platform_app" ] }, + // Used by gnubbyd in ash and lacros. Stores small amounts of data in ash + // prefs which is shared by ash and lacros versions of the extension. + // TODO(b/231890240): Once Terminal SWA runs in lacros rather than ash, we can + // migrate gnubbyd back to using chrome.storage.local and remove this private + // API. + "sharedStoragePrivate": { + "channel": "stable", + "extension_types": ["extension", "platform_app"], + "platforms": ["chromeos", "lacros"], + "allowlist": [ + "6F9E349A0561C78A0D3F41496FE521C5151C7F71", // gnubbyd app stable + "C06709A259378015404ED20F75C7D08547E0F10B", // gnubbyd app dev + "57A1B95957F9EDB159FA9278BF87FE70DF62BED8", // ske stable + "05E9C7F02C6E55E1DE334A1B1EFD2D9A68F10E34" // ske dev + ] + }, "history": { "channel": "stable", "extension_types": ["extension", "legacy_packaged_app"]
diff --git a/chrome/common/extensions/api/api_sources.gni b/chrome/common/extensions/api/api_sources.gni index f0c08e3..5df10f3 100644 --- a/chrome/common/extensions/api/api_sources.gni +++ b/chrome/common/extensions/api/api_sources.gni
@@ -81,12 +81,15 @@ "enterprise_platform_keys.idl", "enterprise_platform_keys_internal.idl", "file_browser_handler_internal.json", + "file_system_provider.idl", + "file_system_provider_internal.idl", "login.idl", "login_screen_storage.idl", "login_state.idl", "platform_keys_internal.idl", "platform_keys.idl", "quick_unlock_private.idl", + "shared_storage_private.idl", "vpn_provider.idl", ] @@ -103,8 +106,6 @@ "enterprise_platform_keys_private.json", "file_manager_private.idl", "file_manager_private_internal.idl", - "file_system_provider.idl", - "file_system_provider_internal.idl", "input_ime.json", "input_method_private.json", "login_screen_ui.idl",
diff --git a/chrome/common/extensions/api/shared_storage_private.idl b/chrome/common/extensions/api/shared_storage_private.idl new file mode 100644 index 0000000..8ef7c83 --- /dev/null +++ b/chrome/common/extensions/api/shared_storage_private.idl
@@ -0,0 +1,30 @@ +// Copyright 2022 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. + +// Used by gnubbyd in ash and lacros. Stores small amounts of data in ash prefs +// which is shared by ash and lacros versions of the extension. +// TODO(b/231890240): Once Terminal SWA runs in lacros rather than ash, we can +// migrate gnubbyd back to using chrome.storage.local and remove this private +// API. +[platforms=("chromeos", "lacros"), + implemented_in="chrome/browser/extensions/api/shared_storage/shared_storage_private_api.h"] +namespace sharedStoragePrivate { + + callback GetCallback = void (object items); + callback SetCallback = void (); + callback RemoveCallback = void (); + + interface Functions { + // Gets all items from shared extension local storage. + [supportsPromises] static void get(GetCallback callback); + + // Sets given items into shared extension local storage. + [supportsPromises] static void set(object items, SetCallback callback); + + // Removes item from shared extension local storage. + [supportsPromises] static void remove( + DOMString[] keys, RemoveCallback callback); + }; +}; +
diff --git a/chrome/common/extensions/chrome_manifest_handlers.cc b/chrome/common/extensions/chrome_manifest_handlers.cc index bdec9c8..49c78e9 100644 --- a/chrome/common/extensions/chrome_manifest_handlers.cc +++ b/chrome/common/extensions/chrome_manifest_handlers.cc
@@ -26,10 +26,10 @@ #if BUILDFLAG(IS_CHROMEOS) #include "chrome/common/extensions/api/file_browser_handlers/file_browser_handler.h" +#include "chrome/common/extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.h" #endif #if BUILDFLAG(IS_CHROMEOS_ASH) -#include "chrome/common/extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.h" #include "chrome/common/extensions/api/input_ime/input_components_handler.h" #endif @@ -61,11 +61,11 @@ #if BUILDFLAG(IS_CHROMEOS) registry->RegisterHandler(std::make_unique<FileBrowserHandlerParser>()); + registry->RegisterHandler( + std::make_unique<FileSystemProviderCapabilitiesHandler>()); #endif #if BUILDFLAG(IS_CHROMEOS_ASH) - registry->RegisterHandler( - std::make_unique<FileSystemProviderCapabilitiesHandler>()); registry->RegisterHandler(std::make_unique<InputComponentsHandler>()); #endif }
diff --git a/chrome/common/extensions/manifest_tests/extension_manifests_web_accessible_resources_unittest.cc b/chrome/common/extensions/manifest_tests/extension_manifests_web_accessible_resources_unittest.cc index c3afd33..db626d53 100644 --- a/chrome/common/extensions/manifest_tests/extension_manifests_web_accessible_resources_unittest.cc +++ b/chrome/common/extensions/manifest_tests/extension_manifests_web_accessible_resources_unittest.cc
@@ -327,28 +327,28 @@ EXPECT_EQ(base::Value::Type::DICTIONARY, manifest_value.type()); return ManifestData(std::move(manifest_value), "test"); }; - scoped_refptr<const Extension> extension1 = + scoped_refptr<const Extension> extension_callee = LoadAndExpectSuccess(get_manifest_data()); - scoped_refptr<const Extension> extension2 = - LoadAndExpectSuccess(get_manifest_data(extension1->id())); - auto initiator_origin = url::Origin::Create(extension2->url()); + scoped_refptr<const Extension> extension_caller = + LoadAndExpectSuccess(get_manifest_data(extension_callee->id())); + auto caller_origin = url::Origin::Create(extension_caller->url()); EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible( - extension2.get(), "test", initiator_origin)); + extension_caller.get(), "test", caller_origin)); EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible( - extension2.get(), "inaccessible", initiator_origin)); - EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible( - extension1.get(), "test", initiator_origin)); + extension_caller.get(), "inaccessible", caller_origin)); + EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible( + extension_callee.get(), "test", caller_origin)); // Test web accessible resource access by specifying an extension wildcard. scoped_refptr<const Extension> wildcard_extension = LoadAndExpectSuccess(get_manifest_data("*")); EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible( - wildcard_extension.get(), "test", initiator_origin)); + wildcard_extension.get(), "test", caller_origin)); auto web_origin = url::Origin::Create(GURL("http://example.com")); EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible( wildcard_extension.get(), "test", web_origin)); EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible( - wildcard_extension.get(), "inaccessible", initiator_origin)); + wildcard_extension.get(), "inaccessible", caller_origin)); } // Tests wildcards of matches.
diff --git a/chrome/common/extensions/permissions/permission_set_unittest.cc b/chrome/common/extensions/permissions/permission_set_unittest.cc index c42251c..390dca74 100644 --- a/chrome/common/extensions/permissions/permission_set_unittest.cc +++ b/chrome/common/extensions/permissions/permission_set_unittest.cc
@@ -828,6 +828,7 @@ skip.insert(APIPermissionID::kFileBrowserHandlerInternal); skip.insert(APIPermissionID::kFileManagerPrivate); skip.insert(APIPermissionID::kFirstRunPrivate); + skip.insert(APIPermissionID::kSharedStoragePrivate); skip.insert(APIPermissionID::kIdentityPrivate); skip.insert(APIPermissionID::kInputMethodPrivate); skip.insert(APIPermissionID::kLanguageSettingsPrivate);
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 74a9365..4011bb6 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -1154,6 +1154,9 @@ // managed guest session clean-up procedure. const char kRestrictedManagedGuestSessionExtensionCleanupExemptList[] = "restricted_managed_guest_session_extension_cleanup_exempt_list"; + +// Dictionary pref for shared extension storage for device pin. +const char kSharedStorage[] = "shared_storage"; #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 445d64e..c37e4df 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -361,6 +361,7 @@ extern const char kSystemProxyUserTrafficHostAndPort[]; extern const char kEduCoexistenceArcMigrationCompleted[]; extern const char kRestrictedManagedGuestSessionExtensionCleanupExemptList[]; +extern const char kSharedStorage[]; #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(IS_CHROMEOS) extern const char kForceMaximizeOnFirstRun[];
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 345c2e3..55d7ec2f 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -1683,16 +1683,20 @@ #endif // BUILDFLAG(ENABLE_EXTENSIONS) } -bool ChromeContentRendererClient::IsSafeRedirectTarget(const GURL& url) { +bool ChromeContentRendererClient::IsSafeRedirectTarget(const GURL& from_url, + const GURL& to_url) { #if BUILDFLAG(ENABLE_EXTENSIONS) - if (url.SchemeIs(extensions::kExtensionScheme)) { + if (to_url.SchemeIs(extensions::kExtensionScheme)) { const extensions::Extension* extension = - extensions::RendererExtensionRegistry::Get()->GetByID(url.host()); + extensions::RendererExtensionRegistry::Get()->GetByID(to_url.host()); if (!extension) return false; // TODO(solomonkinard): Use initiator_origin and add tests. - return extensions::WebAccessibleResourcesInfo::IsResourceWebAccessible( - extension, url.path(), absl::optional<url::Origin>()); + if (extensions::WebAccessibleResourcesInfo::IsResourceWebAccessible( + extension, to_url.path(), absl::optional<url::Origin>())) { + return true; + } + return extension->guid() == from_url.host(); } #endif // BUILDFLAG(ENABLE_EXTENSIONS) return true;
diff --git a/chrome/renderer/chrome_content_renderer_client.h b/chrome/renderer/chrome_content_renderer_client.h index 64b54bc..ca2bd2b 100644 --- a/chrome/renderer/chrome_content_renderer_client.h +++ b/chrome/renderer/chrome_content_renderer_client.h
@@ -193,7 +193,7 @@ blink::URLLoaderThrottleProviderType provider_type) override; blink::WebFrame* FindFrame(blink::WebLocalFrame* relative_to_frame, const std::string& name) override; - bool IsSafeRedirectTarget(const GURL& url) override; + bool IsSafeRedirectTarget(const GURL& from_url, const GURL& to_url) override; void DidSetUserAgent(const std::string& user_agent) override; void AppendContentSecurityPolicy( const blink::WebURL& url,
diff --git a/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc b/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc index aa839e3..422bd70 100644 --- a/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc +++ b/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc
@@ -152,6 +152,8 @@ IDR_ENTERPRISE_PLATFORM_KEYS_TOKEN_JS); source_map->RegisterSource("fileBrowserHandler", IDR_FILE_BROWSER_HANDLER_CUSTOM_BINDINGS_JS); + source_map->RegisterSource("fileSystemProvider", + IDR_FILE_SYSTEM_PROVIDER_CUSTOM_BINDINGS_JS); source_map->RegisterSource("platformKeys", IDR_PLATFORM_KEYS_CUSTOM_BINDINGS_JS); source_map->RegisterSource("platformKeys.getPublicKeyUtil", @@ -175,8 +177,6 @@ IDR_CERTIFICATE_PROVIDER_CUSTOM_BINDINGS_JS); source_map->RegisterSource("fileManagerPrivate", IDR_FILE_MANAGER_PRIVATE_CUSTOM_BINDINGS_JS); - source_map->RegisterSource("fileSystemProvider", - IDR_FILE_SYSTEM_PROVIDER_CUSTOM_BINDINGS_JS); source_map->RegisterSource("terminalPrivate", IDR_TERMINAL_PRIVATE_CUSTOM_BINDINGS_JS);
diff --git a/chrome/renderer/extensions/resource_request_policy.cc b/chrome/renderer/extensions/resource_request_policy.cc index c56f648..9f5612a 100644 --- a/chrome/renderer/extensions/resource_request_policy.cc +++ b/chrome/renderer/extensions/resource_request_policy.cc
@@ -42,13 +42,25 @@ // TODO(devlin): Should we incorporate this into // WebAccessibleResourcesInfo? (extension.is_hosted_app() && !IconsInfo::GetIcons(&extension).empty())) { - web_accessible_ids_.insert(extension.id()); + web_accessible_resources_map_[extension.id()] = extension.guid(); } } +bool ResourceRequestPolicy::IsWebAccessibleHost(const std::string& host) { + if (web_accessible_resources_map_.find(host) != + web_accessible_resources_map_.end()) { + return true; + } + for (const auto& [id, guid] : web_accessible_resources_map_) { + if (host == guid) + return true; + } + return false; +} + void ResourceRequestPolicy::OnExtensionUnloaded( const ExtensionId& extension_id) { - web_accessible_ids_.erase(extension_id); + web_accessible_resources_map_.erase(extension_id); } // This method does a security check whether chrome-extension:// URLs can be @@ -118,7 +130,7 @@ // extension with no web accessible resources. We aren't worried about any // extensions with web accessible resources, since those are inherently // identifiable. - if (!is_dev_tools && !web_accessible_ids_.count(extension_origin.host())) { + if (!is_dev_tools && !IsWebAccessibleHost(extension_origin.host())) { // Failures are recorded here, successes will be in the browser. RecordExtensionResourceAccessResult( ukm::SourceIdObj::FromInt64(frame->GetDocument().GetUkmSourceId()), @@ -128,7 +140,8 @@ } const Extension* extension = - RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(resource_url); + RendererExtensionRegistry::Get()->GetExtensionOrAppByURL( + resource_url, true /*include_guid*/); if (is_dev_tools) { // Allow the load in the case of a non-existent extension. We'll just get a // 404 from the browser process.
diff --git a/chrome/renderer/extensions/resource_request_policy.h b/chrome/renderer/extensions/resource_request_policy.h index 63566f0..da943fe 100644 --- a/chrome/renderer/extensions/resource_request_policy.h +++ b/chrome/renderer/extensions/resource_request_policy.h
@@ -5,8 +5,9 @@ #ifndef CHROME_RENDERER_EXTENSIONS_RESOURCE_REQUEST_POLICY_H_ #define CHROME_RENDERER_EXTENSIONS_RESOURCE_REQUEST_POLICY_H_ -#include <set> +#include <map> +#include "extensions/common/extension_guid.h" #include "extensions/common/extension_id.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/page_transition_types.h" @@ -45,11 +46,15 @@ const absl::optional<url::Origin>& initiator_origin); private: + // Determine if the host is web accessible. + bool IsWebAccessibleHost(const std::string& host); + Dispatcher* dispatcher_; - // The set of extension IDs with any potentially web- or webview-accessible - // resources. - std::set<ExtensionId> web_accessible_ids_; + // 1:1 mapping of extension IDs with any potentially web- or webview- + // accessible resources to their corresponding GUIDs. + using WebAccessibleHostMap = std::map<ExtensionId, ExtensionGuid>; + WebAccessibleHostMap web_accessible_resources_map_; }; } // namespace extensions
diff --git a/chrome/renderer/resources/renderer_resources.grd b/chrome/renderer/resources/renderer_resources.grd index 0cb8ab1..c7237c98 100644 --- a/chrome/renderer/resources/renderer_resources.grd +++ b/chrome/renderer/resources/renderer_resources.grd
@@ -51,6 +51,7 @@ <include name="IDR_ENTERPRISE_PLATFORM_KEYS_SUBTLE_CRYPTO_JS" file="extensions\enterprise_platform_keys\subtle_crypto.js" type="BINDATA" /> <include name="IDR_ENTERPRISE_PLATFORM_KEYS_TOKEN_JS" file="extensions\enterprise_platform_keys\token.js" type="BINDATA" /> <include name="IDR_FILE_BROWSER_HANDLER_CUSTOM_BINDINGS_JS" file="extensions\file_browser_handler_custom_bindings.js" type="BINDATA" /> + <include name="IDR_FILE_SYSTEM_PROVIDER_CUSTOM_BINDINGS_JS" file="extensions\file_system_provider_custom_bindings.js" type="BINDATA" /> <include name="IDR_PLATFORM_KEYS_CUSTOM_BINDINGS_JS" file="extensions\platform_keys_custom_bindings.js" type="BINDATA" /> <include name="IDR_PLATFORM_KEYS_GET_PUBLIC_KEY_JS" file="extensions\platform_keys\get_public_key.js" type="BINDATA" /> <include name="IDR_PLATFORM_KEYS_KEY_JS" file="extensions\platform_keys\key.js" type="BINDATA" /> @@ -66,7 +67,6 @@ <if expr="chromeos_ash"> <include name="IDR_CERTIFICATE_PROVIDER_CUSTOM_BINDINGS_JS" file="extensions\certificate_provider_custom_bindings.js" type="BINDATA" /> <include name="IDR_FILE_MANAGER_PRIVATE_CUSTOM_BINDINGS_JS" file="extensions\file_manager_private_custom_bindings.js" type="BINDATA" /> - <include name="IDR_FILE_SYSTEM_PROVIDER_CUSTOM_BINDINGS_JS" file="extensions\file_system_provider_custom_bindings.js" type="BINDATA" /> <include name="IDR_TERMINAL_PRIVATE_CUSTOM_BINDINGS_JS" file="extensions\terminal_private_custom_bindings.js" type="BINDATA" /> <!-- ChromeOS IME Mojo service and bindings. -->
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 33f2252..8162f660 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2891,6 +2891,7 @@ "../browser/extensions/cross_origin_isolation_browsertest.cc", "../browser/extensions/cross_origin_xhr_apitest.cc", "../browser/extensions/crx_installer_browsertest.cc", + "../browser/extensions/dynamic_origin_browsertest.cc", "../browser/extensions/error_console/error_console_browsertest.cc", "../browser/extensions/events_apitest.cc", "../browser/extensions/extension_action_runner_browsertest.cc", @@ -3088,6 +3089,7 @@ "../browser/extensions/api/platform_keys/platform_keys_test_base.cc", "../browser/extensions/api/platform_keys/platform_keys_test_base.h", "../browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc", + "../browser/extensions/api/shared_storage/shared_storage_private_apitest.cc", "../browser/extensions/api/system_display/system_display_chromeos_apitest.cc", "../browser/extensions/api/terminal/terminal_private_apitest.cc", "../browser/extensions/api/terminal/terminal_private_browsertest.cc", @@ -4525,6 +4527,7 @@ "../browser/chromeos/policy/dlp/dlp_content_manager_lacros_browsertest.cc", "../browser/chromeos/policy/dlp/dlp_content_manager_test_helper.cc", "../browser/chromeos/policy/dlp/dlp_content_manager_test_helper.h", + "../browser/extensions/api/shared_storage/shared_storage_private_apitest.cc", "../browser/lacros/browser_test_util.cc", "../browser/lacros/browser_test_util.h", "../browser/lacros/device_attributes_lacros_browsertest.cc", @@ -4550,6 +4553,7 @@ data = [ "data/media/", + "data/extensions/api_test/shared_storage_private/", "data/extensions/api_test/login_screen_apis/", "data/extensions/platform_apps/minimal/", ]
diff --git a/chrome/test/data/extensions/api_test/shared_storage_private/background.js b/chrome/test/data/extensions/api_test/shared_storage_private/background.js new file mode 100644 index 0000000..659dbc2 --- /dev/null +++ b/chrome/test/data/extensions/api_test/shared_storage_private/background.js
@@ -0,0 +1,31 @@ +// Copyright 2022 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. + +// Basic browser tests for the sharedStoragePrivate API. +chrome.test.runTests([ + async function testStorage() { + // Set values and ensure that get() returns them. + await chrome.sharedStoragePrivate.set({a:1, b:2}); + let items = await chrome.sharedStoragePrivate.get(); + chrome.test.assertEq(2, Object.keys(items).length); + chrome.test.assertEq(1, items.a); + chrome.test.assertEq(2, items.b); + + // Set should merge new values into existing ones. + await chrome.sharedStoragePrivate.set({b:22, c:3}); + items = await chrome.sharedStoragePrivate.get(); + chrome.test.assertEq(3, Object.keys(items).length); + chrome.test.assertEq(1, items.a); + chrome.test.assertEq(22, items.b); + chrome.test.assertEq(3, items.c); + + // Remove specified keys, unknown keys ignored. + await chrome.sharedStoragePrivate.remove(['a', 'b', 'x']); + items = await chrome.sharedStoragePrivate.get(); + chrome.test.assertEq(1, Object.keys(items).length); + chrome.test.assertEq(3, items.c); + + chrome.test.succeed(); + }, +]);
diff --git a/chrome/test/data/extensions/api_test/shared_storage_private/manifest.json b/chrome/test/data/extensions/api_test/shared_storage_private/manifest.json new file mode 100644 index 0000000..39e595e --- /dev/null +++ b/chrome/test/data/extensions/api_test/shared_storage_private/manifest.json
@@ -0,0 +1,8 @@ +{ + "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGoDQBIKdoGu4vjQZMeEqsqRzk2tXjoOmt1wYYZIa9Y7qYZs6FA1KqmKb0hvEsKFk1oP8HAu13eyTND7Znf3TloOgEB4oQ1U0sBmRIf8jCvIkyBdMnmMu2t50QPt22LiI/AUDsdCqsHHQBo2lM4c4OTYi2jDD452bPVMeb6xpleQIDAQAB", + "name": "chrome.sharedStoragePrivate API Test Extension - using key from shared dev", + "version": "0.1", + "manifest_version": 3, + "background": { "service_worker": "background.js" }, + "permissions": ["sharedStoragePrivate"] +}
diff --git a/chrome/test/data/webui/chromeos/os_feedback_ui/share_data_page_test.js b/chrome/test/data/webui/chromeos/os_feedback_ui/share_data_page_test.js index 690362d..b65233c9 100644 --- a/chrome/test/data/webui/chromeos/os_feedback_ui/share_data_page_test.js +++ b/chrome/test/data/webui/chromeos/os_feedback_ui/share_data_page_test.js
@@ -213,8 +213,9 @@ /** * Test that when when the send button is clicked, an on-continue is fired. * Case 4: Do not share email or screenshot. + * 4.1) No screenshot and screenshot checkbox is unchecked. */ - test('SendReportDoNotShareEmail', async () => { + test('SendReportDoNotShareEmailNoScreenshotUnchecked', async () => { await initializePage(); page.feedbackContext = fakeFeedbackContext; // When there is not a screenshot. @@ -224,30 +225,74 @@ // Select the "Don't include email address" option. getElement('#userEmailDropDown').value = ''; - let request = (await clickSendAndWait(page)).report; + const request = (await clickSendAndWait(page)).report; assertFalse(!!request.feedbackContext.email); assertFalse(request.includeScreenshot); + }); + + /** + * Test that when when the send button is clicked, an on-continue is fired. + * Case 4: Do not share email or screenshot. + * 4.2) No screenshot and screenshot checkbox is checked. + */ + test('SendReportDoNotShareEmailNoScreenshotChecked', async () => { + await initializePage(); + page.feedbackContext = fakeFeedbackContext; + // When there is not a screenshot. + page.screenshotUrl = ''; + assertFalse(!!getElement('#screenshotImage').src); + + // Select the "Don't include email address" option. + getElement('#userEmailDropDown').value = ''; // When the checkbox is selected but there is not a screenshot. getElement('#screenshotCheckbox').checked = true; assertFalse(!!getElement('#screenshotImage').src); - request = (await clickSendAndWait(page)).report; + const request = (await clickSendAndWait(page)).report; assertFalse(!!request.feedbackContext.email); assertFalse(request.includeScreenshot); + }); + + /** + * Test that when when the send button is clicked, an on-continue is fired. + * Case 4: Do not share email or screenshot. + * 4.3) Has screenshot but screenshot checkbox is unchecked. + */ + test('SendReportDoNotShareEmailHasScreenshotUnchecked', async () => { + await initializePage(); + page.feedbackContext = fakeFeedbackContext; + + // Select the "Don't include email address" option. + getElement('#userEmailDropDown').value = ''; // When there is a screenshot but it is not selected. page.screenshotUrl = fakeImageUrl; assertEquals(fakeImageUrl, getElement('#screenshotImage').src); getElement('#screenshotCheckbox').checked = false; - request = (await clickSendAndWait(page)).report; + + const request = (await clickSendAndWait(page)).report; assertFalse(!!request.feedbackContext.email); assertFalse(request.includeScreenshot); }); + // Test that the send button will be disabled once clicked. + test('DisableSendButtonAfterClick', async () => { + await initializePage(); + page.feedbackContext = fakeFeedbackContext; + + const sendButton = getElement('#buttonSend'); + + assertFalse(sendButton.disabled); + + await clickSendAndWait(page); + + assertTrue(sendButton.disabled); + }); + // Test that the screenshot checkbox is disabled when no screenshot. test('screenshotNotAvailable', async () => { await initializePage();
diff --git a/chrome/test/data/webui/chromeos/personalization_app/wallpaper_images_element_test.ts b/chrome/test/data/webui/chromeos/personalization_app/wallpaper_images_element_test.ts index cd6258eb..e37f9839c 100644 --- a/chrome/test/data/webui/chromeos/personalization_app/wallpaper_images_element_test.ts +++ b/chrome/test/data/webui/chromeos/personalization_app/wallpaper_images_element_test.ts
@@ -173,7 +173,8 @@ Parameters<IFrameApi['sendImageTiles']>; assertEquals(imagesGrid, target); const tiles = getDarkLightImageTiles( - false, personalizationStore.data.wallpaper.backdrop.images['id_0']); + wallpaperImagesElement.isDarkModeActive, + personalizationStore.data.wallpaper.backdrop.images['id_0']); assertDeepEquals(tiles, data); assertEquals(data[0]!.preview.length, 2); // Check that light variant comes before dark variant. @@ -196,7 +197,8 @@ assertEquals(imagesGrid, target); assertDeepEquals( getDarkLightImageTiles( - false, personalizationStore.data.wallpaper.backdrop.images['id_1']), + wallpaperImagesElement.isDarkModeActive, + personalizationStore.data.wallpaper.backdrop.images['id_1']), data); });
diff --git a/chrome/updater/win/app_install_controller.cc b/chrome/updater/win/app_install_controller.cc index 495d91d..65e3298 100644 --- a/chrome/updater/win/app_install_controller.cc +++ b/chrome/updater/win/app_install_controller.cc
@@ -24,6 +24,7 @@ #include "base/process/launch.h" #include "base/sequence_checker.h" #include "base/strings/escape.h" +#include "base/strings/strcat.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -37,6 +38,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/win/atl.h" +#include "base/win/registry.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_variant.h" #include "base/win/shlwapi.h" @@ -51,6 +53,7 @@ #include "chrome/updater/win/manifest_util.h" #include "chrome/updater/win/scoped_impersonation.h" #include "chrome/updater/win/user_info.h" +#include "chrome/updater/win/win_constants.h" #include "chrome/updater/win/win_util.h" #pragma clang diagnostic push @@ -384,6 +387,22 @@ } } +void SetUsageStats(UpdaterScope scope, + const std::string& app_id, + bool usage_stats_enabled) { + const LONG result = + base::win::RegKey( + scope == UpdaterScope::kUser ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, + base::StrCat({scope == UpdaterScope::kUser ? CLIENT_STATE_KEY + : CLIENT_STATE_MEDIUM_KEY, + base::SysUTF8ToWide(app_id)}) + .c_str(), + Wow6432(KEY_WRITE)) + .WriteValue(L"usagestats", usage_stats_enabled ? 1 : 0); + VLOG_IF(1, result != ERROR_SUCCESS) + << "Error writing usage stats for " << app_id << ":" << result; +} + // Implements installing a single application by invoking the code in // |UpdateService|, listening to |UpdateService| and UI events, and // driving the UI code by calling the functions exposed by @@ -549,23 +568,29 @@ if (tag_args) request.brand_code = tag_args->brand_code; - update_service_->RegisterApp( - request, + base::ThreadPool::PostTaskAndReply( + FROM_HERE, + base::BindOnce(&SetUsageStats, GetUpdaterScope(), app_id_, + tag_args && tag_args->usage_stats_enable && + *tag_args->usage_stats_enable), base::BindOnce( - [](scoped_refptr<AppInstallControllerImpl> self, - const RegistrationResponse& response) { - DCHECK(response.status_code == kRegistrationSuccess || - response.status_code == kRegistrationAlreadyRegistered); - self->update_service_->Update( - self->app_id_, GetInstallDataIndexFromAppArgs(self->app_id_), - UpdateService::Priority::kForeground, - UpdateService::PolicySameVersionUpdate::kAllowed, - base::BindRepeating(&AppInstallControllerImpl::StateChange, - self), - base::BindOnce(&AppInstallControllerImpl::InstallComplete, - self)); - }, - base::WrapRefCounted(this))); + &UpdateService::RegisterApp, update_service_, request, + base::BindOnce( + [](scoped_refptr<AppInstallControllerImpl> self, + const RegistrationResponse& response) { + DCHECK(response.status_code == kRegistrationSuccess || + response.status_code == kRegistrationAlreadyRegistered); + self->update_service_->Update( + self->app_id_, + GetInstallDataIndexFromAppArgs(self->app_id_), + UpdateService::Priority::kForeground, + UpdateService::PolicySameVersionUpdate::kAllowed, + base::BindRepeating(&AppInstallControllerImpl::StateChange, + self), + base::BindOnce(&AppInstallControllerImpl::InstallComplete, + self)); + }, + base::WrapRefCounted(this)))); } void AppInstallControllerImpl::InstallAppOffline( @@ -651,26 +676,32 @@ if (tag_args) request.brand_code = tag_args->brand_code; - update_service_->RegisterApp( - request, + base::ThreadPool::PostTaskAndReply( + FROM_HERE, + base::BindOnce(&SetUsageStats, GetUpdaterScope(), app_id_, + tag_args && tag_args->usage_stats_enable && + *tag_args->usage_stats_enable), base::BindOnce( - [](scoped_refptr<AppInstallControllerImpl> self, - const base::FilePath& installer_path, - const std::string& install_args, const std::string& install_data, - const std::string& install_settings, - const RegistrationResponse& response) { - DCHECK(response.status_code == kRegistrationSuccess || - response.status_code == kRegistrationAlreadyRegistered); - self->update_service_->RunInstaller( - self->app_id_, installer_path, install_args, install_data, - install_settings, - base::BindRepeating(&AppInstallControllerImpl::StateChange, - self), - base::BindOnce(&AppInstallControllerImpl::InstallComplete, - self)); - }, - base::WrapRefCounted(this), installer_path, install_args, - install_data, install_settings)); + &UpdateService::RegisterApp, update_service_, request, + base::BindOnce( + [](scoped_refptr<AppInstallControllerImpl> self, + const base::FilePath& installer_path, + const std::string& install_args, + const std::string& install_data, + const std::string& install_settings, + const RegistrationResponse& response) { + DCHECK(response.status_code == kRegistrationSuccess || + response.status_code == kRegistrationAlreadyRegistered); + self->update_service_->RunInstaller( + self->app_id_, installer_path, install_args, install_data, + install_settings, + base::BindRepeating(&AppInstallControllerImpl::StateChange, + self), + base::BindOnce(&AppInstallControllerImpl::InstallComplete, + self)); + }, + base::WrapRefCounted(this), installer_path, install_args, + install_data, install_settings))); } // TODO(crbug.com/1218219) - propagate error code in case of errors.
diff --git a/chromeos/components/quick_answers/understanding/intent_generator.cc b/chromeos/components/quick_answers/understanding/intent_generator.cc index 2195420..0ce926b8 100644 --- a/chromeos/components/quick_answers/understanding/intent_generator.cc +++ b/chromeos/components/quick_answers/understanding/intent_generator.cc
@@ -164,10 +164,14 @@ "always trigger feature is enabled"; // Check spelling if the selected text is a valid single word. if (iter.IsWord() && iter.prev() == 0 && iter.pos() == u16_text.length()) { + // Search server do not provide useful information for proper nouns and + // abbreviations (such as "Amy" and "ASAP"). Check spelling of the word in + // lower case to filter out such cases. + auto text = base::UTF16ToUTF8( + base::i18n::ToLower(base::UTF8ToUTF16(request.selected_text))); spell_checker_->CheckSpelling( - request.selected_text, - base::BindOnce(&IntentGenerator::CheckSpellingCallback, - weak_factory_.GetWeakPtr(), request)); + text, base::BindOnce(&IntentGenerator::CheckSpellingCallback, + weak_factory_.GetWeakPtr(), request)); return; } }
diff --git a/chromeos/components/quick_answers/understanding/intent_generator_unittest.cc b/chromeos/components/quick_answers/understanding/intent_generator_unittest.cc index cac724b6..eb074b6 100644 --- a/chromeos/components/quick_answers/understanding/intent_generator_unittest.cc +++ b/chromeos/components/quick_answers/understanding/intent_generator_unittest.cc
@@ -577,7 +577,8 @@ EXPECT_EQ(kWord, intent_info_.intent_text); } -TEST_F(IntentGeneratorTest, ShouldTriggerForSingleWordInDictionaryWithDigits) { +TEST_F(IntentGeneratorTest, + ShouldNotTriggerForSingleWordInDictionaryWithDigits) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( chromeos::features::kQuickAnswersAlwaysTriggerForSingleWord); @@ -605,6 +606,34 @@ EXPECT_EQ(kWord, intent_info_.intent_text); } +TEST_F(IntentGeneratorTest, ShouldNotTriggerForProperNounInDictionary) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature( + chromeos::features::kQuickAnswersAlwaysTriggerForSingleWord); + + const std::string kWord = "Amy"; + + // No Annotation provided. + std::vector<TextAnnotationPtr> annotations; + UseFakeServiceConnection(annotations); + + // Add word to the dictionary. + spell_checker()->AddWordToDictionary(kWord); + + // Word selected. + std::unique_ptr<QuickAnswersRequest> quick_answers_request = + std::make_unique<QuickAnswersRequest>(); + quick_answers_request->selected_text = kWord; + + intent_generator_->GenerateIntent(*quick_answers_request); + task_environment_.RunUntilIdle(); + + // Should not generate dictionary intent if the word contains digits even if + // it is in the dictionary. + EXPECT_EQ(IntentType::kUnknown, intent_info_.intent_type); + EXPECT_EQ(kWord, intent_info_.intent_text); +} + TEST_F(IntentGeneratorTest, ShouldFallbackToAnnotationsForWordNotInDictionaryNoAnnotation) { base::test::ScopedFeatureList feature_list;
diff --git a/chromeos/crosapi/mojom/file_system_provider.mojom b/chromeos/crosapi/mojom/file_system_provider.mojom index 16fa2d8..ff195b5 100644 --- a/chromeos/crosapi/mojom/file_system_provider.mojom +++ b/chromeos/crosapi/mojom/file_system_provider.mojom
@@ -20,6 +20,14 @@ string id@1; }; +// The primary data source for the file system. +[Stable, Extensible] +enum FileSystemSource { + [Default] kFile, + kNetwork, + kDevice +}; + // Provides immutable metadata about a file system. [Stable] struct FileSystemMetadata { @@ -128,9 +136,16 @@ // cannot be type-mapped due to build-time dependency inversions. // Provider will typically be an extension_id but is intentionally left // abstract to support multi-profile in the future. + // |delivery_failure| is set to true if the operation could not be forwarded + // to the extension for any reason. [MinVersion=1] - ForwardOperation@0(string provider, int32 histogram_value, string event_name, - array<mojo_base.mojom.Value> args); + DeprecatedForwardOperation@0( + string provider, int32 histogram_value, string event_name, + array<mojo_base.mojom.Value> args); + [MinVersion=2] + ForwardOperation@1( + string provider, int32 histogram_value, string event_name, + array<mojo_base.mojom.Value> args) => (bool delivery_failure); }; // Implemented by Ash. Extensions in Lacros can register themselves as file @@ -187,4 +202,13 @@ OperationFinished@6(FSPOperationResponse response, FileSystemId file_system_id, int64 request_id, array<mojo_base.mojom.Value> args) => (string error); + + // Called by Lacros when a filesystem providing extension is loaded. + [MinVersion=2] + ExtensionLoaded@7(bool configurable, bool watchable, bool multiple_mounts, + FileSystemSource source, string extension_name, string extension_id); + + // Called by Lacros when a filesystem providing extension is unloaded. + [MinVersion=2] + ExtensionUnloaded@8(string id, bool due_to_shutdown); };
diff --git a/chromeos/crosapi/mojom/prefs.mojom b/chromeos/crosapi/mojom/prefs.mojom index 1907bbc2..ddb3180 100644 --- a/chromeos/crosapi/mojom/prefs.mojom +++ b/chromeos/crosapi/mojom/prefs.mojom
@@ -85,6 +85,8 @@ [MinVersion=4] kPreferredLanguages = 28, // M100: language::prefs::kApplicationLocale (profile) [MinVersion=4] kApplicationLocale = 29, + // M104: prefs::kSharedStorage (profile) + [MinVersion=5] kSharedStorage = 30, }; // Information about who or what is controlling a particular pref. This is used
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.cc b/chromeos/services/assistant/assistant_manager_service_impl.cc index 3f9805c..b0b3846 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.cc +++ b/chromeos/services/assistant/assistant_manager_service_impl.cc
@@ -251,8 +251,8 @@ // TODO(b/225063204): For phase 1, fallback to load libassistant.so from // rootfs if installabtion failed. No error handling needed. auto* client = chromeos::DlcserviceClient::Get(); - if (!client) { - InitAssistant(user); + if (dlc_path_.has_value() || !client) { + InitAssistant(user, dlc_path_); return; } @@ -270,6 +270,7 @@ // We cannot cleanly stop the service if it is in the process of starting up. DCHECK_NE(GetState(), State::STARTING); + weak_factory_.InvalidateWeakPtrs(); SetStateAndInformObservers(State::STOPPED); media_host_->Stop(); @@ -471,15 +472,14 @@ void AssistantManagerServiceImpl::OnInstallDlcComplete( const absl::optional<UserInfo>& user, const chromeos::DlcserviceClient::InstallResult& result) { - absl::optional<std::string> dlc_path; if (result.error == dlcservice::kErrorNone) { DVLOG(3) << "Installed libassistant.so from DLC"; - dlc_path = result.root_path; + dlc_path_ = result.root_path; } else { DVLOG(1) << "Failed to install libassistant.so from DLC: " << result.error; } - InitAssistant(user, dlc_path); + InitAssistant(user, dlc_path_); } void AssistantManagerServiceImpl::InitAssistant(
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.h b/chromeos/services/assistant/assistant_manager_service_impl.h index 605ead99..68703fb 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.h +++ b/chromeos/services/assistant/assistant_manager_service_impl.h
@@ -195,9 +195,8 @@ const chromeos::DlcserviceClient::InstallResult& result); // Optional `dlc_path`, where the DLC libassistant.so is mounted. - void InitAssistant( - const absl::optional<UserInfo>& user, - const absl::optional<std::string>& dlc_path = absl::nullopt); + void InitAssistant(const absl::optional<UserInfo>& user, + const absl::optional<std::string>& dlc_path); void OnServiceStarted(); void OnServiceRunning(); bool IsServiceStarted() const; @@ -278,6 +277,9 @@ chromeos::libassistant::mojom::BootupConfigPtr bootup_config_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; + // Mounted path of libassistant.so. Will not change within a chrome session. + absl::optional<std::string> dlc_path_; + base::ScopedObservation<DeviceActions, AppListEventSubscriber, &DeviceActions::AddAndFireAppListEventSubscriber,
diff --git a/chromeos/services/libassistant/libassistant_service.cc b/chromeos/services/libassistant/libassistant_service.cc index ac0e707..645cfb9 100644 --- a/chromeos/services/libassistant/libassistant_service.cc +++ b/chromeos/services/libassistant/libassistant_service.cc
@@ -76,9 +76,15 @@ return; } + if (dlc_path_ == dlc_path) { + DVLOG(3) << "Skip loading libassistant DLC with the same root path."; + return; + } + dlc_path_ = dlc_path; + base::FilePath path = GetLibassisantPath(dlc_path.value()); // Self-resets are not allowed on unique_ptr. - dlc_library_.reset(); + // We should only load the DLC once. dlc_library_ = base::ScopedNativeLibrary(path); if (IsDlcLibraryValid()) { DVLOG(3) << "Loaded libassistant shared library from: " << path; @@ -105,6 +111,7 @@ bool IsDlcLibraryValid() const { return dlc_library_.is_valid(); } assistant_client::PlatformApi* const platform_api_; + absl::optional<std::string> dlc_path_; base::ScopedNativeLibrary dlc_library_; };
diff --git a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java index 38f4a7b4..7c44f1a 100644 --- a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java +++ b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java
@@ -316,6 +316,8 @@ Log.w(TAG, "Bad URI %s", params.getUrl().getSpec(), ex); return OverrideUrlLoadingResult.forNoOverride(); } + } else if (isSupportedWtaiProtocol(params.getUrl())) { + targetIntent = parseWtaiMcProtocol(params.getUrl()); } else { targetIntent = new Intent(Intent.ACTION_VIEW); targetIntent.setData(Uri.parse(params.getUrl().getSpec())); @@ -528,23 +530,21 @@ * If accessing a file URL, ensure that the user has granted the necessary file access * to the app. */ - private boolean startFileIntentIfNecessary(ExternalNavigationParams params) { - if (params.getUrl().getScheme().equals(UrlConstants.FILE_SCHEME)) { - @MimeTypeUtils.Type - int mimeType = MimeTypeUtils.getMimeTypeForUrl(params.getUrl()); - RecordHistogram.recordEnumeratedHistogram( - "Android.Intent.OpenFileType", mimeType, MimeTypeUtils.NUM_MIME_TYPE_ENTRIES); - String permissionNeeded = MimeTypeUtils.getPermissionNameForMimeType(mimeType); + private boolean handleFileUrlPermissions(ExternalNavigationParams params) { + if (!params.getUrl().getScheme().equals(UrlConstants.FILE_SCHEME)) return false; - if (permissionNeeded == null) return false; + @MimeTypeUtils.Type + int mimeType = MimeTypeUtils.getMimeTypeForUrl(params.getUrl()); + RecordHistogram.recordEnumeratedHistogram( + "Android.Intent.OpenFileType", mimeType, MimeTypeUtils.NUM_MIME_TYPE_ENTRIES); + String permissionNeeded = MimeTypeUtils.getPermissionNameForMimeType(mimeType); - if (shouldRequestFileAccess(params.getUrl(), permissionNeeded)) { - startFileIntent(params, permissionNeeded); - if (DEBUG) Log.i(TAG, "Requesting filesystem access"); - return true; - } - } - return false; + if (permissionNeeded == null) return false; + + if (!shouldRequestFileAccess(params.getUrl(), permissionNeeded)) return false; + requestFilePermissions(params, permissionNeeded); + if (DEBUG) Log.i(TAG, "Requesting filesystem access"); + return true; } /** @@ -555,7 +555,8 @@ * @param permissionNeeded The name of the Android permission needed to access the file. */ @VisibleForTesting - protected void startFileIntent(ExternalNavigationParams params, String permissionNeeded) { + protected void requestFilePermissions( + ExternalNavigationParams params, String permissionNeeded) { PermissionCallback permissionCallback = new PermissionCallback() { @Override public void onRequestPermissionsResult(String[] permissions, int[] grantResults) { @@ -731,20 +732,23 @@ return false; } - private boolean handleWtaiMcProtocol(ExternalNavigationParams params) { - if (!params.getUrl().getSpec().startsWith(WTAI_MC_URL_PREFIX)) return false; - // wtai://wp/mc;number - // number=string(phone-number) - String phoneNumber = params.getUrl().getSpec().substring(WTAI_MC_URL_PREFIX.length()); - startActivity( - new Intent(Intent.ACTION_VIEW, Uri.parse(WebView.SCHEME_TEL + phoneNumber)), false); - if (DEBUG) Log.i(TAG, "wtai:// link handled"); - RecordUserAction.record("Android.PhoneIntent"); - return true; + private static boolean isSupportedWtaiProtocol(GURL url) { + return url.getSpec().startsWith(WTAI_MC_URL_PREFIX); } - private boolean isUnhandledWtaiProtocol(ExternalNavigationParams params) { + private static Intent parseWtaiMcProtocol(GURL url) { + assert isSupportedWtaiProtocol(url); + // wtai://wp/mc;number + // number=string(phone-number) + String phoneNumber = url.getSpec().substring(WTAI_MC_URL_PREFIX.length()); + if (DEBUG) Log.i(TAG, "wtai:// link handled"); + RecordUserAction.record("Android.PhoneIntent"); + return new Intent(Intent.ACTION_VIEW, Uri.parse(WebView.SCHEME_TEL + phoneNumber)); + } + + private static boolean isUnhandledWtaiProtocol(ExternalNavigationParams params) { if (!params.getUrl().getSpec().startsWith(WTAI_URL_PREFIX)) return false; + if (isSupportedWtaiProtocol(params.getUrl())) return false; if (DEBUG) Log.i(TAG, "Unsupported wtai:// link"); return true; } @@ -1327,9 +1331,18 @@ // Don't allow external fallback URLs by default. canLaunchExternalFallbackResult.set(false); + if (!maybeSetSmsPackage(targetIntent)) maybeRecordPhoneIntentMetrics(targetIntent); + // http://crbug.com/170925: We need to show the intent picker when we receive an intent from // another app that 30x redirects to a YouTube/Google Maps/Play Store/Google+ URL etc. boolean incomingIntentRedirect = isIncomingIntentRedirect(params); + boolean isExternalProtocol = !UrlUtilities.isAcceptedScheme(params.getUrl()); + + GURL intentDataUrl = new GURL(targetIntent.getDataString()); + // intent: URLs are considered an external protocol, but may still contain a Data URI that + // this app does support, and may still end up launching this app. + boolean isIntentWithSupportedProtocol = UrlUtilities.hasIntentScheme(params.getUrl()) + && UrlUtilities.isAcceptedScheme(intentDataUrl); if (shouldBlockAllExternalAppLaunches(params, incomingIntentRedirect)) { return OverrideUrlLoadingResult.forNoOverride(); @@ -1339,20 +1352,9 @@ return OverrideUrlLoadingResult.forNoOverride(); } - GURL intentDataUrl = new GURL(targetIntent.getDataString()); - boolean isExternalProtocol = !UrlUtilities.isAcceptedScheme(params.getUrl()); - // intent: URLs are considered an external protocol, but may still contain a Data URI that - // this app does support, and may still end up launching this app. - boolean isIntentWithSupportedProtocol = UrlUtilities.hasIntentScheme(params.getUrl()) - && UrlUtilities.isAcceptedScheme(intentDataUrl); - - if (isInternalPdfDownload(isExternalProtocol, params)) { - return OverrideUrlLoadingResult.forNoOverride(); - } - // This check should happen for reloads, navigations, etc..., which is why // it occurs before the subsequent blocks. - if (startFileIntentIfNecessary(params)) { + if (handleFileUrlPermissions(params)) { return OverrideUrlLoadingResult.forAsyncAction( OverrideUrlLoadingAsyncActionType.UI_GATING_BROWSER_NAVIGATION); } @@ -1363,36 +1365,8 @@ return OverrideUrlLoadingResult.forNoOverride(); } - int pageTransitionCore = params.getPageTransition() & PageTransition.CORE_MASK; - boolean isLink = params.isLinkTransition(); - boolean isFromIntent = params.isFromIntent(); - boolean isFormSubmit = pageTransitionCore == PageTransition.FORM_SUBMIT; - boolean linkNotFromIntent = isLink && !isFromIntent; - - if (handleCCTRedirectsToInstantApps(params, isExternalProtocol, incomingIntentRedirect)) { - return OverrideUrlLoadingResult.forExternalIntent(); - } else if (redirectShouldStayInApp(params, isExternalProtocol, targetIntent)) { - return OverrideUrlLoadingResult.forNoOverride(); - } - - if (!maybeSetSmsPackage(targetIntent)) maybeRecordPhoneIntentMetrics(targetIntent); - - Intent debugIntent = new Intent(targetIntent); - QueryIntentActivitiesSupplier resolvingInfos = - new QueryIntentActivitiesSupplier(targetIntent); - if (!preferToShowIntentPicker(params, pageTransitionCore, isExternalProtocol, isFormSubmit, - incomingIntentRedirect, isFromIntent, resolvingInfos)) { - return OverrideUrlLoadingResult.forNoOverride(); - } - if (isLinkFromChromeInternalPage(params)) return OverrideUrlLoadingResult.forNoOverride(); - if (handleWtaiMcProtocol(params)) { - return OverrideUrlLoadingResult.forExternalIntent(); - } - // TODO: handle other WTAI schemes. - if (isUnhandledWtaiProtocol(params)) return OverrideUrlLoadingResult.forNoOverride(); - if (hasInternalScheme(params.getUrl(), targetIntent) || hasContentScheme(params.getUrl(), targetIntent) || hasFileSchemeInIntentURI(params.getUrl(), targetIntent)) { @@ -1405,6 +1379,34 @@ return OverrideUrlLoadingResult.forNoOverride(); } + if (isInternalPdfDownload(isExternalProtocol, params)) { + return OverrideUrlLoadingResult.forNoOverride(); + } + + if (isUnhandledWtaiProtocol(params)) return OverrideUrlLoadingResult.forNoOverride(); + + int pageTransitionCore = params.getPageTransition() & PageTransition.CORE_MASK; + boolean isLink = params.isLinkTransition(); + boolean isFromIntent = params.isFromIntent(); + boolean isFormSubmit = pageTransitionCore == PageTransition.FORM_SUBMIT; + boolean linkNotFromIntent = isLink && !isFromIntent; + + if (handleCCTRedirectsToInstantApps(params, isExternalProtocol, incomingIntentRedirect)) { + return OverrideUrlLoadingResult.forExternalIntent(); + } + + if (redirectShouldStayInApp(params, isExternalProtocol, targetIntent)) { + return OverrideUrlLoadingResult.forNoOverride(); + } + + Intent debugIntent = new Intent(targetIntent); + QueryIntentActivitiesSupplier resolvingInfos = + new QueryIntentActivitiesSupplier(targetIntent); + if (!preferToShowIntentPicker(params, pageTransitionCore, isExternalProtocol, isFormSubmit, + incomingIntentRedirect, isFromIntent, resolvingInfos)) { + return OverrideUrlLoadingResult.forNoOverride(); + } + // From this point on, we have determined it is safe to launch an External App from a // fallback URL. canLaunchExternalFallbackResult.set(true);
diff --git a/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java b/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java index 1eda2ba0..e051f64 100644 --- a/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java +++ b/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java
@@ -430,12 +430,6 @@ @Test @SmallTest public void testWtai() { - // Start the telephone application with the given number. - checkUrl("wtai://wp/mc;0123456789") - .withIsIncognito(true) - .expecting(OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT, - START_OTHER_ACTIVITY | INTENT_SANITIZATION_EXCEPTION); - // These two cases are currently unimplemented. checkUrl("wtai://wp/sd;0123456789") .expecting(OverrideUrlLoadingResultType.NO_OVERRIDE, @@ -2571,7 +2565,7 @@ public boolean mShouldRequestFileAccess; public String mNewUrlAfterClobbering; public String mReferrerUrlForClobbering; - public boolean mStartFileIntentCalled; + public boolean mRequestFilePermissionsCalled; public Intent mStartActivityInIncognitoIntent; public boolean mStartIncognitoIntentCalled; public boolean mCanShowIncognitoDialog; @@ -2633,8 +2627,9 @@ } @Override - protected void startFileIntent(ExternalNavigationParams params, String permissionNeeded) { - mStartFileIntentCalled = true; + protected void requestFilePermissions( + ExternalNavigationParams params, String permissionNeeded) { + mRequestFilePermissionsCalled = true; } @Override @@ -3148,7 +3143,7 @@ Assert.assertEquals(expectStartIncognito, mUrlHandler.mStartIncognitoIntentCalled); Assert.assertEquals(expectStartActivity, startActivityCalled); Assert.assertEquals(expectStartWebApk, startWebApkCalled); - Assert.assertEquals(expectStartFile, mUrlHandler.mStartFileIntentCalled); + Assert.assertEquals(expectStartFile, mUrlHandler.mRequestFilePermissionsCalled); Assert.assertEquals(expectProxyForIA, mUrlHandler.mCalledWithProxy); if (startActivityCalled && expectSaneIntent) {
diff --git a/components/omnibox/browser/history_fuzzy_provider.cc b/components/omnibox/browser/history_fuzzy_provider.cc index 60ecd15d..800a0b1 100644 --- a/components/omnibox/browser/history_fuzzy_provider.cc +++ b/components/omnibox/browser/history_fuzzy_provider.cc
@@ -28,6 +28,7 @@ #include "components/omnibox/browser/autocomplete_match_type.h" #include "components/omnibox/browser/autocomplete_provider_client.h" #include "components/omnibox/browser/autocomplete_result.h" +#include "components/omnibox/browser/bookmark_provider.h" #include "components/omnibox/browser/history_quick_provider.h" #include "components/search_engines/omnibox_focus_type.h" #include "components/url_formatter/elide_url.h" @@ -532,13 +533,14 @@ std::vector<fuzzy::Correction> corrections; DVLOG(1) << "FindCorrections: <" << text << "> ---> ?{"; if (root_.FindCorrections(text, kToleranceSchedule, corrections)) { - DVLOG(1) << "Trie contains input; no fuzzy results needed?"; - AddMatchForText(u"INPUT ON TRIE"); + DVLOG(1) << "Trie contains input; no fuzzy results needed"; } if (!corrections.empty()) { // Use of `scoped_refptr` is required here because destructor is private. scoped_refptr<HistoryQuickProvider> history_quick_provider = new HistoryQuickProvider(client()); + scoped_refptr<BookmarkProvider> bookmark_provider = + new BookmarkProvider(client()); for (const auto& correction : corrections) { std::u16string fixed = text; correction.ApplyTo(fixed); @@ -554,33 +556,14 @@ fixed, fixed.length(), autocomplete_input_.current_page_classification(), client()->GetSchemeClassifier()); + history_quick_provider->Start(corrected_input, false); DCHECK(history_quick_provider->done()); + bookmark_provider->Start(corrected_input, false); + DCHECK(bookmark_provider->done()); - // TODO(orinj): Optimize with move not copy; requires provider change. - // Consider taking only the most relevant match. - for (const auto& history_quick_match : - history_quick_provider->matches()) { - DVLOG(1) << "HQP match: " << history_quick_match.contents; - matches_.push_back(history_quick_match); - - // Update match in place. - AutocompleteMatch& match = matches_.back(); - match.provider = this; - match.inline_autocompletion.clear(); - match.allowed_to_be_default_match = false; - // TODO(orinj): Determine suitable relevance penalty; it should - // likely take into account the edit distance or size of correction. - // Using 9/10 reasonably took a 1334 relevance match down to 1200, - // but was harmful to HQP suggestions: as soon as a '.' was - // appended, a bunch of ~800 navsuggest results overtook a better - // HQP result that was bumped down to ~770. Using 95/100 lets this - // result compete in the navsuggest range. - match.relevance = match.relevance * 95 / 100; - match.contents_class.clear(); - match.contents_class.push_back( - {0, AutocompleteMatch::ACMatchClassification::DIM}); - } + AddConvertedMatches(history_quick_provider->matches()); + AddConvertedMatches(bookmark_provider->matches()); } } DVLOG(1) << "}?"; @@ -596,6 +579,32 @@ matches_.push_back(std::move(match)); } +void HistoryFuzzyProvider::AddConvertedMatches(const ACMatches& matches) { + // TODO(orinj): Optimize with move not copy; requires provider change. + // Consider taking only the most relevant match. + for (const auto& original_match : matches) { + DVLOG(1) << "Converted match: " << original_match.contents; + matches_.push_back(original_match); + + // Update match in place. + AutocompleteMatch& match = matches_.back(); + match.provider = this; + match.inline_autocompletion.clear(); + match.allowed_to_be_default_match = false; + // TODO(orinj): Determine suitable relevance penalty; it should + // likely take into account the edit distance or size of correction. + // Using 9/10 reasonably took a 1334 relevance match down to 1200, + // but was harmful to HQP suggestions: as soon as a '.' was + // appended, a bunch of ~800 navsuggest results overtook a better + // HQP result that was bumped down to ~770. Using 95/100 lets this + // result compete in the navsuggest range. + match.relevance = match.relevance * 95 / 100; + match.contents_class.clear(); + match.contents_class.push_back( + {0, AutocompleteMatch::ACMatchClassification::DIM}); + } +} + void HistoryFuzzyProvider::OnUrlsLoaded(fuzzy::Node node) { root_ = std::move(node); }
diff --git a/components/omnibox/browser/history_fuzzy_provider.h b/components/omnibox/browser/history_fuzzy_provider.h index dd8cb19..e1f3b1f 100644 --- a/components/omnibox/browser/history_fuzzy_provider.h +++ b/components/omnibox/browser/history_fuzzy_provider.h
@@ -198,6 +198,9 @@ // Adds one match for the given corrected `text`. void AddMatchForText(std::u16string text); + // Add multiple matches, converting them to fuzzy suggestions in the process. + void AddConvertedMatches(const ACMatches& matches); + // Main thread callback to receive trie of URLs loaded from database. void OnUrlsLoaded(fuzzy::Node node);
diff --git a/components/omnibox/browser/omnibox_field_trial.cc b/components/omnibox/browser/omnibox_field_trial.cc index 918d58f..d7a0b6d 100644 --- a/components/omnibox/browser/omnibox_field_trial.cc +++ b/components/omnibox/browser/omnibox_field_trial.cc
@@ -610,10 +610,6 @@ return base::FeatureList::IsEnabled(omnibox::kOmniboxFuzzyUrlSuggestions); } -bool OmniboxFieldTrial::IsPedalsAndroidBatch1Enabled() { - return base::FeatureList::IsEnabled(omnibox::kOmniboxPedalsAndroidBatch1); -} - bool OmniboxFieldTrial::IsExperimentalKeywordModeEnabled() { return base::FeatureList::IsEnabled(omnibox::kExperimentalKeywordMode); }
diff --git a/components/omnibox/browser/omnibox_field_trial.h b/components/omnibox/browser/omnibox_field_trial.h index 6f6d5c3..e57303c7 100644 --- a/components/omnibox/browser/omnibox_field_trial.h +++ b/components/omnibox/browser/omnibox_field_trial.h
@@ -356,9 +356,6 @@ // Returns true if the fuzzy URL suggestions feature is enabled. bool IsFuzzyUrlSuggestionsEnabled(); -// Returns true if the first batch of Pedals on Android is enabled. -bool IsPedalsAndroidBatch1Enabled(); - // Simply a convenient wrapper for testing a flag. Used downstream for an // assortment of keyword mode experiments. bool IsExperimentalKeywordModeEnabled();
diff --git a/components/omnibox/common/omnibox_features.cc b/components/omnibox/common/omnibox_features.cc index 9ab8c4af..3a83062 100644 --- a/components/omnibox/common/omnibox_features.cc +++ b/components/omnibox/common/omnibox_features.cc
@@ -266,11 +266,6 @@ const base::Feature kOmniboxFuzzyUrlSuggestions{ "OmniboxFuzzyUrlSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; -// Feature used to enable the first batch of Pedals on Android. The Pedals, -// which will be enabled on Android, should be already enabled on desktop. -const base::Feature kOmniboxPedalsAndroidBatch1{ - "OmniboxPedalsAndroidBatch1", base::FEATURE_ENABLED_BY_DEFAULT}; - // When enabled, use Assistant for omnibox voice query recognition instead of // Android's built-in voice recognition service. Only works on Android. const base::Feature kOmniboxAssistantVoiceSearch{
diff --git a/components/omnibox/common/omnibox_features.h b/components/omnibox/common/omnibox_features.h index 902cddc..aa7009c 100644 --- a/components/omnibox/common/omnibox_features.h +++ b/components/omnibox/common/omnibox_features.h
@@ -76,7 +76,6 @@ extern const base::Feature kNtpRealboxSuggestionAnswers; extern const base::Feature kNtpRealboxTailSuggest; extern const base::Feature kOmniboxFuzzyUrlSuggestions; -extern const base::Feature kOmniboxPedalsAndroidBatch1; // Omnibox UI - these affect the UI or function of the location bar (not the // popup).
diff --git a/components/policy/resources/webui/BUILD.gn b/components/policy/resources/webui/BUILD.gn new file mode 100644 index 0000000..4259578 --- /dev/null +++ b/components/policy/resources/webui/BUILD.gn
@@ -0,0 +1,15 @@ +# Copyright 2022 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("//tools/polymer/html_to_js.gni") + +html_to_js("web_components") { + js_files = [ + "policy_conflict.js", + "policy_row.js", + "policy_precedence_row.js", + "policy_table.js", + "status_box.js", + ] +}
diff --git a/components/policy/resources/webui/policy_conflict.html b/components/policy/resources/webui/policy_conflict.html new file mode 100644 index 0000000..3419e29b --- /dev/null +++ b/components/policy/resources/webui/policy_conflict.html
@@ -0,0 +1,15 @@ +<link rel="stylesheet" href="./policy.css"> +<style> + :host(:not([hidden])) { + display: block; + } +</style> +<div class="policy conflict row" role="row"> + <div class="name" role="rowheader">$i18n{conflictValue}</div> + <div class="value" role="cell"></div> + <div class="source" role="cell"></div> + <div class="scope" role="cell"></div> + <div class="level" role="cell"></div> + <div class="messages" role="cell"></div> + <div class="toggle" role="cell"></div> +</div>
diff --git a/components/policy/resources/webui/policy_conflict.js b/components/policy/resources/webui/policy_conflict.js new file mode 100644 index 0000000..7c11265c --- /dev/null +++ b/components/policy/resources/webui/policy_conflict.js
@@ -0,0 +1,50 @@ +// Copyright 2022 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 './strings.m.js'; + +import {CustomElement} from 'chrome://resources/js/custom_element.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +import {getTrustedHTML} from 'chrome://resources/js/static_types.js'; + +/** + * @typedef {{ + * level: string, + * scope: string, + * source: string, + * value: any, + * }} + */ +export let Conflict; + +export class PolicyConflictElement extends CustomElement { + static get template() { + return getTrustedHTML`{__html_template__}`; + } + + connectedCallback() { + this.setAttribute('role', 'rowgroup'); + } + + /** + * @param {Conflict} conflict + * @param {string} rowLabel + */ + initialize(conflict, rowLabel) { + this.shadowRoot.querySelector('.scope').textContent = + loadTimeData.getString( + conflict.scope === 'user' ? 'scopeUser' : 'scopeDevice'); + this.shadowRoot.querySelector('.level').textContent = + loadTimeData.getString( + conflict.level === 'recommended' ? 'levelRecommended' : + 'levelMandatory'); + this.shadowRoot.querySelector('.source').textContent = + loadTimeData.getString(conflict.source); + this.shadowRoot.querySelector('.value').textContent = conflict.value; + this.shadowRoot.querySelector('.name').textContent = + loadTimeData.getString(rowLabel); + } +} + +customElements.define('policy-conflict', PolicyConflictElement);
diff --git a/components/policy/resources/webui/policy_precedence_row.html b/components/policy/resources/webui/policy_precedence_row.html new file mode 100644 index 0000000..12e08d4f --- /dev/null +++ b/components/policy/resources/webui/policy_precedence_row.html
@@ -0,0 +1,10 @@ +<link rel="stylesheet" href="./policy.css"> +<style> + :host(:not([hidden])) { + display: block; + } +</style> +<div class="precedence row" role="row"> + <div class="name" role="rowheader">$i18n{labelPrecedence}</div> + <div class="value" role="cell"></div> +</div>
diff --git a/components/policy/resources/webui/policy_precedence_row.js b/components/policy/resources/webui/policy_precedence_row.js new file mode 100644 index 0000000..bed3445 --- /dev/null +++ b/components/policy/resources/webui/policy_precedence_row.js
@@ -0,0 +1,30 @@ +// Copyright 2022 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 './strings.m.js'; + +import {CustomElement} from 'chrome://resources/js/custom_element.js'; +import {getTrustedHTML} from 'chrome://resources/js/static_types.js'; + +export class PolicyPrecedenceRowElement extends CustomElement { + static get template() { + return getTrustedHTML`{__html_template__}`; + } + + connectedCallback() { + this.setAttribute('role', 'rowgroup'); + this.classList.add('policy-precedence-data'); + } + + /** + * @param {Array<string>} precedenceOrder Array containing ordered strings + * which represent the order of policy precedence. + */ + initialize(precedenceOrder) { + this.shadowRoot.querySelector('.precedence.row > .value').textContent = + precedenceOrder.join(' > '); + } +} + +customElements.define('policy-precedence-row', PolicyPrecedenceRowElement);
diff --git a/components/policy/resources/webui/policy_row.html b/components/policy/resources/webui/policy_row.html new file mode 100644 index 0000000..93fb274 --- /dev/null +++ b/components/policy/resources/webui/policy_row.html
@@ -0,0 +1,44 @@ +<link rel="stylesheet" href="./policy.css"> +<style> + :host(:not([hidden])) { + display: block; + } +</style> +<div class="policy row" role="row"> + <div class="name" role="rowheader" aria-labelledby="name"> + <a class="link" target="_blank"> + <span id="name"></span> + <img src="chrome://resources/images/open_in_new.svg"> + </a> + </div> + <div class="value" role="cell"></div> + <div class="source" role="cell"></div> + <div class="scope" role="cell"></div> + <div class="level" role="cell"></div> + <div class="messages" role="cell"></div> + <div class="toggle" role="cell"> + <a is="action-link" class="show-more">$i18n{showMore}</a> + <a is="action-link" class="show-less" hidden>$i18n{showLess}</a> + </div> +</div> +<div class="value row" role="row" hidden> + <div class="name" role="rowheader">$i18n{value}</div> + <div class="value" role="cell"></div> + <div class="copy" role="cell"> + <a is="action-link" class="copy-value link" role="cell"> + <img src="chrome://resources/images/icon_copy_content.svg"> + </a> + </div> +</div> +<div class="errors row" role="row" hidden> + <div class="name" role="rowheader">$i18n{error}</div> + <div class="value" role="cell"></div> +</div> +<div class="warnings row" role="row" hidden> + <div class="name" role="rowheader">$i18n{warning}</div> + <div class="value" role="cell"></div> +</div> +<div class="infos row" role="row" hidden> + <div class="name" role="rowheader">$i18n{info}</div> + <div class="value" role="cell"></div> +</div>
diff --git a/components/policy/resources/webui/policy_row.js b/components/policy/resources/webui/policy_row.js new file mode 100644 index 0000000..948488c --- /dev/null +++ b/components/policy/resources/webui/policy_row.js
@@ -0,0 +1,236 @@ +// Copyright 2022 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 'chrome://resources/js/action_link.js'; +import './policy_conflict.js'; +import './strings.m.js'; + +import {CustomElement} from 'chrome://resources/js/custom_element.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +import {getTrustedHTML} from 'chrome://resources/js/static_types.js'; + +/** + * @typedef {{ + * ignored?: boolean, + * name: string, + * level: string, + * link: ?string, + * scope: string, + * source: string, + * error: string, + * warning: string, + * info: string, + * value: any, + * deprecated: ?boolean, + * future: ?boolean, + * allSourcesMerged: ?boolean, + * conflicts: ?Array<!Conflict>, + * superseded: ?Array<!Conflict>, + * }} + */ +export let Policy; + +export class PolicyRowElement extends CustomElement { + static get template() { + return getTrustedHTML`{__html_template__}`; + } + + connectedCallback() { + const toggle = this.shadowRoot.querySelector('.policy.row .toggle'); + toggle.addEventListener('click', () => this.toggleExpanded_()); + + const copy = this.shadowRoot.querySelector('.copy-value'); + copy.addEventListener('click', () => this.copyValue_()); + + this.setAttribute('role', 'rowgroup'); + this.classList.add('policy-data'); + } + + /** @param {Policy} policy */ + initialize(policy) { + /** @type {Policy} */ + this.policy = policy; + + /** @private {boolean} */ + this.unset_ = policy.value === undefined; + + /** @private {boolean} */ + this.hasErrors_ = !!policy.error; + + /** @private {boolean} */ + this.hasWarnings_ = !!policy.warning; + + /** @private {boolean} */ + this.hasInfos_ = !!policy.info; + + /** @private {boolean} */ + this.hasConflicts_ = !!policy.conflicts; + + /** @private {boolean} */ + this.hasSuperseded_ = !!policy.superseded; + + /** @private {boolean} */ + this.isMergedValue_ = !!policy.allSourcesMerged; + + /** @private {boolean} */ + this.deprecated_ = !!policy.deprecated; + + /** @private {boolean} */ + this.future_ = !!policy.future; + + // Populate the name column. + const nameDisplay = this.shadowRoot.querySelector('.name .link span'); + nameDisplay.textContent = policy.name; + if (policy.link) { + const link = this.shadowRoot.querySelector('.name .link'); + link.href = policy.link; + link.title = loadTimeData.getStringF('policyLearnMore', policy.name); + } else { + this.classList.add('no-help-link'); + } + + // Populate the remaining columns with policy scope, level and value if a + // value has been set. Otherwise, leave them blank. + if (!this.unset_) { + const scopeDisplay = this.shadowRoot.querySelector('.scope'); + scopeDisplay.textContent = loadTimeData.getString( + policy.scope === 'user' ? 'scopeUser' : 'scopeDevice'); + + const levelDisplay = this.shadowRoot.querySelector('.level'); + levelDisplay.textContent = loadTimeData.getString( + policy.level === 'recommended' ? 'levelRecommended' : + 'levelMandatory'); + + const sourceDisplay = this.shadowRoot.querySelector('.source'); + sourceDisplay.textContent = loadTimeData.getString(policy.source); + // Reduces load on the DOM for long values; + const truncatedValue = + (policy.value && policy.value.toString().length > 256) ? + `${policy.value.toString().substr(0, 256)}\u2026` : + policy.value; + + const valueDisplay = this.shadowRoot.querySelector('.value'); + valueDisplay.textContent = truncatedValue; + + const copyLink = this.shadowRoot.querySelector('.copy .link'); + copyLink.title = loadTimeData.getStringF('policyCopyValue', policy.name); + + const valueRowContentDisplay = + this.shadowRoot.querySelector('.value.row .value'); + valueRowContentDisplay.textContent = policy.value; + + const errorRowContentDisplay = + this.shadowRoot.querySelector('.errors.row .value'); + errorRowContentDisplay.textContent = policy.error; + const warningRowContentDisplay = + this.shadowRoot.querySelector('.warnings.row .value'); + warningRowContentDisplay.textContent = policy.warning; + const infoRowContentDisplay = + this.shadowRoot.querySelector('.infos.row .value'); + infoRowContentDisplay.textContent = policy.info; + + const messagesDisplay = this.shadowRoot.querySelector('.messages'); + const errorsNotice = + this.hasErrors_ ? loadTimeData.getString('error') : ''; + const deprecationNotice = + this.deprecated_ ? loadTimeData.getString('deprecated') : ''; + const futureNotice = this.future_ ? loadTimeData.getString('future') : ''; + const warningsNotice = + this.hasWarnings_ ? loadTimeData.getString('warning') : ''; + const conflictsNotice = this.hasConflicts_ && !this.isMergedValue_ ? + loadTimeData.getString('conflict') : + ''; + const ignoredNotice = + this.policy.ignored ? loadTimeData.getString('ignored') : ''; + let notice = + [ + errorsNotice, deprecationNotice, futureNotice, warningsNotice, + ignoredNotice, conflictsNotice + ].filter(x => !!x) + .join(', ') || + loadTimeData.getString('ok'); + const supersededNotice = this.hasSuperseded_ && !this.isMergedValue_ ? + loadTimeData.getString('superseding') : + ''; + if (supersededNotice) { + // Include superseded notice regardless of other notices + notice += `, ${supersededNotice}`; + } + messagesDisplay.textContent = notice; + + if (policy.conflicts) { + policy.conflicts.forEach(conflict => { + const row = document.createElement('policy-conflict'); + row.initialize(conflict, 'conflictValue'); + row.classList.add('policy-conflict-data'); + this.shadowRoot.appendChild(row); + }); + } + if (policy.superseded) { + policy.superseded.forEach(superseded => { + const row = document.createElement('policy-conflict'); + row.initialize(superseded, 'supersededValue'); + row.classList.add('policy-superseded-data'); + this.shadowRoot.appendChild(row); + }); + } + } else { + const messagesDisplay = this.shadowRoot.querySelector('.messages'); + messagesDisplay.textContent = loadTimeData.getString('unset'); + } + } + + /** + * Copies the policy's value to the clipboard. + * @private + */ + copyValue_() { + const policyValueDisplay = + this.shadowRoot.querySelector('.value.row .value'); + + // Select the text that will be copied. + const selection = window.getSelection(); + const range = window.document.createRange(); + range.selectNodeContents(policyValueDisplay); + selection.removeAllRanges(); + selection.addRange(range); + + // Copy the policy value to the clipboard. + navigator.clipboard.writeText(policyValueDisplay.innerText).catch(error => { + console.error('Unable to copy policy value to clipboard:', error); + }); + } + + /** + * Toggle the visibility of an additional row containing the complete text. + * @private + */ + toggleExpanded_() { + const warningRowDisplay = this.shadowRoot.querySelector('.warnings.row'); + const errorRowDisplay = this.shadowRoot.querySelector('.errors.row'); + const infoRowDisplay = this.shadowRoot.querySelector('.infos.row'); + const valueRowDisplay = this.shadowRoot.querySelector('.value.row'); + valueRowDisplay.hidden = !valueRowDisplay.hidden; + this.classList.toggle('expanded', !valueRowDisplay.hidden); + + this.shadowRoot.querySelector('.show-more').hidden = + !valueRowDisplay.hidden; + this.shadowRoot.querySelector('.show-less').hidden = valueRowDisplay.hidden; + if (this.hasWarnings_) { + warningRowDisplay.hidden = !warningRowDisplay.hidden; + } + if (this.hasErrors_) { + errorRowDisplay.hidden = !errorRowDisplay.hidden; + } + if (this.hasInfos_) { + infoRowDisplay.hidden = !infoRowDisplay.hidden; + } + this.shadowRoot.querySelectorAll('.policy-conflict-data') + .forEach(row => row.hidden = !row.hidden); + this.shadowRoot.querySelectorAll('.policy-superseded-data') + .forEach(row => row.hidden = !row.hidden); + } +} + +customElements.define('policy-row', PolicyRowElement);
diff --git a/components/policy/resources/webui/policy_table.html b/components/policy/resources/webui/policy_table.html new file mode 100644 index 0000000..041a12f --- /dev/null +++ b/components/policy/resources/webui/policy_table.html
@@ -0,0 +1,17 @@ +<link rel="stylesheet" href="./policy.css"> +<div class="policy-table" role="table" aria-labelledby="policy-header"> + <h3 class="header" id="policy-header"></h3> + <p class="id"></p> + <div class="main"> + <div class="header row" role="row"> + <div class="name" role="columnheader">$i18n{headerName}</div> + <div class="value" role="columnheader">$i18n{headerValue}</div> + <div class="source" role="columnheader">$i18n{headerSource}</div> + <div class="scope" role="columnheader">$i18n{headerScope}</div> + <div class="level" role="columnheader">$i18n{headerLevel}</div> + <div class="messages" role="columnheader">$i18n{headerStatus}</div> + <div class="toggle" role="columnheader"></div> + </div> + <div class="no-policy">$i18n{noPoliciesSet}</div> + </div> +</div>
diff --git a/components/policy/resources/webui/policy_table.js b/components/policy/resources/webui/policy_table.js new file mode 100644 index 0000000..4e3a956 --- /dev/null +++ b/components/policy/resources/webui/policy_table.js
@@ -0,0 +1,113 @@ +// Copyright 2022 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 './strings.m.js'; +import './policy_row.js'; +import './policy_precedence_row.js'; + +import {CustomElement} from 'chrome://resources/js/custom_element.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +import {getTrustedHTML} from 'chrome://resources/js/static_types.js'; + +/** + * @typedef {{ + * id: ?string, + * isExtension?: boolean, + * name: string, + * policies: !Array<!Policy>, + * precedenceOrder: ?Array<string>, + * }} + */ +export let PolicyTableModel; + +export class PolicyTableElement extends CustomElement { + static get template() { + return getTrustedHTML`{__html_template__}`; + } + + constructor() { + super(); + + this.policies_ = {}; + this.filterPattern_ = ''; + } + + /** @param {PolicyTableModel} dataModel */ + update(dataModel) { + // Clear policies + const mainContent = this.shadowRoot.querySelector('.main'); + const policies = this.shadowRoot.querySelectorAll('.policy-data'); + this.shadowRoot.querySelector('.header').textContent = dataModel.name; + this.shadowRoot.querySelector('.id').textContent = dataModel.id; + this.shadowRoot.querySelector('.id').hidden = !dataModel.id; + policies.forEach(row => mainContent.removeChild(row)); + + dataModel.policies + .sort((a, b) => { + if ((a.value !== undefined && b.value !== undefined) || + a.value === b.value) { + if (a.link !== undefined && b.link !== undefined) { + // Sorting the policies in ascending alpha order. + return a.name > b.name ? 1 : -1; + } + + // Sorting so unknown policies are last. + return a.link !== undefined ? -1 : 1; + } + + // Sorting so unset values are last. + return a.value !== undefined ? -1 : 1; + }) + .forEach(policy => { + const policyRow = document.createElement('policy-row'); + policyRow.initialize(policy); + mainContent.appendChild(policyRow); + }); + this.filter(); + + // Show the current policy precedence order in the Policy Precedence table. + if (dataModel.name === 'Policy Precedence') { + // Clear previous precedence row. + const precedenceRowOld = + this.shadowRoot.querySelectorAll('.policy-precedence-data'); + precedenceRowOld.forEach(row => mainContent.removeChild(row)); + + const precedenceRow = document.createElement('policy-precedence-row'); + precedenceRow.initialize(dataModel.precedenceOrder); + mainContent.appendChild(precedenceRow); + } + } + + /** + * Set the filter pattern. Only policies whose name contains |pattern| are + * shown in the policy table. The filter is case insensitive. It can be + * disabled by setting |pattern| to an empty string. + * @param {string} pattern The filter pattern. + */ + setFilterPattern(pattern) { + this.filterPattern_ = pattern.toLowerCase(); + this.filter(); + } + + /** + * Filter policies. Only policies whose name contains the filter pattern are + * shown in the table. Furthermore, policies whose value is not currently + * set are only shown if the corresponding checkbox is checked. + */ + filter() { + const showUnset = document.querySelector('#show-unset').checked; + const policies = this.shadowRoot.querySelectorAll('.policy-data'); + for (let i = 0; i < policies.length; i++) { + const policyDisplay = policies[i]; + policyDisplay.hidden = + policyDisplay.policy.value === undefined && !showUnset || + policyDisplay.policy.name.toLowerCase().indexOf( + this.filterPattern_) === -1; + } + this.shadowRoot.querySelector('.no-policy').hidden = + !!this.shadowRoot.querySelector('.policy-data:not([hidden])'); + } +} + +customElements.define('policy-table', PolicyTableElement);
diff --git a/components/policy/resources/webui/status_box.html b/components/policy/resources/webui/status_box.html new file mode 100644 index 0000000..c1dc9a6 --- /dev/null +++ b/components/policy/resources/webui/status_box.html
@@ -0,0 +1,88 @@ +<link rel="stylesheet" href="./policy.css"> +<fieldset> + <legend class="legend"></legend> + <div class="status-entry" hidden> + <div class="label">$i18n{labelVersion}</div> + <div class="version"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelMachineEnrollmentMachineName}</div> + <div class="machine-enrollment-name"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelMachineEnrollmentDomain}</div> + <div class="machine-enrollment-domain"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelMachineEnrollmentToken}</div> + <div class="machine-enrollment-token"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelMachineEntrollmentDeviceId}</div> + <div class="machine-enrollment-device-id"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelUsername}</div> + <div class="username"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelManagedBy}</div> + <div class="managed-by"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelGaiaId}</div> + <div class="gaia-id"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelClientId}</div> + <div class="client-id"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelAssetId}</div> + <div class="asset-id"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelLocation}</div> + <div class="location"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelDirectoryApiId}</div> + <div class="directory-api-id"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelTimeSinceLastFetchAttempt}</div> + <div class="time-since-last-fetch-attempt"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelTimeSinceLastRefresh}</div> + <div class="time-since-last-refresh"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelRefreshInterval}</div> + <div class="refresh-interval"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelPoliciesPush}</div> + <div class="policy-push"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelStatus}</div> + <div class="status"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelIsAffiliated}</div> + <div class="is-affiliated"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelIsOffHoursActive}</div> + <div class="is-offhours-active"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelVersion}</div> + <div class="version"></div> + </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelLastCloudReportSentTimestamp}</div> + <div class="last-cloud-report-sent-timestamp"></div> + </div> +</fieldset>
diff --git a/components/policy/resources/webui/status_box.js b/components/policy/resources/webui/status_box.js new file mode 100644 index 0000000..1ca67f0 --- /dev/null +++ b/components/policy/resources/webui/status_box.js
@@ -0,0 +1,130 @@ +// Copyright 2022 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 './strings.m.js'; + +import {CustomElement} from 'chrome://resources/js/custom_element.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +import {getTrustedHTML} from 'chrome://resources/js/static_types.js'; + +export class StatusBoxElement extends CustomElement { + static get template() { + return getTrustedHTML`{__html_template__}`; + } + + /** + * Sets the text of a particular named label element in the status box + * and updates the visibility if needed. + * @param {string} labelName The name of the label element that is being + * updated. + * @param {string} labelValue The new text content for the label. + * @param {boolean=} needsToBeShown True if we want to show the label + * False otherwise. + */ + setLabelAndShow_(labelName, labelValue, needsToBeShown = true) { + const labelElement = this.shadowRoot.querySelector(labelName); + labelElement.textContent = labelValue ? ' ' + labelValue : ''; + if (needsToBeShown) { + labelElement.parentElement.hidden = false; + } + } + + /** + * Populate the box with the given cloud policy status. + * @param {string} scope The policy scope, either "device", "machine", + * "user", or "updater". + * @param {Object} status Dictionary with information about the status. + */ + initialize(scope, status) { + const notSpecifiedString = loadTimeData.getString('notSpecified'); + + // Set appropriate box legend based on status key + this.shadowRoot.querySelector('.legend').textContent = + loadTimeData.getString(status.boxLegendKey); + + if (scope === 'device') { + // Populate the device naming information. + // Populate the asset identifier. + this.setLabelAndShow_('.asset-id', status.assetId || notSpecifiedString); + + // Populate the device location. + this.setLabelAndShow_('.location', status.location || notSpecifiedString); + + // Populate the directory API ID. + this.setLabelAndShow_( + '.directory-api-id', status.directoryApiId || notSpecifiedString); + this.setLabelAndShow_('.client-id', status.clientId); + // For off-hours policy, indicate if it's active or not. + if (status.isOffHoursActive != null) { + this.setLabelAndShow_( + '.is-offhours-active', + loadTimeData.getString( + status.isOffHoursActive ? 'offHoursActive' : + 'offHoursNotActive')); + } + } else if (scope === 'machine') { + this.setLabelAndShow_('.machine-enrollment-device-id', status.deviceId); + this.setLabelAndShow_( + '.machine-enrollment-token', status.enrollmentToken); + if (status.machine) { + this.setLabelAndShow_('.machine-enrollment-name', status.machine); + } + this.setLabelAndShow_('.machine-enrollment-domain', status.domain); + } else if (scope === 'updater') { + if (status.version) { + this.setLabelAndShow_('.version', status.version); + } + if (status.domain) { + this.setLabelAndShow_('.machine-enrollment-domain', status.domain); + } + } else { + // Populate the topmost item with the username. + this.setLabelAndShow_('.username', status.username); + // Populate the user gaia id. + this.setLabelAndShow_('.gaia-id', status.gaiaId || notSpecifiedString); + this.setLabelAndShow_('.client-id', status.clientId); + if (status.isAffiliated != null) { + this.setLabelAndShow_( + '.is-affiliated', + loadTimeData.getString( + status.isAffiliated ? 'isAffiliatedYes' : 'isAffiliatedNo')); + } + } + + if (status.enterpriseDomainManager) { + this.setLabelAndShow_('.managed-by', status.enterpriseDomainManager); + } + + if (status.timeSinceLastFetchAttempt) { + this.setLabelAndShow_( + '.time-since-last-fetch-attempt', status.timeSinceLastFetchAttempt); + } + + if (status.timeSinceLastRefresh) { + this.setLabelAndShow_( + '.time-since-last-refresh', status.timeSinceLastRefresh); + } + + if (scope !== 'updater') { + if (status.refreshInterval) { + this.setLabelAndShow_('.refresh-interval', status.refreshInterval); + } + this.setLabelAndShow_('.status', status.status); + this.setLabelAndShow_( + '.policy-push', + loadTimeData.getString( + status.policiesPushAvailable ? 'policiesPushOn' : + 'policiesPushOff')); + } + + if (status.lastCloudReportSentTimestamp) { + this.setLabelAndShow_( + '.last-cloud-report-sent-timestamp', + status.lastCloudReportSentTimestamp + ' (' + + status.timeSinceLastCloudReportSent + ')'); + } + } +} + +customElements.define('status-box', StatusBoxElement);
diff --git a/components/resources/BUILD.gn b/components/resources/BUILD.gn index 0dc4635..59ff209 100644 --- a/components/resources/BUILD.gn +++ b/components/resources/BUILD.gn
@@ -67,7 +67,10 @@ "dev_ui_components_resources.pak", ] - deps = [ "//components/local_state:build" ] + deps = [ + "//components/local_state:build", + "//components/policy/resources/webui:web_components", + ] output_dir = "$root_gen_dir/components" }
diff --git a/components/resources/policy_resources.grdp b/components/resources/policy_resources.grdp index 427d31ee..2670f27d 100644 --- a/components/resources/policy_resources.grdp +++ b/components/resources/policy_resources.grdp
@@ -4,4 +4,9 @@ <include name="IDR_POLICY_HTML" file="../policy/resources/webui/policy.html" type="BINDATA" /> <include name="IDR_POLICY_BASE_JS" file="../policy/resources/webui/policy_base.js" preprocess="true" type="BINDATA" /> <include name="IDR_POLICY_JS" file="../policy/resources/webui/policy.js" type="BINDATA" /> + <include name="IDR_POLICY_POLICY_CONFLICT_JS" file="${root_gen_dir}/components/policy/resources/webui/policy_conflict.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_POLICY_POLICY_ROW_JS" file="${root_gen_dir}/components/policy/resources/webui/policy_row.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_POLICY_POLICY_PRECEDENCE_ROW_JS" file="${root_gen_dir}/components/policy/resources/webui/policy_precedence_row.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_POLICY_POLICY_TABLE_JS" file="${root_gen_dir}/components/policy/resources/webui/policy_table.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_POLICY_STATUS_BOX_JS" file="${root_gen_dir}/components/policy/resources/webui/status_box.js" use_base_dir="false" type="BINDATA" /> </grit-part>
diff --git a/components/safe_browsing/core/browser/realtime/url_lookup_service_unittest.cc b/components/safe_browsing/core/browser/realtime/url_lookup_service_unittest.cc index f937319..128ed7e 100644 --- a/components/safe_browsing/core/browser/realtime/url_lookup_service_unittest.cc +++ b/components/safe_browsing/core/browser/realtime/url_lookup_service_unittest.cc
@@ -1227,8 +1227,6 @@ // Enable extended reporting. EnableExtendedReporting(); rt_service()->set_bypass_probability_for_tests(true); - // When feature is not enabled, a sampled ping should not be sent. - EXPECT_FALSE(CanSendRTSampleRequest()); feature_list_.InitAndDisableFeature( safe_browsing::kSendSampledPingsForProtegoAllowlistDomains); // After enabling the feature, a sampled ping should be sent.
diff --git a/components/safe_browsing/core/common/features.cc b/components/safe_browsing/core/common/features.cc index 8ccddc8..d0bb3e7 100644 --- a/components/safe_browsing/core/common/features.cc +++ b/components/safe_browsing/core/common/features.cc
@@ -133,7 +133,7 @@ const base::Feature kSendSampledPingsForProtegoAllowlistDomains{ "SafeBrowsingSendSampledPingsForProtegoAllowlistDomains", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kSuspiciousSiteTriggerQuotaFeature{ "SafeBrowsingSuspiciousSiteTriggerQuota", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/components/translate/translate_internals/translate_internals.html b/components/translate/translate_internals/translate_internals.html index 30cb08a..1147ec59 100644 --- a/components/translate/translate_internals/translate_internals.html +++ b/components/translate/translate_internals/translate_internals.html
@@ -83,10 +83,10 @@ Content-Language </th> <th class="detection-logs-html-root-language"> - html lang attribute + HTML lang attribute </th> <th class="detection-logs-cld-language"> - Model Language + Model language </th> <th class="detection-logs-detection-model-version"> Model version @@ -98,7 +98,7 @@ Is model reliable? </th> <th class="detection-logs-has-notranslate"> - notranslate meta + Notranslate meta </th> <th class="detection-logs-adopted-language"> Adopted language
diff --git a/components/webcrypto/BUILD.gn b/components/webcrypto/BUILD.gn index 77f6eca..40bbe75c 100644 --- a/components/webcrypto/BUILD.gn +++ b/components/webcrypto/BUILD.gn
@@ -45,8 +45,6 @@ "algorithms/x25519.cc", "blink_key_handle.cc", "blink_key_handle.h", - "crypto_data.cc", - "crypto_data.h", "generate_key_result.cc", "generate_key_result.h", "jwk.cc",
diff --git a/components/webcrypto/algorithm_dispatch.cc b/components/webcrypto/algorithm_dispatch.cc index 9116fbb0..b65c57a 100644 --- a/components/webcrypto/algorithm_dispatch.cc +++ b/components/webcrypto/algorithm_dispatch.cc
@@ -7,7 +7,6 @@ #include "components/webcrypto/algorithm_implementation.h" #include "components/webcrypto/algorithm_implementations.h" #include "components/webcrypto/algorithm_registry.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" @@ -19,7 +18,7 @@ Status DecryptDontCheckKeyUsage(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { if (algorithm.Id() != key.Algorithm().Id()) return Status::ErrorUnexpected(); @@ -34,7 +33,7 @@ Status EncryptDontCheckUsage(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { if (algorithm.Id() != key.Algorithm().Id()) return Status::ErrorUnexpected(); @@ -62,7 +61,7 @@ Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { if (!key.KeyUsageAllows(blink::kWebCryptoKeyUsageEncrypt)) return Status::ErrorUnexpected(); @@ -71,7 +70,7 @@ Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { if (!key.KeyUsageAllows(blink::kWebCryptoKeyUsageDecrypt)) return Status::ErrorUnexpected(); @@ -79,7 +78,7 @@ } Status Digest(const blink::WebCryptoAlgorithm& algorithm, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { const AlgorithmImplementation* impl = nullptr; Status status = GetAlgorithmImplementation(algorithm.Id(), &impl); @@ -132,7 +131,7 @@ } Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -173,7 +172,7 @@ Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { if (!key.KeyUsageAllows(blink::kWebCryptoKeyUsageSign)) return Status::ErrorUnexpected(); @@ -190,8 +189,8 @@ Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) { if (!key.KeyUsageAllows(blink::kWebCryptoKeyUsageVerify)) return Status::ErrorUnexpected(); @@ -218,12 +217,12 @@ Status status = ExportKey(format, key_to_wrap, &exported_data); if (status.IsError()) return status; - return EncryptDontCheckUsage(wrapping_algorithm, wrapping_key, - CryptoData(exported_data), buffer); + return EncryptDontCheckUsage(wrapping_algorithm, wrapping_key, exported_data, + buffer); } Status UnwrapKey(blink::WebCryptoKeyFormat format, - const CryptoData& wrapped_key_data, + base::span<const uint8_t> wrapped_key_data, const blink::WebCryptoKey& wrapping_key, const blink::WebCryptoAlgorithm& wrapping_algorithm, const blink::WebCryptoAlgorithm& algorithm, @@ -246,8 +245,7 @@ // key_ops). As long as the ImportKey error messages don't describe actual // key bytes however this should be OK. For more discussion see // http://crbug.com/372040 - return ImportKey(format, CryptoData(buffer), algorithm, extractable, usages, - key); + return ImportKey(format, buffer, algorithm, extractable, usages, key); } Status DeriveBits(const blink::WebCryptoAlgorithm& algorithm, @@ -312,7 +310,7 @@ return status; // Create the key using the derived bytes. - return ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(derived_bytes), + return ImportKey(blink::kWebCryptoKeyFormatRaw, derived_bytes, import_algorithm, extractable, usages, derived_key); } @@ -331,7 +329,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) { const AlgorithmImplementation* impl = nullptr; Status status = GetAlgorithmImplementation(algorithm.Id(), &impl);
diff --git a/components/webcrypto/algorithm_dispatch.h b/components/webcrypto/algorithm_dispatch.h index fe3d9e5d..100e91ba 100644 --- a/components/webcrypto/algorithm_dispatch.h +++ b/components/webcrypto/algorithm_dispatch.h
@@ -10,11 +10,11 @@ #include <memory> #include <vector> +#include "base/containers/span.h" #include "third_party/blink/public/platform/web_crypto.h" namespace webcrypto { -class CryptoData; class GenerateKeyResult; class Status; @@ -28,16 +28,16 @@ Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer); Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer); Status Digest(const blink::WebCryptoAlgorithm& algorithm, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer); Status GenerateKey(const blink::WebCryptoAlgorithm& algorithm, @@ -46,7 +46,7 @@ GenerateKeyResult* result); Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -58,13 +58,13 @@ Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer); Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match); Status WrapKey(blink::WebCryptoKeyFormat format, @@ -74,7 +74,7 @@ std::vector<uint8_t>* buffer); Status UnwrapKey(blink::WebCryptoKeyFormat format, - const CryptoData& wrapped_key_data, + base::span<const uint8_t> wrapped_key_data, const blink::WebCryptoKey& wrapping_key, const blink::WebCryptoAlgorithm& wrapping_algorithm, const blink::WebCryptoAlgorithm& algorithm, @@ -121,7 +121,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key); } // namespace webcrypto
diff --git a/components/webcrypto/algorithm_implementation.cc b/components/webcrypto/algorithm_implementation.cc index fe4622a6..63b78dc 100644 --- a/components/webcrypto/algorithm_implementation.cc +++ b/components/webcrypto/algorithm_implementation.cc
@@ -15,7 +15,7 @@ Status AlgorithmImplementation::Encrypt( const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const { return Status::ErrorUnsupported(); } @@ -23,14 +23,14 @@ Status AlgorithmImplementation::Decrypt( const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const { return Status::ErrorUnsupported(); } Status AlgorithmImplementation::Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const { return Status::ErrorUnsupported(); } @@ -38,15 +38,15 @@ Status AlgorithmImplementation::Verify( const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) const { return Status::ErrorUnsupported(); } Status AlgorithmImplementation::Digest( const blink::WebCryptoAlgorithm& algorithm, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const { return Status::ErrorUnsupported(); } @@ -77,7 +77,7 @@ Status AlgorithmImplementation::ImportKey( blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -103,7 +103,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const { return Status::ErrorUnsupported(); }
diff --git a/components/webcrypto/algorithm_implementation.h b/components/webcrypto/algorithm_implementation.h index 900c614..97e6e901e 100644 --- a/components/webcrypto/algorithm_implementation.h +++ b/components/webcrypto/algorithm_implementation.h
@@ -10,11 +10,11 @@ #include <memory> #include <vector> +#include "base/containers/span.h" #include "third_party/blink/public/platform/web_crypto.h" namespace webcrypto { -class CryptoData; class GenerateKeyResult; class Status; @@ -51,7 +51,7 @@ // (crypto.subtle.encrypt() dispatches to this) virtual Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const; // This is what is run whenever the spec says: @@ -60,7 +60,7 @@ // (crypto.subtle.decrypt() dispatches to this) virtual Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const; // This is what is run whenever the spec says: @@ -69,7 +69,7 @@ // (crypto.subtle.sign() dispatches to this) virtual Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const; // This is what is run whenever the spec says: @@ -78,8 +78,8 @@ // (crypto.subtle.verify() dispatches to this) virtual Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) const; // This is what is run whenever the spec says: @@ -87,7 +87,7 @@ // // (crypto.subtle.digest() dispatches to this) virtual Status Digest(const blink::WebCryptoAlgorithm& algorithm, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const; // This is what is run whenever the spec says: @@ -126,7 +126,7 @@ // // (crypto.subtle.importKey() dispatches to this). virtual Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -193,7 +193,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const; };
diff --git a/components/webcrypto/algorithms/aes.cc b/components/webcrypto/algorithms/aes.cc index 5d121339..fe293ff 100644 --- a/components/webcrypto/algorithms/aes.cc +++ b/components/webcrypto/algorithms/aes.cc
@@ -9,7 +9,6 @@ #include "components/webcrypto/algorithms/secret_key_util.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -77,7 +76,7 @@ } Status AesAlgorithm::ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -105,7 +104,7 @@ } } -Status AesAlgorithm::ImportKeyRaw(const CryptoData& key_data, +Status AesAlgorithm::ImportKeyRaw(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -114,7 +113,7 @@ if (status.IsError()) return status; - const unsigned int keylen_bytes = key_data.byte_length(); + const size_t keylen_bytes = key_data.size(); // 192-bit AES is intentionally unsupported (http://crbug.com/533699). if (keylen_bytes == 24) @@ -132,7 +131,7 @@ extractable, usages, key); } -Status AesAlgorithm::ImportKeyJwk(const CryptoData& key_data, +Status AesAlgorithm::ImportKeyJwk(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -169,8 +168,7 @@ } } - return ImportKeyRaw(CryptoData(raw_data), algorithm, extractable, usages, - key); + return ImportKeyRaw(raw_data, algorithm, extractable, usages, key); } Status AesAlgorithm::ExportKeyRaw(const blink::WebCryptoKey& key, @@ -183,7 +181,7 @@ std::vector<uint8_t>* buffer) const { const std::vector<uint8_t>& raw_data = GetSymmetricKeyData(key); - WriteSecretKeyJwk(CryptoData(raw_data), + WriteSecretKeyJwk(raw_data, MakeJwkAesAlgorithmName(jwk_suffix_, raw_data.size()), key.Extractable(), key.Usages(), buffer); @@ -195,7 +193,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const { if (algorithm.ParamsType() != blink::kWebCryptoKeyAlgorithmParamsTypeAes || type != blink::kWebCryptoKeyTypeSecret)
diff --git a/components/webcrypto/algorithms/aes.h b/components/webcrypto/algorithms/aes.h index b7b0ad559..0be65b8 100644 --- a/components/webcrypto/algorithms/aes.h +++ b/components/webcrypto/algorithms/aes.h
@@ -34,7 +34,7 @@ GenerateKeyResult* result) const override; Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -48,7 +48,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const override; Status GetKeyLength(const blink::WebCryptoAlgorithm& key_length_algorithm, @@ -56,13 +56,13 @@ unsigned int* length_bits) const override; private: - Status ImportKeyRaw(const CryptoData& key_data, + Status ImportKeyRaw(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, blink::WebCryptoKey* key) const; - Status ImportKeyJwk(const CryptoData& key_data, + Status ImportKeyJwk(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages,
diff --git a/components/webcrypto/algorithms/aes_cbc.cc b/components/webcrypto/algorithms/aes_cbc.cc index 7c3d67a..473a001 100644 --- a/components/webcrypto/algorithms/aes_cbc.cc +++ b/components/webcrypto/algorithms/aes_cbc.cc
@@ -13,7 +13,6 @@ #include "components/webcrypto/algorithms/aes.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -39,7 +38,7 @@ Status AesCbcEncryptDecrypt(EncryptOrDecrypt cipher_operation, const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); @@ -52,7 +51,7 @@ // According to the openssl docs, the amount of data written may be as large // as (data_size + cipher_block_size - 1), constrained to a multiple of // cipher_block_size. - base::CheckedNumeric<int> output_max_len = data.byte_length(); + base::CheckedNumeric<int> output_max_len = data.size(); output_max_len += AES_BLOCK_SIZE - 1; if (!output_max_len.IsValid()) return Status::ErrorDataTooLarge(); @@ -77,8 +76,8 @@ buffer->resize(base::ValueOrDieForType<size_t>(output_max_len)); int output_len = 0; - if (!EVP_CipherUpdate(context.get(), buffer->data(), &output_len, - data.bytes(), data.byte_length())) { + if (!EVP_CipherUpdate(context.get(), buffer->data(), &output_len, data.data(), + base::checked_cast<int>(data.size()))) { return Status::OperationError(); } int final_output_chunk_len = 0; @@ -102,14 +101,14 @@ Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { return AesCbcEncryptDecrypt(ENCRYPT, algorithm, key, data, buffer); } Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { return AesCbcEncryptDecrypt(DECRYPT, algorithm, key, data, buffer); }
diff --git a/components/webcrypto/algorithms/aes_cbc_unittest.cc b/components/webcrypto/algorithms/aes_cbc_unittest.cc index f5a9790..dc94f94 100644 --- a/components/webcrypto/algorithms/aes_cbc_unittest.cc +++ b/components/webcrypto/algorithms/aes_cbc_unittest.cc
@@ -9,10 +9,10 @@ #include <memory> #include <utility> +#include "base/containers/span.h" #include "base/values.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/public/platform/web_crypto_key_algorithm.h" @@ -63,7 +63,7 @@ // Pretend the input is large. Don't pass data pointer as NULL in case that // is special cased; the implementation shouldn't actually dereference the // data. - CryptoData input(&iv[0], INT_MAX - 3); + base::span<const uint8_t> input(iv.data(), INT_MAX - 3); EXPECT_EQ( Status::ErrorDataTooLarge(), @@ -105,7 +105,7 @@ // Import the key. blink::WebCryptoKey key; Status status = ImportKey( - key_format, CryptoData(key_data), + key_format, key_data, CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), true, blink::kWebCryptoKeyUsageEncrypt | blink::kWebCryptoKeyUsageDecrypt, &key); @@ -124,8 +124,8 @@ test->GetString("encrypt_error", &encrypt_error); std::vector<uint8_t> output; - status = Encrypt(CreateAesCbcAlgorithm(test_iv), key, - CryptoData(test_plain_text), &output); + status = Encrypt(CreateAesCbcAlgorithm(test_iv), key, test_plain_text, + &output); ASSERT_EQ(encrypt_error, StatusToString(status)); if (status.IsError()) continue; @@ -147,8 +147,8 @@ test->GetString("decrypt_error", &decrypt_error); std::vector<uint8_t> output; - status = Decrypt(CreateAesCbcAlgorithm(test_iv), key, - CryptoData(test_cipher_text), &output); + status = Decrypt(CreateAesCbcAlgorithm(test_iv), key, test_cipher_text, + &output); ASSERT_EQ(decrypt_error, StatusToString(status)); if (status.IsError()) continue; @@ -207,8 +207,7 @@ TEST_F(WebCryptoAesCbcTest, ImportKeyEmptyUsage) { blink::WebCryptoKey key; ASSERT_EQ(Status::ErrorCreateKeyEmptyUsages(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(std::vector<uint8_t>(16)), + ImportKey(blink::kWebCryptoKeyFormatRaw, std::vector<uint8_t>(16), CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), true, 0, &key)); } @@ -338,14 +337,15 @@ blink::WebCryptoKey key; // Fail on empty JSON. EXPECT_EQ(Status::ErrorJwkNotDictionary(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(), + ImportKey(blink::kWebCryptoKeyFormatJwk, {}, CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), false, blink::kWebCryptoKeyUsageEncrypt, &key)); // Fail on invalid JSON. const std::string bad_json = R"({ "kty": "oct", "alg": "HS256", "use": )"; EXPECT_EQ(Status::ErrorJwkNotDictionary(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(bad_json), + ImportKey(blink::kWebCryptoKeyFormatJwk, + base::as_bytes(base::make_span(bad_json)), CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), false, blink::kWebCryptoKeyUsageEncrypt, &key)); } @@ -410,8 +410,7 @@ blink::WebCryptoKey unwrapped_key; ASSERT_EQ(Status::ErrorAes192BitUnsupported(), - UnwrapKey(blink::kWebCryptoKeyFormatRaw, CryptoData(wrapped_key), - wrapping_key, + UnwrapKey(blink::kWebCryptoKeyFormatRaw, wrapped_key, wrapping_key, CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesKw), CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), true, blink::kWebCryptoKeyUsageEncrypt, &unwrapped_key)); @@ -438,8 +437,8 @@ blink::WebCryptoKey key; ASSERT_EQ(Status::ErrorCreateKeyBadUsages(), - ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(key_bytes), - algorithm, true, bad_usages[i], &key)); + ImportKey(blink::kWebCryptoKeyFormatRaw, key_bytes, algorithm, + true, bad_usages[i], &key)); } } @@ -527,18 +526,16 @@ blink::WebCryptoKey unwrapped_public_key; - ASSERT_EQ( - Status::Success(), - UnwrapKey(blink::kWebCryptoKeyFormatSpki, CryptoData(wrapped_public_key), - wrapping_key, wrap_algorithm, rsa_import_algorithm, true, - blink::kWebCryptoKeyUsageVerify, &unwrapped_public_key)); + ASSERT_EQ(Status::Success(), + UnwrapKey(blink::kWebCryptoKeyFormatSpki, wrapped_public_key, + wrapping_key, wrap_algorithm, rsa_import_algorithm, true, + blink::kWebCryptoKeyUsageVerify, &unwrapped_public_key)); blink::WebCryptoKey unwrapped_private_key; ASSERT_EQ(Status::Success(), - UnwrapKey(blink::kWebCryptoKeyFormatPkcs8, - CryptoData(wrapped_private_key), wrapping_key, - wrap_algorithm, rsa_import_algorithm, true, + UnwrapKey(blink::kWebCryptoKeyFormatPkcs8, wrapped_private_key, + wrapping_key, wrap_algorithm, rsa_import_algorithm, true, blink::kWebCryptoKeyUsageSign, &unwrapped_private_key)); // Export unwrapped key pair as SPKI + PKCS8
diff --git a/components/webcrypto/algorithms/aes_ctr.cc b/components/webcrypto/algorithms/aes_ctr.cc index 27e6e7a..2b3771a 100644 --- a/components/webcrypto/algorithms/aes_ctr.cc +++ b/components/webcrypto/algorithms/aes_ctr.cc
@@ -16,7 +16,6 @@ #include "components/webcrypto/algorithms/aes.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/abseil-cpp/absl/numeric/int128.h" @@ -44,23 +43,23 @@ // // |output| must have the same length as |input|. Status AesCtrEncrypt128BitCounter(const EVP_CIPHER* cipher, - const CryptoData& raw_key, - const CryptoData& input, + base::span<const uint8_t> raw_key, + base::span<const uint8_t> input, base::span<const uint8_t, 16> counter, base::span<uint8_t> output) { DCHECK(cipher); - DCHECK_EQ(input.byte_length(), output.size()); + DCHECK_EQ(input.size(), output.size()); crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); bssl::ScopedEVP_CIPHER_CTX context; - if (!EVP_CipherInit_ex(context.get(), cipher, nullptr, raw_key.bytes(), + if (!EVP_CipherInit_ex(context.get(), cipher, nullptr, raw_key.data(), counter.data(), ENCRYPT)) { return Status::OperationError(); } int output_len = 0; - if (!EVP_CipherUpdate(context.get(), output.data(), &output_len, - input.bytes(), input.byte_length())) { + if (!EVP_CipherUpdate(context.get(), output.data(), &output_len, input.data(), + base::checked_cast<int>(input.size()))) { return Status::OperationError(); } int final_output_chunk_len = 0; @@ -70,7 +69,7 @@ } output_len += final_output_chunk_len; - if (static_cast<unsigned int>(output_len) != input.byte_length()) + if (static_cast<size_t>(output_len) != input.size()) return Status::ErrorUnexpected(); return Status::Success(); @@ -139,7 +138,7 @@ // encrypt/decrypt. Status AesCtrEncryptDecrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { const blink::WebCryptoAesCtrParams* params = algorithm.AesCtrParams(); const std::vector<uint8_t>& raw_key = GetSymmetricKeyData(key); @@ -155,7 +154,7 @@ // The output of AES-CTR is the same size as the input. However BoringSSL // expects buffer sizes as an "int". - base::CheckedNumeric<int> output_max_len = data.byte_length(); + base::CheckedNumeric<int> output_max_len = data.size(); if (!output_max_len.IsValid()) return Status::ErrorDataTooLarge(); @@ -168,8 +167,8 @@ GetCounter(counter_block, counter_length_bits); if (counter_length_bits == 128) { - return AesCtrEncrypt128BitCounter(cipher, CryptoData(raw_key), data, - counter_block, *buffer); + return AesCtrEncrypt128BitCounter(cipher, raw_key, data, counter_block, + *buffer); } // The total number of possible counter values is pow(2, counter_length_bits) @@ -192,28 +191,28 @@ // If the counter can be incremented for the entire input without // wrapping-around, do it as a single call into BoringSSL. if (num_blocks_until_reset >= num_output_blocks) { - return AesCtrEncrypt128BitCounter(cipher, CryptoData(raw_key), data, - counter_block, *buffer); + return AesCtrEncrypt128BitCounter(cipher, raw_key, data, counter_block, + *buffer); } // Otherwise the encryption needs to be done in 2 parts. The first part using // the current counter_block, and the next part resetting the counter portion // of the block to zero. - // This is guaranteed to fit in an "unsigned int" because input size in bytes - // fits in an "unsigned int". - unsigned int input_size_part1 = - static_cast<unsigned int>(num_blocks_until_reset * AES_BLOCK_SIZE); - DCHECK_LT(input_size_part1, data.byte_length()); + // This is guaranteed to fit in an `size_t` because it is bounded by the input + // size. + size_t input_size_part1 = + static_cast<size_t>(num_blocks_until_reset * AES_BLOCK_SIZE); + DCHECK_LT(input_size_part1, data.size()); base::span<uint8_t> output_part1 = base::make_span(*buffer).first(input_size_part1); base::span<uint8_t> output_part2 = base::make_span(*buffer).subspan(input_size_part1); // Encrypt the first part (before wrap-around). - Status status = AesCtrEncrypt128BitCounter( - cipher, CryptoData(raw_key), CryptoData(data.bytes(), input_size_part1), - counter_block, output_part1); + Status status = + AesCtrEncrypt128BitCounter(cipher, raw_key, data.first(input_size_part1), + counter_block, output_part1); if (status.IsError()) return status; @@ -221,11 +220,9 @@ std::array<uint8_t, AES_BLOCK_SIZE> counter_block_part2 = BlockWithZeroedCounter(counter_block, counter_length_bits); - return AesCtrEncrypt128BitCounter( - cipher, CryptoData(raw_key), - CryptoData(data.bytes() + input_size_part1, - data.byte_length() - input_size_part1), - counter_block_part2, output_part2); + return AesCtrEncrypt128BitCounter(cipher, raw_key, + data.subspan(input_size_part1), + counter_block_part2, output_part2); } class AesCtrImplementation : public AesAlgorithm { @@ -234,14 +231,14 @@ Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { return AesCtrEncryptDecrypt(algorithm, key, data, buffer); } Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { return AesCtrEncryptDecrypt(algorithm, key, data, buffer); }
diff --git a/components/webcrypto/algorithms/aes_ctr_unittest.cc b/components/webcrypto/algorithms/aes_ctr_unittest.cc index c91ea0f00..49da5a0 100644 --- a/components/webcrypto/algorithms/aes_ctr_unittest.cc +++ b/components/webcrypto/algorithms/aes_ctr_unittest.cc
@@ -5,9 +5,9 @@ #include <stddef.h> #include <stdint.h> +#include "base/containers/span.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/public/platform/web_crypto_key_algorithm.h" @@ -112,13 +112,13 @@ // Test encryption. EXPECT_EQ(Status::Success(), Encrypt(CreateAesCtrAlgorithm(counter, test.counter_length), key, - CryptoData(plaintext), &output)); + plaintext, &output)); EXPECT_EQ(ciphertext, output); // Test decryption. EXPECT_EQ(Status::Success(), Decrypt(CreateAesCtrAlgorithm(counter, test.counter_length), key, - CryptoData(ciphertext), &output)); + ciphertext, &output)); EXPECT_EQ(plaintext, output); } } @@ -133,13 +133,13 @@ for (size_t bad_length : {0, 15, 17}) { std::vector<uint8_t> bad_counter(bad_length); - EXPECT_EQ(Status::ErrorIncorrectSizeAesCtrCounter(), - Encrypt(CreateAesCtrAlgorithm(bad_counter, 128), key, - CryptoData(input), &output)); + EXPECT_EQ( + Status::ErrorIncorrectSizeAesCtrCounter(), + Encrypt(CreateAesCtrAlgorithm(bad_counter, 128), key, input, &output)); - EXPECT_EQ(Status::ErrorIncorrectSizeAesCtrCounter(), - Decrypt(CreateAesCtrAlgorithm(bad_counter, 128), key, - CryptoData(input), &output)); + EXPECT_EQ( + Status::ErrorIncorrectSizeAesCtrCounter(), + Decrypt(CreateAesCtrAlgorithm(bad_counter, 128), key, input, &output)); } } @@ -153,12 +153,12 @@ // The counter length cannot be less than 1 or greater than 128. for (uint8_t bad_length : {0, 129}) { EXPECT_EQ(Status::ErrorInvalidAesCtrCounterLength(), - Encrypt(CreateAesCtrAlgorithm(counter, bad_length), key, - CryptoData(input), &output)); + Encrypt(CreateAesCtrAlgorithm(counter, bad_length), key, input, + &output)); EXPECT_EQ(Status::ErrorInvalidAesCtrCounterLength(), - Decrypt(CreateAesCtrAlgorithm(counter, bad_length), key, - CryptoData(input), &output)); + Decrypt(CreateAesCtrAlgorithm(counter, bad_length), key, input, + &output)); } } @@ -178,8 +178,8 @@ // 16 and 17 AES blocks worth of data respectively (AES blocks are 16 bytes // long). - CryptoData input_16(buffer.data(), 256); - CryptoData input_17(buffer.data(), 272); + auto input_16 = base::make_span(buffer).first(256); + auto input_17 = base::make_span(buffer).first(272); std::vector<uint8_t> output;
diff --git a/components/webcrypto/algorithms/aes_gcm.cc b/components/webcrypto/algorithms/aes_gcm.cc index 0f3f70c..73c5cf2 100644 --- a/components/webcrypto/algorithms/aes_gcm.cc +++ b/components/webcrypto/algorithms/aes_gcm.cc
@@ -11,7 +11,6 @@ #include "components/webcrypto/algorithms/aes.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -35,7 +34,7 @@ Status AesGcmEncryptDecrypt(EncryptOrDecrypt mode, const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { const std::vector<uint8_t>& raw_key = GetSymmetricKeyData(key); const blink::WebCryptoAesGcmParams* params = algorithm.AesGcmParams(); @@ -53,10 +52,10 @@ } } - return AeadEncryptDecrypt( - mode, raw_key, data, tag_length_bits / 8, CryptoData(params->Iv()), - CryptoData(params->OptionalAdditionalData()), - GetAesGcmAlgorithmFromKeySize(raw_key.size()), buffer); + return AeadEncryptDecrypt(mode, raw_key, data, tag_length_bits / 8, + params->Iv(), params->OptionalAdditionalData(), + GetAesGcmAlgorithmFromKeySize(raw_key.size()), + buffer); } class AesGcmImplementation : public AesAlgorithm { @@ -65,14 +64,14 @@ Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { return AesGcmEncryptDecrypt(ENCRYPT, algorithm, key, data, buffer); } Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { return AesGcmEncryptDecrypt(DECRYPT, algorithm, key, data, buffer); }
diff --git a/components/webcrypto/algorithms/aes_gcm_unittest.cc b/components/webcrypto/algorithms/aes_gcm_unittest.cc index 0dfedb8..300a067 100644 --- a/components/webcrypto/algorithms/aes_gcm_unittest.cc +++ b/components/webcrypto/algorithms/aes_gcm_unittest.cc
@@ -8,7 +8,6 @@ #include "base/values.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -46,7 +45,7 @@ CreateAesGcmAlgorithm(iv, additional_data, tag_length_bits); std::vector<uint8_t> output; - Status status = Encrypt(algorithm, key, CryptoData(plain_text), &output); + Status status = Encrypt(algorithm, key, plain_text, &output); if (status.IsError()) return status; @@ -90,7 +89,7 @@ authentication_tag.begin(), authentication_tag.end()); - return Decrypt(algorithm, key, CryptoData(cipher_text_with_tag), plain_text); + return Decrypt(algorithm, key, cipher_text_with_tag, plain_text); } class WebCryptoAesGcmTest : public WebCryptoTestBase {};
diff --git a/components/webcrypto/algorithms/aes_kw.cc b/components/webcrypto/algorithms/aes_kw.cc index fc6e033..b7e3254 100644 --- a/components/webcrypto/algorithms/aes_kw.cc +++ b/components/webcrypto/algorithms/aes_kw.cc
@@ -12,7 +12,6 @@ #include "base/numerics/safe_math.h" #include "components/webcrypto/algorithms/aes.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/boringssl/src/include/openssl/aes.h" @@ -30,15 +29,15 @@ Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); // These length checks are done in order to give a more specific // error. These are not required for correctness. - if (data.byte_length() < 16) + if (data.size() < 16) return Status::ErrorDataTooSmall(); - if (data.byte_length() % 8) + if (data.size() % 8) return Status::ErrorInvalidAesKwDataLength(); // Key import validates key sizes, so the bits computation will not @@ -52,14 +51,14 @@ } // Key wrap's overhead is 8 bytes. - base::CheckedNumeric<size_t> length(data.byte_length()); + base::CheckedNumeric<size_t> length(data.size()); length += 8; if (!length.IsValid()) return Status::ErrorDataTooLarge(); buffer->resize(length.ValueOrDie()); if (AES_wrap_key(&aes_key, nullptr /* default IV */, buffer->data(), - data.bytes(), data.byte_length()) < 0) { + data.data(), data.size()) < 0) { return Status::OperationError(); } @@ -68,15 +67,15 @@ Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); // These length checks are done in order to give a more specific // error. These are not required for correctness. - if (data.byte_length() < 24) + if (data.size() < 24) return Status::ErrorDataTooSmall(); - if (data.byte_length() % 8) + if (data.size() % 8) return Status::ErrorInvalidAesKwDataLength(); // Key import validates key sizes, so the bits computation will not @@ -90,10 +89,10 @@ } // Key wrap's overhead is 8 bytes. - buffer->resize(data.byte_length() - 8); + buffer->resize(data.size() - 8); if (AES_unwrap_key(&aes_key, nullptr /* default IV */, buffer->data(), - data.bytes(), data.byte_length()) < 0) { + data.data(), data.size()) < 0) { return Status::OperationError(); }
diff --git a/components/webcrypto/algorithms/aes_kw_unittest.cc b/components/webcrypto/algorithms/aes_kw_unittest.cc index 857b4bb..9d12964 100644 --- a/components/webcrypto/algorithms/aes_kw_unittest.cc +++ b/components/webcrypto/algorithms/aes_kw_unittest.cc
@@ -10,7 +10,6 @@ #include "base/values.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/public/platform/web_crypto_key_algorithm.h" @@ -46,8 +45,7 @@ TEST_F(WebCryptoAesKwTest, ImportKeyEmptyUsage) { blink::WebCryptoKey key; EXPECT_EQ(Status::ErrorCreateKeyEmptyUsages(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(std::vector<uint8_t>(16)), + ImportKey(blink::kWebCryptoKeyFormatRaw, std::vector<uint8_t>(16), CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesKw), true, 0, &key)); } @@ -103,10 +101,10 @@ // Import a 128-bit Key Encryption Key (KEK) std::string key_raw_hex_in = "025a8cf3f08b4f6c5f33bbc76a471939"; - ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(HexStringToBytes(key_raw_hex_in)), algorithm, - true, blink::kWebCryptoKeyUsageWrapKey, &key)); + ASSERT_EQ( + Status::Success(), + ImportKey(blink::kWebCryptoKeyFormatRaw, HexStringToBytes(key_raw_hex_in), + algorithm, true, blink::kWebCryptoKeyUsageWrapKey, &key)); std::vector<uint8_t> key_raw_out; EXPECT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatRaw, key, &key_raw_out)); @@ -114,41 +112,40 @@ // Import a 192-bit KEK key_raw_hex_in = "c0192c6466b2370decbb62b2cfef4384544ffeb4d2fbc103"; - ASSERT_EQ(Status::ErrorAes192BitUnsupported(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(HexStringToBytes(key_raw_hex_in)), algorithm, - true, blink::kWebCryptoKeyUsageWrapKey, &key)); + ASSERT_EQ( + Status::ErrorAes192BitUnsupported(), + ImportKey(blink::kWebCryptoKeyFormatRaw, HexStringToBytes(key_raw_hex_in), + algorithm, true, blink::kWebCryptoKeyUsageWrapKey, &key)); // Import a 256-bit Key Encryption Key (KEK) key_raw_hex_in = "e11fe66380d90fa9ebefb74e0478e78f95664d0c67ca20ce4a0b5842863ac46f"; - ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(HexStringToBytes(key_raw_hex_in)), algorithm, - true, blink::kWebCryptoKeyUsageWrapKey, &key)); + ASSERT_EQ( + Status::Success(), + ImportKey(blink::kWebCryptoKeyFormatRaw, HexStringToBytes(key_raw_hex_in), + algorithm, true, blink::kWebCryptoKeyUsageWrapKey, &key)); EXPECT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatRaw, key, &key_raw_out)); EXPECT_BYTES_EQ_HEX(key_raw_hex_in, key_raw_out); // Fail import of 0 length key - EXPECT_EQ( - Status::ErrorImportAesKeyLength(), - ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(HexStringToBytes("")), - algorithm, true, blink::kWebCryptoKeyUsageWrapKey, &key)); + EXPECT_EQ(Status::ErrorImportAesKeyLength(), + ImportKey(blink::kWebCryptoKeyFormatRaw, HexStringToBytes(""), + algorithm, true, blink::kWebCryptoKeyUsageWrapKey, &key)); // Fail import of 120-bit KEK key_raw_hex_in = "3e4566a2bdaa10cb68134fa66c15dd"; - EXPECT_EQ(Status::ErrorImportAesKeyLength(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(HexStringToBytes(key_raw_hex_in)), algorithm, - true, blink::kWebCryptoKeyUsageWrapKey, &key)); + EXPECT_EQ( + Status::ErrorImportAesKeyLength(), + ImportKey(blink::kWebCryptoKeyFormatRaw, HexStringToBytes(key_raw_hex_in), + algorithm, true, blink::kWebCryptoKeyUsageWrapKey, &key)); // Fail import of 200-bit KEK key_raw_hex_in = "0a1d88608a5ad9fec64f1ada269ebab4baa2feeb8d95638c0e"; - EXPECT_EQ(Status::ErrorImportAesKeyLength(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(HexStringToBytes(key_raw_hex_in)), algorithm, - true, blink::kWebCryptoKeyUsageWrapKey, &key)); + EXPECT_EQ( + Status::ErrorImportAesKeyLength(), + ImportKey(blink::kWebCryptoKeyFormatRaw, HexStringToBytes(key_raw_hex_in), + algorithm, true, blink::kWebCryptoKeyUsageWrapKey, &key)); } TEST_F(WebCryptoAesKwTest, UnwrapFailures) { @@ -168,12 +165,12 @@ blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw( test_kek, CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesKw), blink::kWebCryptoKeyUsageUnwrapKey); - EXPECT_EQ(Status::ErrorUnexpected(), - UnwrapKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(test_ciphertext), wrapping_key, - CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), - CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), true, - blink::kWebCryptoKeyUsageEncrypt, &unwrapped_key)); + EXPECT_EQ( + Status::ErrorUnexpected(), + UnwrapKey(blink::kWebCryptoKeyFormatRaw, test_ciphertext, wrapping_key, + CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), + CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), true, + blink::kWebCryptoKeyUsageEncrypt, &unwrapped_key)); } TEST_F(WebCryptoAesKwTest, AesKwRawSymkeyWrapUnwrapKnownAnswer) { @@ -211,13 +208,12 @@ // Unwrap the known ciphertext to get a new test_key. blink::WebCryptoKey unwrapped_key; - ASSERT_EQ( - Status::Success(), - UnwrapKey( - blink::kWebCryptoKeyFormatRaw, CryptoData(test_ciphertext), - wrapping_key, wrapping_algorithm, - CreateHmacImportAlgorithmNoLength(blink::kWebCryptoAlgorithmIdSha1), - true, blink::kWebCryptoKeyUsageSign, &unwrapped_key)); + ASSERT_EQ(Status::Success(), + UnwrapKey(blink::kWebCryptoKeyFormatRaw, test_ciphertext, + wrapping_key, wrapping_algorithm, + CreateHmacImportAlgorithmNoLength( + blink::kWebCryptoAlgorithmIdSha1), + true, blink::kWebCryptoKeyUsageSign, &unwrapped_key)); EXPECT_FALSE(key.IsNull()); EXPECT_TRUE(key.Handle()); EXPECT_EQ(blink::kWebCryptoKeyTypeSecret, key.GetType()); @@ -256,8 +252,8 @@ ASSERT_EQ( Status::Success(), UnwrapKey( - blink::kWebCryptoKeyFormatRaw, CryptoData(test_ciphertext), - wrapping_key, wrapping_algorithm, + blink::kWebCryptoKeyFormatRaw, test_ciphertext, wrapping_key, + wrapping_algorithm, CreateHmacImportAlgorithmNoLength(blink::kWebCryptoAlgorithmIdSha1), false, blink::kWebCryptoKeyUsageSign | blink::kWebCryptoKeyUsageVerify, @@ -275,15 +271,14 @@ ASSERT_EQ(Status::Success(), Sign(CreateAlgorithm(blink::kWebCryptoAlgorithmIdHmac), key, - CryptoData(test_message), &signature)); + test_message, &signature)); EXPECT_GT(signature.size(), 0u); bool verify_result; - ASSERT_EQ( - Status::Success(), - Verify(CreateAlgorithm(blink::kWebCryptoAlgorithmIdHmac), key, - CryptoData(signature), CryptoData(test_message), &verify_result)); + ASSERT_EQ(Status::Success(), + Verify(CreateAlgorithm(blink::kWebCryptoAlgorithmIdHmac), key, + signature, test_message, &verify_result)); } TEST_F(WebCryptoAesKwTest, AesKwRawSymkeyWrapUnwrapErrors) { @@ -315,15 +310,15 @@ test_ciphertext.begin() + 23); blink::WebCryptoKey unwrapped_key; EXPECT_EQ(Status::ErrorDataTooSmall(), - UnwrapKey(blink::kWebCryptoKeyFormatRaw, CryptoData(small_data), - wrapping_key, wrapping_algorithm, key_algorithm, true, + UnwrapKey(blink::kWebCryptoKeyFormatRaw, small_data, wrapping_key, + wrapping_algorithm, key_algorithm, true, blink::kWebCryptoKeyUsageEncrypt, &unwrapped_key)); // Unwrap with wrapped data size not a multiple of 8 bytes must fail. const std::vector<uint8_t> unaligned_data(test_ciphertext.begin(), test_ciphertext.end() - 2); EXPECT_EQ(Status::ErrorInvalidAesKwDataLength(), - UnwrapKey(blink::kWebCryptoKeyFormatRaw, CryptoData(unaligned_data), + UnwrapKey(blink::kWebCryptoKeyFormatRaw, unaligned_data, wrapping_key, wrapping_algorithm, key_algorithm, true, blink::kWebCryptoKeyUsageEncrypt, &unwrapped_key)); } @@ -351,9 +346,8 @@ // AES-KW's built-in integrity check. blink::WebCryptoKey unwrapped_key; EXPECT_EQ(Status::OperationError(), - UnwrapKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(Corrupted(test_ciphertext)), wrapping_key, - wrapping_algorithm, + UnwrapKey(blink::kWebCryptoKeyFormatRaw, Corrupted(test_ciphertext), + wrapping_key, wrapping_algorithm, CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), true, blink::kWebCryptoKeyUsageEncrypt, &unwrapped_key)); } @@ -385,13 +379,12 @@ // Unwrap the known wrapped key data to produce a new key blink::WebCryptoKey unwrapped_key; - ASSERT_EQ( - Status::Success(), - UnwrapKey( - blink::kWebCryptoKeyFormatJwk, CryptoData(wrapped_key_data), - wrapping_key, wrapping_algorithm, - CreateHmacImportAlgorithmNoLength(blink::kWebCryptoAlgorithmIdSha256), - true, blink::kWebCryptoKeyUsageVerify, &unwrapped_key)); + ASSERT_EQ(Status::Success(), + UnwrapKey(blink::kWebCryptoKeyFormatJwk, wrapped_key_data, + wrapping_key, wrapping_algorithm, + CreateHmacImportAlgorithmNoLength( + blink::kWebCryptoAlgorithmIdSha256), + true, blink::kWebCryptoKeyUsageVerify, &unwrapped_key)); // Validate the new key's attributes. EXPECT_FALSE(unwrapped_key.IsNull()); @@ -434,8 +427,8 @@ blink::WebCryptoKey key; ASSERT_EQ(Status::ErrorCreateKeyBadUsages(), - ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(key_bytes), - algorithm, true, bad_usages[i], &key)); + ImportKey(blink::kWebCryptoKeyFormatRaw, key_bytes, algorithm, + true, bad_usages[i], &key)); } } @@ -457,9 +450,9 @@ // Import the wrapping key. blink::WebCryptoKey wrapping_key; ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(std::vector<uint8_t>(16)), unwrap_algorithm, - true, blink::kWebCryptoKeyUsageUnwrapKey, &wrapping_key)); + ImportKey(blink::kWebCryptoKeyFormatRaw, std::vector<uint8_t>(16), + unwrap_algorithm, true, + blink::kWebCryptoKeyUsageUnwrapKey, &wrapping_key)); // The JWK plain text is: // {"kty":"oct","alg":"HS256","k":"GADWrMRHwQfoNaXU5fZvTg"} @@ -472,13 +465,13 @@ blink::WebCryptoKey key; - ASSERT_EQ(Status::ErrorCreateKeyBadUsages(), - UnwrapKey(blink::kWebCryptoKeyFormatJwk, - CryptoData(HexStringToBytes(kWrappedJwk)), wrapping_key, - unwrap_algorithm, - CreateHmacImportAlgorithmNoLength( - blink::kWebCryptoAlgorithmIdSha256), - true, bad_usages[i], &key)); + ASSERT_EQ( + Status::ErrorCreateKeyBadUsages(), + UnwrapKey(blink::kWebCryptoKeyFormatJwk, HexStringToBytes(kWrappedJwk), + wrapping_key, unwrap_algorithm, + CreateHmacImportAlgorithmNoLength( + blink::kWebCryptoAlgorithmIdSha256), + true, bad_usages[i], &key)); } } @@ -500,9 +493,9 @@ // Import the wrapping key. blink::WebCryptoKey wrapping_key; ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(std::vector<uint8_t>(16)), unwrap_algorithm, - true, blink::kWebCryptoKeyUsageUnwrapKey, &wrapping_key)); + ImportKey(blink::kWebCryptoKeyFormatRaw, std::vector<uint8_t>(16), + unwrap_algorithm, true, + blink::kWebCryptoKeyUsageUnwrapKey, &wrapping_key)); // The JWK plaintext is: // { "kty": "RSA","alg": "RS256","n": "...","e": "AQAB"} @@ -521,14 +514,14 @@ blink::WebCryptoKey key; - ASSERT_EQ(Status::ErrorCreateKeyBadUsages(), - UnwrapKey(blink::kWebCryptoKeyFormatJwk, - CryptoData(HexStringToBytes(kWrappedJwk)), wrapping_key, - unwrap_algorithm, - CreateRsaHashedImportAlgorithm( - blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, - blink::kWebCryptoAlgorithmIdSha256), - true, bad_usages[i], &key)); + ASSERT_EQ( + Status::ErrorCreateKeyBadUsages(), + UnwrapKey(blink::kWebCryptoKeyFormatJwk, HexStringToBytes(kWrappedJwk), + wrapping_key, unwrap_algorithm, + CreateRsaHashedImportAlgorithm( + blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, + blink::kWebCryptoAlgorithmIdSha256), + true, bad_usages[i], &key)); } }
diff --git a/components/webcrypto/algorithms/asymmetric_key_util.cc b/components/webcrypto/algorithms/asymmetric_key_util.cc index 07d4f6b3..d481d05 100644 --- a/components/webcrypto/algorithms/asymmetric_key_util.cc +++ b/components/webcrypto/algorithms/asymmetric_key_util.cc
@@ -9,7 +9,6 @@ #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" @@ -93,13 +92,13 @@ return Status::Success(); } -Status ImportUnverifiedPkeyFromSpki(const CryptoData& key_data, +Status ImportUnverifiedPkeyFromSpki(base::span<const uint8_t> key_data, int expected_pkey_id, bssl::UniquePtr<EVP_PKEY>* out_pkey) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); CBS cbs; - CBS_init(&cbs, key_data.bytes(), key_data.byte_length()); + CBS_init(&cbs, key_data.data(), key_data.size()); bssl::UniquePtr<EVP_PKEY> pkey(EVP_parse_public_key(&cbs)); if (!pkey || CBS_len(&cbs) != 0) return Status::DataError(); @@ -111,13 +110,13 @@ return Status::Success(); } -Status ImportUnverifiedPkeyFromPkcs8(const CryptoData& key_data, +Status ImportUnverifiedPkeyFromPkcs8(base::span<const uint8_t> key_data, int expected_pkey_id, bssl::UniquePtr<EVP_PKEY>* out_pkey) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); CBS cbs; - CBS_init(&cbs, key_data.bytes(), key_data.byte_length()); + CBS_init(&cbs, key_data.data(), key_data.size()); bssl::UniquePtr<EVP_PKEY> pkey(EVP_parse_private_key(&cbs)); if (!pkey || CBS_len(&cbs) != 0) return Status::DataError();
diff --git a/components/webcrypto/algorithms/asymmetric_key_util.h b/components/webcrypto/algorithms/asymmetric_key_util.h index 2355bd3c..4c9b868 100644 --- a/components/webcrypto/algorithms/asymmetric_key_util.h +++ b/components/webcrypto/algorithms/asymmetric_key_util.h
@@ -5,6 +5,7 @@ #ifndef COMPONENTS_WEBCRYPTO_ALGORITHMS_ASYMMETRIC_KEY_UTIL_H_ #define COMPONENTS_WEBCRYPTO_ALGORITHMS_ASYMMETRIC_KEY_UTIL_H_ +#include "base/containers/span.h" #include "third_party/blink/public/platform/web_crypto_algorithm.h" #include "third_party/blink/public/platform/web_crypto_key.h" #include "third_party/boringssl/src/include/openssl/base.h" @@ -13,7 +14,6 @@ namespace webcrypto { -class CryptoData; class Status; // Creates a WebCrypto public key given an EVP_PKEY. This step includes @@ -36,7 +36,7 @@ // key may be invalid, and should be verified using something like // RSA_check_key(). The only validation performed by this function is to ensure // the key type matched |expected_pkey_id|. -Status ImportUnverifiedPkeyFromSpki(const CryptoData& key_data, +Status ImportUnverifiedPkeyFromSpki(base::span<const uint8_t> key_data, int expected_pkey_id, bssl::UniquePtr<EVP_PKEY>* pkey); @@ -44,7 +44,7 @@ // asymmetric key may be invalid, and should be verified using something like // RSA_check_key(). The only validation performed by this function is to ensure // the key type matched |expected_pkey_id|. -Status ImportUnverifiedPkeyFromPkcs8(const CryptoData& key_data, +Status ImportUnverifiedPkeyFromPkcs8(base::span<const uint8_t> key_data, int expected_pkey_id, bssl::UniquePtr<EVP_PKEY>* pkey);
diff --git a/components/webcrypto/algorithms/ec.cc b/components/webcrypto/algorithms/ec.cc index 30b7b239e..147c0d8 100644 --- a/components/webcrypto/algorithms/ec.cc +++ b/components/webcrypto/algorithms/ec.cc
@@ -8,10 +8,10 @@ #include <utility> +#include "base/containers/span.h" #include "components/webcrypto/algorithms/asymmetric_key_util.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" @@ -163,7 +163,7 @@ std::vector<uint8_t> padded_bytes(padded_length); if (!BN_bn2bin_padded(padded_bytes.data(), padded_bytes.size(), value)) return Status::OperationError(); - jwk->SetBytes(member_name, CryptoData(padded_bytes)); + jwk->SetBytes(member_name, padded_bytes); return Status::Success(); } @@ -172,7 +172,7 @@ const std::string& member_name, size_t expected_length, bssl::UniquePtr<BIGNUM>* out) { - std::string bytes; + std::vector<uint8_t> bytes; Status status = jwk.GetBytes(member_name, &bytes); if (status.IsError()) return status; @@ -182,7 +182,7 @@ bytes.size()); } - out->reset(CreateBIGNUM(bytes)); + out->reset(BN_bin2bn(bytes.data(), bytes.size(), nullptr)); return Status::Success(); } @@ -292,7 +292,7 @@ } Status EcAlgorithm::ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -328,7 +328,7 @@ } } -Status EcAlgorithm::ImportKeyRaw(const CryptoData& key_data, +Status EcAlgorithm::ImportKeyRaw(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -354,7 +354,7 @@ // Convert the "raw" input from X9.62 format to an EC_POINT. if (!EC_POINT_oct2point(EC_KEY_get0_group(ec.get()), point.get(), - key_data.bytes(), key_data.byte_length(), nullptr)) { + key_data.data(), key_data.size(), nullptr)) { return Status::DataError(); } @@ -380,7 +380,7 @@ usages, key); } -Status EcAlgorithm::ImportKeyPkcs8(const CryptoData& key_data, +Status EcAlgorithm::ImportKeyPkcs8(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -408,7 +408,7 @@ extractable, usages, key); } -Status EcAlgorithm::ImportKeySpki(const CryptoData& key_data, +Status EcAlgorithm::ImportKeySpki(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -438,7 +438,7 @@ // The format for JWK EC keys is given by: // https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-36#section-6.2 -Status EcAlgorithm::ImportKeyJwk(const CryptoData& key_data, +Status EcAlgorithm::ImportKeyJwk(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -653,7 +653,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const { if (algorithm.ParamsType() != blink::kWebCryptoKeyAlgorithmParamsTypeEc) return Status::ErrorUnexpected();
diff --git a/components/webcrypto/algorithms/ec.h b/components/webcrypto/algorithms/ec.h index 048bc50e..03a508f 100644 --- a/components/webcrypto/algorithms/ec.h +++ b/components/webcrypto/algorithms/ec.h
@@ -33,7 +33,7 @@ GenerateKeyResult* result) const override; Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -47,29 +47,29 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const override; private: - Status ImportKeyRaw(const CryptoData& key_data, + Status ImportKeyRaw(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, blink::WebCryptoKey* key) const; - Status ImportKeyPkcs8(const CryptoData& key_data, + Status ImportKeyPkcs8(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, blink::WebCryptoKey* key) const; - Status ImportKeySpki(const CryptoData& key_data, + Status ImportKeySpki(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, blink::WebCryptoKey* key) const; - Status ImportKeyJwk(const CryptoData& key_data, + Status ImportKeyJwk(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages,
diff --git a/components/webcrypto/algorithms/ecdh.cc b/components/webcrypto/algorithms/ecdh.cc index 208472f..ec6cc74 100644 --- a/components/webcrypto/algorithms/ecdh.cc +++ b/components/webcrypto/algorithms/ecdh.cc
@@ -7,11 +7,11 @@ #include <memory> +#include "base/containers/span.h" #include "components/webcrypto/algorithm_implementation.h" #include "components/webcrypto/algorithms/ec.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h"
diff --git a/components/webcrypto/algorithms/ecdh_unittest.cc b/components/webcrypto/algorithms/ecdh_unittest.cc index d9cd676e..f281acc 100644 --- a/components/webcrypto/algorithms/ecdh_unittest.cc +++ b/components/webcrypto/algorithms/ecdh_unittest.cc
@@ -8,7 +8,6 @@ #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/ec.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -48,10 +47,10 @@ EXPECT_TRUE(test->GetDictionary("public_key", &public_key_json)); blink::WebCryptoNamedCurve curve = GetCurveNameFromDictionary(public_key_json); - EXPECT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, - CryptoData(MakeJsonVector(*public_key_json)), - CreateEcdhImportAlgorithm(curve), true, 0, public_key)); + EXPECT_EQ( + Status::Success(), + ImportKey(blink::kWebCryptoKeyFormatJwk, MakeJsonVector(*public_key_json), + CreateEcdhImportAlgorithm(curve), true, 0, public_key)); // If the test didn't specify an error for private key import, that implies // it expects success. @@ -63,8 +62,7 @@ EXPECT_TRUE(test->GetDictionary("private_key", &private_key_json)); curve = GetCurveNameFromDictionary(private_key_json); Status status = ImportKey( - blink::kWebCryptoKeyFormatJwk, - CryptoData(MakeJsonVector(*private_key_json)), + blink::kWebCryptoKeyFormatJwk, MakeJsonVector(*private_key_json), CreateEcdhImportAlgorithm(curve), true, blink::kWebCryptoKeyUsageDeriveBits | blink::kWebCryptoKeyUsageDeriveKey, private_key); @@ -108,7 +106,7 @@ std::vector<uint8_t> expected_bytes = GetBytesFromHexString(test, "derived_bytes"); - EXPECT_EQ(CryptoData(expected_bytes), CryptoData(derived_bytes)); + EXPECT_EQ(expected_bytes, derived_bytes); } } @@ -313,10 +311,10 @@ EXPECT_TRUE(test->GetDictionary("public_key", &public_key_json)); blink::WebCryptoNamedCurve curve = GetCurveNameFromDictionary(public_key_json); - ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, - CryptoData(MakeJsonVector(*public_key_json)), - CreateEcdhImportAlgorithm(curve), true, 0, &key)); + ASSERT_EQ( + Status::Success(), + ImportKey(blink::kWebCryptoKeyFormatJwk, MakeJsonVector(*public_key_json), + CreateEcdhImportAlgorithm(curve), true, 0, &key)); EXPECT_EQ(0, key.Usages()); // Import the private key. @@ -325,7 +323,7 @@ curve = GetCurveNameFromDictionary(private_key_json); ASSERT_EQ(Status::ErrorCreateKeyEmptyUsages(), ImportKey(blink::kWebCryptoKeyFormatJwk, - CryptoData(MakeJsonVector(*private_key_json)), + MakeJsonVector(*private_key_json), CreateEcdhImportAlgorithm(curve), true, 0, &key)); }
diff --git a/components/webcrypto/algorithms/ecdsa.cc b/components/webcrypto/algorithms/ecdsa.cc index 00a83c3..5a7ecd99c 100644 --- a/components/webcrypto/algorithms/ecdsa.cc +++ b/components/webcrypto/algorithms/ecdsa.cc
@@ -7,11 +7,11 @@ #include <memory> +#include "base/containers/span.h" #include "components/webcrypto/algorithm_implementation.h" #include "components/webcrypto/algorithms/ec.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" @@ -109,7 +109,7 @@ // ECDSA-Sig-Value. Status ConvertWebCryptoSignatureToDerSignature( EVP_PKEY* key, - const CryptoData& signature, + base::span<const uint8_t> signature, std::vector<uint8_t>* der_signature, bool* incorrect_length) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); @@ -124,10 +124,12 @@ // is returned here rather than an error, so that the caller can fail // verification with a boolean, rather than reject the promise with an // exception. - if (signature.byte_length() != 2 * order_size_bytes) { + if (signature.size() != 2 * order_size_bytes) { *incorrect_length = true; return Status::Success(); } + base::span<const uint8_t> r_bytes = signature.first(order_size_bytes); + base::span<const uint8_t> s_bytes = signature.subspan(order_size_bytes); *incorrect_length = false; @@ -136,9 +138,8 @@ if (!ecdsa_sig) return Status::OperationError(); - if (!BN_bin2bn(signature.bytes(), order_size_bytes, ecdsa_sig->r) || - !BN_bin2bn(signature.bytes() + order_size_bytes, order_size_bytes, - ecdsa_sig->s)) { + if (!BN_bin2bn(r_bytes.data(), r_bytes.size(), ecdsa_sig->r) || + !BN_bin2bn(s_bytes.data(), s_bytes.size(), ecdsa_sig->s)) { return Status::ErrorUnexpected(); } @@ -176,7 +177,7 @@ Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { if (key.GetType() != blink::kWebCryptoKeyTypePrivate) return Status::ErrorUnexpectedKeyType(); @@ -195,7 +196,7 @@ bssl::ScopedEVP_MD_CTX ctx; size_t sig_len = 0; if (!EVP_DigestSignInit(ctx.get(), nullptr, digest, nullptr, private_key) || - !EVP_DigestSignUpdate(ctx.get(), data.bytes(), data.byte_length()) || + !EVP_DigestSignUpdate(ctx.get(), data.data(), data.size()) || !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) { return Status::OperationError(); } @@ -213,8 +214,8 @@ Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) const override { if (key.GetType() != blink::kWebCryptoKeyTypePublic) return Status::ErrorUnexpectedKeyType(); @@ -242,7 +243,7 @@ bssl::ScopedEVP_MD_CTX ctx; if (!EVP_DigestVerifyInit(ctx.get(), nullptr, digest, nullptr, public_key) || - !EVP_DigestVerifyUpdate(ctx.get(), data.bytes(), data.byte_length())) { + !EVP_DigestVerifyUpdate(ctx.get(), data.data(), data.size())) { return Status::OperationError(); }
diff --git a/components/webcrypto/algorithms/ecdsa_unittest.cc b/components/webcrypto/algorithms/ecdsa_unittest.cc index 3503a9a..5390ab4 100644 --- a/components/webcrypto/algorithms/ecdsa_unittest.cc +++ b/components/webcrypto/algorithms/ecdsa_unittest.cc
@@ -5,9 +5,9 @@ #include <stddef.h> #include <stdint.h> +#include "base/containers/span.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -133,22 +133,20 @@ std::vector<uint8_t> signature1; std::vector<uint8_t> signature2; ASSERT_EQ(Status::Success(), - Sign(algorithm, private_key, CryptoData(message), &signature1)); + Sign(algorithm, private_key, message, &signature1)); ASSERT_EQ(Status::Success(), - Sign(algorithm, private_key, CryptoData(message), &signature2)); + Sign(algorithm, private_key, message, &signature2)); // The two signatures should be different. - EXPECT_NE(CryptoData(signature1), CryptoData(signature2)); + EXPECT_NE(signature1, signature2); // And both should be valid signatures which can be verified. bool signature_matches; - ASSERT_EQ(Status::Success(), - Verify(algorithm, public_key, CryptoData(signature1), - CryptoData(message), &signature_matches)); + ASSERT_EQ(Status::Success(), Verify(algorithm, public_key, signature1, + message, &signature_matches)); EXPECT_TRUE(signature_matches); - ASSERT_EQ(Status::Success(), - Verify(algorithm, public_key, CryptoData(signature2), - CryptoData(message), &signature_matches)); + ASSERT_EQ(Status::Success(), Verify(algorithm, public_key, signature2, + message, &signature_matches)); EXPECT_TRUE(signature_matches); } @@ -174,9 +172,9 @@ // Import the public key. blink::WebCryptoKey key; - Status status = ImportKey(key_format, CryptoData(key_data), - CreateEcdsaImportAlgorithm(curve), true, - blink::kWebCryptoKeyUsageVerify, &key); + Status status = + ImportKey(key_format, key_data, CreateEcdsaImportAlgorithm(curve), true, + blink::kWebCryptoKeyUsageVerify, &key); ASSERT_EQ(expected_error, StatusToString(status)); if (status.IsError()) continue; @@ -192,8 +190,8 @@ blink::WebCryptoAlgorithm hash = GetDigestAlgorithm(test, "hash"); bool verify_result; - status = Verify(CreateEcdsaAlgorithm(hash.Id()), key, CryptoData(signature), - CryptoData(message), &verify_result); + status = Verify(CreateEcdsaAlgorithm(hash.Id()), key, signature, message, + &verify_result); ASSERT_EQ(expected_error, StatusToString(status)); if (status.IsError()) continue; @@ -252,9 +250,9 @@ ASSERT_TRUE(test->GetString("error", &expected_error)); blink::WebCryptoKey key; - Status status = ImportKey( - key_format, CryptoData(key_data), CreateEcdsaImportAlgorithm(curve), - true, GetExpectedUsagesForKeyImport(key_format, test), &key); + Status status = + ImportKey(key_format, key_data, CreateEcdsaImportAlgorithm(curve), true, + GetExpectedUsagesForKeyImport(key_format, test), &key); ASSERT_EQ(expected_error, StatusToString(status)); } } @@ -287,7 +285,7 @@ // Import the key using JWK blink::WebCryptoKey key; ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(jwk_bytes), + ImportKey(blink::kWebCryptoKeyFormatJwk, jwk_bytes, CreateEcdsaImportAlgorithm(curve), true, blink::kWebCryptoKeyUsageSign, &key)); @@ -304,19 +302,19 @@ // expectation. jwk_bytes = exported_bytes; ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(jwk_bytes), + ImportKey(blink::kWebCryptoKeyFormatJwk, jwk_bytes, CreateEcdsaImportAlgorithm(curve), true, blink::kWebCryptoKeyUsageSign, &key)); // Export the key as JWK (again) ASSERT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatJwk, key, &exported_bytes)); - EXPECT_EQ(CryptoData(jwk_bytes), CryptoData(exported_bytes)); + EXPECT_EQ(jwk_bytes, exported_bytes); // Export the key as PKCS8 ASSERT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatPkcs8, key, &exported_bytes)); - EXPECT_EQ(CryptoData(pkcs8_bytes), CryptoData(exported_bytes)); + EXPECT_EQ(pkcs8_bytes, exported_bytes); // ------------------------------------------------- // Test from PKCS8, and then export to {JWK, PKCS8} @@ -327,8 +325,8 @@ // during export). std::vector<uint8_t> pkcs8_input_bytes = GetBytesFromHexString( test, test->FindKey("original_pkcs8") ? "original_pkcs8" : "pkcs8"); - CryptoData pkcs8_input_data(pkcs8_input_bytes.empty() ? pkcs8_bytes - : pkcs8_input_bytes); + base::span<const uint8_t> pkcs8_input_data( + pkcs8_input_bytes.empty() ? pkcs8_bytes : pkcs8_input_bytes); // Import the key using PKCS8 ASSERT_EQ(Status::Success(), @@ -339,12 +337,12 @@ // Export the key as PKCS8 ASSERT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatPkcs8, key, &exported_bytes)); - EXPECT_EQ(CryptoData(pkcs8_bytes), CryptoData(exported_bytes)); + EXPECT_EQ(pkcs8_bytes, exported_bytes); // Export the key as JWK ASSERT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatJwk, key, &exported_bytes)); - EXPECT_EQ(CryptoData(jwk_bytes), CryptoData(exported_bytes)); + EXPECT_EQ(jwk_bytes, exported_bytes); } }
diff --git a/components/webcrypto/algorithms/ed25519.cc b/components/webcrypto/algorithms/ed25519.cc index 153b853..9b88fed 100644 --- a/components/webcrypto/algorithms/ed25519.cc +++ b/components/webcrypto/algorithms/ed25519.cc
@@ -19,7 +19,7 @@ public: Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { // TODO(crbug.com/1032821): Implement this. return Status::ErrorUnsupported(); @@ -27,8 +27,8 @@ Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) const override { // TODO(crbug.com/1032821): Implement this. return Status::ErrorUnsupported();
diff --git a/components/webcrypto/algorithms/hkdf.cc b/components/webcrypto/algorithms/hkdf.cc index e7fa63c..179ad392 100644 --- a/components/webcrypto/algorithms/hkdf.cc +++ b/components/webcrypto/algorithms/hkdf.cc
@@ -10,7 +10,6 @@ #include "components/webcrypto/algorithms/secret_key_util.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -30,7 +29,7 @@ HkdfImplementation() {} Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -43,7 +42,7 @@ } } - Status ImportKeyRaw(const CryptoData& key_data, + Status ImportKeyRaw(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -106,7 +105,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const override { if (algorithm.ParamsType() != blink::kWebCryptoKeyAlgorithmParamsTypeNone || type != blink::kWebCryptoKeyTypeSecret)
diff --git a/components/webcrypto/algorithms/hmac.cc b/components/webcrypto/algorithms/hmac.cc index 0049cdc..1d9d9c0 100644 --- a/components/webcrypto/algorithms/hmac.cc +++ b/components/webcrypto/algorithms/hmac.cc
@@ -13,7 +13,6 @@ #include "components/webcrypto/algorithms/secret_key_util.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" @@ -87,7 +86,7 @@ Status SignHmac(const std::vector<uint8_t>& raw_key, const blink::WebCryptoAlgorithm& hash, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); @@ -99,8 +98,8 @@ buffer->resize(hmac_expected_length); unsigned int hmac_actual_length; - if (!HMAC(digest_algorithm, raw_key.data(), raw_key.size(), data.bytes(), - data.byte_length(), buffer->data(), &hmac_actual_length)) { + if (!HMAC(digest_algorithm, raw_key.data(), raw_key.size(), data.data(), + data.size(), buffer->data(), &hmac_actual_length)) { return Status::OperationError(); } @@ -144,7 +143,7 @@ } Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -172,7 +171,7 @@ } } - Status ImportKeyRaw(const CryptoData& key_data, + Status ImportKeyRaw(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -185,8 +184,7 @@ algorithm.HmacImportParams(); unsigned int keylen_bits = 0; - status = GetHmacImportKeyLengthBits(params, key_data.byte_length(), - &keylen_bits); + status = GetHmacImportKeyLengthBits(params, key_data.size(), &keylen_bits); if (status.IsError()) return status; @@ -201,14 +199,14 @@ } // Otherwise zero out the unused bits in the key data before importing. - std::vector<uint8_t> modified_key_data( - key_data.bytes(), key_data.bytes() + key_data.byte_length()); + std::vector<uint8_t> modified_key_data(key_data.data(), + key_data.data() + key_data.size()); TruncateToBitLength(keylen_bits, &modified_key_data); - return CreateWebCryptoSecretKey(CryptoData(modified_key_data), - key_algorithm, extractable, usages, key); + return CreateWebCryptoSecretKey(modified_key_data, key_algorithm, + extractable, usages, key); } - Status ImportKeyJwk(const CryptoData& key_data, + Status ImportKeyJwk(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -232,8 +230,7 @@ if (status.IsError()) return status; - return ImportKeyRaw(CryptoData(raw_data), algorithm, extractable, usages, - key); + return ImportKeyRaw(raw_data, algorithm, extractable, usages, key); } Status ExportKeyRaw(const blink::WebCryptoKey& key, @@ -251,15 +248,15 @@ if (!algorithm_name) return Status::ErrorUnexpected(); - WriteSecretKeyJwk(CryptoData(raw_data), algorithm_name, key.Extractable(), - key.Usages(), buffer); + WriteSecretKeyJwk(raw_data, algorithm_name, key.Extractable(), key.Usages(), + buffer); return Status::Success(); } Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { const blink::WebCryptoAlgorithm& hash = key.Algorithm().HmacParams()->GetHash(); @@ -269,8 +266,8 @@ Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) const override { std::vector<uint8_t> result; Status status = Sign(algorithm, key, data, &result); @@ -279,9 +276,9 @@ return status; // Do not allow verification of truncated MACs. - *signature_match = result.size() == signature.byte_length() && - crypto::SecureMemEqual(result.data(), signature.bytes(), - signature.byte_length()); + *signature_match = result.size() == signature.size() && + crypto::SecureMemEqual(result.data(), signature.data(), + signature.size()); return Status::Success(); } @@ -290,7 +287,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const override { if (algorithm.ParamsType() != blink::kWebCryptoKeyAlgorithmParamsTypeHmac || type != blink::kWebCryptoKeyTypeSecret)
diff --git a/components/webcrypto/algorithms/hmac_unittest.cc b/components/webcrypto/algorithms/hmac_unittest.cc index 02eeae5..604ee91 100644 --- a/components/webcrypto/algorithms/hmac_unittest.cc +++ b/components/webcrypto/algorithms/hmac_unittest.cc
@@ -12,10 +12,10 @@ #include "base/check.h" #include "base/containers/contains.h" #include "base/containers/flat_set.h" +#include "base/containers/span.h" #include "base/values.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -154,7 +154,7 @@ const std::vector<uint8_t>& message) { std::vector<uint8_t> output; auto status = Sign(CreateAlgorithm(blink::kWebCryptoAlgorithmIdHmac), key, - CryptoData(message), &output); + message, &output); CHECK(status == Status::Success()); return output; } @@ -164,7 +164,7 @@ const std::vector<uint8_t>& hmac) { bool match = false; auto status = Verify(CreateAlgorithm(blink::kWebCryptoAlgorithmIdHmac), key, - CryptoData(hmac), CryptoData(message), &match); + hmac, message, &match); CHECK(status == Status::Success()); return match; } @@ -248,12 +248,12 @@ TEST_F(WebCryptoHmacTest, ImportKeyEmptyUsage) { blink::WebCryptoKey key; std::string key_raw_hex_in = "025a8cf3f08b4f6c5f33bbc76a471939"; - EXPECT_EQ(Status::ErrorCreateKeyEmptyUsages(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(HexStringToBytes(key_raw_hex_in)), - CreateHmacImportAlgorithmNoLength( - blink::kWebCryptoAlgorithmIdSha1), - true, 0, &key)); + EXPECT_EQ( + Status::ErrorCreateKeyEmptyUsages(), + ImportKey( + blink::kWebCryptoKeyFormatRaw, HexStringToBytes(key_raw_hex_in), + CreateHmacImportAlgorithmNoLength(blink::kWebCryptoAlgorithmIdSha1), + true, 0, &key)); } TEST_F(WebCryptoHmacTest, ImportKeyJwkKeyOpsSignVerify) { @@ -345,8 +345,8 @@ dict.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg"); std::vector<uint8_t> json_vec = MakeJsonVector(dict); EXPECT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json_vec), - algorithm, extractable, usages, &key)); + ImportKey(blink::kWebCryptoKeyFormatJwk, json_vec, algorithm, + extractable, usages, &key)); EXPECT_TRUE(key.Handle()); EXPECT_EQ(blink::kWebCryptoKeyTypeSecret, key.GetType()); EXPECT_EQ(extractable, key.Extractable()); @@ -368,8 +368,8 @@ dict.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg"); json_vec = MakeJsonVector(dict); EXPECT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json_vec), - algorithm, extractable, usages, &key)); + ImportKey(blink::kWebCryptoKeyFormatJwk, json_vec, algorithm, + extractable, usages, &key)); // Extractable cases: // 1. input=T, JWK=F ==> fail (inconsistent) @@ -377,11 +377,11 @@ // 2. input=T, JWK=T ==> pass, result extractable is T // 3. input=F, JWK=T ==> pass, result extractable is F EXPECT_EQ(Status::ErrorJwkExtInconsistent(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json_vec), - algorithm, true, usages, &key)); + ImportKey(blink::kWebCryptoKeyFormatJwk, json_vec, algorithm, true, + usages, &key)); EXPECT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json_vec), - algorithm, false, usages, &key)); + ImportKey(blink::kWebCryptoKeyFormatJwk, json_vec, algorithm, false, + usages, &key)); EXPECT_FALSE(key.Extractable()); dict.SetBoolean("ext", true); EXPECT_EQ(Status::Success(), @@ -404,14 +404,14 @@ extractable, blink::kWebCryptoKeyUsageEncrypt, &key)); // Fail: Input usage (encrypt) is inconsistent with JWK value (use=sig). EXPECT_EQ(Status::ErrorJwkUseInconsistent(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json_vec), + ImportKey(blink::kWebCryptoKeyFormatJwk, json_vec, CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), extractable, blink::kWebCryptoKeyUsageEncrypt, &key)); // Fail: Input algorithm (HMAC SHA1) is inconsistent with JWK value // (HMAC SHA256). EXPECT_EQ(Status::ErrorJwkAlgorithmInconsistent(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json_vec), + ImportKey(blink::kWebCryptoKeyFormatJwk, json_vec, CreateHmacImportAlgorithmNoLength( blink::kWebCryptoAlgorithmIdSha1), extractable, usages, &key)); @@ -428,18 +428,17 @@ // Fail: Input usages (encrypt) is not a subset of the JWK value // (sign|verify). Moreover "encrypt" is not a valid usage for HMAC. - EXPECT_EQ( - Status::ErrorCreateKeyBadUsages(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json_vec), algorithm, - extractable, blink::kWebCryptoKeyUsageEncrypt, &key)); + EXPECT_EQ(Status::ErrorCreateKeyBadUsages(), + ImportKey(blink::kWebCryptoKeyFormatJwk, json_vec, algorithm, + extractable, blink::kWebCryptoKeyUsageEncrypt, &key)); // Fail: Input usages (encrypt|sign|verify) is not a subset of the JWK // value (sign|verify). Moreover "encrypt" is not a valid usage for HMAC. usages = blink::kWebCryptoKeyUsageEncrypt | blink::kWebCryptoKeyUsageSign | blink::kWebCryptoKeyUsageVerify; EXPECT_EQ(Status::ErrorCreateKeyBadUsages(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json_vec), - algorithm, extractable, usages, &key)); + ImportKey(blink::kWebCryptoKeyFormatJwk, json_vec, algorithm, + extractable, usages, &key)); // TODO(padolph): kty vs alg consistency tests: Depending on the kty value, // only certain alg values are permitted. For example, when kty = "RSA" alg @@ -485,7 +484,7 @@ ASSERT_EQ(Status::Success(), Sign(CreateAlgorithm(blink::kWebCryptoAlgorithmIdHmac), key, - CryptoData(message_raw), &output)); + message_raw, &output)); const std::string mac_raw = "769f00d3e6a6cc1fb426a14a4f76c6462e6149726e0dee0ec0cf97a16605ac8b"; @@ -523,7 +522,7 @@ ASSERT_TRUE(DeserializeKeyForClone(blink::WebCryptoKeyAlgorithm::CreateHmac( blink::kWebCryptoAlgorithmIdSha1, 0), blink::kWebCryptoKeyTypeSecret, true, - usages, CryptoData(), &key)); + usages, {}, &key)); // Export the key in JWK format and validate. std::vector<uint8_t> json; @@ -534,7 +533,7 @@ // Now try re-importing the JWK key. key = blink::WebCryptoKey::CreateNull(); EXPECT_EQ(Status::ErrorHmacImportEmptyKey(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json), + ImportKey(blink::kWebCryptoKeyFormatJwk, json, CreateHmacImportAlgorithmNoLength( blink::kWebCryptoAlgorithmIdSha1), true, usages, &key)); @@ -549,8 +548,8 @@ blink::WebCryptoKey key; ASSERT_EQ(Status::ErrorHmacImportEmptyKey(), - ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(), - import_algorithm, true, usages, &key)); + ImportKey(blink::kWebCryptoKeyFormatRaw, {}, import_algorithm, true, + usages, &key)); } // Imports an HMAC key contaning 1 byte data, however the length was set to 0. @@ -563,18 +562,20 @@ std::vector<uint8_t> key_data(1); ASSERT_EQ(Status::ErrorHmacImportBadLength(), - ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(key_data), - import_algorithm, true, usages, &key)); + ImportKey(blink::kWebCryptoKeyFormatRaw, key_data, import_algorithm, + true, usages, &key)); } -// Import a huge hmac key (UINT_MAX bytes). This will fail before actually -// reading the bytes, as the key is too large. +// Import a huge hmac key (UINT_MAX bytes). TEST_F(WebCryptoHmacTest, ImportRawKeyTooLarge) { - CryptoData big_data(nullptr, UINT_MAX); // Invalid data of big length. + // Invalid data of big length. This span is invalid, but ImportKey should fail + // before actually reading the bytes, as the key is too large. + base::span<const uint8_t> big_data(static_cast<const uint8_t*>(nullptr), + UINT_MAX); blink::WebCryptoKey key; EXPECT_EQ(Status::ErrorDataTooLarge(), - ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(big_data), + ImportKey(blink::kWebCryptoKeyFormatRaw, big_data, CreateHmacImportAlgorithmNoLength( blink::kWebCryptoAlgorithmIdSha1), true, blink::kWebCryptoKeyUsageSign, &key)); @@ -584,8 +585,7 @@ TEST_F(WebCryptoHmacTest, ImportRawKeyLengthTooLarge) { blink::WebCryptoKey key; EXPECT_EQ(Status::ErrorHmacImportBadLength(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(std::vector<uint8_t>(15)), + ImportKey(blink::kWebCryptoKeyFormatRaw, std::vector<uint8_t>(15), CreateHmacImportAlgorithmWithLength( blink::kWebCryptoAlgorithmIdSha1, 128), true, blink::kWebCryptoKeyUsageSign, &key)); @@ -595,8 +595,7 @@ TEST_F(WebCryptoHmacTest, ImportRawKeyLengthTooSmall) { blink::WebCryptoKey key; EXPECT_EQ(Status::ErrorHmacImportBadLength(), - ImportKey(blink::kWebCryptoKeyFormatRaw, - CryptoData(std::vector<uint8_t>(16)), + ImportKey(blink::kWebCryptoKeyFormatRaw, std::vector<uint8_t>(16), CreateHmacImportAlgorithmWithLength( blink::kWebCryptoAlgorithmIdSha1, 120), true, blink::kWebCryptoKeyUsageSign, &key)); @@ -609,7 +608,7 @@ blink::WebCryptoKey key; EXPECT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(data), + ImportKey(blink::kWebCryptoKeyFormatRaw, data, CreateHmacImportAlgorithmWithLength( blink::kWebCryptoAlgorithmIdSha1, 12), true, blink::kWebCryptoKeyUsageSign, &key));
diff --git a/components/webcrypto/algorithms/pbkdf2.cc b/components/webcrypto/algorithms/pbkdf2.cc index fc8a64cf..2e05d59 100644 --- a/components/webcrypto/algorithms/pbkdf2.cc +++ b/components/webcrypto/algorithms/pbkdf2.cc
@@ -6,11 +6,11 @@ #include <memory> +#include "base/containers/span.h" #include "components/webcrypto/algorithm_implementation.h" #include "components/webcrypto/algorithms/secret_key_util.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -29,7 +29,7 @@ Pbkdf2Implementation() {} Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -42,7 +42,7 @@ } } - Status ImportKeyRaw(const CryptoData& key_data, + Status ImportKeyRaw(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -108,7 +108,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const override { if (algorithm.ParamsType() != blink::kWebCryptoKeyAlgorithmParamsTypeNone || type != blink::kWebCryptoKeyTypeSecret)
diff --git a/components/webcrypto/algorithms/rsa.cc b/components/webcrypto/algorithms/rsa.cc index 250138e..e12e133 100644 --- a/components/webcrypto/algorithms/rsa.cc +++ b/components/webcrypto/algorithms/rsa.cc
@@ -7,10 +7,10 @@ #include <utility> #include "base/check_op.h" +#include "base/containers/span.h" #include "components/webcrypto/algorithms/asymmetric_key_util.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" @@ -31,14 +31,14 @@ // for "oth". struct JwkRsaInfo { bool is_private_key = false; - std::string n; - std::string e; - std::string d; - std::string p; - std::string q; - std::string dp; - std::string dq; - std::string qi; + std::vector<uint8_t> n; + std::vector<uint8_t> e; + std::vector<uint8_t> d; + std::vector<uint8_t> p; + std::vector<uint8_t> q; + std::vector<uint8_t> dp; + std::vector<uint8_t> dq; + std::vector<uint8_t> qi; }; // Parses a UTF-8 encoded JWK (key_data), and extracts the RSA components to @@ -48,7 +48,7 @@ // * expected_extractable must be consistent with the JWK's "ext", if // present. // * expected_usages must be a subset of the JWK's "key_ops" if present. -Status ReadRsaKeyJwk(const CryptoData& key_data, +Status ReadRsaKeyJwk(base::span<const uint8_t> key_data, const std::string& expected_alg, bool expected_extractable, blink::WebCryptoKeyUsageMask expected_usages, @@ -177,14 +177,14 @@ blink::WebCryptoKey* key) { bssl::UniquePtr<RSA> rsa(RSA_new()); - rsa->n = CreateBIGNUM(params.n); - rsa->e = CreateBIGNUM(params.e); - rsa->d = CreateBIGNUM(params.d); - rsa->p = CreateBIGNUM(params.p); - rsa->q = CreateBIGNUM(params.q); - rsa->dmp1 = CreateBIGNUM(params.dp); - rsa->dmq1 = CreateBIGNUM(params.dq); - rsa->iqmp = CreateBIGNUM(params.qi); + rsa->n = BN_bin2bn(params.n.data(), params.n.size(), nullptr); + rsa->e = BN_bin2bn(params.e.data(), params.e.size(), nullptr); + rsa->d = BN_bin2bn(params.d.data(), params.d.size(), nullptr); + rsa->p = BN_bin2bn(params.p.data(), params.p.size(), nullptr); + rsa->q = BN_bin2bn(params.q.data(), params.q.size(), nullptr); + rsa->dmp1 = BN_bin2bn(params.dp.data(), params.dp.size(), nullptr); + rsa->dmq1 = BN_bin2bn(params.dq.data(), params.dq.size(), nullptr); + rsa->iqmp = BN_bin2bn(params.qi.data(), params.qi.size(), nullptr); if (!rsa->n || !rsa->e || !rsa->d || !rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) { @@ -208,13 +208,13 @@ Status ImportRsaPublicKey(const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& n, - const CryptoData& e, + base::span<const uint8_t> n, + base::span<const uint8_t> e, blink::WebCryptoKey* key) { bssl::UniquePtr<RSA> rsa(RSA_new()); - rsa->n = BN_bin2bn(n.bytes(), n.byte_length(), nullptr); - rsa->e = BN_bin2bn(e.bytes(), e.byte_length(), nullptr); + rsa->n = BN_bin2bn(n.data(), n.size(), nullptr); + rsa->e = BN_bin2bn(e.data(), e.size(), nullptr); if (!rsa->n || !rsa->e) return Status::OperationError(); @@ -338,7 +338,7 @@ } Status RsaHashedAlgorithm::ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -371,7 +371,7 @@ } Status RsaHashedAlgorithm::ImportKeyPkcs8( - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -401,7 +401,7 @@ } Status RsaHashedAlgorithm::ImportKeySpki( - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -424,7 +424,7 @@ } Status RsaHashedAlgorithm::ImportKeyJwk( - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -455,8 +455,8 @@ return jwk.is_private_key ? ImportRsaPrivateKey(algorithm, extractable, usages, jwk, key) - : ImportRsaPublicKey(algorithm, extractable, usages, - CryptoData(jwk.n), CryptoData(jwk.e), key); + : ImportRsaPublicKey(algorithm, extractable, usages, jwk.n, jwk.e, + key); } Status RsaHashedAlgorithm::ExportKeyPkcs8(const blink::WebCryptoKey& key, @@ -498,23 +498,23 @@ switch (key.GetType()) { case blink::kWebCryptoKeyTypePublic: { JwkWriter writer(jwk_algorithm, key.Extractable(), key.Usages(), "RSA"); - writer.SetBytes("n", CryptoData(BIGNUMToVector(rsa->n))); - writer.SetBytes("e", CryptoData(BIGNUMToVector(rsa->e))); + writer.SetBytes("n", BIGNUMToVector(RSA_get0_n(rsa))); + writer.SetBytes("e", BIGNUMToVector(RSA_get0_e(rsa))); writer.ToJson(buffer); return Status::Success(); } case blink::kWebCryptoKeyTypePrivate: { JwkWriter writer(jwk_algorithm, key.Extractable(), key.Usages(), "RSA"); - writer.SetBytes("n", CryptoData(BIGNUMToVector(rsa->n))); - writer.SetBytes("e", CryptoData(BIGNUMToVector(rsa->e))); - writer.SetBytes("d", CryptoData(BIGNUMToVector(rsa->d))); + writer.SetBytes("n", BIGNUMToVector(RSA_get0_n(rsa))); + writer.SetBytes("e", BIGNUMToVector(RSA_get0_e(rsa))); + writer.SetBytes("d", BIGNUMToVector(RSA_get0_d(rsa))); // Although these are "optional" in the JWA, WebCrypto spec requires them // to be emitted. - writer.SetBytes("p", CryptoData(BIGNUMToVector(rsa->p))); - writer.SetBytes("q", CryptoData(BIGNUMToVector(rsa->q))); - writer.SetBytes("dp", CryptoData(BIGNUMToVector(rsa->dmp1))); - writer.SetBytes("dq", CryptoData(BIGNUMToVector(rsa->dmq1))); - writer.SetBytes("qi", CryptoData(BIGNUMToVector(rsa->iqmp))); + writer.SetBytes("p", BIGNUMToVector(RSA_get0_p(rsa))); + writer.SetBytes("q", BIGNUMToVector(RSA_get0_q(rsa))); + writer.SetBytes("dp", BIGNUMToVector(RSA_get0_dmp1(rsa))); + writer.SetBytes("dq", BIGNUMToVector(RSA_get0_dmq1(rsa))); + writer.SetBytes("qi", BIGNUMToVector(RSA_get0_iqmp(rsa))); writer.ToJson(buffer); return Status::Success(); } @@ -530,7 +530,7 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const { if (algorithm.ParamsType() != blink::kWebCryptoKeyAlgorithmParamsTypeRsaHashed)
diff --git a/components/webcrypto/algorithms/rsa.h b/components/webcrypto/algorithms/rsa.h index c66eff21..c9872b2 100644 --- a/components/webcrypto/algorithms/rsa.h +++ b/components/webcrypto/algorithms/rsa.h
@@ -41,7 +41,7 @@ GenerateKeyResult* result) const override; Status ImportKey(blink::WebCryptoKeyFormat format, - const CryptoData& key_data, + base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -55,23 +55,23 @@ blink::WebCryptoKeyType type, bool extractable, blink::WebCryptoKeyUsageMask usages, - const CryptoData& key_data, + base::span<const uint8_t> key_data, blink::WebCryptoKey* key) const override; private: - Status ImportKeyPkcs8(const CryptoData& key_data, + Status ImportKeyPkcs8(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, blink::WebCryptoKey* key) const; - Status ImportKeySpki(const CryptoData& key_data, + Status ImportKeySpki(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, blink::WebCryptoKey* key) const; - Status ImportKeyJwk(const CryptoData& key_data, + Status ImportKeyJwk(base::span<const uint8_t> key_data, const blink::WebCryptoAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages,
diff --git a/components/webcrypto/algorithms/rsa_oaep.cc b/components/webcrypto/algorithms/rsa_oaep.cc index ddf01ce5..c9b5996a 100644 --- a/components/webcrypto/algorithms/rsa_oaep.cc +++ b/components/webcrypto/algorithms/rsa_oaep.cc
@@ -8,10 +8,10 @@ #include <memory> +#include "base/containers/span.h" #include "components/webcrypto/algorithms/rsa.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -42,7 +42,7 @@ EncryptDecryptFunc encrypt_decrypt_func, const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); @@ -79,15 +79,15 @@ // Determine the maximum length of the output. size_t outlen = 0; - if (!encrypt_decrypt_func(ctx.get(), nullptr, &outlen, data.bytes(), - data.byte_length())) { + if (!encrypt_decrypt_func(ctx.get(), nullptr, &outlen, data.data(), + data.size())) { return Status::OperationError(); } buffer->resize(outlen); // Do the actual encryption/decryption. - if (!encrypt_decrypt_func(ctx.get(), buffer->data(), &outlen, data.bytes(), - data.byte_length())) { + if (!encrypt_decrypt_func(ctx.get(), buffer->data(), &outlen, data.data(), + data.size())) { return Status::OperationError(); } buffer->resize(outlen); @@ -121,7 +121,7 @@ Status Encrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { if (key.GetType() != blink::kWebCryptoKeyTypePublic) return Status::ErrorUnexpectedKeyType(); @@ -132,7 +132,7 @@ Status Decrypt(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { if (key.GetType() != blink::kWebCryptoKeyTypePrivate) return Status::ErrorUnexpectedKeyType();
diff --git a/components/webcrypto/algorithms/rsa_oaep_unittest.cc b/components/webcrypto/algorithms/rsa_oaep_unittest.cc index fb8f718..da232f7 100644 --- a/components/webcrypto/algorithms/rsa_oaep_unittest.cc +++ b/components/webcrypto/algorithms/rsa_oaep_unittest.cc
@@ -6,9 +6,9 @@ #include <stdint.h> #include "base/base64url.h" +#include "base/containers/span.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" #include "testing/gtest/include/gtest/gtest.h" @@ -56,7 +56,7 @@ blink::WebCryptoKey private_key; ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatPkcs8, - CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)), + HexStringToBytes(kPrivateKeyPkcs8DerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaOaep, blink::kWebCryptoAlgorithmIdSha1), @@ -186,17 +186,14 @@ blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label); std::vector<uint8_t> decrypted_data; ASSERT_EQ(Status::Success(), - Decrypt(op_algorithm, private_key, CryptoData(ciphertext), - &decrypted_data)); + Decrypt(op_algorithm, private_key, ciphertext, &decrypted_data)); EXPECT_BYTES_EQ(plaintext, decrypted_data); std::vector<uint8_t> encrypted_data; ASSERT_EQ(Status::Success(), - Encrypt(op_algorithm, public_key, CryptoData(plaintext), - &encrypted_data)); + Encrypt(op_algorithm, public_key, plaintext, &encrypted_data)); std::vector<uint8_t> redecrypted_data; - ASSERT_EQ(Status::Success(), - Decrypt(op_algorithm, private_key, CryptoData(encrypted_data), - &redecrypted_data)); + ASSERT_EQ(Status::Success(), Decrypt(op_algorithm, private_key, + encrypted_data, &redecrypted_data)); EXPECT_BYTES_EQ(plaintext, redecrypted_data); } } @@ -229,27 +226,26 @@ blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label); // Test that a message just before the boundary succeeds. - std::string large_message; + std::vector<uint8_t> large_message; large_message.resize(kMaxMessageSize - 1, 'A'); std::vector<uint8_t> ciphertext; - ASSERT_EQ(Status::Success(), Encrypt(op_algorithm, public_key, - CryptoData(large_message), &ciphertext)); + ASSERT_EQ(Status::Success(), + Encrypt(op_algorithm, public_key, large_message, &ciphertext)); // Test that a message at the boundary succeeds. large_message.resize(kMaxMessageSize, 'A'); ciphertext.clear(); - ASSERT_EQ(Status::Success(), Encrypt(op_algorithm, public_key, - CryptoData(large_message), &ciphertext)); + ASSERT_EQ(Status::Success(), + Encrypt(op_algorithm, public_key, large_message, &ciphertext)); // Test that a message greater than the largest size fails. large_message.resize(kMaxMessageSize + 1, 'A'); ciphertext.clear(); ASSERT_EQ(Status::OperationError(), - Encrypt(op_algorithm, public_key, CryptoData(large_message), - &ciphertext)); + Encrypt(op_algorithm, public_key, large_message, &ciphertext)); } // Ensures that if the selected hash algorithm for the RSA-OAEP message is too @@ -276,20 +272,19 @@ std::vector<uint8_t> label; blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label); - std::string small_message("A"); + std::vector<uint8_t> small_message = {'A'}; std::vector<uint8_t> ciphertext; // This is an operation error, as the internal consistency checking of the // algorithm parameters is up to the implementation. ASSERT_EQ(Status::OperationError(), - Encrypt(op_algorithm, public_key, CryptoData(small_message), - &ciphertext)); + Encrypt(op_algorithm, public_key, small_message, &ciphertext)); } TEST_F(WebCryptoRsaOaepTest, DecryptWithLargeMessageFails) { blink::WebCryptoKey private_key; ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatPkcs8, - CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)), + HexStringToBytes(kPrivateKeyPkcs8DerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaOaep, blink::kWebCryptoAlgorithmIdSha1), @@ -300,12 +295,11 @@ std::vector<uint8_t> label; blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label); - std::string large_dummy_message(kModulusLengthBits / 8, 'A'); + std::vector<uint8_t> large_dummy_message(kModulusLengthBits / 8, 'A'); std::vector<uint8_t> plaintext; - ASSERT_EQ(Status::OperationError(), - Decrypt(op_algorithm, private_key, CryptoData(large_dummy_message), - &plaintext)); + ASSERT_EQ(Status::OperationError(), Decrypt(op_algorithm, private_key, + large_dummy_message, &plaintext)); } TEST_F(WebCryptoRsaOaepTest, WrapUnwrapRawKey) { @@ -341,16 +335,15 @@ // Verify that |wrapped_key| can be decrypted and yields the key data. // Because |private_key| supports both decrypt and unwrap, this is valid. std::vector<uint8_t> decrypted_key; - ASSERT_EQ(Status::Success(), - Decrypt(wrapping_algorithm, private_key, CryptoData(wrapped_key), - &decrypted_key)); + ASSERT_EQ(Status::Success(), Decrypt(wrapping_algorithm, private_key, + wrapped_key, &decrypted_key)); EXPECT_BYTES_EQ_HEX(key_hex, decrypted_key); // Now attempt to unwrap the key, which should also decrypt the data. blink::WebCryptoKey unwrapped_key; ASSERT_EQ(Status::Success(), - UnwrapKey(blink::kWebCryptoKeyFormatRaw, CryptoData(wrapped_key), - private_key, wrapping_algorithm, key_algorithm, true, + UnwrapKey(blink::kWebCryptoKeyFormatRaw, wrapped_key, private_key, + wrapping_algorithm, key_algorithm, true, blink::kWebCryptoKeyUsageEncrypt, &unwrapped_key)); ASSERT_FALSE(unwrapped_key.IsNull()); @@ -440,17 +433,16 @@ // Verify that |wrapped_key| can be decrypted and yields a valid JWK object. // Because |private_key| supports both decrypt and unwrap, this is valid. std::vector<uint8_t> decrypted_jwk; - ASSERT_EQ(Status::Success(), - Decrypt(wrapping_algorithm, private_key, CryptoData(wrapped_key), - &decrypted_jwk)); + ASSERT_EQ(Status::Success(), Decrypt(wrapping_algorithm, private_key, + wrapped_key, &decrypted_jwk)); EXPECT_TRUE(VerifySecretJwk(decrypted_jwk, "A128CBC", key_hex, blink::kWebCryptoKeyUsageEncrypt)); // Now attempt to unwrap the key, which should also decrypt the data. blink::WebCryptoKey unwrapped_key; ASSERT_EQ(Status::Success(), - UnwrapKey(blink::kWebCryptoKeyFormatJwk, CryptoData(wrapped_key), - private_key, wrapping_algorithm, key_algorithm, true, + UnwrapKey(blink::kWebCryptoKeyFormatJwk, wrapped_key, private_key, + wrapping_algorithm, key_algorithm, true, blink::kWebCryptoKeyUsageEncrypt, &unwrapped_key)); ASSERT_FALSE(unwrapped_key.IsNull()); @@ -488,7 +480,7 @@ blink::WebCryptoKey public_key; ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatSpki, - CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)), + HexStringToBytes(kPublicKeySpkiDerHex), import_algorithm, true, test.usage, &public_key)); // Export the public key as JWK and verify its contents @@ -501,8 +493,8 @@ // Import the JWK back in to create a new key blink::WebCryptoKey public_key2; ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(jwk), - import_algorithm, true, test.usage, &public_key2)); + ImportKey(blink::kWebCryptoKeyFormatJwk, jwk, import_algorithm, + true, test.usage, &public_key2)); ASSERT_TRUE(public_key2.Handle()); EXPECT_EQ(blink::kWebCryptoKeyTypePublic, public_key2.GetType()); EXPECT_TRUE(public_key2.Extractable());
diff --git a/components/webcrypto/algorithms/rsa_pss.cc b/components/webcrypto/algorithms/rsa_pss.cc index 1771aea..ae61efa 100644 --- a/components/webcrypto/algorithms/rsa_pss.cc +++ b/components/webcrypto/algorithms/rsa_pss.cc
@@ -39,7 +39,7 @@ Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { return RsaSign(key, algorithm.RsaPssParams()->SaltLengthBytes(), data, buffer); @@ -47,8 +47,8 @@ Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) const override { return RsaVerify(key, algorithm.RsaPssParams()->SaltLengthBytes(), signature, data, signature_match);
diff --git a/components/webcrypto/algorithms/rsa_pss_unittest.cc b/components/webcrypto/algorithms/rsa_pss_unittest.cc index 2c1a744..786a3a8 100644 --- a/components/webcrypto/algorithms/rsa_pss_unittest.cc +++ b/components/webcrypto/algorithms/rsa_pss_unittest.cc
@@ -8,7 +8,6 @@ #include "base/strings/string_number_conversions.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" #include "testing/gtest/include/gtest/gtest.h" @@ -54,31 +53,26 @@ std::vector<uint8_t> signature1; std::vector<uint8_t> signature2; - ASSERT_EQ(Status::Success(), - Sign(params, private_key, CryptoData(message), &signature1)); - ASSERT_EQ(Status::Success(), - Sign(params, private_key, CryptoData(message), &signature2)); + ASSERT_EQ(Status::Success(), Sign(params, private_key, message, &signature1)); + ASSERT_EQ(Status::Success(), Sign(params, private_key, message, &signature2)); // The signatures will be different because of the salt. - EXPECT_NE(CryptoData(signature1), CryptoData(signature2)); + EXPECT_NE(signature1, signature2); // However both signatures should work when verifying. bool is_match = false; ASSERT_EQ(Status::Success(), - Verify(params, public_key, CryptoData(signature1), - CryptoData(message), &is_match)); + Verify(params, public_key, signature1, message, &is_match)); EXPECT_TRUE(is_match); ASSERT_EQ(Status::Success(), - Verify(params, public_key, CryptoData(signature2), - CryptoData(message), &is_match)); + Verify(params, public_key, signature2, message, &is_match)); EXPECT_TRUE(is_match); // Corrupt the signature and verification must fail. - ASSERT_EQ(Status::Success(), - Verify(params, public_key, CryptoData(Corrupted(signature2)), - CryptoData(message), &is_match)); + ASSERT_EQ(Status::Success(), Verify(params, public_key, Corrupted(signature2), + message, &is_match)); EXPECT_FALSE(is_match); } @@ -107,25 +101,21 @@ std::vector<uint8_t> signature1; std::vector<uint8_t> signature2; - ASSERT_EQ(Status::Success(), - Sign(params, private_key, CryptoData(message), &signature1)); - ASSERT_EQ(Status::Success(), - Sign(params, private_key, CryptoData(message), &signature2)); + ASSERT_EQ(Status::Success(), Sign(params, private_key, message, &signature1)); + ASSERT_EQ(Status::Success(), Sign(params, private_key, message, &signature2)); // The signatures will be the same this time. - EXPECT_EQ(CryptoData(signature1), CryptoData(signature2)); + EXPECT_EQ(signature1, signature2); // Make sure that verification works. bool is_match = false; ASSERT_EQ(Status::Success(), - Verify(params, public_key, CryptoData(signature1), - CryptoData(message), &is_match)); + Verify(params, public_key, signature1, message, &is_match)); EXPECT_TRUE(is_match); // Corrupt the signature and verification must fail. - ASSERT_EQ(Status::Success(), - Verify(params, public_key, CryptoData(Corrupted(signature2)), - CryptoData(message), &is_match)); + ASSERT_EQ(Status::Success(), Verify(params, public_key, Corrupted(signature2), + message, &is_match)); EXPECT_FALSE(is_match); } @@ -146,19 +136,17 @@ std::vector<uint8_t> message; // Empty message. std::vector<uint8_t> signature; - ASSERT_EQ(Status::Success(), - Sign(params, private_key, CryptoData(message), &signature)); + ASSERT_EQ(Status::Success(), Sign(params, private_key, message, &signature)); // Make sure that verification works. bool is_match = false; - ASSERT_EQ(Status::Success(), Verify(params, public_key, CryptoData(signature), - CryptoData(message), &is_match)); + ASSERT_EQ(Status::Success(), + Verify(params, public_key, signature, message, &is_match)); EXPECT_TRUE(is_match); // Corrupt the signature and verification must fail. - ASSERT_EQ(Status::Success(), - Verify(params, public_key, CryptoData(Corrupted(signature)), - CryptoData(message), &is_match)); + ASSERT_EQ(Status::Success(), Verify(params, public_key, Corrupted(signature), + message, &is_match)); EXPECT_FALSE(is_match); } @@ -237,7 +225,7 @@ const char* key) { auto pubkey = blink::WebCryptoKey::CreateNull(); webcrypto::Status result = ImportKey( - blink::kWebCryptoKeyFormatSpki, CryptoData(HexStringToBytes(key)), + blink::kWebCryptoKeyFormatSpki, HexStringToBytes(key), CreateRsaHashedImportAlgorithm(blink::kWebCryptoAlgorithmIdRsaPss, hash), true, blink::kWebCryptoKeyUsageVerify, &pubkey); CHECK(result == Status::Success()); @@ -249,8 +237,8 @@ const std::vector<uint8_t>& signature, const std::vector<uint8_t>& message) { bool is_match = false; - auto result = Verify(CreateRsaPssAlgorithm(salt_length), pubkey, - CryptoData(signature), CryptoData(message), &is_match); + auto result = Verify(CreateRsaPssAlgorithm(salt_length), pubkey, signature, + message, &is_match); CHECK(result == Status::Success()); return is_match; }
diff --git a/components/webcrypto/algorithms/rsa_sign.cc b/components/webcrypto/algorithms/rsa_sign.cc index 04fb270..8bd826a4 100644 --- a/components/webcrypto/algorithms/rsa_sign.cc +++ b/components/webcrypto/algorithms/rsa_sign.cc
@@ -8,7 +8,6 @@ #include "components/webcrypto/algorithms/rsa_sign.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/blink/public/platform/web_crypto_key_algorithm.h" @@ -71,7 +70,7 @@ Status RsaSign(const blink::WebCryptoKey& key, unsigned int pss_salt_length_bytes, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) { if (key.GetType() != blink::kWebCryptoKeyTypePrivate) return Status::ErrorUnexpectedKeyType(); @@ -99,7 +98,7 @@ if (status.IsError()) return status; - if (!EVP_DigestSignUpdate(ctx.get(), data.bytes(), data.byte_length()) || + if (!EVP_DigestSignUpdate(ctx.get(), data.data(), data.size()) || !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) { return Status::OperationError(); } @@ -114,8 +113,8 @@ Status RsaVerify(const blink::WebCryptoKey& key, unsigned int pss_salt_length_bytes, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) { if (key.GetType() != blink::kWebCryptoKeyTypePublic) return Status::ErrorUnexpectedKeyType(); @@ -138,11 +137,11 @@ if (status.IsError()) return status; - if (!EVP_DigestVerifyUpdate(ctx.get(), data.bytes(), data.byte_length())) + if (!EVP_DigestVerifyUpdate(ctx.get(), data.data(), data.size())) return Status::OperationError(); - *signature_match = 1 == EVP_DigestVerifyFinal(ctx.get(), signature.bytes(), - signature.byte_length()); + *signature_match = + 1 == EVP_DigestVerifyFinal(ctx.get(), signature.data(), signature.size()); return Status::Success(); }
diff --git a/components/webcrypto/algorithms/rsa_sign.h b/components/webcrypto/algorithms/rsa_sign.h index 2e3f092..d0abe50 100644 --- a/components/webcrypto/algorithms/rsa_sign.h +++ b/components/webcrypto/algorithms/rsa_sign.h
@@ -9,13 +9,14 @@ #include <vector> +#include "base/containers/span.h" + namespace blink { class WebCryptoKey; } namespace webcrypto { -class CryptoData; class Status; // Helper functions for doing RSA-SSA signing and verification @@ -26,13 +27,13 @@ Status RsaSign(const blink::WebCryptoKey& key, unsigned int pss_salt_length_bytes, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer); Status RsaVerify(const blink::WebCryptoKey& key, unsigned int pss_salt_length_bytes, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match); } // namespace webcrypto
diff --git a/components/webcrypto/algorithms/rsa_ssa.cc b/components/webcrypto/algorithms/rsa_ssa.cc index 2500b3a..d7e3d46 100644 --- a/components/webcrypto/algorithms/rsa_ssa.cc +++ b/components/webcrypto/algorithms/rsa_ssa.cc
@@ -38,15 +38,15 @@ Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { return RsaSign(key, 0, data, buffer); } Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, - const CryptoData& signature, - const CryptoData& data, + base::span<const uint8_t> signature, + base::span<const uint8_t> data, bool* signature_match) const override { return RsaVerify(key, 0, signature, data, signature_match); }
diff --git a/components/webcrypto/algorithms/rsa_ssa_unittest.cc b/components/webcrypto/algorithms/rsa_ssa_unittest.cc index eb23a328..fb92af4a 100644 --- a/components/webcrypto/algorithms/rsa_ssa_unittest.cc +++ b/components/webcrypto/algorithms/rsa_ssa_unittest.cc
@@ -6,10 +6,10 @@ #include <stdint.h> #include "base/check_op.h" +#include "base/containers/span.h" #include "base/values.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -43,7 +43,7 @@ blink::WebCryptoKey key; ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatSpki, - CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)), + HexStringToBytes(kPublicKeySpkiDerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha256), @@ -54,14 +54,13 @@ EXPECT_EQ(blink::kWebCryptoKeyUsageVerify, key.Usages()); EXPECT_EQ(kModulusLengthBits, key.Algorithm().RsaHashedParams()->ModulusLengthBits()); - EXPECT_BYTES_EQ_HEX( - "010001", - CryptoData(key.Algorithm().RsaHashedParams()->PublicExponent())); + EXPECT_BYTES_EQ_HEX("010001", + key.Algorithm().RsaHashedParams()->PublicExponent()); // Failing case: Import RSA key but provide an inconsistent input algorithm. EXPECT_EQ(Status::ErrorUnsupportedImportKeyFormat(), ImportKey(blink::kWebCryptoKeyFormatSpki, - CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)), + HexStringToBytes(kPublicKeySpkiDerHex), CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), true, blink::kWebCryptoKeyUsageEncrypt, &key)); @@ -80,7 +79,7 @@ // Failing case: Try to export a non-extractable key ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatSpki, - CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)), + HexStringToBytes(kPublicKeySpkiDerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha256), @@ -103,7 +102,7 @@ blink::WebCryptoKey key; ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatPkcs8, - CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)), + HexStringToBytes(kPrivateKeyPkcs8DerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha1), @@ -116,9 +115,8 @@ key.Algorithm().RsaHashedParams()->GetHash().Id()); EXPECT_EQ(kModulusLengthBits, key.Algorithm().RsaHashedParams()->ModulusLengthBits()); - EXPECT_BYTES_EQ_HEX( - "010001", - CryptoData(key.Algorithm().RsaHashedParams()->PublicExponent())); + EXPECT_BYTES_EQ_HEX("010001", + key.Algorithm().RsaHashedParams()->PublicExponent()); std::vector<uint8_t> exported_key; ASSERT_EQ(Status::Success(), @@ -131,7 +129,7 @@ // * AES-CBC doesn't support "sign" usage EXPECT_EQ(Status::ErrorUnsupportedImportKeyFormat(), ImportKey(blink::kWebCryptoKeyFormatPkcs8, - CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)), + HexStringToBytes(kPrivateKeyPkcs8DerHex), CreateAlgorithm(blink::kWebCryptoAlgorithmIdAesCbc), true, blink::kWebCryptoKeyUsageSign, &key)); } @@ -144,7 +142,7 @@ blink::WebCryptoKey key; ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatPkcs8, - CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)), + HexStringToBytes(kPrivateKeyPkcs8DerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha1), @@ -174,23 +172,22 @@ "\"JxVqukEm0kqB86Uoy_sn9WiG-" "ECp9uhuF6RLlP6TGVhLjiL93h5aLjvYqluo2FhBlOshkKz4MrhH8To9JKefTQ\"}"; - ASSERT_EQ(CryptoData(std::string(expected_jwk)), - CryptoData(exported_key_jwk)); + EXPECT_BYTES_EQ( + base::as_bytes(base::make_span(base::StringPiece(expected_jwk))), + exported_key_jwk); - ASSERT_EQ( - Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(exported_key_jwk), - CreateRsaHashedImportAlgorithm( - blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, - blink::kWebCryptoAlgorithmIdSha1), - true, blink::kWebCryptoKeyUsageSign, &key)); + ASSERT_EQ(Status::Success(), + ImportKey(blink::kWebCryptoKeyFormatJwk, exported_key_jwk, + CreateRsaHashedImportAlgorithm( + blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, + blink::kWebCryptoAlgorithmIdSha1), + true, blink::kWebCryptoKeyUsageSign, &key)); std::vector<uint8_t> exported_key_pkcs8; ASSERT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatPkcs8, key, &exported_key_pkcs8)); - ASSERT_EQ(CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)), - CryptoData(exported_key_pkcs8)); + ASSERT_EQ(HexStringToBytes(kPrivateKeyPkcs8DerHex), exported_key_pkcs8); } // Tests importing multiple RSA private keys from JWK, and then exporting to @@ -348,13 +345,12 @@ public_key, &public_key_spki)); public_key = blink::WebCryptoKey::CreateNull(); - ASSERT_EQ( - Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatSpki, CryptoData(public_key_spki), - CreateRsaHashedImportAlgorithm( - blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, - blink::kWebCryptoAlgorithmIdSha256), - true, public_usages, &public_key)); + ASSERT_EQ(Status::Success(), + ImportKey(blink::kWebCryptoKeyFormatSpki, public_key_spki, + CreateRsaHashedImportAlgorithm( + blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, + blink::kWebCryptoAlgorithmIdSha256), + true, public_usages, &public_key)); EXPECT_EQ(modulus_length, public_key.Algorithm().RsaHashedParams()->ModulusLengthBits()); @@ -362,13 +358,12 @@ EXPECT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatPkcs8, private_key, &private_key_pkcs8)); private_key = blink::WebCryptoKey::CreateNull(); - ASSERT_EQ( - Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatPkcs8, CryptoData(private_key_pkcs8), - CreateRsaHashedImportAlgorithm( - blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, - blink::kWebCryptoAlgorithmIdSha256), - true, private_usages, &private_key)); + ASSERT_EQ(Status::Success(), + ImportKey(blink::kWebCryptoKeyFormatPkcs8, private_key_pkcs8, + CreateRsaHashedImportAlgorithm( + blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, + blink::kWebCryptoAlgorithmIdSha256), + true, private_usages, &private_key)); EXPECT_EQ(modulus_length, private_key.Algorithm().RsaHashedParams()->ModulusLengthBits()); @@ -548,48 +543,42 @@ // Compute a signature. const std::vector<uint8_t> data = HexStringToBytes("010203040506070809"); - ASSERT_EQ(Status::Success(), - Sign(algorithm, private_key, CryptoData(data), &signature)); + ASSERT_EQ(Status::Success(), Sign(algorithm, private_key, data, &signature)); // Ensure truncated signature does not verify by passing one less byte. EXPECT_EQ(Status::Success(), Verify(algorithm, public_key, - CryptoData(signature.data(), - static_cast<unsigned int>(signature.size()) - 1), - CryptoData(data), &signature_match)); + base::make_span(signature).first(signature.size() - 1), data, + &signature_match)); EXPECT_FALSE(signature_match); // Ensure truncated signature does not verify by passing no bytes. - EXPECT_EQ(Status::Success(), Verify(algorithm, public_key, CryptoData(), - CryptoData(data), &signature_match)); + EXPECT_EQ(Status::Success(), + Verify(algorithm, public_key, {}, data, &signature_match)); EXPECT_FALSE(signature_match); // Ensure corrupted signature does not verify. std::vector<uint8_t> corrupt_sig = signature; corrupt_sig[corrupt_sig.size() / 2] ^= 0x1; EXPECT_EQ(Status::Success(), - Verify(algorithm, public_key, CryptoData(corrupt_sig), - CryptoData(data), &signature_match)); + Verify(algorithm, public_key, corrupt_sig, data, &signature_match)); EXPECT_FALSE(signature_match); // Ensure signatures that are greater than the modulus size fail. - const unsigned int long_message_size_bytes = 1024; + const size_t long_message_size_bytes = 1024; DCHECK_GT(long_message_size_bytes, kModulusLengthBits / 8); const unsigned char kLongSignature[long_message_size_bytes] = {0}; - EXPECT_EQ(Status::Success(), - Verify(algorithm, public_key, - CryptoData(kLongSignature, sizeof(kLongSignature)), - CryptoData(data), &signature_match)); + EXPECT_EQ(Status::Success(), Verify(algorithm, public_key, kLongSignature, + data, &signature_match)); EXPECT_FALSE(signature_match); // Ensure that signing and verifying with an incompatible algorithm fails. algorithm = CreateAlgorithm(blink::kWebCryptoAlgorithmIdRsaOaep); EXPECT_EQ(Status::ErrorUnexpected(), - Sign(algorithm, private_key, CryptoData(data), &signature)); + Sign(algorithm, private_key, data, &signature)); EXPECT_EQ(Status::ErrorUnexpected(), - Verify(algorithm, public_key, CryptoData(signature), - CryptoData(data), &signature_match)); + Verify(algorithm, public_key, signature, data, &signature_match)); // Some crypto libraries (NSS) can automatically select the RSA SSA inner hash // based solely on the contents of the input signature data. In the Web Crypto @@ -603,12 +592,12 @@ // Compute a signature using SHA-1 as the inner hash. EXPECT_EQ(Status::Success(), Sign(CreateAlgorithm(blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5), - private_key, CryptoData(data), &signature)); + private_key, data, &signature)); blink::WebCryptoKey public_key_256; EXPECT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatSpki, - CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)), + HexStringToBytes(kPublicKeySpkiDerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha256), @@ -627,8 +616,7 @@ bool is_match; EXPECT_EQ(Status::Success(), Verify(CreateAlgorithm(blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5), - public_key_256, CryptoData(signature), CryptoData(data), - &is_match)); + public_key_256, signature, data, &is_match)); EXPECT_FALSE(is_match); } @@ -665,14 +653,13 @@ GetBytesFromHexString(test, "signature_hex"); signature.clear(); - ASSERT_EQ(Status::Success(), Sign(algorithm, private_key, - CryptoData(test_message), &signature)); + ASSERT_EQ(Status::Success(), + Sign(algorithm, private_key, test_message, &signature)); EXPECT_BYTES_EQ(test_signature, signature); bool is_match = false; - ASSERT_EQ(Status::Success(), - Verify(algorithm, public_key, CryptoData(test_signature), - CryptoData(test_message), &is_match)); + ASSERT_EQ(Status::Success(), Verify(algorithm, public_key, test_signature, + test_message, &is_match)); EXPECT_TRUE(is_match); } } @@ -697,8 +684,8 @@ blink::WebCryptoKey public_key; ASSERT_EQ(Status::ErrorCreateKeyBadUsages(), ImportKey(blink::kWebCryptoKeyFormatSpki, - CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)), - algorithm, false, bad_usages[i], &public_key)); + HexStringToBytes(kPublicKeySpkiDerHex), algorithm, + false, bad_usages[i], &public_key)); } } @@ -816,7 +803,7 @@ // Public without usage does not throw an error. ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatSpki, - CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)), + HexStringToBytes(kPublicKeySpkiDerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha256), @@ -826,7 +813,7 @@ // Private empty usage will throw an error. ASSERT_EQ(Status::ErrorCreateKeyEmptyUsages(), ImportKey(blink::kWebCryptoKeyFormatPkcs8, - CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)), + HexStringToBytes(kPrivateKeyPkcs8DerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha1), @@ -837,7 +824,7 @@ ExportKey(blink::kWebCryptoKeyFormatJwk, public_key, &public_jwk)); ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(public_jwk), + ImportKey(blink::kWebCryptoKeyFormatJwk, public_jwk, CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha256), @@ -847,7 +834,7 @@ // With correct usage to get correct imported private_key std::vector<uint8_t> private_jwk; ImportKey(blink::kWebCryptoKeyFormatPkcs8, - CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)), + HexStringToBytes(kPrivateKeyPkcs8DerHex), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha1), @@ -857,7 +844,7 @@ private_key, &private_jwk)); ASSERT_EQ(Status::ErrorCreateKeyEmptyUsages(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(private_jwk), + ImportKey(blink::kWebCryptoKeyFormatJwk, private_jwk, CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha1), @@ -891,7 +878,7 @@ blink::WebCryptoKey public_key; ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatSpki, - CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)), + HexStringToBytes(kPublicKeySpkiDerHex), import_algorithm, true, test.usage, &public_key)); // Export the public key as JWK and verify its contents @@ -904,8 +891,8 @@ // Import the JWK back in to create a new key blink::WebCryptoKey public_key2; ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(jwk), - import_algorithm, true, test.usage, &public_key2)); + ImportKey(blink::kWebCryptoKeyFormatJwk, jwk, import_algorithm, + true, test.usage, &public_key2)); ASSERT_TRUE(public_key2.Handle()); EXPECT_EQ(blink::kWebCryptoKeyTypePublic, public_key2.GetType()); EXPECT_TRUE(public_key2.Extractable()); @@ -915,7 +902,7 @@ std::vector<uint8_t> spki; ASSERT_EQ(Status::Success(), ExportKey(blink::kWebCryptoKeyFormatSpki, public_key2, &spki)); - EXPECT_BYTES_EQ_HEX(kPublicKeySpkiDerHex, CryptoData(spki)); + EXPECT_BYTES_EQ_HEX(kPublicKeySpkiDerHex, spki); } } @@ -977,7 +964,8 @@ blink::WebCryptoKey key; ASSERT_EQ( Status::ErrorJwkNotDictionary(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(bad_data), + ImportKey(blink::kWebCryptoKeyFormatJwk, + base::as_bytes(base::make_span(bad_data)), CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha256), @@ -1006,7 +994,7 @@ if (key_format == blink::kWebCryptoKeyFormatSpki) usages = blink::kWebCryptoKeyUsageVerify; blink::WebCryptoKey key; - Status status = ImportKey(key_format, CryptoData(key_data), + Status status = ImportKey(key_format, key_data, CreateRsaHashedImportAlgorithm( blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5, blink::kWebCryptoAlgorithmIdSha256),
diff --git a/components/webcrypto/algorithms/secret_key_util.cc b/components/webcrypto/algorithms/secret_key_util.cc index cb20290..c0bb075 100644 --- a/components/webcrypto/algorithms/secret_key_util.cc +++ b/components/webcrypto/algorithms/secret_key_util.cc
@@ -6,7 +6,6 @@ #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" @@ -32,13 +31,13 @@ } result->AssignSecretKey(blink::WebCryptoKey::Create( - CreateSymmetricKeyHandle(CryptoData(random_bytes)), - blink::kWebCryptoKeyTypeSecret, extractable, algorithm, usages)); + CreateSymmetricKeyHandle(random_bytes), blink::kWebCryptoKeyTypeSecret, + extractable, algorithm, usages)); return Status::Success(); } -Status CreateWebCryptoSecretKey(const CryptoData& key_data, +Status CreateWebCryptoSecretKey(base::span<const uint8_t> key_data, const blink::WebCryptoKeyAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -49,7 +48,7 @@ return Status::Success(); } -void WriteSecretKeyJwk(const CryptoData& raw_key_data, +void WriteSecretKeyJwk(base::span<const uint8_t> raw_key_data, const std::string& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -60,7 +59,7 @@ } Status ReadSecretKeyNoExpectedAlgJwk( - const CryptoData& key_data, + base::span<const uint8_t> key_data, bool expected_extractable, blink::WebCryptoKeyUsageMask expected_usages, std::vector<uint8_t>* raw_key_data, @@ -70,13 +69,7 @@ if (status.IsError()) return status; - std::string jwk_k_value; - status = jwk->GetBytes("k", &jwk_k_value); - if (status.IsError()) - return status; - raw_key_data->assign(jwk_k_value.begin(), jwk_k_value.end()); - - return Status::Success(); + return jwk->GetBytes("k", raw_key_data); } } // namespace webcrypto
diff --git a/components/webcrypto/algorithms/secret_key_util.h b/components/webcrypto/algorithms/secret_key_util.h index f0404f6..50d63bd 100644 --- a/components/webcrypto/algorithms/secret_key_util.h +++ b/components/webcrypto/algorithms/secret_key_util.h
@@ -10,6 +10,7 @@ #include <string> #include <vector> +#include "base/containers/span.h" #include "third_party/blink/public/platform/web_crypto_algorithm.h" #include "third_party/blink/public/platform/web_crypto_key.h" @@ -17,7 +18,6 @@ namespace webcrypto { -class CryptoData; class GenerateKeyResult; class JwkReader; class Status; @@ -35,7 +35,7 @@ // Creates a WebCrypto secret key given the raw data. The provided |key_data| // will be copied into the new key. This function does not do any validation // checks for the provided parameters. -Status CreateWebCryptoSecretKey(const CryptoData& key_data, +Status CreateWebCryptoSecretKey(base::span<const uint8_t> key_data, const blink::WebCryptoKeyAlgorithm& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -46,7 +46,7 @@ // * algorithm: The JWK algorithm name (i.e. "alg") // * extractable: The JWK extractability (i.e. "ext") // * usages: The JWK usages (i.e. "key_ops") -void WriteSecretKeyJwk(const CryptoData& raw_key_data, +void WriteSecretKeyJwk(base::span<const uint8_t> raw_key_data, const std::string& algorithm, bool extractable, blink::WebCryptoKeyUsageMask usages, @@ -59,7 +59,7 @@ // present. // * expected_usages must be a subset of the JWK's "key_ops" if present. Status ReadSecretKeyNoExpectedAlgJwk( - const CryptoData& key_data, + base::span<const uint8_t> key_data, bool expected_extractable, blink::WebCryptoKeyUsageMask expected_usages, std::vector<uint8_t>* raw_key_data,
diff --git a/components/webcrypto/algorithms/sha.cc b/components/webcrypto/algorithms/sha.cc index efb32a1..ba6d1b5 100644 --- a/components/webcrypto/algorithms/sha.cc +++ b/components/webcrypto/algorithms/sha.cc
@@ -7,9 +7,9 @@ #include <vector> #include "base/check_op.h" +#include "base/containers/span.h" #include "components/webcrypto/algorithm_implementation.h" #include "components/webcrypto/algorithms/util.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/boringssl/src/include/openssl/digest.h" @@ -21,10 +21,8 @@ class ShaImplementation : public AlgorithmImplementation { public: Status Digest(const blink::WebCryptoAlgorithm& algorithm, - const CryptoData& data, + base::span<const uint8_t> data, std::vector<uint8_t>* buffer) const override { - // http://crbug.com/366427: the spec does not define any other failures for - // digest, so none of the subsequent errors are spec compliant. bssl::ScopedEVP_MD_CTX digest_context; crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); @@ -35,8 +33,7 @@ if (!EVP_DigestInit_ex(digest_context.get(), digest_algorithm, nullptr)) return Status::OperationError(); - if (!EVP_DigestUpdate(digest_context.get(), data.bytes(), - data.byte_length())) + if (!EVP_DigestUpdate(digest_context.get(), data.data(), data.size())) return Status::OperationError(); const size_t hash_expected_size = EVP_MD_CTX_size(digest_context.get());
diff --git a/components/webcrypto/algorithms/sha_unittest.cc b/components/webcrypto/algorithms/sha_unittest.cc index 5345d17..1b57e75 100644 --- a/components/webcrypto/algorithms/sha_unittest.cc +++ b/components/webcrypto/algorithms/sha_unittest.cc
@@ -8,7 +8,6 @@ #include "base/values.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" @@ -36,8 +35,7 @@ std::vector<uint8_t> test_output = GetBytesFromHexString(test, "output"); std::vector<uint8_t> output; - ASSERT_EQ(Status::Success(), - Digest(test_algorithm, CryptoData(test_input), &output)); + ASSERT_EQ(Status::Success(), Digest(test_algorithm, test_input, &output)); EXPECT_BYTES_EQ(test_output, output); } }
diff --git a/components/webcrypto/algorithms/test_helpers.cc b/components/webcrypto/algorithms/test_helpers.cc index 4de80cd..ccee6fa 100644 --- a/components/webcrypto/algorithms/test_helpers.cc +++ b/components/webcrypto/algorithms/test_helpers.cc
@@ -18,7 +18,6 @@ #include "base/strings/string_util.h" #include "base/values.h" #include "components/webcrypto/algorithm_dispatch.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/jwk.h" #include "components/webcrypto/status.h" @@ -77,19 +76,6 @@ return !(a == b); } -void PrintTo(const CryptoData& data, ::std::ostream* os) { - *os << "[" << base::HexEncode(data.bytes(), data.byte_length()) << "]"; -} - -bool operator==(const CryptoData& a, const CryptoData& b) { - return a.byte_length() == b.byte_length() && - memcmp(a.bytes(), b.bytes(), a.byte_length()) == 0; -} - -bool operator!=(const CryptoData& a, const CryptoData& b) { - return !(a == b); -} - static std::string ErrorTypeToString(blink::WebCryptoErrorType type) { switch (type) { case blink::kWebCryptoErrorTypeNotSupported: @@ -297,9 +283,8 @@ blink::WebCryptoKeyUsageMask usage) { blink::WebCryptoKey key; bool extractable = true; - EXPECT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatRaw, CryptoData(key_raw), - algorithm, extractable, usage, &key)); + EXPECT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatRaw, key_raw, + algorithm, extractable, usage, &key)); EXPECT_FALSE(key.IsNull()); EXPECT_TRUE(key.Handle()); @@ -319,8 +304,8 @@ blink::WebCryptoKey* public_key, blink::WebCryptoKey* private_key) { ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatSpki, CryptoData(spki_der), - algorithm, true, public_key_usages, public_key)); + ImportKey(blink::kWebCryptoKeyFormatSpki, spki_der, algorithm, true, + public_key_usages, public_key)); EXPECT_FALSE(public_key->IsNull()); EXPECT_TRUE(public_key->Handle()); EXPECT_EQ(blink::kWebCryptoKeyTypePublic, public_key->GetType()); @@ -329,8 +314,8 @@ EXPECT_EQ(public_key_usages, public_key->Usages()); ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatPkcs8, CryptoData(pkcs8_der), - algorithm, extractable, private_key_usages, private_key)); + ImportKey(blink::kWebCryptoKeyFormatPkcs8, pkcs8_der, algorithm, + extractable, private_key_usages, private_key)); EXPECT_FALSE(private_key->IsNull()); EXPECT_TRUE(private_key->Handle()); EXPECT_EQ(blink::kWebCryptoKeyTypePrivate, private_key->GetType()); @@ -344,9 +329,8 @@ bool extractable, blink::WebCryptoKeyUsageMask usages, blink::WebCryptoKey* key) { - return ImportKey(blink::kWebCryptoKeyFormatJwk, - CryptoData(MakeJsonVector(dict)), algorithm, extractable, - usages, key); + return ImportKey(blink::kWebCryptoKeyFormatJwk, MakeJsonVector(dict), + algorithm, extractable, usages, key); } Status ImportKeyJwkFromDict(const base::DictionaryValue& dict, @@ -529,9 +513,8 @@ EXPECT_TRUE(VerifySecretJwk(json, jwk_alg, key_hex, usages)); // Import the JWK-formatted key. - ASSERT_EQ(Status::Success(), - ImportKey(blink::kWebCryptoKeyFormatJwk, CryptoData(json), - import_algorithm, true, usages, &key)); + ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatJwk, json, + import_algorithm, true, usages, &key)); EXPECT_TRUE(key.Handle()); EXPECT_EQ(blink::kWebCryptoKeyTypeSecret, key.GetType()); EXPECT_EQ(import_algorithm.Id(), key.Algorithm().Id());
diff --git a/components/webcrypto/algorithms/test_helpers.h b/components/webcrypto/algorithms/test_helpers.h index 59fd3f39..77cbac5 100644 --- a/components/webcrypto/algorithms/test_helpers.h +++ b/components/webcrypto/algorithms/test_helpers.h
@@ -12,14 +12,17 @@ #include <string> #include <vector> +#include "base/strings/string_number_conversions.h" #include "base/values.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/platform/web_crypto_algorithm.h" #include "third_party/blink/public/platform/web_crypto_key.h" +// Compare the input in hex, because `base::span` supports neither equality nor +// printing. #define EXPECT_BYTES_EQ(expected, actual) \ - EXPECT_EQ(CryptoData(expected), CryptoData(actual)) + EXPECT_EQ(base::HexEncode(expected), base::HexEncode(actual)) #define EXPECT_BYTES_EQ_HEX(expected_hex, actual_bytes) \ EXPECT_BYTES_EQ(HexStringToBytes(expected_hex), actual_bytes) @@ -45,19 +48,13 @@ }; class Status; -class CryptoData; // These functions are used by GTEST to support EXPECT_EQ() for -// webcrypto::Status and webcrypto::CryptoData - +// webcrypto::Status. void PrintTo(const Status& status, ::std::ostream* os); bool operator==(const Status& a, const Status& b); bool operator!=(const Status& a, const Status& b); -void PrintTo(const CryptoData& data, ::std::ostream* os); -bool operator==(const CryptoData& a, const CryptoData& b); -bool operator!=(const CryptoData& a, const CryptoData& b); - // Gives a human-readable description of |status| and any error it represents. std::string StatusToString(const Status& status);
diff --git a/components/webcrypto/algorithms/util.cc b/components/webcrypto/algorithms/util.cc index 557e6cc55..ef747a32 100644 --- a/components/webcrypto/algorithms/util.cc +++ b/components/webcrypto/algorithms/util.cc
@@ -5,7 +5,6 @@ #include "components/webcrypto/algorithms/util.h" #include "base/check_op.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "third_party/boringssl/src/include/openssl/aead.h" @@ -60,17 +59,12 @@ return (a & b) == b; } -BIGNUM* CreateBIGNUM(const std::string& n) { - return BN_bin2bn(reinterpret_cast<const uint8_t*>(n.data()), n.size(), - nullptr); -} - Status AeadEncryptDecrypt(EncryptOrDecrypt mode, - const std::vector<uint8_t>& raw_key, - const CryptoData& data, + base::span<const uint8_t> raw_key, + base::span<const uint8_t> data, unsigned int tag_length_bytes, - const CryptoData& iv, - const CryptoData& additional_data, + base::span<const uint8_t> iv, + base::span<const uint8_t> additional_data, const EVP_AEAD* aead_alg, std::vector<uint8_t>* buffer) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); @@ -88,24 +82,22 @@ int ok; if (mode == DECRYPT) { - if (data.byte_length() < tag_length_bytes) + if (data.size() < tag_length_bytes) return Status::ErrorDataTooSmall(); - buffer->resize(data.byte_length() - tag_length_bytes); + buffer->resize(data.size() - tag_length_bytes); ok = EVP_AEAD_CTX_open(ctx.get(), buffer->data(), &len, buffer->size(), - iv.bytes(), iv.byte_length(), data.bytes(), - data.byte_length(), additional_data.bytes(), - additional_data.byte_length()); + iv.data(), iv.size(), data.data(), data.size(), + additional_data.data(), additional_data.size()); } else { // No need to check for unsigned integer overflow here (seal fails if // the output buffer is too small). - buffer->resize(data.byte_length() + EVP_AEAD_max_overhead(aead_alg)); + buffer->resize(data.size() + EVP_AEAD_max_overhead(aead_alg)); ok = EVP_AEAD_CTX_seal(ctx.get(), buffer->data(), &len, buffer->size(), - iv.bytes(), iv.byte_length(), data.bytes(), - data.byte_length(), additional_data.bytes(), - additional_data.byte_length()); + iv.data(), iv.size(), data.data(), data.size(), + additional_data.data(), additional_data.size()); } if (!ok)
diff --git a/components/webcrypto/algorithms/util.h b/components/webcrypto/algorithms/util.h index ffa70b09..7e95bf69 100644 --- a/components/webcrypto/algorithms/util.h +++ b/components/webcrypto/algorithms/util.h
@@ -11,6 +11,7 @@ #include <stddef.h> #include <stdint.h> +#include "base/containers/span.h" #include "third_party/blink/public/platform/web_crypto_algorithm.h" #include "third_party/blink/public/platform/web_crypto_key.h" #include "third_party/boringssl/src/include/openssl/base.h" @@ -20,7 +21,6 @@ namespace webcrypto { -class CryptoData; class Status; // Returns the EVP_MD that corresponds with |hash_algorithm|, or nullptr on @@ -63,9 +63,6 @@ bool ContainsKeyUsages(blink::WebCryptoKeyUsageMask a, blink::WebCryptoKeyUsageMask b); -// Allocates a new BIGNUM given a std::string big-endian representation. -BIGNUM* CreateBIGNUM(const std::string& n); - // The values of these constants correspond with the "enc" parameter of // EVP_CipherInit_ex(), do not change. enum EncryptOrDecrypt { DECRYPT = 0, ENCRYPT = 1 }; @@ -75,11 +72,11 @@ // * |aead_alg| the algorithm (for instance AES-GCM) // * |buffer| where the ciphertext or plaintext is written to. Status AeadEncryptDecrypt(EncryptOrDecrypt mode, - const std::vector<uint8_t>& raw_key, - const CryptoData& data, + base::span<const uint8_t> raw_key, + base::span<const uint8_t> data, unsigned int tag_length_bytes, - const CryptoData& iv, - const CryptoData& additional_data, + base::span<const uint8_t> iv, + base::span<const uint8_t> additional_data, const EVP_AEAD* aead_alg, std::vector<uint8_t>* buffer);
diff --git a/components/webcrypto/blink_key_handle.cc b/components/webcrypto/blink_key_handle.cc index ef292be..73cef9d 100644 --- a/components/webcrypto/blink_key_handle.cc +++ b/components/webcrypto/blink_key_handle.cc
@@ -7,7 +7,6 @@ #include <utility> #include "base/check_op.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "third_party/boringssl/src/include/openssl/evp.h" @@ -31,10 +30,10 @@ // clone synchronously. class Key : public blink::WebCryptoKeyHandle { public: - explicit Key(const CryptoData& serialized_key_data) + explicit Key(base::span<const uint8_t> serialized_key_data) : serialized_key_data_( - serialized_key_data.bytes(), - serialized_key_data.bytes() + serialized_key_data.byte_length()) {} + serialized_key_data.data(), + serialized_key_data.data() + serialized_key_data.size()) {} ~Key() override {} @@ -52,7 +51,7 @@ class SymKey : public Key { public: - explicit SymKey(const CryptoData& raw_key_data) : Key(raw_key_data) {} + explicit SymKey(base::span<const uint8_t> raw_key_data) : Key(raw_key_data) {} SymKey(const SymKey&) = delete; SymKey& operator=(const SymKey&) = delete; @@ -69,7 +68,7 @@ // After construction the |pkey| should NOT be mutated. AsymKey(bssl::UniquePtr<EVP_PKEY> pkey, const std::vector<uint8_t>& serialized_key_data) - : Key(CryptoData(serialized_key_data)), pkey_(std::move(pkey)) {} + : Key(serialized_key_data), pkey_(std::move(pkey)) {} AsymKey(const AsymKey&) = delete; AsymKey& operator=(const AsymKey&) = delete; @@ -106,7 +105,7 @@ } blink::WebCryptoKeyHandle* CreateSymmetricKeyHandle( - const CryptoData& key_bytes) { + base::span<const uint8_t> key_bytes) { return new SymKey(key_bytes); }
diff --git a/components/webcrypto/blink_key_handle.h b/components/webcrypto/blink_key_handle.h index 5c5a624..cb8896c6 100644 --- a/components/webcrypto/blink_key_handle.h +++ b/components/webcrypto/blink_key_handle.h
@@ -9,6 +9,7 @@ #include <vector> +#include "base/containers/span.h" #include "third_party/blink/public/platform/web_crypto_key.h" #include "third_party/boringssl/src/include/openssl/base.h" @@ -22,8 +23,6 @@ namespace webcrypto { -class CryptoData; - // Returns a reference to the symmetric key data wrapped by the given Blink // key. The returned reference is owned by |key|. This function must only be // called on secret keys (HMAC, AES, etc). @@ -42,7 +41,7 @@ // Creates a symmetric key handle that can be passed to Blink. The caller takes // ownership of the returned pointer. blink::WebCryptoKeyHandle* CreateSymmetricKeyHandle( - const CryptoData& key_bytes); + base::span<const uint8_t> key_bytes); // Creates an asymmetric key handle that can be passed to Blink. The caller // takes
diff --git a/components/webcrypto/crypto_data.cc b/components/webcrypto/crypto_data.cc deleted file mode 100644 index 62c75ea..0000000 --- a/components/webcrypto/crypto_data.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/webcrypto/crypto_data.h" - -namespace webcrypto { - -CryptoData::CryptoData() : bytes_(nullptr), byte_length_(0) {} - -CryptoData::CryptoData(const unsigned char* bytes, unsigned int byte_length) - : bytes_(bytes), byte_length_(byte_length) { -} - -CryptoData::CryptoData(const std::vector<unsigned char>& bytes) - : bytes_(bytes.data()), - byte_length_(static_cast<unsigned int>(bytes.size())) {} - -CryptoData::CryptoData(const std::string& bytes) - : bytes_(bytes.size() ? reinterpret_cast<const unsigned char*>(bytes.data()) - : nullptr), - byte_length_(static_cast<unsigned int>(bytes.size())) {} - -CryptoData::CryptoData(const blink::WebVector<unsigned char>& bytes) - : bytes_(bytes.data()), - byte_length_(static_cast<unsigned int>(bytes.size())) {} - -} // namespace webcrypto
diff --git a/components/webcrypto/crypto_data.h b/components/webcrypto/crypto_data.h deleted file mode 100644 index 31f3546..0000000 --- a/components/webcrypto/crypto_data.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_WEBCRYPTO_CRYPTO_DATA_H_ -#define COMPONENTS_WEBCRYPTO_CRYPTO_DATA_H_ - -#include <string> -#include <vector> - -#include "third_party/blink/public/platform/web_vector.h" - -namespace webcrypto { - -// Helper to pass around a range of immutable bytes. This is conceptually -// similar to base::StringPiece, but for crypto byte data. -// -// The data used at construction is NOT owned, and should remain valid as long -// as the CryptoData is being used. -class CryptoData { - public: - // Constructs empty data. - CryptoData(); - - CryptoData(const unsigned char* bytes, unsigned int byte_length); - - // These constructors do NOT copy the data. Hence the base pointer should - // remain valid for the lifetime of CryptoData. - explicit CryptoData(const std::vector<unsigned char>& bytes); - explicit CryptoData(const std::string& bytes); - explicit CryptoData(const blink::WebVector<unsigned char>& bytes); - - const unsigned char* bytes() const { return bytes_; } - unsigned int byte_length() const { return byte_length_; } - - private: - const unsigned char* const bytes_; - const unsigned int byte_length_; -}; - -} // namespace webcrypto - -#endif // COMPONENTS_WEBCRYPTO_CRYPTO_DATA_H_
diff --git a/components/webcrypto/fuzzer_support.cc b/components/webcrypto/fuzzer_support.cc index 15623285..e90e72b 100644 --- a/components/webcrypto/fuzzer_support.cc +++ b/components/webcrypto/fuzzer_support.cc
@@ -5,11 +5,10 @@ #include "components/webcrypto/fuzzer_support.h" #include "base/command_line.h" +#include "base/containers/span.h" #include "base/lazy_instance.h" -#include "base/numerics/safe_conversions.h" #include "base/task/single_thread_task_executor.h" #include "components/webcrypto/algorithm_dispatch.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" #include "mojo/core/embedder/embedder.h" #include "third_party/blink/public/platform/platform.h" @@ -90,7 +89,7 @@ blink::WebCryptoKey key; webcrypto::Status status = webcrypto::ImportKey( - format, webcrypto::CryptoData(data, base::checked_cast<uint32_t>(size)), + format, base::make_span(data, size), CreateEcImportAlgorithm(algorithm_id, curve), true, usages, &key); // These errors imply a bad setup of parameters, and means ImportKey() may not @@ -135,8 +134,7 @@ blink::WebCryptoKey key; webcrypto::Status status = webcrypto::ImportKey( - blink::kWebCryptoKeyFormatRaw, - webcrypto::CryptoData(data, base::checked_cast<uint32_t>(size)), + blink::kWebCryptoKeyFormatRaw, base::make_span(data, size), CreateEcImportAlgorithm(algorithm_id, curve), true, usages, &key); // These errors imply a bad setup of parameters, and means ImportKey() may not @@ -169,7 +167,7 @@ blink::WebCryptoKey key; webcrypto::Status status = webcrypto::ImportKey( - format, webcrypto::CryptoData(data, base::checked_cast<uint32_t>(size)), + format, base::make_span(data, size), CreateRsaHashedImportAlgorithm(algorithm_id, hash_id), true, usages, &key);
diff --git a/components/webcrypto/jwk.cc b/components/webcrypto/jwk.cc index 8578653..2a6f31e 100644 --- a/components/webcrypto/jwk.cc +++ b/components/webcrypto/jwk.cc
@@ -15,7 +15,6 @@ #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "components/webcrypto/algorithms/util.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/status.h" // JSON Web Key Format (JWK) is defined by: @@ -198,14 +197,14 @@ JwkReader::~JwkReader() { } -Status JwkReader::Init(const CryptoData& bytes, +Status JwkReader::Init(base::span<const uint8_t> bytes, bool expected_extractable, blink::WebCryptoKeyUsageMask expected_usages, const std::string& expected_kty, const std::string& expected_alg) { // Parse the incoming JWK JSON. - base::StringPiece json_string(reinterpret_cast<const char*>(bytes.bytes()), - bytes.byte_length()); + base::StringPiece json_string(reinterpret_cast<const char*>(bytes.data()), + bytes.size()); { // Limit the visibility for |value| as it is moved to |dict_| (via @@ -293,7 +292,7 @@ } Status JwkReader::GetBytes(const std::string& member_name, - std::string* result) const { + std::vector<uint8_t>* result) const { std::string base64_string; Status status = GetString(member_name, &base64_string); if (status.IsError()) @@ -301,17 +300,19 @@ // The JSON web signature spec says that padding is omitted. // https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-36#section-2 + std::string result_str; if (!base::Base64UrlDecode(base64_string, base::Base64UrlDecodePolicy::DISALLOW_PADDING, - result)) { + &result_str)) { return Status::ErrorJwkBase64Decode(member_name); } + result->assign(result_str.begin(), result_str.end()); return Status::Success(); } Status JwkReader::GetBigInteger(const std::string& member_name, - std::string* result) const { + std::vector<uint8_t>* result) const { Status status = GetBytes(member_name, result); if (status.IsError()) return status; @@ -379,13 +380,13 @@ } void JwkWriter::SetBytes(const std::string& member_name, - const CryptoData& value) { + base::span<const uint8_t> value) { // The JSON web signature spec says that padding is omitted. // https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-36#section-2 std::string base64url_encoded; base::Base64UrlEncode( - base::StringPiece(reinterpret_cast<const char*>(value.bytes()), - value.byte_length()), + base::StringPiece(reinterpret_cast<const char*>(value.data()), + value.size()), base::Base64UrlEncodePolicy::OMIT_PADDING, &base64url_encoded); dict_.SetStringKey(member_name, base64url_encoded);
diff --git a/components/webcrypto/jwk.h b/components/webcrypto/jwk.h index 63b4ccc..fbc92ea 100644 --- a/components/webcrypto/jwk.h +++ b/components/webcrypto/jwk.h
@@ -10,12 +10,12 @@ #include <memory> #include <vector> +#include "base/containers/span.h" #include "base/values.h" #include "third_party/blink/public/platform/web_crypto.h" namespace webcrypto { -class CryptoData; class Status; // Helper class for parsing a JWK from JSON. @@ -40,7 +40,7 @@ // * Have an "alg" matching |expected_alg| // // NOTE: If |expected_alg| is empty, then the test on "alg" is skipped. - Status Init(const CryptoData& bytes, + Status Init(base::span<const uint8_t> bytes, bool expected_extractable, blink::WebCryptoKeyUsageMask expected_usages, const std::string& expected_kty, @@ -75,14 +75,15 @@ // Extracts the required string member |member_name| and saves the // base64url-decoded bytes to |*result|. If the member does not exist or is // not a string, or could not be base64url-decoded, returns an error. - Status GetBytes(const std::string& member_name, std::string* result) const; + Status GetBytes(const std::string& member_name, + std::vector<uint8_t>* result) const; // Extracts the required base64url member, which is interpreted as being a // big-endian unsigned integer. // // Sequences that contain leading zeros will be rejected. Status GetBigInteger(const std::string& member_name, - std::string* result) const; + std::vector<uint8_t>* result) const; // Extracts the optional boolean member |member_name| and saves the result to // |*result| if it was found. If the member exists and is not a boolean, @@ -117,7 +118,8 @@ void SetString(const std::string& member_name, const std::string& value); // Sets a bytes member |value| to |value| by base64 url-safe encoding it. - void SetBytes(const std::string& member_name, const CryptoData& value); + void SetBytes(const std::string& member_name, + base::span<const uint8_t> value); // Flattens the JWK to JSON (UTF-8 encoded if necessary, however in practice // it will be ASCII).
diff --git a/components/webcrypto/status_unittest.cc b/components/webcrypto/status_unittest.cc index 27dd89d..a59ea2f 100644 --- a/components/webcrypto/status_unittest.cc +++ b/components/webcrypto/status_unittest.cc
@@ -5,7 +5,6 @@ #include "components/webcrypto/status.h" #include "components/webcrypto/algorithm_dispatch.h" #include "components/webcrypto/algorithms/test_helpers.h" -#include "components/webcrypto/crypto_data.h" #include "third_party/blink/public/platform/web_crypto_algorithm.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/public/platform/web_crypto_key_algorithm.h"
diff --git a/components/webcrypto/webcrypto_impl.cc b/components/webcrypto/webcrypto_impl.cc index 0383e31..e217bac 100644 --- a/components/webcrypto/webcrypto_impl.cc +++ b/components/webcrypto/webcrypto_impl.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/check_op.h" +#include "base/containers/span.h" #include "base/lazy_instance.h" #include "base/location.h" #include "base/task/single_thread_task_runner.h" @@ -20,7 +21,6 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "components/webcrypto/algorithm_dispatch.h" -#include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/status.h" #include "third_party/blink/public/platform/web_crypto_key_algorithm.h" @@ -389,9 +389,8 @@ EncryptState* state = passed_state.get(); if (state->cancelled()) return; - state->status = - webcrypto::Encrypt(state->algorithm, state->key, - webcrypto::CryptoData(state->data), &state->buffer); + state->status = webcrypto::Encrypt(state->algorithm, state->key, state->data, + &state->buffer); state->origin_thread->PostTask( FROM_HERE, base::BindOnce(DoEncryptReply, std::move(passed_state))); } @@ -407,9 +406,8 @@ DecryptState* state = passed_state.get(); if (state->cancelled()) return; - state->status = - webcrypto::Decrypt(state->algorithm, state->key, - webcrypto::CryptoData(state->data), &state->buffer); + state->status = webcrypto::Decrypt(state->algorithm, state->key, state->data, + &state->buffer); state->origin_thread->PostTask( FROM_HERE, base::BindOnce(DoDecryptReply, std::move(passed_state))); } @@ -424,8 +422,8 @@ DigestState* state = passed_state.get(); if (state->cancelled()) return; - state->status = webcrypto::Digest( - state->algorithm, webcrypto::CryptoData(state->data), &state->buffer); + state->status = + webcrypto::Digest(state->algorithm, state->data, &state->buffer); state->origin_thread->PostTask( FROM_HERE, base::BindOnce(DoDigestReply, std::move(passed_state))); } @@ -463,9 +461,9 @@ ImportKeyState* state = passed_state.get(); if (state->cancelled()) return; - state->status = webcrypto::ImportKey( - state->format, webcrypto::CryptoData(state->key_data), state->algorithm, - state->extractable, state->usages, &state->key); + state->status = + webcrypto::ImportKey(state->format, state->key_data, state->algorithm, + state->extractable, state->usages, &state->key); if (state->status.IsSuccess()) { DCHECK(state->key.Handle()); DCHECK(!state->key.Algorithm().IsNull()); @@ -514,9 +512,8 @@ SignState* state = passed_state.get(); if (state->cancelled()) return; - state->status = - webcrypto::Sign(state->algorithm, state->key, - webcrypto::CryptoData(state->data), &state->buffer); + state->status = webcrypto::Sign(state->algorithm, state->key, state->data, + &state->buffer); state->origin_thread->PostTask( FROM_HERE, base::BindOnce(DoSignReply, std::move(passed_state))); @@ -536,9 +533,9 @@ VerifySignatureState* state = passed_state.get(); if (state->cancelled()) return; - state->status = webcrypto::Verify( - state->algorithm, state->key, webcrypto::CryptoData(state->signature), - webcrypto::CryptoData(state->data), &state->verify_result); + state->status = + webcrypto::Verify(state->algorithm, state->key, state->signature, + state->data, &state->verify_result); state->origin_thread->PostTask( FROM_HERE, base::BindOnce(DoVerifyReply, std::move(passed_state))); @@ -575,10 +572,9 @@ if (state->cancelled()) return; state->status = webcrypto::UnwrapKey( - state->format, webcrypto::CryptoData(state->wrapped_key), - state->wrapping_key, state->unwrap_algorithm, - state->unwrapped_key_algorithm, state->extractable, state->usages, - &state->unwrapped_key); + state->format, state->wrapped_key, state->wrapping_key, + state->unwrap_algorithm, state->unwrapped_key_algorithm, + state->extractable, state->usages, &state->unwrapped_key); state->origin_thread->PostTask( FROM_HERE, base::BindOnce(DoUnwrapKeyReply, std::move(passed_state))); @@ -637,6 +633,8 @@ blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { DCHECK(!algorithm.IsNull()); + if (result.Cancelled()) + return; std::unique_ptr<EncryptState> state(new EncryptState( algorithm, key, std::move(data), result, std::move(task_runner))); @@ -653,6 +651,8 @@ blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { DCHECK(!algorithm.IsNull()); + if (result.Cancelled()) + return; std::unique_ptr<DecryptState> state(new DecryptState( algorithm, key, std::move(data), result, std::move(task_runner))); @@ -668,6 +668,8 @@ blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { DCHECK(!algorithm.IsNull()); + if (result.Cancelled()) + return; std::unique_ptr<DigestState> state( new DigestState(algorithm, blink::WebCryptoKey::CreateNull(), @@ -685,6 +687,8 @@ blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { DCHECK(!algorithm.IsNull()); + if (result.Cancelled()) + return; std::unique_ptr<GenerateKeyState> state(new GenerateKeyState( algorithm, extractable, usages, result, std::move(task_runner))); @@ -702,6 +706,8 @@ blink::WebCryptoKeyUsageMask usages, blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + if (result.Cancelled()) + return; std::unique_ptr<ImportKeyState> state( new ImportKeyState(format, std::move(key_data), algorithm, extractable, usages, result, std::move(task_runner))); @@ -716,6 +722,8 @@ const blink::WebCryptoKey& key, blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + if (result.Cancelled()) + return; std::unique_ptr<ExportKeyState> state( new ExportKeyState(format, key, result, std::move(task_runner))); if (!CryptoThreadPool::PostTask( @@ -730,6 +738,8 @@ blink::WebVector<unsigned char> data, blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + if (result.Cancelled()) + return; std::unique_ptr<SignState> state(new SignState( algorithm, key, std::move(data), result, std::move(task_runner))); if (!CryptoThreadPool::PostTask(FROM_HERE, @@ -745,6 +755,8 @@ blink::WebVector<unsigned char> data, blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + if (result.Cancelled()) + return; std::unique_ptr<VerifySignatureState> state(new VerifySignatureState( algorithm, key, std::move(signature), std::move(data), result, std::move(task_runner))); @@ -761,6 +773,8 @@ const blink::WebCryptoAlgorithm& wrap_algorithm, blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + if (result.Cancelled()) + return; std::unique_ptr<WrapKeyState> state( new WrapKeyState(format, key, wrapping_key, wrap_algorithm, result, std::move(task_runner))); @@ -780,6 +794,8 @@ blink::WebCryptoKeyUsageMask usages, blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + if (result.Cancelled()) + return; std::unique_ptr<UnwrapKeyState> state( new UnwrapKeyState(format, std::move(wrapped_key), wrapping_key, unwrap_algorithm, unwrapped_key_algorithm, extractable, @@ -796,6 +812,8 @@ unsigned int length_bits, blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + if (result.Cancelled()) + return; std::unique_ptr<DeriveBitsState> state(new DeriveBitsState( algorithm, base_key, length_bits, result, std::move(task_runner))); if (!CryptoThreadPool::PostTask( @@ -813,6 +831,8 @@ blink::WebCryptoKeyUsageMask usages, blink::WebCryptoResult result, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + if (result.Cancelled()) + return; std::unique_ptr<DeriveKeyState> state(new DeriveKeyState( algorithm, base_key, import_algorithm, key_length_algorithm, extractable, usages, result, std::move(task_runner))); @@ -832,7 +852,7 @@ blink::WebCryptoKey& key) { return webcrypto::DeserializeKeyForClone( algorithm, type, extractable, usages, - webcrypto::CryptoData(key_data, key_data_size), &key); + base::make_span(key_data, key_data_size), &key); } bool WebCryptoImpl::SerializeKeyForClone(
diff --git a/content/browser/file_system_access/file_system_access_write_lock_manager.cc b/content/browser/file_system_access/file_system_access_write_lock_manager.cc index 8b6fd568..0b0a336e 100644 --- a/content/browser/file_system_access/file_system_access_write_lock_manager.cc +++ b/content/browser/file_system_access/file_system_access_write_lock_manager.cc
@@ -3,19 +3,93 @@ // found in the LICENSE file. #include "content/browser/file_system_access/file_system_access_write_lock_manager.h" +#include "base/files/file_path.h" +#include "base/memory/scoped_refptr.h" +#include "components/services/storage/public/cpp/buckets/bucket_locator.h" +#include "storage/browser/file_system/file_system_url.h" +#include "storage/common/file_system/file_system_types.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace content { -FileSystemAccessWriteLockManager::WriteLock::WriteLock( - base::WeakPtr<FileSystemAccessWriteLockManager> lock_manager, - const storage::FileSystemURL& url, - const WriteLockType& type, - base::PassKey<FileSystemAccessWriteLockManager> /*pass_key*/) - : lock_manager_(lock_manager), url_(url), type_(type) {} +using EntryLocator = FileSystemAccessWriteLockManager::EntryLocator; +using WriteLock = FileSystemAccessWriteLockManager::WriteLock; -FileSystemAccessWriteLockManager::WriteLock::~WriteLock() { +// static +EntryLocator EntryLocator::FromFileSystemURL( + const storage::FileSystemURL& url) { + EntryPathType path_type; + switch (url.type()) { + case storage::kFileSystemTypeLocal: + case storage::kFileSystemTypeTest: + path_type = EntryPathType::kLocal; + break; + case storage::kFileSystemTypeTemporary: + path_type = EntryPathType::kSandboxed; + break; + default: + DCHECK_EQ(url.mount_type(), + storage::FileSystemType::kFileSystemTypeExternal); + path_type = EntryPathType::kExternal; + } + base::FilePath path = + path_type == EntryPathType::kLocal ? url.path() : url.virtual_path(); + // Sandboxed file system URLs may or may not have a bucket locator. If they + // don't, construct a dummy bucket locator and populate it with the URL's + // storage key to ensure that files of the same relative path in different + // sandboxed file systems represent distinct locks. Note that files in the + // same file system can use different locks if one has bucket information and + // one does not, though we don't expect this to happen in practice... + // + // TODO(crbug.com/1329927): If/when we require all FileSystemURLs in sandboxed + // file systems to have a bucket locator, replace this logic with a DCHECK. + absl::optional<storage::BucketLocator> maybe_bucket_locator = absl::nullopt; + if (path_type == EntryPathType::kSandboxed) { + storage::BucketLocator bucket_locator; + if (url.bucket().has_value()) { + bucket_locator = url.bucket().value(); + } else { + bucket_locator.storage_key = url.storage_key(); + } + maybe_bucket_locator.emplace(std::move(bucket_locator)); + } + return EntryLocator(path_type, path, maybe_bucket_locator); +} + +EntryLocator::EntryLocator( + const EntryPathType& type, + const base::FilePath& path, + const absl::optional<storage::BucketLocator>& bucket_locator) + : type(type), path(path), bucket_locator(bucket_locator) { + // Files in the sandboxed file system must have a `bucket_locator`. See the + // comment in `EntryLocator::FromFileSystemURL()`. Files outside of the + // sandboxed file system should not be keyed by StorageKey to ensure that + // separate sites cannot hold their own exclusive locks to the same file. + DCHECK_EQ(type == EntryPathType::kSandboxed, bucket_locator.has_value()); +} +EntryLocator::EntryLocator(const EntryLocator&) = default; +EntryLocator::~EntryLocator() = default; + +bool EntryLocator::operator<(const EntryLocator& other) const { + return std::tie(type, path, bucket_locator) < + std::tie(other.type, other.path, other.bucket_locator); +} + +WriteLock::WriteLock( + base::WeakPtr<FileSystemAccessWriteLockManager> lock_manager, + const EntryLocator& entry_locator, + const WriteLockType& type, + const scoped_refptr<WriteLock> parent_lock, + base::PassKey<FileSystemAccessWriteLockManager> pass_key) + : lock_manager_(lock_manager), + entry_locator_(entry_locator), + type_(type), + parent_lock_(std::move(parent_lock)) {} + +WriteLock::~WriteLock() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (lock_manager_) - lock_manager_->ReleaseLock(url_); + lock_manager_->ReleaseLock(entry_locator_); } FileSystemAccessWriteLockManager::FileSystemAccessWriteLockManager( @@ -23,26 +97,54 @@ FileSystemAccessWriteLockManager::~FileSystemAccessWriteLockManager() = default; -absl::optional<scoped_refptr<FileSystemAccessWriteLockManager::WriteLock>> +absl::optional<scoped_refptr<WriteLock>> FileSystemAccessWriteLockManager::TakeLock(const storage::FileSystemURL& url, WriteLockType lock_type) { - auto lock_it = locks_.find(url); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + EntryLocator entry_locator = EntryLocator::FromFileSystemURL(url); + return TakeLockImpl(entry_locator, lock_type); +} + +absl::optional<scoped_refptr<WriteLock>> +FileSystemAccessWriteLockManager::TakeLockImpl( + const EntryLocator& entry_locator, + WriteLockType lock_type) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + auto lock_it = locks_.find(entry_locator); WriteLock* existing_lock = lock_it != locks_.end() ? lock_it->second : nullptr; if (!existing_lock) { + // Recursively try to acquire shared locks on all parent directories. If any + // parent directories are locked, lock acquisition should fail. + scoped_refptr<WriteLock> parent_lock; + auto parent_path = entry_locator.path.DirName(); + if (parent_path != entry_locator.path) { + EntryLocator parent_entry_locator{entry_locator.type, parent_path, + entry_locator.bucket_locator}; + auto maybe_parent_lock = + TakeLockImpl(parent_entry_locator, WriteLockType::kShared); + if (!maybe_parent_lock.has_value()) + return absl::nullopt; + + parent_lock = std::move(maybe_parent_lock.value()); + } + // There are no locks on the file, we can take any type of lock. WriteLock* new_lock = - new WriteLock(weak_factory_.GetWeakPtr(), url, lock_type, PassKey()); - // The lock is owned by the caller, a raw pointer is stored `locks_` to be - // able to increase the refcount when a new shared lock is requested on a - // URL that has an existing one. + new WriteLock(weak_factory_.GetWeakPtr(), entry_locator, lock_type, + std::move(parent_lock), PassKey()); + // The lock is owned by the caller or its child lock. A raw pointer is + // stored `locks_` to be able to increase the refcount when a new shared + // lock is requested on a URL that has an existing one. // // It is safe to store raw pointers in `locks_` because when a lock is // destroyed, it's entry in the map is erased. This means that any raw // pointer in the map points to a valid object, and is therefore safe to // dereference. - locks_.emplace(url, new_lock); + locks_.emplace(std::move(entry_locator), new_lock); return base::WrapRefCounted<WriteLock>(new_lock); } @@ -61,8 +163,10 @@ } void FileSystemAccessWriteLockManager::ReleaseLock( - const storage::FileSystemURL& url) { - size_t count_removed = locks_.erase(url); + const EntryLocator& entry_locator) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + size_t count_removed = locks_.erase(entry_locator); DCHECK_EQ(1u, count_removed); }
diff --git a/content/browser/file_system_access/file_system_access_write_lock_manager.h b/content/browser/file_system_access/file_system_access_write_lock_manager.h index 125f1b3..a3838e53 100644 --- a/content/browser/file_system_access/file_system_access_write_lock_manager.h +++ b/content/browser/file_system_access/file_system_access_write_lock_manager.h
@@ -7,12 +7,20 @@ #include <map> +#include "base/files/file_path.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" +#include "base/sequence_checker.h" #include "base/types/pass_key.h" +#include "components/services/storage/public/cpp/buckets/bucket_locator.h" #include "content/common/content_export.h" -#include "storage/browser/file_system/file_system_url.h" #include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/blink/public/common/storage_key/storage_key.h" + +namespace storage { +class FileSystemURL; +} // namespace storage namespace content { @@ -33,13 +41,46 @@ kShared }; - // This class represents an active write lock on a file. The lock is released - // on destruction. + enum class EntryPathType { + // A path on the local file system. Files with these paths can be operated + // on by base::File. + kLocal, + + // A path on an "external" file system. These paths can only be accessed via + // the filesystem abstraction in //storage/browser/file_system, and a + // storage::FileSystemURL of type storage::kFileSystemTypeExternal. + kExternal, + + // A path from a sandboxed file system. These paths can be accessed by a + // storage::FileSystemURL of type storage::kFileSystemTypeTemporary. + kSandboxed, + }; + + struct EntryLocator { + static EntryLocator FromFileSystemURL(const storage::FileSystemURL& url); + + EntryLocator(const EntryPathType& type, + const base::FilePath& path, + const absl::optional<storage::BucketLocator>& bucket_locator); + EntryLocator(const EntryLocator&); + ~EntryLocator(); + + bool operator<(const EntryLocator& other) const; + + const EntryPathType type; + const base::FilePath path; + // Non-null iff `type` is kSandboxed. + const absl::optional<storage::BucketLocator> bucket_locator; + }; + + // This class represents an active write lock on a file or directory. The lock + // is released on destruction. class CONTENT_EXPORT WriteLock : public base::RefCounted<WriteLock> { public: WriteLock(base::WeakPtr<FileSystemAccessWriteLockManager> lock_manager, - const storage::FileSystemURL& url, + const EntryLocator& entry_locator, const WriteLockType& type, + const scoped_refptr<WriteLock> parent_lock, base::PassKey<FileSystemAccessWriteLockManager> pass_key); WriteLock(WriteLock const&) = delete; @@ -52,15 +93,25 @@ // The lock is released on destruction. ~WriteLock(); + SEQUENCE_CHECKER(sequence_checker_); + // The FileSystemAccessWriteLockManager that created this instance. Used on // destruction to release the lock on the file. - base::WeakPtr<FileSystemAccessWriteLockManager> lock_manager_; + base::WeakPtr<FileSystemAccessWriteLockManager> lock_manager_ + GUARDED_BY_CONTEXT(sequence_checker_); - // URL of the file associated with this lock. It is used to unlock the - // exclusive write lock on closure/destruction. - const storage::FileSystemURL url_; + // Locator of the file or directory associated with this lock. It is used to + // unlock the exclusive write lock on closure/destruction. + const EntryLocator entry_locator_; const WriteLockType type_; + + // When a file or directory is locked, it acquires a shared lock on its + // parent directory, which acquires a shared lock on its parent, and so + // forth. When this instance goes away, the associated ancestor locks are + // automatically released. May be null if this instance represents the root + // of its file system. + const scoped_refptr<WriteLock> parent_lock_; }; explicit FileSystemAccessWriteLockManager( @@ -73,19 +124,25 @@ FileSystemAccessWriteLockManager const&) = delete; // Attempts to take a lock on `url`. Returns the lock if successful. - absl::optional<scoped_refptr<FileSystemAccessWriteLockManager::WriteLock>> - TakeLock(const storage::FileSystemURL& url, WriteLockType lock_type); + absl::optional<scoped_refptr<WriteLock>> TakeLock( + const storage::FileSystemURL& url, + WriteLockType lock_type); private: - // Releases the lock on `url`. Called from the WriteLock destructor. - void ReleaseLock(const storage::FileSystemURL& url); + absl::optional<scoped_refptr<WriteLock>> TakeLockImpl( + const EntryLocator& entry_locator, + WriteLockType lock_type); - std::map<storage::FileSystemURL, - FileSystemAccessWriteLockManager::WriteLock*, - storage::FileSystemURL::Comparator> - locks_; + // Releases the lock on `entry_locator`. Called from the WriteLock destructor. + void ReleaseLock(const EntryLocator& entry_locator); - base::WeakPtrFactory<FileSystemAccessWriteLockManager> weak_factory_{this}; + SEQUENCE_CHECKER(sequence_checker_); + + std::map<EntryLocator, WriteLock*> locks_ + GUARDED_BY_CONTEXT(sequence_checker_); + + base::WeakPtrFactory<FileSystemAccessWriteLockManager> weak_factory_ + GUARDED_BY_CONTEXT(sequence_checker_){this}; }; } // namespace content
diff --git a/content/browser/file_system_access/file_system_access_write_lock_manager_unittest.cc b/content/browser/file_system_access/file_system_access_write_lock_manager_unittest.cc new file mode 100644 index 0000000..c31b66a --- /dev/null +++ b/content/browser/file_system_access/file_system_access_write_lock_manager_unittest.cc
@@ -0,0 +1,372 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/file_system_access/file_system_access_write_lock_manager.h" + +#include "base/files/file_path.h" +#include "base/files/scoped_temp_dir.h" +#include "base/test/task_environment.h" +#include "base/test/test_future.h" +#include "content/browser/file_system_access/file_system_access_manager_impl.h" +#include "content/browser/file_system_access/file_system_access_transfer_token_impl.h" +#include "content/public/test/browser_task_environment.h" +#include "storage/browser/blob/blob_storage_context.h" +#include "storage/browser/file_system/external_mount_points.h" +#include "storage/browser/file_system/file_system_url.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/browser/test/test_file_system_context.h" +#include "storage/common/file_system/file_system_types.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/mojom/file_system_access/file_system_access_data_transfer_token.mojom.h" +#include "third_party/blink/public/mojom/file_system_access/file_system_access_directory_handle.mojom.h" +#include "third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom.h" + +namespace content { + +using WriteLock = FileSystemAccessWriteLockManager::WriteLock; +using WriteLockType = FileSystemAccessWriteLockManager::WriteLockType; +using storage::FileSystemURL; + +static constexpr char kTestMountPoint[] = "testfs"; + +class FileSystemAccessWriteLockManagerTest : public testing::Test { + public: + FileSystemAccessWriteLockManagerTest() + : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {} + + void SetUp() override { + ASSERT_TRUE(dir_.CreateUniqueTempDir()); + + // Register an external mount point to test support for virtual paths. + // This maps the virtual path a native local path to make these tests work + // on all platforms. We're not testing more complicated ChromeOS specific + // file system backends here. + storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem( + kTestMountPoint, storage::kFileSystemTypeLocal, + storage::FileSystemMountOption(), dir_.GetPath()); + + file_system_context_ = storage::CreateFileSystemContextForTesting( + /*quota_manager_proxy=*/nullptr, dir_.GetPath()); + + chrome_blob_context_ = base::MakeRefCounted<ChromeBlobStorageContext>(); + chrome_blob_context_->InitializeOnIOThread(base::FilePath(), + base::FilePath(), nullptr); + + manager_ = base::MakeRefCounted<FileSystemAccessManagerImpl>( + file_system_context_, chrome_blob_context_, + /*permission_context=*/nullptr, + /*off_the_record=*/false); + } + + void TearDown() override { + manager_.reset(); + + task_environment_.RunUntilIdle(); + EXPECT_TRUE(dir_.Delete()); + } + + void AssertAncestorLockBehavior(const FileSystemURL& parent_url, + const FileSystemURL& child_url) { + // Parent cannot take exclusive lock if child is exclusively locked. + { + auto child_lock = + manager_->TakeWriteLock(child_url, WriteLockType::kExclusive); + ASSERT_TRUE(child_lock.has_value()); + + auto parent_lock = + manager_->TakeWriteLock(parent_url, WriteLockType::kExclusive); + ASSERT_FALSE(parent_lock.has_value()); + } + + // Parent can take shared lock if child is exclusively locked. + { + auto child_lock = + manager_->TakeWriteLock(child_url, WriteLockType::kExclusive); + ASSERT_TRUE(child_lock.has_value()); + + auto parent_lock = + manager_->TakeWriteLock(parent_url, WriteLockType::kShared); + ASSERT_TRUE(parent_lock.has_value()); + } + + // Child cannot take exclusive lock if parent is exclusively locked. + { + auto parent_lock = + manager_->TakeWriteLock(parent_url, WriteLockType::kExclusive); + ASSERT_TRUE(parent_lock.has_value()); + + auto child_lock = + manager_->TakeWriteLock(child_url, WriteLockType::kExclusive); + ASSERT_FALSE(child_lock.has_value()); + } + + // Child cannot take shared lock if parent is exclusively locked. + { + auto parent_lock = + manager_->TakeWriteLock(parent_url, WriteLockType::kExclusive); + ASSERT_TRUE(parent_lock.has_value()); + + auto child_lock = + manager_->TakeWriteLock(child_url, WriteLockType::kShared); + ASSERT_FALSE(child_lock.has_value()); + } + + // Parent cannot take exclusive lock if child holds a shared lock. + { + auto child_lock = + manager_->TakeWriteLock(child_url, WriteLockType::kShared); + ASSERT_TRUE(child_lock.has_value()); + + auto parent_lock = + manager_->TakeWriteLock(parent_url, WriteLockType::kExclusive); + ASSERT_FALSE(parent_lock.has_value()); + } + + // Parent can take shared lock if child holds a shared lock. + { + auto child_lock = + manager_->TakeWriteLock(child_url, WriteLockType::kShared); + ASSERT_TRUE(child_lock.has_value()); + + auto parent_lock = + manager_->TakeWriteLock(parent_url, WriteLockType::kShared); + ASSERT_TRUE(parent_lock.has_value()); + } + + // Child can take exclusive lock if parent holds a shared lock. + { + auto parent_lock = + manager_->TakeWriteLock(parent_url, WriteLockType::kShared); + ASSERT_TRUE(parent_lock.has_value()); + + auto child_lock = + manager_->TakeWriteLock(child_url, WriteLockType::kExclusive); + ASSERT_TRUE(child_lock.has_value()); + } + + // Child can take shared lock if parent holds a shared lock. + { + auto parent_lock = + manager_->TakeWriteLock(parent_url, WriteLockType::kShared); + ASSERT_TRUE(parent_lock.has_value()); + + auto child_lock = + manager_->TakeWriteLock(child_url, WriteLockType::kShared); + ASSERT_TRUE(child_lock.has_value()); + } + } + + protected: + const blink::StorageKey kTestStorageKey = + blink::StorageKey::CreateFromStringForTesting("https://example.com/test"); + + BrowserTaskEnvironment task_environment_; + + base::ScopedTempDir dir_; + scoped_refptr<storage::FileSystemContext> file_system_context_; + scoped_refptr<ChromeBlobStorageContext> chrome_blob_context_; + scoped_refptr<FileSystemAccessManagerImpl> manager_; +}; + +TEST_F(FileSystemAccessWriteLockManagerTest, ExclusiveLock) { + base::FilePath path = dir_.GetPath().AppendASCII("foo"); + auto url = manager_->CreateFileSystemURLFromPath( + FileSystemAccessEntryFactory::PathType::kLocal, path); + + { + auto exclusive_lock = + manager_->TakeWriteLock(url, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock.has_value()); + + // Cannot take another lock while the file is exclusively locked. + auto another_exclusive_lock = + manager_->TakeWriteLock(url, WriteLockType::kExclusive); + ASSERT_FALSE(another_exclusive_lock.has_value()); + auto shared_lock = manager_->TakeWriteLock(url, WriteLockType::kShared); + ASSERT_FALSE(shared_lock.has_value()); + } + + // The exclusive lock has been released and should be available to be + // re-acquired. + auto exclusive_lock = manager_->TakeWriteLock(url, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock.has_value()); +} + +TEST_F(FileSystemAccessWriteLockManagerTest, SharedLock) { + base::FilePath path = dir_.GetPath().AppendASCII("foo"); + auto url = manager_->CreateFileSystemURLFromPath( + FileSystemAccessEntryFactory::PathType::kLocal, path); + + { + auto shared_lock = manager_->TakeWriteLock(url, WriteLockType::kShared); + ASSERT_TRUE(shared_lock.has_value()); + + // Can take another shared lock, but not an exclusive lock. + auto another_shared_lock = + manager_->TakeWriteLock(url, WriteLockType::kShared); + ASSERT_TRUE(another_shared_lock.has_value()); + auto exclusive_lock = + manager_->TakeWriteLock(url, WriteLockType::kExclusive); + ASSERT_FALSE(exclusive_lock.has_value()); + } + + // The shared locks have been released and we should be available to acquire + // an exclusive lock. + auto exclusive_lock = manager_->TakeWriteLock(url, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock.has_value()); +} + +TEST_F(FileSystemAccessWriteLockManagerTest, SandboxedFile) { + auto url = file_system_context_->CreateCrackedFileSystemURL( + kTestStorageKey, storage::kFileSystemTypeTemporary, + base::FilePath::FromUTF8Unsafe("test/foo/bar")); + + { + auto exclusive_lock = + manager_->TakeWriteLock(url, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock.has_value()); + + // Cannot take another lock while the file is exclusively locked. + auto another_exclusive_lock = + manager_->TakeWriteLock(url, WriteLockType::kExclusive); + ASSERT_FALSE(another_exclusive_lock.has_value()); + auto shared_lock = manager_->TakeWriteLock(url, WriteLockType::kShared); + ASSERT_FALSE(shared_lock.has_value()); + } + + // The exclusive lock has been released and should be available to be + // re-acquired. + auto exclusive_lock = manager_->TakeWriteLock(url, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock.has_value()); +} + +TEST_F(FileSystemAccessWriteLockManagerTest, SandboxedFilesSamePath) { + // Sandboxed files of the same relative path do not lock across sites if the + // BucketLocator is set. + const blink::StorageKey kOtherStorageKey = + blink::StorageKey::CreateFromStringForTesting("https://foo.com/test"); + auto url1 = file_system_context_->CreateCrackedFileSystemURL( + kOtherStorageKey, storage::kFileSystemTypeTemporary, + base::FilePath::FromUTF8Unsafe("test/foo/bar")); + auto url2 = file_system_context_->CreateCrackedFileSystemURL( + kTestStorageKey, storage::kFileSystemTypeTemporary, + base::FilePath::FromUTF8Unsafe("test/foo/bar")); + + // Take a lock on the file in the first file system. + auto exclusive_lock1 = + manager_->TakeWriteLock(url1, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock1.has_value()); + auto another_exclusive_lock1 = + manager_->TakeWriteLock(url1, WriteLockType::kExclusive); + ASSERT_FALSE(another_exclusive_lock1.has_value()); + + // Can still take a lock on the file in the second file system. + auto exclusive_lock2 = + manager_->TakeWriteLock(url2, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock2.has_value()); + auto another_exclusive_lock2 = + manager_->TakeWriteLock(url2, WriteLockType::kExclusive); + ASSERT_FALSE(another_exclusive_lock2.has_value()); +} + +TEST_F(FileSystemAccessWriteLockManagerTest, DifferentBackends) { + // We'll use the same path and pretend they're from different backends. + base::FilePath path = + base::FilePath::FromUTF8Unsafe(kTestMountPoint).AppendASCII("foo"); + + // File on a local file system. + auto local_url = manager_->CreateFileSystemURLFromPath( + FileSystemAccessEntryFactory::PathType::kLocal, path); + + // File with the same path on an external file system. + auto external_url = manager_->CreateFileSystemURLFromPath( + FileSystemAccessEntryFactory::PathType::kExternal, path); + + EXPECT_EQ(local_url.path(), external_url.virtual_path()); + + // Take a lock on the file in the local file system. + auto local_exclusive_lock = + manager_->TakeWriteLock(local_url, WriteLockType::kExclusive); + ASSERT_TRUE(local_exclusive_lock.has_value()); + auto another_local_exclusive_lock = + manager_->TakeWriteLock(local_url, WriteLockType::kExclusive); + ASSERT_FALSE(another_local_exclusive_lock.has_value()); + + // Can still take a lock on the file in the external file system. + auto external_exclusive_lock = + manager_->TakeWriteLock(external_url, WriteLockType::kExclusive); + ASSERT_TRUE(external_exclusive_lock.has_value()); + auto another_external_exclusive_lock = + manager_->TakeWriteLock(external_url, WriteLockType::kExclusive); + ASSERT_FALSE(another_external_exclusive_lock.has_value()); +} + +TEST_F(FileSystemAccessWriteLockManagerTest, LockAcrossSites) { + base::FilePath path = dir_.GetPath().AppendASCII("foo"); + auto url1 = FileSystemURL::CreateForTest(kTestStorageKey, + storage::kFileSystemTypeLocal, path); + + // Select the same local file from another site. + auto url2 = FileSystemURL::CreateForTest( + blink::StorageKey::CreateFromStringForTesting("https://foo.com/bar"), + storage::kFileSystemTypeLocal, path); + + EXPECT_EQ(url1.path(), url2.path()); + EXPECT_NE(url1.storage_key(), url2.storage_key()); + + { + auto exclusive_lock = + manager_->TakeWriteLock(url1, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock.has_value()); + + // Other sites cannot access the file while it is exclusively locked. + auto another_exclusive_lock = + manager_->TakeWriteLock(url2, WriteLockType::kExclusive); + ASSERT_FALSE(another_exclusive_lock.has_value()); + auto shared_lock = manager_->TakeWriteLock(url2, WriteLockType::kShared); + ASSERT_FALSE(shared_lock.has_value()); + } + + // The exclusive lock has been released and should be available to be + // re-acquired. + auto exclusive_lock = + manager_->TakeWriteLock(url2, WriteLockType::kExclusive); + ASSERT_TRUE(exclusive_lock.has_value()); +} + +TEST_F(FileSystemAccessWriteLockManagerTest, AncestorLocks) { + base::FilePath parent_path = dir_.GetPath().AppendASCII("foo"); + auto parent_url = manager_->CreateFileSystemURLFromPath( + FileSystemAccessEntryFactory::PathType::kLocal, parent_path); + auto child_url = manager_->CreateFileSystemURLFromPath( + FileSystemAccessEntryFactory::PathType::kLocal, + parent_path.Append(FILE_PATH_LITERAL("child"))); + + AssertAncestorLockBehavior(parent_url, child_url); +} + +TEST_F(FileSystemAccessWriteLockManagerTest, AncestorLocksExternal) { + base::FilePath parent_path = + base::FilePath::FromUTF8Unsafe(kTestMountPoint).AppendASCII("foo"); + auto parent_url = manager_->CreateFileSystemURLFromPath( + FileSystemAccessEntryFactory::PathType::kExternal, parent_path); + auto child_url = manager_->CreateFileSystemURLFromPath( + FileSystemAccessEntryFactory::PathType::kExternal, + parent_path.Append(FILE_PATH_LITERAL("child"))); + + AssertAncestorLockBehavior(parent_url, child_url); +} + +TEST_F(FileSystemAccessWriteLockManagerTest, AncestorLocksSandboxed) { + auto parent_path = base::FilePath::FromUTF8Unsafe("test/foo/bar"); + auto parent_url = file_system_context_->CreateCrackedFileSystemURL( + kTestStorageKey, storage::kFileSystemTypeTemporary, parent_path); + auto child_url = file_system_context_->CreateCrackedFileSystemURL( + kTestStorageKey, storage::kFileSystemTypeTemporary, + parent_path.Append(FILE_PATH_LITERAL("child"))); + + AssertAncestorLockBehavior(parent_url, child_url); +} + +} // namespace content
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index 875b85e..a712ef8 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -3395,8 +3395,8 @@ response_should_be_rendered_ = !is_download && (!response_head_->headers.get() || - (response_head_->headers->response_code() != 204 && - response_head_->headers->response_code() != 205 && + (response_head_->headers->response_code() != net::HTTP_NO_CONTENT && + response_head_->headers->response_code() != net::HTTP_RESET_CONTENT && !ShouldRenderFallbackContentForResponse(*response_head_->headers))); // Response that will not commit should be marked as aborted in the
diff --git a/content/browser/tracing/file_tracing_provider_impl.cc b/content/browser/tracing/file_tracing_provider_impl.cc index e960df4..74ddb92 100644 --- a/content/browser/tracing/file_tracing_provider_impl.cc +++ b/content/browser/tracing/file_tracing_provider_impl.cc
@@ -5,7 +5,7 @@ #include "content/browser/tracing/file_tracing_provider_impl.h" #include "base/files/file_path.h" -#include "base/trace_event/trace_event.h" +#include "base/trace_event/base_tracing.h" namespace content { @@ -29,6 +29,8 @@ void FileTracingProviderImpl::FileTracingDisable(const void* id) { TRACE_EVENT_NESTABLE_ASYNC_END0( kFileTracingEventCategoryGroup, FILE_TRACING_PREFIX, id); + // TODO(crbug.com/1021571): Remove this once fixed. + PERFETTO_INTERNAL_ADD_EMPTY_EVENT(); } void FileTracingProviderImpl::FileTracingEventBegin(const char* name,
diff --git a/content/public/common/content_switch_dependent_feature_overrides.cc b/content/public/common/content_switch_dependent_feature_overrides.cc index 90ada40..50fece0 100644 --- a/content/public/common/content_switch_dependent_feature_overrides.cc +++ b/content/public/common/content_switch_dependent_feature_overrides.cc
@@ -98,6 +98,9 @@ {switches::kEnableExperimentalWebPlatformFeatures, std::cref(blink::features::kEditContext), base::FeatureList::OVERRIDE_ENABLE_FEATURE}, + {switches::kEnableExperimentalWebPlatformFeatures, + std::cref(network::features::kReduceAcceptLanguage), + base::FeatureList::OVERRIDE_ENABLE_FEATURE}, // Overrides for --enable-experimental-cookie-features. {switches::kEnableExperimentalCookieFeatures,
diff --git a/content/public/renderer/content_renderer_client.cc b/content/public/renderer/content_renderer_client.cc index 63456aa..de7f7113f 100644 --- a/content/public/renderer/content_renderer_client.cc +++ b/content/public/renderer/content_renderer_client.cc
@@ -238,7 +238,8 @@ return nullptr; } -bool ContentRendererClient::IsSafeRedirectTarget(const GURL& url) { +bool ContentRendererClient::IsSafeRedirectTarget(const GURL& from_url, + const GURL& to_url) { return true; }
diff --git a/content/public/renderer/content_renderer_client.h b/content/public/renderer/content_renderer_client.h index 3c2b0f1..1dfe162 100644 --- a/content/public/renderer/content_renderer_client.h +++ b/content/public/renderer/content_renderer_client.h
@@ -382,8 +382,8 @@ virtual blink::WebFrame* FindFrame(blink::WebLocalFrame* relative_to_frame, const std::string& name); - // Returns true if it is safe to redirect to |url|, otherwise returns false. - virtual bool IsSafeRedirectTarget(const GURL& url); + // Returns true only if it's safe to redirect `from_url` to `to_url`. + virtual bool IsSafeRedirectTarget(const GURL& from_url, const GURL& to_url); // The user agent string is given from the browser process. This is called at // most once.
diff --git a/content/public/test/slow_download_http_response.cc b/content/public/test/slow_download_http_response.cc index a130df57..b0c7789 100644 --- a/content/public/test/slow_download_http_response.cc +++ b/content/public/test/slow_download_http_response.cc
@@ -61,7 +61,7 @@ response.emplace_back("Content-type", "application/octet-stream"); response.emplace_back("Cache-Control", "max-age=0"); - if (base::LowerCaseEqualsASCII(kKnownSizeUrl, url_)) { + if (base::EqualsCaseInsensitiveASCII(kKnownSizeUrl, url_)) { response.emplace_back( "Content-Length", base::NumberToString(kFirstResponsePartSize + kSecondResponsePartSize));
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 16322f24..aac0af9 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -401,7 +401,8 @@ const GURL& to_url) { return IsSafeRedirectTarget(from_url, to_url) && (!GetContentClient()->renderer() || // null in unit tests. - GetContentClient()->renderer()->IsSafeRedirectTarget(to_url)); + GetContentClient()->renderer()->IsSafeRedirectTarget(from_url, + to_url)); } blink::WebResourceRequestSenderDelegate*
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 9cf1d55..9a54afa 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -2153,6 +2153,7 @@ "../browser/file_system_access/file_system_access_file_writer_impl_unittest.cc", "../browser/file_system_access/file_system_access_handle_base_unittest.cc", "../browser/file_system_access/file_system_access_manager_impl_unittest.cc", + "../browser/file_system_access/file_system_access_write_lock_manager_unittest.cc", "../browser/file_system_access/file_system_chooser_unittest.cc", "../browser/file_system_access/safe_move_helper_unittest.cc", "../browser/first_party_sets/addition_overlaps_union_find_unittest.cc", @@ -3071,6 +3072,7 @@ "//content/test/gpu/validate_tag_consistency.py", "//build/util/lib/results/", + "//content/test/gpu/gold_inexact_matching/", "//content/test/gpu/flake_suppressor/", "//testing/unexpected_passes_common/", ]
diff --git a/content/test/data/accessibility/html/popup-api-expected-auralinux.txt b/content/test/data/accessibility/html/popup-api-expected-auralinux.txt new file mode 100644 index 0000000..55534dc90 --- /dev/null +++ b/content/test/data/accessibility/html/popup-api-expected-auralinux.txt
@@ -0,0 +1,35 @@ +[document web] +++[push button] name='Button pointing to hidden popup' +++[entry] selectable-text +++[static] name='Text input pointing to hidden popup ' +++[push button] name='Show button pointing to hidden hint' description='Hint' description-from:tooltip +++[entry] description='Hint' selectable-text description-from:tooltip +++[static] name='Search input pointing to hidden hint ' +++[push button] name='Hide button pointing to hidden async' +++[entry] selectable-text +++[static] name='Email input pointing to hidden async ' +++[push button] name='Button pointing to showing popup' +++[entry] selectable-text +++[static] name='Tel input pointing to showing popup ' +++[push button] name='Show button pointing to showing hint' description='Hint (nested)' described-by description-from:tooltip +++[entry] description='Hint (nested)' selectable-text described-by description-from:tooltip +++[static] name='Url input pointing to showing hint ' +++[section] +++++[static] name='Popup' +++++[section] description-for +++++++[static] name='Hint (nested)' +++[push button] name='Hide button pointing to showing async' +++[entry] selectable-text +++[static] name='Text input pointing to showing async ' +++[section] +++++[static] name='Async' +++[push button] name='Button pointing to non-popup' +++[entry] selectable-text +++[static] name='Text input pointing to non-popup' +++[section] +++++[static] name='No popup attribute' +++[push button] name='Button pointing to invalid popup value' +++[entry] selectable-text +++[static] name='Text input pointing to invalid popup value' +++[section] +++++[static] name='Invalid popup attribute value'
diff --git a/content/test/data/attribution_reporting/register_attribution_src.js b/content/test/data/attribution_reporting/register_attribution_src.js index de3a565..7680cad 100644 --- a/content/test/data/attribution_reporting/register_attribution_src.js +++ b/content/test/data/attribution_reporting/register_attribution_src.js
@@ -4,12 +4,7 @@ function createAttributionSrcImg(src) { const img = document.createElement('img'); - img.setAttribute('target', "top"); - img.width = 100; - img.height = 100; - img.setAttribute("attributionsrc", src); - document.body.appendChild(img); - return img; + img.attributionSrc = src; } function createAttributionSrcAnchor({ @@ -22,8 +17,8 @@ } = {}) { const anchor = document.createElement('a'); anchor.href = url; - anchor.setAttribute('target', target); - anchor.setAttribute("attributionsrc", attributionsrc); + anchor.target = target; + anchor.attributionSrc = attributionsrc; anchor.width = 100; anchor.height = 100; anchor.id = id;
diff --git a/content/test/gpu/gold_inexact_matching/base_parameter_optimizer.py b/content/test/gpu/gold_inexact_matching/base_parameter_optimizer.py index c46ff32..5fa2fb7 100644 --- a/content/test/gpu/gold_inexact_matching/base_parameter_optimizer.py +++ b/content/test/gpu/gold_inexact_matching/base_parameter_optimizer.py
@@ -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 collections import glob import hashlib import itertools @@ -13,11 +14,13 @@ import shutil import subprocess import tempfile +import typing from PIL import Image # pylint: disable=import-error import requests # pylint: disable=import-error +from gold_inexact_matching import common_typing as ct from gold_inexact_matching import parameter_set CHROMIUM_SRC_DIR = os.path.realpath( @@ -39,7 +42,7 @@ # 4 channels, ranging from 0-255 each. MAX_DELTA_THRESHOLD = 255 * 4 - def __init__(self, args, test_name): + def __init__(self, args: ct.ParsedCmdArgs, test_name: str): """ Args: args: The parse arguments from an argparse.ArgumentParser. @@ -57,13 +60,13 @@ # A map of strings, denoting a resolution or trace, to an iterable of # strings, denoting images that are that dimension or belong to that # trace. - self._images = {} + self._images = collections.defaultdict(set) self._VerifyArgs() parameter_set.ParameterSet.ignored_border_thickness = \ self._args.ignored_border_thickness @classmethod - def AddArguments(cls, parser): + def AddArguments(cls, parser: ct.CmdArgParser) -> ct.ArgumentGroupTuple: """Add optimizer-specific arguments to the parser. Args: @@ -176,7 +179,7 @@ return common_group, sobel_group, fuzzy_group - def _VerifyArgs(self): + def _VerifyArgs(self) -> None: """Verifies that the provided arguments are valid for an optimizer.""" assert self._args.target_success_percent > 0 assert self._args.target_success_percent <= 100 @@ -192,7 +195,7 @@ assert self._args.min_delta_threshold <= self._args.max_delta_threshold assert self._args.ignored_border_thickness >= 0 - def RunOptimization(self): + def RunOptimization(self) -> None: """Runs an optimization for whatever test and parameters were supplied. The results should be printed to stdout when they are available. @@ -222,16 +225,16 @@ for f in glob.iglob(os.path.join(tempfile.gettempdir(), 'goldctl-*')): shutil.rmtree(f) - def _RunOptimizationImpl(self): + def _RunOptimizationImpl(self) -> None: """Runs the algorithm-specific optimization code for an optimizer.""" raise NotImplementedError() - def _GetMostPermissiveParameters(self): + def _GetMostPermissiveParameters(self) -> parameter_set.ParameterSet: return parameter_set.ParameterSet(self._args.max_max_diff, self._args.max_delta_threshold, self._args.min_edge_threshold) - def _DownloadData(self): + def _DownloadData(self) -> None: """Downloads all the necessary data for a test.""" assert self._working_dir logging.info('Downloading images') @@ -259,14 +262,14 @@ logging.info('Found %d images for group %s', len(digests), grouping) logging.debug('Digests: %r', digests) - def _DownloadExpectations(self, url): + def _DownloadExpectations(self, url: str) -> None: """Downloads the expectation JSON from Gold into memory.""" logging.info('Downloading expectations JSON') r = requests.get(url) assert r.status_code == 200 self._expectations = r.json() - def _DownloadImagesForResolutionGrouping(self): + def _DownloadImagesForResolutionGrouping(self) -> None: """Downloads all the positive images for a test to disk. Images are grouped by resolution. @@ -294,10 +297,9 @@ for digest in positive_digests: content = self._DownloadImageWithDigest(digest) image = Image.open(io.BytesIO(content)) - self._images.setdefault('%dx%d' % (image.size[0], image.size[1]), - []).append(digest) + self._images['%dx%d' % (image.size[0], image.size[1])].add(digest) - def _DownloadImagesForTraceGrouping(self): + def _DownloadImagesForTraceGrouping(self) -> None: """Download all recent positive images for a test to disk. Images are grouped by Skia Gold trace ID, i.e. each hardware/software @@ -307,7 +309,6 @@ # The downloaded trace data contains a list of traces, each with a list of # digests. The digests should be unique within each trace, but convert to # sets just to be sure. - filtered_traces = {} for trace in self._expectations['traces']: trace_id = trace['trace_id'] digests = set(trace['digests']) @@ -316,12 +317,11 @@ 'Failed to find any positive digests for test %s and trace %s. ' 'This is likely due to the trace being old.', self._test_name, trace_id) - filtered_traces[trace_id] = digests + self._images[trace_id] = digests for d in digests: self._DownloadImageWithDigest(d) - self._images = filtered_traces - def _DownloadImageWithDigest(self, digest): + def _DownloadImageWithDigest(self, digest: str) -> bytes: """Downloads an image with the given digest and saves it to disk. Args: @@ -337,7 +337,7 @@ outfile.write(r.content) return r.content - def _GetImagePath(self, digest): + def _GetImagePath(self, digest: str) -> str: """Gets a filepath to an image based on digest. Args: @@ -348,7 +348,7 @@ """ return os.path.join(self._working_dir, '%s.png' % digest) - def _GetGoldctlBinary(self): + def _GetGoldctlBinary(self) -> str: """Gets the filepath to the goldctl binary to use. Returns: @@ -364,7 +364,8 @@ 'Could not find goldctl binary. Checked %s' % GOLDCTL_PATHS) return self._goldctl_binary - def _RunComparisonForParameters(self, parameters): + def _RunComparisonForParameters(self, parameters: parameter_set.ParameterSet + ) -> typing.Tuple[bool, int, int]: """Runs a comparison for all image combinations using some parameters. Args: @@ -414,7 +415,9 @@ '%d', successful, max_num_pixels, max_max_delta) return successful, max_num_pixels, max_max_delta - def _GenerateComparisonCmd(self, left_digest, right_digest, parameters): + def _GenerateComparisonCmd(self, left_digest: str, right_digest: str, + parameters: parameter_set.ParameterSet + ) -> typing.List[str]: """Generates a comparison command for the given arguments. The returned command can be passed directly to a subprocess call. @@ -440,7 +443,8 @@ return cmd -def RunCommandAndExtractData(cmd): +def RunCommandAndExtractData(cmd: typing.List[str] + ) -> typing.Tuple[bool, int, int]: """Runs a comparison command and extracts data from it. This is outside of the parameter optimizers because it is meant to be run via
diff --git a/content/test/gpu/gold_inexact_matching/binary_search_parameter_optimizer.py b/content/test/gpu/gold_inexact_matching/binary_search_parameter_optimizer.py index 62eb8f37..15945e1 100644 --- a/content/test/gpu/gold_inexact_matching/binary_search_parameter_optimizer.py +++ b/content/test/gpu/gold_inexact_matching/binary_search_parameter_optimizer.py
@@ -4,8 +4,10 @@ import logging +import typing import gold_inexact_matching.base_parameter_optimizer as base_optimizer +from gold_inexact_matching import common_typing as ct from gold_inexact_matching import parameter_set @@ -20,11 +22,11 @@ UNLOCKED_PARAM_DELTA_THRESHOLD = 2 UNLOCKED_PARAM_EDGE_THRESHOLD = 3 - def __init__(self, args, test_name): + def __init__(self, args: ct.ParsedCmdArgs, test_name: str): self._unlocked_parameter = None super().__init__(args, test_name) - def _VerifyArgs(self): + def _VerifyArgs(self) -> None: super()._VerifyArgs() max_diff_locked = self._args.max_max_diff == self._args.min_max_diff @@ -46,10 +48,10 @@ else: self._unlocked_parameter = self.UNLOCKED_PARAM_EDGE_THRESHOLD - def _RunOptimizationImpl(self): + def _RunOptimizationImpl(self) -> None: known_good, known_bad = self._GetStartingValues() while (abs(known_good - known_bad)) > 1: - midpoint = (known_good + known_bad) / 2 + midpoint = (known_good + known_bad) // 2 parameters = self._CreateParameterSet(midpoint) success, _, _ = self._RunComparisonForParameters(parameters) if success: @@ -60,7 +62,7 @@ known_bad = midpoint print('Found optimal parameters: %s' % parameters) - def _GetStartingValues(self): + def _GetStartingValues(self) -> typing.Tuple[int, int]: """Gets the initial good/bad values for the binary search. Returns: @@ -75,7 +77,7 @@ return self._args.max_delta_threshold, self._args.min_delta_threshold return self._args.min_edge_threshold, self._args.max_edge_threshold - def _CreateParameterSet(self, value): + def _CreateParameterSet(self, value: int) -> parameter_set.ParameterSet: """Creates a parameter_set.ParameterSet to test. Args:
diff --git a/content/test/gpu/gold_inexact_matching/brute_force_parameter_optimizer.py b/content/test/gpu/gold_inexact_matching/brute_force_parameter_optimizer.py index d7a6a03..b7ea139e 100644 --- a/content/test/gpu/gold_inexact_matching/brute_force_parameter_optimizer.py +++ b/content/test/gpu/gold_inexact_matching/brute_force_parameter_optimizer.py
@@ -19,7 +19,7 @@ optimize multiple parameters. """ - def _VerifyArgs(self): + def _VerifyArgs(self) -> None: # range/xrange(x, y) returns the range in [x, y), so adjust by 1 to make # the range inclusive. # We go from max to min instead of min to max for this parameter, so @@ -28,7 +28,7 @@ self._args.max_max_diff += 1 self._args.max_delta_threshold += 1 - def _RunOptimizationImpl(self): + def _RunOptimizationImpl(self) -> None: # Look for the minimum max_delta that results in a successful comparison # for each possible edge_threshold/max_diff combination. for edge_threshold in range(self._args.max_edge_threshold,
diff --git a/content/test/gpu/gold_inexact_matching/common_typing.py b/content/test/gpu/gold_inexact_matching/common_typing.py new file mode 100644 index 0000000..070a248 --- /dev/null +++ b/content/test/gpu/gold_inexact_matching/common_typing.py
@@ -0,0 +1,12 @@ +# Copyright 2022 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. +"""Helper module to store file-independent, common type hinting.""" + +import argparse +import typing + +CmdArgParser = argparse.ArgumentParser +ParsedCmdArgs = argparse.Namespace +ArgumentGroup = 'argparse._ArgumentGroup' +ArgumentGroupTuple = typing.Tuple[ArgumentGroup, ArgumentGroup, ArgumentGroup]
diff --git a/content/test/gpu/gold_inexact_matching/iterative_parameter_optimizer.py b/content/test/gpu/gold_inexact_matching/iterative_parameter_optimizer.py index 0eea5c32..1d1ac8c 100644 --- a/content/test/gpu/gold_inexact_matching/iterative_parameter_optimizer.py +++ b/content/test/gpu/gold_inexact_matching/iterative_parameter_optimizer.py
@@ -4,6 +4,7 @@ import gold_inexact_matching.base_parameter_optimizer as base_optimizer +from gold_inexact_matching import common_typing as ct # This is an abstract class itself, so it's fine that it doesn't implement @@ -20,7 +21,7 @@ base_optimizer.BaseParameterOptimizer.MAX_DELTA_THRESHOLD) @classmethod - def AddArguments(cls, parser): + def AddArguments(cls, parser: ct.CmdArgParser) -> ct.ArgumentGroupTuple: common_group, sobel_group, fuzzy_group = super(IterativeParameterOptimizer, cls).AddArguments(parser) @@ -45,7 +46,7 @@ return common_group, sobel_group, fuzzy_group - def _VerifyArgs(self): + def _VerifyArgs(self) -> None: super()._VerifyArgs() assert self._args.edge_threshold_step >= self.MIN_EDGE_THRESHOLD_STEP
diff --git a/content/test/gpu/gold_inexact_matching/local_minima_parameter_optimizer.py b/content/test/gpu/gold_inexact_matching/local_minima_parameter_optimizer.py index 4389dc9..6d793d9 100644 --- a/content/test/gpu/gold_inexact_matching/local_minima_parameter_optimizer.py +++ b/content/test/gpu/gold_inexact_matching/local_minima_parameter_optimizer.py
@@ -11,6 +11,7 @@ import gold_inexact_matching.iterative_parameter_optimizer\ as iterative_optimizer +from gold_inexact_matching import common_typing as ct from gold_inexact_matching import parameter_set @@ -24,7 +25,7 @@ MIN_EDGE_THRESHOLD_WEIGHT = 0 MIN_MAX_DIFF_WEIGHT = MIN_DELTA_THRESHOLD_WEIGHT = 0 - def __init__(self, args, test_name): + def __init__(self, args: ct.ParsedCmdArgs, test_name: str): super().__init__(args, test_name) # These are (or will be) maps of ints to maps of ints to ints, i.e. a 2D # array containing ints, just using maps instead of lists. They hold the @@ -40,7 +41,7 @@ self._permissive_edge_map = {} @classmethod - def AddArguments(cls, parser): + def AddArguments(cls, parser: ct.CmdArgParser) -> ct.ArgumentGroupTuple: common_group, sobel_group, fuzzy_group = super( LocalMinimaParameterOptimizer, cls).AddArguments(parser) @@ -75,7 +76,7 @@ return common_group, sobel_group, fuzzy_group - def _VerifyArgs(self): + def _VerifyArgs(self) -> None: super()._VerifyArgs() assert self._args.edge_threshold_weight >= self.MIN_EDGE_THRESHOLD_WEIGHT @@ -83,7 +84,7 @@ assert self._args.max_diff_weight >= self.MIN_MAX_DIFF_WEIGHT assert self._args.delta_threshold_weight >= self.MIN_DELTA_THRESHOLD_WEIGHT - def _RunOptimizationImpl(self): + def _RunOptimizationImpl(self) -> None: visited_parameters = set() to_visit = collections.deque() smallest_weight = sys.maxsize @@ -130,7 +131,9 @@ for p in smallest_parameters: print(p) - def _ParametersAreGuaranteedToFail(self, parameters): + def _ParametersAreGuaranteedToFail(self, + parameters: parameter_set.ParameterSet + ) -> bool: """Checks whether the given ParameterSet is guaranteed to fail. A ParameterSet is guaranteed to fail if we have already tried and failed @@ -163,7 +166,8 @@ return False - def _UpdateMostPermissiveFailedParameters(self, parameters): + def _UpdateMostPermissiveFailedParameters( + self, parameters: parameter_set.ParameterSet) -> None: """Updates the array of most permissive failed parameters. This is used in conjunction with _ParametersAreGuaranteedToFail to prune @@ -222,7 +226,7 @@ if adjacent != starting_parameters: yield adjacent - def _GetWeight(self, parameters): + def _GetWeight(self, parameters: parameter_set.ParameterSet) -> int: return (parameters.max_diff * self._args.max_diff_weight + parameters.delta_threshold * self._args.delta_threshold_weight + (self.MAX_EDGE_THRESHOLD - parameters.edge_threshold) *
diff --git a/content/test/gpu/gold_inexact_matching/optimizer_set.py b/content/test/gpu/gold_inexact_matching/optimizer_set.py index 6a8d6f2..61de3014 100644 --- a/content/test/gpu/gold_inexact_matching/optimizer_set.py +++ b/content/test/gpu/gold_inexact_matching/optimizer_set.py
@@ -2,12 +2,17 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import typing + +from gold_inexact_matching import base_parameter_optimizer as bpo +from gold_inexact_matching import common_typing as ct class OptimizerSet(): """Class to run a ParameterOptimizer for multiple tests.""" - def __init__(self, args, optimizer_class): + def __init__(self, args: ct.ParsedCmdArgs, + optimizer_class: typing.Type[bpo.BaseParameterOptimizer]): """ Args: args: The parse arguments from an argparse.ArgumentParser. @@ -16,7 +21,7 @@ self._args = args self._optimizer_class = optimizer_class - def RunOptimization(self): + def RunOptimization(self) -> None: test_names = set(self._args.test_names) for name in test_names: print('Running optimization for test %s' % name)
diff --git a/content/test/gpu/gold_inexact_matching/parameter_set.py b/content/test/gpu/gold_inexact_matching/parameter_set.py index f707c98..c9b73ff 100644 --- a/content/test/gpu/gold_inexact_matching/parameter_set.py +++ b/content/test/gpu/gold_inexact_matching/parameter_set.py
@@ -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 typing class ParameterSet(): @@ -11,7 +12,7 @@ # passed around everywhere. ignored_border_thickness = 0 - def __init__(self, max_diff, delta_threshold, edge_threshold): + def __init__(self, max_diff: int, delta_threshold: int, edge_threshold: int): """ Args: max_diff: The maximum number of pixels that are allowed to differ. @@ -23,7 +24,7 @@ self.delta_threshold = delta_threshold self.edge_threshold = edge_threshold - def AsList(self): + def AsList(self) -> typing.List[str]: """Returns the object's data in list format. The returned object is suitable for appending to a "goldctl match" command @@ -43,21 +44,21 @@ 'sobel_edge_threshold:%d' % self.edge_threshold, ] - def __str__(self): + def __str__(self) -> str: return ('Max different pixels: %d, Max per-channel delta sum: %d, Sobel ' 'edge threshold: %d, Ignored border thickness: %d') % ( self.max_diff, self.delta_threshold, self.edge_threshold, self.ignored_border_thickness) - def __eq__(self, other): + def __eq__(self, other: 'ParameterSet') -> bool: return (self.max_diff == other.max_diff and self.delta_threshold == other.delta_threshold and self.edge_threshold == other.edge_threshold and self.ignored_border_thickness == other.ignored_border_thickness) - def __ne__(self, other): + def __ne__(self, other: 'ParameterSet') -> bool: return not self.__eq__(other) - def __hash__(self): + def __hash__(self) -> int: return hash((self.max_diff, self.delta_threshold, self.edge_threshold, self.ignored_border_thickness))
diff --git a/content/test/gpu/run_pytype.py b/content/test/gpu/run_pytype.py index 522fa96..c919cd8 100755 --- a/content/test/gpu/run_pytype.py +++ b/content/test/gpu/run_pytype.py
@@ -43,6 +43,7 @@ FILES_AND_DIRECTORIES_TO_CHECK = [ 'flake_suppressor', + 'gold_inexact_matching', 'gpu_tests', ]
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 514ce955..7152d821 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -1720,6 +1720,9 @@ BOOKMARKMANAGERPRIVATE_OPENINNEWTAB = 1657, BOOKMARKMANAGERPRIVATE_OPENINNEWWINDOW = 1658, WMDESKSPRIVATE_REMOVEDESKANDCLOSEWINDOWS = 1659, + SHAREDSTORAGEPRIVATE_GET = 1660, + SHAREDSTORAGEPRIVATE_SET = 1661, + SHAREDSTORAGEPRIVATE_REMOVE = 1662, // Last entry: Add new entries above, then run: // tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY
diff --git a/extensions/browser/extension_navigation_throttle.cc b/extensions/browser/extension_navigation_throttle.cc index f1a368ed..c12b21b 100644 --- a/extensions/browser/extension_navigation_throttle.cc +++ b/extensions/browser/extension_navigation_throttle.cc
@@ -158,8 +158,8 @@ const Extension* target_extension = nullptr; if (url_has_extension_scheme) { // "chrome-extension://" URL. - target_extension = - registry->enabled_extensions().GetExtensionOrAppByURL(url); + target_extension = registry->enabled_extensions().GetExtensionOrAppByURL( + url, true /*include_guid*/); } else if (target_origin.scheme() == kExtensionScheme) { // "blob:chrome-extension://" or "filesystem:chrome-extension://" URL. DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob());
diff --git a/extensions/browser/extension_protocols.cc b/extensions/browser/extension_protocols.cc index 0efb441..fcbc722 100644 --- a/extensions/browser/extension_protocols.cc +++ b/extensions/browser/extension_protocols.cc
@@ -91,6 +91,7 @@ #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" +#include "net/http/http_status_code.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/self_deleting_url_loader_factory.h" @@ -574,7 +575,13 @@ const std::vector<std::string>& removed_headers, const net::HttpRequestHeaders& modified_headers, const net::HttpRequestHeaders& modified_cors_exempt_headers, - const absl::optional<GURL>& new_url) override {} + const absl::optional<GURL>& new_url) override { + // new_url isn't expected to have a value, but prefer it if it's populated. + if (new_url.has_value()) + request_.url = new_url.value(); + + Start(); + } void SetPriority(net::RequestPriority priority, int32_t intra_priority_value) override {} void PauseReadingBodyFromNet() override {} @@ -624,12 +631,30 @@ const std::string extension_id = request_.url.host(); ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_); scoped_refptr<const Extension> extension = - registry->GetExtensionById(extension_id, ExtensionRegistry::EVERYTHING); + registry->GenerateInstalledExtensionsSet()->GetByIDorGUID(extension_id); const ExtensionSet& enabled_extensions = registry->enabled_extensions(); const ProcessMap* process_map = ProcessMap::Get(browser_context_); bool incognito_enabled = extensions::util::IsIncognitoEnabled(extension_id, browser_context_); + // Redirect guid to id. + if (base::FeatureList::IsEnabled( + extensions_features::kExtensionDynamicURLRedirection) && + extension && request_.url.host() == extension->guid()) { + GURL::Replacements replace_host; + replace_host.SetHostStr(extension->id()); + GURL new_url = request_.url.ReplaceComponents(replace_host); + request_.url = new_url; + net::RedirectInfo redirect_info; + redirect_info.new_method = request_.method, + redirect_info.new_url = request_.url; + redirect_info.status_code = net::HTTP_TEMPORARY_REDIRECT; + network::mojom::URLResponseHeadPtr response_head( + ::network::mojom::URLResponseHead::New()); + client_->OnReceiveRedirect(redirect_info, std::move(response_head)); + return; + } + if (!AllowExtensionResourceLoad( request_, request_.destination, static_cast<ui::PageTransition>(request_.transition_type), @@ -965,6 +990,7 @@ const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_EQ(kExtensionScheme, request.url.scheme()); ExtensionURLLoader::CreateAndStart(std::move(loader), std::move(client), request, is_web_view_request_, render_process_id_, extension_info_map_,
diff --git a/extensions/browser/process_manager.cc b/extensions/browser/process_manager.cc index 13b1fcb..4d09fbd 100644 --- a/extensions/browser/process_manager.cc +++ b/extensions/browser/process_manager.cc
@@ -95,6 +95,7 @@ return base::Milliseconds(kEventPageSuspendDelayMs.Get()); } +// TODO(solomonkinard): Take into account GUID-based dynamic URLs. std::string GetExtensionIdForSiteInstance( content::SiteInstance* site_instance) { // <webview> guests always store the ExtensionId in the partition domain.
diff --git a/extensions/common/extension.cc b/extensions/common/extension.cc index f6c71db..ff4412d 100644 --- a/extensions/common/extension.cc +++ b/extensions/common/extension.cc
@@ -284,6 +284,8 @@ } extension->guid_ = base::GUID::GenerateRandomV4(); + extension->dynamic_url_ = Extension::GetBaseURLFromExtensionId( + extension->guid_.AsLowercaseString()); return extension; } @@ -480,6 +482,8 @@ void Extension::SetGUID(const ExtensionGuid& guid) { guid_ = base::GUID::ParseLowercase(guid); DCHECK(guid_.is_valid()); + dynamic_url_ = + Extension::GetBaseURLFromExtensionId(guid_.AsLowercaseString()); } const ExtensionGuid& Extension::guid() const {
diff --git a/extensions/common/extension.h b/extensions/common/extension.h index 6ed829f..313ee0d 100644 --- a/extensions/common/extension.h +++ b/extensions/common/extension.h
@@ -267,7 +267,8 @@ const base::FilePath& path() const { return path_; } const GURL& url() const { return extension_url_; } - const url::Origin& origin() const { return extension_origin_; } + const GURL& dynamic_url() const { return dynamic_url_; } + url::Origin origin() const { return extension_origin_; } mojom::ManifestLocation location() const; const ExtensionId& id() const; const HashedExtensionId& hashed_id() const; @@ -437,6 +438,9 @@ url::Origin extension_origin_; GURL extension_url_; + // The base extension url for the extension using guid. + GURL dynamic_url_; + // The extension's version. base::Version version_;
diff --git a/extensions/common/extension_features.cc b/extensions/common/extension_features.cc index 1c7e095b..40a5341 100644 --- a/extensions/common/extension_features.cc +++ b/extensions/common/extension_features.cc
@@ -86,4 +86,8 @@ const base::Feature kNewExtensionFaviconHandling{ "ExtensionsNewFaviconHandling", base::FEATURE_DISABLED_BY_DEFAULT}; +// Determine if dynamic extension URLs are handled and redirected. +const base::Feature kExtensionDynamicURLRedirection{ + "kExtensionDynamicURLRedirection", base::FEATURE_DISABLED_BY_DEFAULT}; + } // namespace extensions_features
diff --git a/extensions/common/extension_features.h b/extensions/common/extension_features.h index 2261d80e..8b6b326 100644 --- a/extensions/common/extension_features.h +++ b/extensions/common/extension_features.h
@@ -33,6 +33,8 @@ extern const base::Feature kNewExtensionFaviconHandling; +extern const base::Feature kExtensionDynamicURLRedirection; + } // namespace extensions_features #endif // EXTENSIONS_COMMON_EXTENSION_FEATURES_H_
diff --git a/extensions/common/extension_set.cc b/extensions/common/extension_set.cc index b0550097..8bf2917 100644 --- a/extensions/common/extension_set.cc +++ b/extensions/common/extension_set.cc
@@ -12,6 +12,8 @@ namespace extensions { // static +// TODO(solomonkinard): Take GUID-based dynamic URLs in account. Also, +// disambiguate ExtensionHost. ExtensionId ExtensionSet::GetExtensionIdByURL(const GURL& url) { if (url.SchemeIs(kExtensionScheme)) return url.host(); @@ -97,10 +99,11 @@ return extension->id(); } -const Extension* ExtensionSet::GetExtensionOrAppByURL(const GURL& url) const { +const Extension* ExtensionSet::GetExtensionOrAppByURL(const GURL& url, + bool include_guid) const { ExtensionId extension_id = GetExtensionIdByURL(url); if (!extension_id.empty()) - return GetByID(extension_id); + return include_guid ? GetByIDorGUID(extension_id) : GetByID(extension_id); // GetHostedAppByURL already supports filesystem: URLs (via MatchesURL). // TODO(crbug/852162): Add support for blob: URLs in MatchesURL. @@ -144,6 +147,21 @@ return nullptr; } +const Extension* ExtensionSet::GetByGUID(const std::string& guid) const { + for (const auto& extension : extensions_) { + if (extension.second.get()->guid() == guid) + return extension.second.get(); + } + return nullptr; +} + +const Extension* ExtensionSet::GetByIDorGUID( + const std::string& id_or_guid) const { + if (auto* extension = GetByID(id_or_guid)) + return extension; + return GetByGUID(id_or_guid); +} + ExtensionIdSet ExtensionSet::GetIDs() const { ExtensionIdSet ids; for (auto it = extensions_.cbegin(); it != extensions_.cend(); ++it) {
diff --git a/extensions/common/extension_set.h b/extensions/common/extension_set.h index f4c2c32..d1c8e15 100644 --- a/extensions/common/extension_set.h +++ b/extensions/common/extension_set.h
@@ -107,7 +107,8 @@ // NOTE: This can return NULL if called before UpdateExtensions receives // bulk extension data (e.g. if called from // EventBindings::HandleContextCreated) - const Extension* GetExtensionOrAppByURL(const GURL& url) const; + const Extension* GetExtensionOrAppByURL(const GURL& url, + bool include_guid = false) const; // Returns the app specified by the given |url|, if one exists. This will // return NULL if there is no entry with |url|, or if the extension with @@ -126,8 +127,10 @@ // |old_url|. Also returns true if neither URL is in an app. bool InSameExtent(const GURL& old_url, const GURL& new_url) const; - // Look up an Extension object by id. + // Look up an Extension object by id or guid. const Extension* GetByID(const ExtensionId& id) const; + const Extension* GetByGUID(const std::string& guid) const; + const Extension* GetByIDorGUID(const std::string& id_or_guid) const; // Gets the IDs of all extensions in the set. ExtensionIdSet GetIDs() const;
diff --git a/extensions/common/manifest_constants.cc b/extensions/common/manifest_constants.cc index 21996653..aa8c817d 100644 --- a/extensions/common/manifest_constants.cc +++ b/extensions/common/manifest_constants.cc
@@ -158,12 +158,14 @@ const char kWebviewAccessibleResources[] = "accessible_resources"; const char kWebviewName[] = "name"; const char kWebviewPartitions[] = "partitions"; +#if BUILDFLAG(IS_CHROMEOS) +const char kFileSystemProviderCapabilities[] = + "file_system_provider_capabilities"; +#endif #if BUILDFLAG(IS_CHROMEOS_ASH) const char kActionHandlers[] = "action_handlers"; const char kActionHandlerActionKey[] = "action"; const char kActionHandlerEnabledOnLockScreenKey[] = "enabled_on_lock_screen"; -const char kFileSystemProviderCapabilities[] = - "file_system_provider_capabilities"; #endif } // namespace manifest_keys @@ -699,6 +701,15 @@ "Unrecognized property '*' of manifest key '*'."; const char16_t kWebRequestConflictsWithLazyBackground[] = u"The 'webRequest' API cannot be used with event pages."; +#if BUILDFLAG(IS_CHROMEOS) +const char16_t kInvalidFileSystemProviderMissingCapabilities[] = + u"The 'fileSystemProvider' permission requires the " + "'file_system_provider_capabilities' section to be specified in the " + "manifest."; +const char kInvalidFileSystemProviderMissingPermission[] = + "The 'file_system_provider_capabilities' section requires the " + "'fileSystemProvider' permission to be specified in the manifest."; +#endif #if BUILDFLAG(IS_CHROMEOS_ASH) const char kDuplicateActionHandlerFound[] = "'action_handlers' list contains duplicate entries for the action: \"*\"."; @@ -713,13 +724,6 @@ u"Invalid value for 'action_handlers'. Value must be a list of strings or " u"a " "dictionary with 'action' key."; -const char16_t kInvalidFileSystemProviderMissingCapabilities[] = - u"The 'fileSystemProvider' permission requires the " - "'file_system_provider_capabilities' section to be specified in the " - "manifest."; -const char kInvalidFileSystemProviderMissingPermission[] = - "The 'file_system_provider_capabilities' section requires the " - "'fileSystemProvider' permission to be specified in the manifest."; #endif } // namespace manifest_errors
diff --git a/extensions/common/manifest_constants.h b/extensions/common/manifest_constants.h index b9ac0fb5..cf58eb2 100644 --- a/extensions/common/manifest_constants.h +++ b/extensions/common/manifest_constants.h
@@ -160,11 +160,13 @@ extern const char kWebviewName[]; extern const char kWebviewAccessibleResources[]; extern const char kWebviewPartitions[]; +#if BUILDFLAG(IS_CHROMEOS) +extern const char kFileSystemProviderCapabilities[]; +#endif #if BUILDFLAG(IS_CHROMEOS_ASH) extern const char kActionHandlers[]; extern const char kActionHandlerActionKey[]; extern const char kActionHandlerEnabledOnLockScreenKey[]; -extern const char kFileSystemProviderCapabilities[]; #endif } // namespace manifest_keys @@ -461,14 +463,16 @@ extern const char kUnrecognizedManifestKey[]; extern const char kUnrecognizedManifestProperty[]; extern const char16_t kWebRequestConflictsWithLazyBackground[]; +#if BUILDFLAG(IS_CHROMEOS) +extern const char16_t kInvalidFileSystemProviderMissingCapabilities[]; +extern const char kInvalidFileSystemProviderMissingPermission[]; +#endif #if BUILDFLAG(IS_CHROMEOS_ASH) extern const char kDuplicateActionHandlerFound[]; extern const char kIllegalPlugins[]; extern const char16_t kInvalidActionHandlerDictionary[]; extern const char kInvalidActionHandlersActionType[]; extern const char16_t kInvalidActionHandlersType[]; -extern const char16_t kInvalidFileSystemProviderMissingCapabilities[]; -extern const char kInvalidFileSystemProviderMissingPermission[]; #endif } // namespace manifest_errors
diff --git a/extensions/common/manifest_handlers/web_accessible_resources_info.cc b/extensions/common/manifest_handlers/web_accessible_resources_info.cc index 67629ee..e9921fea 100644 --- a/extensions/common/manifest_handlers/web_accessible_resources_info.cc +++ b/extensions/common/manifest_handlers/web_accessible_resources_info.cc
@@ -187,6 +187,7 @@ return true; if (initiator_url.SchemeIs(extensions::kExtensionScheme) && (entry.allow_all_extensions || + extension->id() == initiator_url.host() || base::Contains(entry.extension_ids, initiator_url.host()))) { return true; }
diff --git a/extensions/common/mojom/api_permission_id.mojom b/extensions/common/mojom/api_permission_id.mojom index 7d993eb5..370a7130 100644 --- a/extensions/common/mojom/api_permission_id.mojom +++ b/extensions/common/mojom/api_permission_id.mojom
@@ -261,6 +261,7 @@ kSpeechRecognitionPrivate = 235, kChromeOSDiagnostics = 236, kChromeOSTelemetrySerialNumber = 237, + kSharedStoragePrivate = 238, // Add new entries at the end of the enum and be sure to update the // "ExtensionPermission3" enum in tools/metrics/histograms/enums.xml
diff --git a/extensions/common/permissions/extensions_api_permissions.cc b/extensions/common/permissions/extensions_api_permissions.cc index 2b3c28d..712fb2a8 100644 --- a/extensions/common/permissions/extensions_api_permissions.cc +++ b/extensions/common/permissions/extensions_api_permissions.cc
@@ -54,6 +54,14 @@ APIPermissionInfo::kFlagSupportsContentCapabilities | APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning}, {APIPermissionID::kCrashReportPrivate, "crashReportPrivate"}, + {APIPermissionID::kDeclarativeNetRequest, + declarative_net_request::kDeclarativeNetRequestPermission, + APIPermissionInfo::kFlagCannotBeOptional}, + {APIPermissionID::kDeclarativeNetRequestFeedback, + declarative_net_request::kFeedbackAPIPermission, + APIPermissionInfo::kFlagRequiresManagementUIWarning}, + {APIPermissionID::kDeclarativeNetRequestWithHostAccess, + "declarativeNetRequestWithHostAccess"}, {APIPermissionID::kDeclarativeWebRequest, "declarativeWebRequest"}, {APIPermissionID::kDiagnostics, "diagnostics", APIPermissionInfo::kFlagCannotBeOptional}, @@ -79,9 +87,10 @@ "fileSystem.requestFileSystem"}, {APIPermissionID::kFileSystemRetainEntries, "fileSystem.retainEntries", APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning}, + {APIPermissionID::kFileSystemRequestDownloads, + "fileSystem.requestDownloads"}, {APIPermissionID::kFileSystemWrite, "fileSystem.write", APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning}, - {APIPermissionID::kHid, "hid"}, {APIPermissionID::kImeWindowEnabled, "app.window.ime"}, {APIPermissionID::kOverrideEscFullscreen, @@ -118,6 +127,7 @@ APIPermissionInfo::kFlagRequiresManagementUIWarning}, {APIPermissionID::kSerial, "serial", APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning}, + {APIPermissionID::kSharedStoragePrivate, "sharedStoragePrivate"}, {APIPermissionID::kSocket, "socket", APIPermissionInfo::kFlagCannotBeOptional | APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning, @@ -152,20 +162,10 @@ APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning}, {APIPermissionID::kWebRequest, "webRequest"}, {APIPermissionID::kWebRequestBlocking, "webRequestBlocking"}, - {APIPermissionID::kDeclarativeNetRequest, - declarative_net_request::kDeclarativeNetRequestPermission, - APIPermissionInfo::kFlagCannotBeOptional}, {APIPermissionID::kWebView, "webview", APIPermissionInfo::kFlagCannotBeOptional}, {APIPermissionID::kWindowShape, "app.window.shape"}, - {APIPermissionID::kFileSystemRequestDownloads, - "fileSystem.requestDownloads"}, - {APIPermissionID::kDeclarativeNetRequestFeedback, - declarative_net_request::kFeedbackAPIPermission, - APIPermissionInfo::kFlagRequiresManagementUIWarning}, {APIPermissionID::kWmDesksPrivate, "wmDesksPrivate"}, - {APIPermissionID::kDeclarativeNetRequestWithHostAccess, - "declarativeNetRequestWithHostAccess"}, }; } // namespace
diff --git a/extensions/renderer/renderer_extension_registry.cc b/extensions/renderer/renderer_extension_registry.cc index 0620b41..e22bb19 100644 --- a/extensions/renderer/renderer_extension_registry.cc +++ b/extensions/renderer/renderer_extension_registry.cc
@@ -75,9 +75,10 @@ } const Extension* RendererExtensionRegistry::GetExtensionOrAppByURL( - const GURL& url) const { + const GURL& url, + bool include_guid) const { base::AutoLock lock(lock_); - return extensions_.GetExtensionOrAppByURL(url); + return extensions_.GetExtensionOrAppByURL(url, include_guid); } const Extension* RendererExtensionRegistry::GetHostedAppByURL(
diff --git a/extensions/renderer/renderer_extension_registry.h b/extensions/renderer/renderer_extension_registry.h index 64028af..c822206 100644 --- a/extensions/renderer/renderer_extension_registry.h +++ b/extensions/renderer/renderer_extension_registry.h
@@ -47,10 +47,12 @@ // Forwards to the ExtensionSet methods by the same name. bool Contains(const std::string& id) const; + bool ContainsGUID(const std::string& guid) const; bool Insert(const scoped_refptr<const Extension>& extension); bool Remove(const std::string& id); std::string GetExtensionOrAppIDByURL(const GURL& url) const; - const Extension* GetExtensionOrAppByURL(const GURL& url) const; + const Extension* GetExtensionOrAppByURL(const GURL& url, + bool include_guid = false) const; const Extension* GetHostedAppByURL(const GURL& url) const; const Extension* GetByID(const std::string& id) const; ExtensionIdSet GetIDs() const;
diff --git a/gpu/ipc/service/context_url.cc b/gpu/ipc/service/context_url.cc index 9fb4a76..784ea032 100644 --- a/gpu/ipc/service/context_url.cc +++ b/gpu/ipc/service/context_url.cc
@@ -13,15 +13,15 @@ // static void ContextUrl::SetActiveUrl(const gpu::ContextUrl& active_url) { - bool is_skia_renderer = active_url.url() == "chrome://gpu/SkiaRenderer"; + bool is_chrome = active_url.url().scheme() == "chrome"; { - static crash_reporter::CrashKeyString<8> crash_key( - "gpu-context-is-skia-renderer"); - crash_key.Set(is_skia_renderer ? "true" : "false"); + static crash_reporter::CrashKeyString<128> crash_key( + "gpu-url-chunk-chrome"); + crash_key.Set(is_chrome ? active_url.url().possibly_invalid_spec() : ""); } - if (is_skia_renderer) + if (is_chrome) return; // Skip setting crash key when URL hash hasn't changed.
diff --git a/infra/config/generated/builders/ci/GPU Linux Builder/properties.json b/infra/config/generated/builders/ci/GPU Linux Builder/properties.json index 3ab53a548..91ad6f8 100644 --- a/infra/config/generated/builders/ci/GPU Linux Builder/properties.json +++ b/infra/config/generated/builders/ci/GPU Linux Builder/properties.json
@@ -107,10 +107,6 @@ "group": "tryserver.chromium.linux" }, { - "builder": "linux-rel-orchestrator-pool", - "group": "tryserver.chromium.linux" - }, - { "builder": "linux-rel-warmed", "group": "tryserver.chromium.linux" }
diff --git a/infra/config/generated/builders/ci/Linux Builder/properties.json b/infra/config/generated/builders/ci/Linux Builder/properties.json index 176ac3a..d977b3dd 100644 --- a/infra/config/generated/builders/ci/Linux Builder/properties.json +++ b/infra/config/generated/builders/ci/Linux Builder/properties.json
@@ -107,10 +107,6 @@ "group": "tryserver.chromium.linux" }, { - "builder": "linux-rel-orchestrator-pool", - "group": "tryserver.chromium.linux" - }, - { "builder": "linux-rel-warmed", "group": "tryserver.chromium.linux" },
diff --git "a/infra/config/generated/builders/ci/Linux Release \050NVIDIA\051/properties.json" "b/infra/config/generated/builders/ci/Linux Release \050NVIDIA\051/properties.json" index 74625d9d..1f6393a 100644 --- "a/infra/config/generated/builders/ci/Linux Release \050NVIDIA\051/properties.json" +++ "b/infra/config/generated/builders/ci/Linux Release \050NVIDIA\051/properties.json"
@@ -100,10 +100,6 @@ "group": "tryserver.chromium.linux" }, { - "builder": "linux-rel-orchestrator-pool", - "group": "tryserver.chromium.linux" - }, - { "builder": "linux-rel-warmed", "group": "tryserver.chromium.linux" }
diff --git a/infra/config/generated/builders/ci/Linux Tests/properties.json b/infra/config/generated/builders/ci/Linux Tests/properties.json index d5cab6c..8287dfc5 100644 --- a/infra/config/generated/builders/ci/Linux Tests/properties.json +++ b/infra/config/generated/builders/ci/Linux Tests/properties.json
@@ -100,10 +100,6 @@ "group": "tryserver.chromium.linux" }, { - "builder": "linux-rel-orchestrator-pool", - "group": "tryserver.chromium.linux" - }, - { "builder": "linux-rel-warmed", "group": "tryserver.chromium.linux" },
diff --git a/infra/config/generated/builders/try/linux-rel-orchestrator-pool-compilator/properties.json b/infra/config/generated/builders/try/linux-rel-orchestrator-pool-compilator/properties.json deleted file mode 100644 index 4a5b8329..0000000 --- a/infra/config/generated/builders/try/linux-rel-orchestrator-pool-compilator/properties.json +++ /dev/null
@@ -1,180 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "GPU Linux Builder", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-gpu-archive", - "builder_group": "chromium.gpu", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "use_clang_coverage", - "enable_reclient" - ], - "config": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", - "builder": "Linux Builder", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-linux-archive", - "builder_group": "chromium.linux", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "use_clang_coverage", - "enable_reclient" - ], - "config": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", - "builder": "Linux Release (NVIDIA)", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-gpu-archive", - "builder_group": "chromium.gpu", - "execution_mode": "TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "use_clang_coverage" - ], - "config": "chromium" - }, - "parent": { - "bucket": "ci", - "builder": "GPU Linux Builder", - "project": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", - "builder": "Linux Tests", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-linux-archive", - "builder_group": "chromium.linux", - "execution_mode": "TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "use_clang_coverage" - ], - "config": "chromium" - }, - "parent": { - "bucket": "ci", - "builder": "Linux Builder", - "project": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "GPU Linux Builder", - "project": "chromium" - }, - { - "bucket": "ci", - "builder": "Linux Builder", - "project": "chromium" - } - ], - "builder_ids_in_scope_for_testing": [ - { - "bucket": "ci", - "builder": "Linux Release (NVIDIA)", - "project": "chromium" - }, - { - "bucket": "ci", - "builder": "Linux Tests", - "project": "chromium" - } - ], - "rts_config": { - "condition": "QUICK_RUN_ONLY" - } - } - }, - "$build/code_coverage": { - "coverage_test_types": [ - "unit", - "overall" - ], - "use_clang_coverage": true - }, - "$build/goma": { - "enable_ats": true, - "jobs": 150, - "rpc_extra_params": "?prod", - "server_host": "goma.chromium.org", - "use_luci_auth": true - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.linux", - "orchestrator": { - "builder_group": "tryserver.chromium.linux", - "builder_name": "linux-rel-orchestrator-pool" - }, - "recipe": "chromium/compilator" -} \ No newline at end of file
diff --git a/infra/config/generated/builders/try/linux-rel-orchestrator-pool/properties.json b/infra/config/generated/builders/try/linux-rel-orchestrator-pool/properties.json deleted file mode 100644 index 60a5155..0000000 --- a/infra/config/generated/builders/try/linux-rel-orchestrator-pool/properties.json +++ /dev/null
@@ -1,173 +0,0 @@ -{ - "$build/chromium_orchestrator": { - "compilator": "linux-rel-orchestrator-pool-compilator", - "compilator_watcher_git_revision": "7809a690bbd935bcb3b4d922e24cabe168aaabc8" - }, - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "GPU Linux Builder", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-gpu-archive", - "builder_group": "chromium.gpu", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "use_clang_coverage", - "enable_reclient" - ], - "config": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", - "builder": "Linux Builder", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-linux-archive", - "builder_group": "chromium.linux", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "use_clang_coverage", - "enable_reclient" - ], - "config": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", - "builder": "Linux Release (NVIDIA)", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-gpu-archive", - "builder_group": "chromium.gpu", - "execution_mode": "TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "use_clang_coverage" - ], - "config": "chromium" - }, - "parent": { - "bucket": "ci", - "builder": "GPU Linux Builder", - "project": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", - "builder": "Linux Tests", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-linux-archive", - "builder_group": "chromium.linux", - "execution_mode": "TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium", - "target_bits": 64 - }, - "legacy_gclient_config": { - "apply_configs": [ - "use_clang_coverage" - ], - "config": "chromium" - }, - "parent": { - "bucket": "ci", - "builder": "Linux Builder", - "project": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "GPU Linux Builder", - "project": "chromium" - }, - { - "bucket": "ci", - "builder": "Linux Builder", - "project": "chromium" - } - ], - "builder_ids_in_scope_for_testing": [ - { - "bucket": "ci", - "builder": "Linux Release (NVIDIA)", - "project": "chromium" - }, - { - "bucket": "ci", - "builder": "Linux Tests", - "project": "chromium" - } - ], - "rts_config": { - "condition": "QUICK_RUN_ONLY" - } - } - }, - "$build/code_coverage": { - "coverage_test_types": [ - "unit", - "overall" - ], - "use_clang_coverage": true - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.linux", - "recipe": "chromium/orchestrator" -} \ No newline at end of file
diff --git a/infra/config/generated/cq-builders.md b/infra/config/generated/cq-builders.md index b62d60b..4c43325 100644 --- a/infra/config/generated/cq-builders.md +++ b/infra/config/generated/cq-builders.md
@@ -499,9 +499,6 @@ * [linux-rel-ml](https://ci.chromium.org/p/chromium/builders/try/linux-rel-ml) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""linux-rel-ml"")) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+""linux-rel-ml"")) * Experiment percentage: 5.0 -* [linux-rel-orchestrator-pool](https://ci.chromium.org/p/chromium/builders/try/linux-rel-orchestrator-pool) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""linux-rel-orchestrator-pool"")) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+""linux-rel-orchestrator-pool"")) - * Experiment percentage: 10.0 - * [mac11-arm64-rel](https://ci.chromium.org/p/chromium/builders/try/mac11-arm64-rel) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""mac11-arm64-rel"")) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+""mac11-arm64-rel"")) * Experiment percentage: 100.0
diff --git a/infra/config/generated/luci/commit-queue.cfg b/infra/config/generated/luci/commit-queue.cfg index b74dcbe..7d5707c 100644 --- a/infra/config/generated/luci/commit-queue.cfg +++ b/infra/config/generated/luci/commit-queue.cfg
@@ -1416,17 +1416,6 @@ location_regexp_exclude: ".+/[+]/infra/config/.+" } builders { - name: "chromium/try/linux-rel-orchestrator-pool" - experiment_percentage: 10 - location_regexp: ".*" - location_regexp_exclude: ".+/[+]/docs/.+" - location_regexp_exclude: ".+/[+]/infra/config/.+" - } - builders { - name: "chromium/try/linux-rel-orchestrator-pool-compilator" - includable_only: true - } - builders { name: "chromium/try/linux-rel-warmed" includable_only: true }
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index ae1be59..e8b94f2 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -30918,7 +30918,7 @@ swarming_host: "chromium-swarm.appspot.com" dimensions: "builder:ios16-beta-simulator" dimensions: "cpu:x86-64" - dimensions: "os:Mac-11" + dimensions: "os:Mac-11|Mac-12" dimensions: "pool:luci.chromium.ci" exe { cipd_package: "infra/chromium/bootstrapper/${platform}" @@ -30999,7 +30999,7 @@ swarming_host: "chromium-swarm.appspot.com" dimensions: "builder:ios16-sdk-simulator" dimensions: "cpu:x86-64" - dimensions: "os:Mac-11" + dimensions: "os:Mac-11|Mac-12" dimensions: "pool:luci.chromium.ci" exe { cipd_package: "infra/chromium/bootstrapper/${platform}" @@ -61204,7 +61204,7 @@ swarming_host: "chromium-swarm.appspot.com" dimensions: "builder:ios16-beta-simulator" dimensions: "cpu:x86-64" - dimensions: "os:Mac-11" + dimensions: "os:Mac-11|Mac-12" dimensions: "pool:luci.chromium.try" exe { cipd_package: "infra/chromium/bootstrapper/${platform}" @@ -61296,7 +61296,7 @@ swarming_host: "chromium-swarm.appspot.com" dimensions: "builder:ios16-sdk-simulator" dimensions: "cpu:x86-64" - dimensions: "os:Mac-11" + dimensions: "os:Mac-11|Mac-12" dimensions: "pool:luci.chromium.try" exe { cipd_package: "infra/chromium/bootstrapper/${platform}" @@ -65844,190 +65844,6 @@ } } builders { - name: "linux-rel-orchestrator-pool" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "cores:2" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.try.orchestrator" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/linux-rel-orchestrator-pool/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.linux",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium/orchestrator"' - '}' - execution_timeout_secs: 14400 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-orchestrator@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - experiments { - key: "remove_src_checkout_experiment" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://[^/]*blink_web_tests/.+" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-rel-orchestrator-pool-compilator\">linux-rel-orchestrator-pool-compilator</a>." - } - builders { - name: "linux-rel-orchestrator-pool-compilator" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builder:linux-rel-orchestrator-pool-compilator" - dimensions: "cores:16" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.try" - dimensions: "ssd:1" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/linux-rel-orchestrator-pool-compilator/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.linux",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium/compilator"' - '}' - execution_timeout_secs: 14400 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://[^/]*blink_web_tests/.+" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - description_html: "This is the compilator half of an orchestrator + compilator pair of builders. The orchestrator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-rel-orchestrator-pool\">linux-rel-orchestrator-pool</a>." - } - builders { name: "linux-rel-warmed" swarming_host: "chromium-swarm.appspot.com" dimensions: "builder:linux-rel-warmed"
diff --git a/infra/config/generated/luci/luci-milo.cfg b/infra/config/generated/luci/luci-milo.cfg index 238366a..85d04372 100644 --- a/infra/config/generated/luci/luci-milo.cfg +++ b/infra/config/generated/luci/luci-milo.cfg
@@ -16203,12 +16203,6 @@ name: "buildbucket/luci.chromium.try/linux-rel-ml" } builders { - name: "buildbucket/luci.chromium.try/linux-rel-orchestrator-pool" - } - builders { - name: "buildbucket/luci.chromium.try/linux-rel-orchestrator-pool-compilator" - } - builders { name: "buildbucket/luci.chromium.try/linux-rel-warmed" } builders { @@ -17238,12 +17232,6 @@ name: "buildbucket/luci.chromium.try/linux-rel-ml" } builders { - name: "buildbucket/luci.chromium.try/linux-rel-orchestrator-pool" - } - builders { - name: "buildbucket/luci.chromium.try/linux-rel-orchestrator-pool-compilator" - } - builders { name: "buildbucket/luci.chromium.try/linux-rel-warmed" } builders {
diff --git a/infra/config/subprojects/chromium/ci/chromium.fyi.star b/infra/config/subprojects/chromium/ci/chromium.fyi.star index 65f8c36..2f163c8 100644 --- a/infra/config/subprojects/chromium/ci/chromium.fyi.star +++ b/infra/config/subprojects/chromium/ci/chromium.fyi.star
@@ -1463,7 +1463,7 @@ category = "iOS|iOS16", short_name = "ios16", ), - os = os.MAC_11, + os = os.MAC_DEFAULT, schedule = "0 0,4,8,12,16,20 * * *", triggered_by = [], ) @@ -1490,7 +1490,7 @@ category = "iOS|iOS16", short_name = "sdk16", ), - os = os.MAC_11, + os = os.MAC_DEFAULT, schedule = "0 2,6,10,14,18,22 * * *", triggered_by = [], )
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star index 2698dfc..25ba279 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star
@@ -264,36 +264,6 @@ main_list_view = "try", ) -try_.orchestrator_builder( - name = "linux-rel-orchestrator-pool", - builderless = None, - compilator = "linux-rel-orchestrator-pool-compilator", - mirrors = [ - "ci/Linux Builder", - "ci/Linux Tests", - "ci/GPU Linux Builder", - "ci/Linux Release (NVIDIA)", - ], - try_settings = builder_config.try_settings( - rts_config = builder_config.rts_config( - condition = builder_config.rts_condition.QUICK_RUN_ONLY, - ), - ), - use_clang_coverage = True, - coverage_test_types = ["unit", "overall"], - tryjob = try_.job( - experiment_percentage = 10, - ), - experiments = { - "remove_src_checkout_experiment": 100, - }, - pool = "luci.chromium.try.orchestrator", -) - -try_.compilator_builder( - name = "linux-rel-orchestrator-pool-compilator", -) - # crbug.com/1270571: Experimental bot to test pre-warming try_.orchestrator_builder( name = "linux-rel-warmed",
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star b/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star index a313c4e..f4f27179 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star
@@ -370,7 +370,7 @@ ios_builder( name = "ios16-beta-simulator", - os = os.MAC_11, + os = os.MAC_DEFAULT, mirrors = [ "ci/ios16-beta-simulator", ], @@ -378,7 +378,7 @@ ios_builder( name = "ios16-sdk-simulator", - os = os.MAC_11, + os = os.MAC_DEFAULT, mirrors = [ "ci/ios16-sdk-simulator", ],
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index 930cdd7..8b6ee7c 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -944,6 +944,10 @@ {"enable-feed-ablation", flag_descriptions::kEnableFeedAblationName, flag_descriptions::kEnableFeedAblationDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(kEnableFeedAblation)}, + {"content-suggestions-ui-module-refresh", + flag_descriptions::kContentSuggestionsUIModuleRefreshName, + flag_descriptions::kContentSuggestionsUIModuleRefreshDescription, + flags_ui::kOsIos, FEATURE_VALUE_TYPE(kContentSuggestionsUIModuleRefresh)}, }; bool SkipConditionalFeatureEntry(const flags_ui::FeatureEntry& entry) {
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index 53005641d..b495ad7 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -129,6 +129,12 @@ "When enabled, the Content Suggestions header will be logically moved to " "the Discover feed ScrollView"; +const char kContentSuggestionsUIModuleRefreshName[] = + "Content Suggestions UI Module Refresh"; +const char kContentSuggestionsUIModuleRefreshDescription[] = + "When enabled, the Content Suggestions will be redesigned to be contained " + "into distinct modules."; + const char kContentSuggestionsUIViewControllerMigrationName[] = "Content Suggestions UIViewController migration"; const char kContentSuggestionsUIViewControllerMigrationDescription[] =
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 22c59d3..e032694 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -108,6 +108,11 @@ extern const char kContentSuggestionsHeaderMigrationName[]; extern const char kContentSuggestionsHeaderMigrationDescription[]; +// Title and description for the flag that updates the Content Suggestions to a +// new module design. +extern const char kContentSuggestionsUIModuleRefreshName[]; +extern const char kContentSuggestionsUIModuleRefreshDescription[]; + // Title and description for the flag that moves the Content Suggestions to a // UIViewController. extern const char kContentSuggestionsUIViewControllerMigrationName[];
diff --git a/ios/chrome/browser/send_tab_to_self/send_tab_to_self_browser_agent.mm b/ios/chrome/browser/send_tab_to_self/send_tab_to_self_browser_agent.mm index 574c9be..5e1554a 100644 --- a/ios/chrome/browser/send_tab_to_self/send_tab_to_self_browser_agent.mm +++ b/ios/chrome/browser/send_tab_to_self/send_tab_to_self_browser_agent.mm
@@ -26,8 +26,6 @@ #include "ios/chrome/browser/send_tab_to_self/ios_send_tab_to_self_infobar_delegate.h" #include "ios/chrome/browser/sync/send_tab_to_self_sync_service_factory.h" #import "ios/chrome/browser/web_state_list/web_state_list.h" -#import "ios/web/public/navigation/navigation_item.h" -#import "ios/web/public/navigation/navigation_manager.h" #import "ios/web/public/web_state.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -54,17 +52,13 @@ return; } - web::NavigationItem* current_item = - web_state->GetNavigationManager()->GetLastCommittedItem(); - if (!current_item) { + GURL url_to_share = web_state->GetLastCommittedURL(); + if (url_to_share.is_empty()) { return; } - GURL url = current_item->GetURL(); - std::string title = base::UTF16ToUTF8(current_item->GetTitle()); - std::string target_device = base::SysNSStringToUTF8(target_device_id); - - model_->AddEntry(url, title, target_device); + model_->AddEntry(url_to_share, base::UTF16ToUTF8(web_state->GetTitle()), + base::SysNSStringToUTF8(target_device_id)); } void SendTabToSelfBrowserAgent::SendTabToSelfModelLoaded() {
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h index 06110ed..6f7e000 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h
@@ -25,6 +25,9 @@ // Feature to move the Content Suggestions ViewController to a UIViewController. extern const base::Feature kContentSuggestionsUIViewControllerMigration; +// Feature to section the Content Suggestions into modules. +extern const base::Feature kContentSuggestionsUIModuleRefresh; + // A parameter to indicate whether the native UI is enabled for the discover // feed. extern const char kDiscoverFeedIsNativeUIEnabled[]; @@ -45,4 +48,7 @@ // enabled. bool IsContentSuggestionsUIViewControllerMigrationEnabled(); +// Whether the Content Suggestions UI Module Refresh feature is enabled. +bool IsContentSuggestionsUIModuleRefreshEnabled(); + #endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_FEATURE_H_
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm index 891146d..5cb2131 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm
@@ -28,6 +28,10 @@ "ContentSuggestionsUIViewControllerMigration", base::FEATURE_DISABLED_BY_DEFAULT}; +// Feature disabled by default. +const base::Feature kContentSuggestionsUIModuleRefresh{ + "ContentSuggestionsUIModuleRefresh", base::FEATURE_DISABLED_BY_DEFAULT}; + // A parameter to indicate whether the native UI is enabled for the discover // feed. const char kDiscoverFeedIsNativeUIEnabled[] = "DiscoverFeedIsNativeUIEnabled"; @@ -52,3 +56,7 @@ return base::FeatureList::IsEnabled( kContentSuggestionsUIViewControllerMigration); } + +bool IsContentSuggestionsUIModuleRefreshEnabled() { + return base::FeatureList::IsEnabled(kContentSuggestionsUIModuleRefresh); +}
diff --git a/ios/chrome/browser/ui/webui/policy/policy_ui.mm b/ios/chrome/browser/ui/webui/policy/policy_ui.mm index 22910da..6e096bc 100644 --- a/ios/chrome/browser/ui/webui/policy/policy_ui.mm +++ b/ios/chrome/browser/ui/webui/policy/policy_ui.mm
@@ -90,7 +90,14 @@ source->AddResourcePath("policy.css", IDR_POLICY_CSS); source->AddResourcePath("policy_base.js", IDR_POLICY_BASE_JS); source->AddResourcePath("policy.js", IDR_POLICY_JS); + source->AddResourcePath("policy_conflict.js", IDR_POLICY_POLICY_CONFLICT_JS); + source->AddResourcePath("policy_row.js", IDR_POLICY_POLICY_ROW_JS); + source->AddResourcePath("policy_precedence_row.js", + IDR_POLICY_POLICY_PRECEDENCE_ROW_JS); + source->AddResourcePath("policy_table.js", IDR_POLICY_POLICY_TABLE_JS); + source->AddResourcePath("status_box.js", IDR_POLICY_STATUS_BOX_JS); source->SetDefaultResource(IDR_POLICY_HTML); + source->EnableReplaceI18nInJS(); return source; }
diff --git a/media/base/media_switches.cc b/media/base/media_switches.cc index ee4643e1..58c2ca6 100644 --- a/media/base/media_switches.cc +++ b/media/base/media_switches.cc
@@ -571,7 +571,7 @@ const base::Feature kVp9kSVCHWDecoding { "Vp9kSVCHWDecoding", // TODO(crbug.com/1325698): Remove defined(ARCH_CPU_X86_FAMILY) once this is -// enabled by default on ChromeOS AMD devices. +// enabled by default on ChromeOS ARM devices. #if defined(ARCH_CPU_X86_FAMILY) && BUILDFLAG(IS_CHROMEOS) base::FEATURE_ENABLED_BY_DEFAULT #else
diff --git a/net/base/host_mapping_rules.cc b/net/base/host_mapping_rules.cc index f77d064..de2fd4d 100644 --- a/net/base/host_mapping_rules.cc +++ b/net/base/host_mapping_rules.cc
@@ -110,7 +110,8 @@ base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); // Test for EXCLUSION rule. - if (parts.size() == 2 && base::LowerCaseEqualsASCII(parts[0], "exclude")) { + if (parts.size() == 2 && + base::EqualsCaseInsensitiveASCII(parts[0], "exclude")) { ExclusionRule rule; rule.hostname_pattern = base::ToLowerASCII(parts[1]); exclusion_rules_.push_back(rule); @@ -118,7 +119,7 @@ } // Test for MAP rule. - if (parts.size() == 3 && base::LowerCaseEqualsASCII(parts[0], "map")) { + if (parts.size() == 3 && base::EqualsCaseInsensitiveASCII(parts[0], "map")) { MapRule rule; rule.hostname_pattern = base::ToLowerASCII(parts[1]);
diff --git a/net/base/proxy_string_util.cc b/net/base/proxy_string_util.cc index 56cecfc..4cda416 100644 --- a/net/base/proxy_string_util.cc +++ b/net/base/proxy_string_util.cc
@@ -23,23 +23,23 @@ // This mapping is case-insensitive. If no type could be matched // returns SCHEME_INVALID. ProxyServer::Scheme GetSchemeFromPacTypeInternal(base::StringPiece type) { - if (base::LowerCaseEqualsASCII(type, "proxy")) + if (base::EqualsCaseInsensitiveASCII(type, "proxy")) return ProxyServer::SCHEME_HTTP; - if (base::LowerCaseEqualsASCII(type, "socks")) { + if (base::EqualsCaseInsensitiveASCII(type, "socks")) { // Default to v4 for compatibility. This is because the SOCKS4 vs SOCKS5 // notation didn't originally exist, so if a client returns SOCKS they // really meant SOCKS4. return ProxyServer::SCHEME_SOCKS4; } - if (base::LowerCaseEqualsASCII(type, "socks4")) + if (base::EqualsCaseInsensitiveASCII(type, "socks4")) return ProxyServer::SCHEME_SOCKS4; - if (base::LowerCaseEqualsASCII(type, "socks5")) + if (base::EqualsCaseInsensitiveASCII(type, "socks5")) return ProxyServer::SCHEME_SOCKS5; - if (base::LowerCaseEqualsASCII(type, "direct")) + if (base::EqualsCaseInsensitiveASCII(type, "direct")) return ProxyServer::SCHEME_DIRECT; - if (base::LowerCaseEqualsASCII(type, "https")) + if (base::EqualsCaseInsensitiveASCII(type, "https")) return ProxyServer::SCHEME_HTTPS; - if (base::LowerCaseEqualsASCII(type, "quic")) + if (base::EqualsCaseInsensitiveASCII(type, "quic")) return ProxyServer::SCHEME_QUIC; return ProxyServer::SCHEME_INVALID; @@ -207,19 +207,19 @@ } ProxyServer::Scheme GetSchemeFromUriScheme(base::StringPiece scheme) { - if (base::LowerCaseEqualsASCII(scheme, "http")) + if (base::EqualsCaseInsensitiveASCII(scheme, "http")) return ProxyServer::SCHEME_HTTP; - if (base::LowerCaseEqualsASCII(scheme, "socks4")) + if (base::EqualsCaseInsensitiveASCII(scheme, "socks4")) return ProxyServer::SCHEME_SOCKS4; - if (base::LowerCaseEqualsASCII(scheme, "socks")) + if (base::EqualsCaseInsensitiveASCII(scheme, "socks")) return ProxyServer::SCHEME_SOCKS5; - if (base::LowerCaseEqualsASCII(scheme, "socks5")) + if (base::EqualsCaseInsensitiveASCII(scheme, "socks5")) return ProxyServer::SCHEME_SOCKS5; - if (base::LowerCaseEqualsASCII(scheme, "direct")) + if (base::EqualsCaseInsensitiveASCII(scheme, "direct")) return ProxyServer::SCHEME_DIRECT; - if (base::LowerCaseEqualsASCII(scheme, "https")) + if (base::EqualsCaseInsensitiveASCII(scheme, "https")) return ProxyServer::SCHEME_HTTPS; - if (base::LowerCaseEqualsASCII(scheme, "quic")) + if (base::EqualsCaseInsensitiveASCII(scheme, "quic")) return ProxyServer::SCHEME_QUIC; return ProxyServer::SCHEME_INVALID; }
diff --git a/net/filter/filter_source_stream.cc b/net/filter/filter_source_stream.cc index 6ed1b1d..6691053f 100644 --- a/net/filter/filter_source_stream.cc +++ b/net/filter/filter_source_stream.cc
@@ -82,12 +82,12 @@ const std::string& encoding) { if (encoding.empty()) { return TYPE_NONE; - } else if (base::LowerCaseEqualsASCII(encoding, kBrotli)) { + } else if (base::EqualsCaseInsensitiveASCII(encoding, kBrotli)) { return TYPE_BROTLI; - } else if (base::LowerCaseEqualsASCII(encoding, kDeflate)) { + } else if (base::EqualsCaseInsensitiveASCII(encoding, kDeflate)) { return TYPE_DEFLATE; - } else if (base::LowerCaseEqualsASCII(encoding, kGZip) || - base::LowerCaseEqualsASCII(encoding, kXGZip)) { + } else if (base::EqualsCaseInsensitiveASCII(encoding, kGZip) || + base::EqualsCaseInsensitiveASCII(encoding, kXGZip)) { return TYPE_GZIP; } else { return TYPE_UNKNOWN;
diff --git a/net/http/bidirectional_stream.cc b/net/http/bidirectional_stream.cc index cdd0aa3..3d7f3b5 100644 --- a/net/http/bidirectional_stream.cc +++ b/net/http/bidirectional_stream.cc
@@ -39,23 +39,22 @@ base::Value NetLogHeadersParams(const spdy::Http2HeaderBlock* headers, NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("headers", - ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); - return dict; + base::Value::Dict dict; + dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); + return base::Value(std::move(dict)); } base::Value NetLogParams(const GURL& url, const std::string& method, const HttpRequestHeaders* headers, NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("url", url.possibly_invalid_spec()); - dict.SetStringKey("method", method); - std::string empty; - base::Value headers_param(headers->NetLogParams(empty, capture_mode)); - dict.SetKey("headers", std::move(headers_param)); - return dict; + base::Value::Dict dict; + dict.Set("url", url.possibly_invalid_spec()); + dict.Set("method", method); + base::Value headers_param( + headers->NetLogParams(/*request_line=*/std::string(), capture_mode)); + dict.Set("headers", std::move(headers_param)); + return base::Value(std::move(dict)); } } // namespace
diff --git a/net/http/http_network_session.cc b/net/http/http_network_session.cc index fd3c01b..b51d9d3c 100644 --- a/net/http/http_network_session.cc +++ b/net/http/http_network_session.cc
@@ -285,74 +285,74 @@ } base::Value HttpNetworkSession::QuicInfoToValue() const { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("sessions", - base::Value::FromUniquePtrValue( - quic_stream_factory_.QuicStreamFactoryInfoToValue())); - dict.SetBoolKey("quic_enabled", IsQuicEnabled()); + base::Value::Dict dict; + dict.Set("sessions", quic_stream_factory_.QuicStreamFactoryInfoToValue()); + dict.Set("quic_enabled", IsQuicEnabled()); const QuicParams* quic_params = context_.quic_context->params(); - base::Value connection_options(base::Value::Type::LIST); + base::Value::List connection_options; for (const auto& option : quic_params->connection_options) connection_options.Append(quic::QuicTagToString(option)); - dict.SetKey("connection_options", std::move(connection_options)); + dict.Set("connection_options", std::move(connection_options)); - base::Value supported_versions(base::Value::Type::LIST); + base::Value::List supported_versions; for (const auto& version : quic_params->supported_versions) supported_versions.Append(ParsedQuicVersionToString(version)); - dict.SetKey("supported_versions", std::move(supported_versions)); + dict.Set("supported_versions", std::move(supported_versions)); - base::Value origins_to_force_quic_on(base::Value::Type::LIST); + base::Value::List origins_to_force_quic_on; for (const auto& origin : quic_params->origins_to_force_quic_on) origins_to_force_quic_on.Append(origin.ToString()); - dict.SetKey("origins_to_force_quic_on", std::move(origins_to_force_quic_on)); + dict.Set("origins_to_force_quic_on", std::move(origins_to_force_quic_on)); - dict.SetIntKey("max_packet_length", quic_params->max_packet_length); - dict.SetIntKey("max_server_configs_stored_in_properties", - quic_params->max_server_configs_stored_in_properties); - dict.SetIntKey("idle_connection_timeout_seconds", - quic_params->idle_connection_timeout.InSeconds()); - dict.SetIntKey("reduced_ping_timeout_seconds", - quic_params->reduced_ping_timeout.InSeconds()); - dict.SetBoolKey("retry_without_alt_svc_on_quic_errors", - quic_params->retry_without_alt_svc_on_quic_errors); - dict.SetBoolKey("disable_bidirectional_streams", - quic_params->disable_bidirectional_streams); - dict.SetBoolKey("close_sessions_on_ip_change", - quic_params->close_sessions_on_ip_change); - dict.SetBoolKey("goaway_sessions_on_ip_change", - quic_params->goaway_sessions_on_ip_change); - dict.SetBoolKey("migrate_sessions_on_network_change_v2", - quic_params->migrate_sessions_on_network_change_v2); - dict.SetBoolKey("migrate_sessions_early_v2", - quic_params->migrate_sessions_early_v2); - dict.SetIntKey("retransmittable_on_wire_timeout_milliseconds", - quic_params->retransmittable_on_wire_timeout.InMilliseconds()); - dict.SetBoolKey("retry_on_alternate_network_before_handshake", - quic_params->retry_on_alternate_network_before_handshake); - dict.SetBoolKey("migrate_idle_sessions", quic_params->migrate_idle_sessions); - dict.SetIntKey("idle_session_migration_period_seconds", - quic_params->idle_session_migration_period.InSeconds()); - dict.SetIntKey("max_time_on_non_default_network_seconds", - quic_params->max_time_on_non_default_network.InSeconds()); - dict.SetIntKey( - "max_num_migrations_to_non_default_network_on_write_error", - quic_params->max_migrations_to_non_default_network_on_write_error); - dict.SetIntKey( + dict.Set("max_packet_length", + static_cast<int>(quic_params->max_packet_length)); + dict.Set( + "max_server_configs_stored_in_properties", + static_cast<int>(quic_params->max_server_configs_stored_in_properties)); + dict.Set("idle_connection_timeout_seconds", + static_cast<int>(quic_params->idle_connection_timeout.InSeconds())); + dict.Set("reduced_ping_timeout_seconds", + static_cast<int>(quic_params->reduced_ping_timeout.InSeconds())); + dict.Set("retry_without_alt_svc_on_quic_errors", + quic_params->retry_without_alt_svc_on_quic_errors); + dict.Set("disable_bidirectional_streams", + quic_params->disable_bidirectional_streams); + dict.Set("close_sessions_on_ip_change", + quic_params->close_sessions_on_ip_change); + dict.Set("goaway_sessions_on_ip_change", + quic_params->goaway_sessions_on_ip_change); + dict.Set("migrate_sessions_on_network_change_v2", + quic_params->migrate_sessions_on_network_change_v2); + dict.Set("migrate_sessions_early_v2", quic_params->migrate_sessions_early_v2); + dict.Set("retransmittable_on_wire_timeout_milliseconds", + static_cast<int>( + quic_params->retransmittable_on_wire_timeout.InMilliseconds())); + dict.Set("retry_on_alternate_network_before_handshake", + quic_params->retry_on_alternate_network_before_handshake); + dict.Set("migrate_idle_sessions", quic_params->migrate_idle_sessions); + dict.Set( + "idle_session_migration_period_seconds", + static_cast<int>(quic_params->idle_session_migration_period.InSeconds())); + dict.Set("max_time_on_non_default_network_seconds", + static_cast<int>( + quic_params->max_time_on_non_default_network.InSeconds())); + dict.Set("max_num_migrations_to_non_default_network_on_write_error", + quic_params->max_migrations_to_non_default_network_on_write_error); + dict.Set( "max_num_migrations_to_non_default_network_on_path_degrading", quic_params->max_migrations_to_non_default_network_on_path_degrading); - dict.SetBoolKey("allow_server_migration", - quic_params->allow_server_migration); - dict.SetBoolKey("race_stale_dns_on_connection", - quic_params->race_stale_dns_on_connection); - dict.SetBoolKey("estimate_initial_rtt", quic_params->estimate_initial_rtt); - dict.SetBoolKey("server_push_cancellation", - params_.enable_server_push_cancellation); - dict.SetIntKey("initial_rtt_for_handshake_milliseconds", - quic_params->initial_rtt_for_handshake.InMilliseconds()); + dict.Set("allow_server_migration", quic_params->allow_server_migration); + dict.Set("race_stale_dns_on_connection", + quic_params->race_stale_dns_on_connection); + dict.Set("estimate_initial_rtt", quic_params->estimate_initial_rtt); + dict.Set("server_push_cancellation", params_.enable_server_push_cancellation); + dict.Set("initial_rtt_for_handshake_milliseconds", + static_cast<int>( + quic_params->initial_rtt_for_handshake.InMilliseconds())); - return dict; + return base::Value(std::move(dict)); } void HttpNetworkSession::CloseAllConnections(int net_error,
diff --git a/net/http/http_stream_factory_unittest.cc b/net/http/http_stream_factory_unittest.cc index 0749d57..b1085bb 100644 --- a/net/http/http_stream_factory_unittest.cc +++ b/net/http/http_stream_factory_unittest.cc
@@ -1067,10 +1067,10 @@ // Return count of distinct QUIC sessions. int GetQuicSessionCount(HttpNetworkSession* session) { base::Value dict(session->QuicInfoToValue()); - base::Value* session_list = dict.FindListKey("sessions"); + base::Value::List* session_list = dict.GetDict().FindList("sessions"); if (!session_list) return -1; - return session_list->GetListDeprecated().size(); + return session_list->size(); } TEST_F(HttpStreamFactoryTest, PrivacyModeUsesDifferentSocketPoolGroup) {
diff --git a/net/log/net_log_source.cc b/net/log/net_log_source.cc index db42730..e17ae08 100644 --- a/net/log/net_log_source.cc +++ b/net/log/net_log_source.cc
@@ -49,12 +49,16 @@ return id != kInvalidId; } +void NetLogSource::AddToEventParameters(base::Value::Dict& event_params) const { + base::Value::Dict dict; + dict.Set("type", static_cast<int>(type)); + dict.Set("id", static_cast<int>(id)); + event_params.Set("source_dependency", std::move(dict)); +} + void NetLogSource::AddToEventParameters(base::Value* event_params) const { DCHECK(event_params->is_dict()); - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("type", static_cast<int>(type)); - dict.SetIntKey("id", static_cast<int>(id)); - event_params->SetKey("source_dependency", std::move(dict)); + AddToEventParameters(event_params->GetDict()); } base::Value NetLogSource::ToEventParameters() const {
diff --git a/net/log/net_log_source.h b/net/log/net_log_source.h index fd0b737..9179709 100644 --- a/net/log/net_log_source.h +++ b/net/log/net_log_source.h
@@ -8,13 +8,10 @@ #include <stdint.h> #include "base/time/time.h" +#include "base/values.h" #include "net/base/net_export.h" #include "net/log/net_log_source_type.h" -namespace base { -class Value; -} - namespace net { // Identifies the entity that generated this log. The |id| field should @@ -33,6 +30,8 @@ // Adds the source to a dictionary containing event parameters, // using the name "source_dependency". + void AddToEventParameters(base::Value::Dict& event_params) const; + // Legacy version of above method. Should be removed once no longer used. void AddToEventParameters(base::Value* event_params) const; // Returns a dictionary with a single entry named "source_dependency" that
diff --git a/net/proxy_resolution/pac_file_fetcher_impl.cc b/net/proxy_resolution/pac_file_fetcher_impl.cc index 33bc9d7..c0ffd19 100644 --- a/net/proxy_resolution/pac_file_fetcher_impl.cc +++ b/net/proxy_resolution/pac_file_fetcher_impl.cc
@@ -10,6 +10,8 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/ranges/algorithm.h" +#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -49,15 +51,14 @@ constexpr base::TimeDelta kDefaultMaxDuration = base::Seconds(30); // Returns true if |mime_type| is one of the known PAC mime type. -bool IsPacMimeType(const std::string& mime_type) { - static const char* const kSupportedPacMimeTypes[] = { - "application/x-ns-proxy-autoconfig", "application/x-javascript-config", +constexpr bool IsPacMimeType(base::StringPiece mime_type) { + constexpr base::StringPiece kSupportedPacMimeTypes[] = { + "application/x-ns-proxy-autoconfig", + "application/x-javascript-config", }; - for (size_t i = 0; i < std::size(kSupportedPacMimeTypes); ++i) { - if (base::LowerCaseEqualsASCII(mime_type, kSupportedPacMimeTypes[i])) - return true; - } - return false; + return base::ranges::any_of(kSupportedPacMimeTypes, [&](auto pac_mime_type) { + return base::EqualsCaseInsensitiveASCII(pac_mime_type, mime_type); + }); } struct BomMapping {
diff --git a/net/proxy_resolution/proxy_bypass_rules.cc b/net/proxy_resolution/proxy_bypass_rules.cc index b0a7061..59ee7b42 100644 --- a/net/proxy_resolution/proxy_bypass_rules.cc +++ b/net/proxy_resolution/proxy_bypass_rules.cc
@@ -108,9 +108,9 @@ // <local> and <-loopback> are special syntax used by WinInet's bypass list // -- we allow it on all platforms and interpret it the same way. - if (base::LowerCaseEqualsASCII(raw, kBypassSimpleHostnames)) + if (base::EqualsCaseInsensitiveASCII(raw, kBypassSimpleHostnames)) return std::make_unique<BypassSimpleHostnamesRule>(); - if (base::LowerCaseEqualsASCII(raw, kSubtractImplicitBypasses)) + if (base::EqualsCaseInsensitiveASCII(raw, kSubtractImplicitBypasses)) return std::make_unique<SubtractImplicitBypassesRule>(); return SchemeHostPortMatcherRule::FromUntrimmedRawString(raw_untrimmed);
diff --git a/net/quic/dedicated_web_transport_http3_client.cc b/net/quic/dedicated_web_transport_http3_client.cc index c639251..fdaa2b1 100644 --- a/net/quic/dedicated_web_transport_http3_client.cc +++ b/net/quic/dedicated_web_transport_http3_client.cc
@@ -97,17 +97,17 @@ const absl::optional<WebTransportError>& error) { net_log.AddEvent( NetLogEventType::QUIC_SESSION_WEBTRANSPORT_CLIENT_STATE_CHANGED, [&] { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("last_state", WebTransportStateString(last_state)); - dict.SetStringKey("next_state", WebTransportStateString(next_state)); + base::Value::Dict dict; + dict.Set("last_state", WebTransportStateString(last_state)); + dict.Set("next_state", WebTransportStateString(next_state)); if (error.has_value()) { - base::Value error_dict(base::Value::Type::DICTIONARY); - error_dict.SetIntKey("net_error", error->net_error); - error_dict.SetIntKey("quic_error", error->quic_error); - error_dict.SetStringKey("details", error->details); - dict.SetKey("error", std::move(error_dict)); + base::Value::Dict error_dict; + error_dict.Set("net_error", error->net_error); + error_dict.Set("quic_error", error->quic_error); + error_dict.Set("details", error->details); + dict.Set("error", std::move(error_dict)); } - return dict; + return base::Value(std::move(dict)); }); } @@ -281,14 +281,13 @@ // requires implementing ProofHandler::OnProofVerifyDetailsAvailable. crypto_config_(CreateProofVerifier(isolation_key_, context, parameters), /* session_cache */ nullptr) { - net_log_.BeginEvent(NetLogEventType::QUIC_SESSION_WEBTRANSPORT_CLIENT_ALIVE, - [&] { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("url", url.possibly_invalid_spec()); - dict.SetStringKey("network_isolation_key", - isolation_key.ToDebugString()); - return dict; - }); + net_log_.BeginEvent( + NetLogEventType::QUIC_SESSION_WEBTRANSPORT_CLIENT_ALIVE, [&] { + base::Value::Dict dict; + dict.Set("url", url.possibly_invalid_spec()); + dict.Set("network_isolation_key", isolation_key.ToDebugString()); + return base::Value(std::move(dict)); + }); } DedicatedWebTransportHttp3Client::~DedicatedWebTransportHttp3Client() {
diff --git a/net/quic/quic_chromium_client_session.cc b/net/quic/quic_chromium_client_session.cc index ceae5f6..36b8f36 100644 --- a/net/quic/quic_chromium_client_session.cc +++ b/net/quic/quic_chromium_client_session.cc
@@ -187,36 +187,36 @@ base::Value NetLogQuicMigrationFailureParams( quic::QuicConnectionId connection_id, base::StringPiece reason) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("connection_id", connection_id.ToString()); - dict.SetStringKey("reason", reason); - return dict; + base::Value::Dict dict; + dict.Set("connection_id", connection_id.ToString()); + dict.Set("reason", reason); + return base::Value(std::move(dict)); } base::Value NetLogQuicMigrationSuccessParams( quic::QuicConnectionId connection_id) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("connection_id", connection_id.ToString()); - return dict; + base::Value::Dict dict; + dict.Set("connection_id", connection_id.ToString()); + return base::Value(std::move(dict)); } base::Value NetLogProbingResultParams( NetworkChangeNotifier::NetworkHandle network, const quic::QuicSocketAddress* peer_address, bool is_success) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("network", base::NumberToString(network)); - dict.SetStringKey("peer address", peer_address->ToString()); - dict.SetBoolKey("is_success", is_success); - return dict; + base::Value::Dict dict; + dict.Set("network", base::NumberToString(network)); + dict.Set("peer address", peer_address->ToString()); + dict.Set("is_success", is_success); + return base::Value(std::move(dict)); } base::Value NetLogAcceptChFrameReceivedParams( spdy::AcceptChOriginValuePair entry) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("origin", entry.origin); - dict.SetStringKey("accept_ch", entry.value); - return dict; + base::Value::Dict dict; + dict.Set("origin", entry.origin); + dict.Set("accept_ch", entry.value); + return base::Value(std::move(dict)); } // Histogram for recording the different reasons that a QUIC session is unable @@ -290,22 +290,21 @@ const quic::ParsedQuicVersionVector& supported_versions, int cert_verify_flags, bool require_confirmation) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("host", session_key->server_id().host()); - dict.SetIntKey("port", session_key->server_id().port()); - dict.SetStringKey("privacy_mode", - PrivacyModeToDebugString(session_key->privacy_mode())); - dict.SetStringKey("network_isolation_key", - session_key->network_isolation_key().ToDebugString()); - dict.SetBoolKey("require_confirmation", require_confirmation); - dict.SetIntKey("cert_verify_flags", cert_verify_flags); - dict.SetStringKey("connection_id", connection_id.ToString()); + base::Value::Dict dict; + dict.Set("host", session_key->server_id().host()); + dict.Set("port", session_key->server_id().port()); + dict.Set("privacy_mode", + PrivacyModeToDebugString(session_key->privacy_mode())); + dict.Set("network_isolation_key", + session_key->network_isolation_key().ToDebugString()); + dict.Set("require_confirmation", require_confirmation); + dict.Set("cert_verify_flags", cert_verify_flags); + dict.Set("connection_id", connection_id.ToString()); if (!client_connection_id.IsEmpty()) { - dict.SetStringKey("client_connection_id", client_connection_id.ToString()); + dict.Set("client_connection_id", client_connection_id.ToString()); } - dict.SetStringKey("versions", - ParsedQuicVersionVectorToString(supported_versions)); - return dict; + dict.Set("versions", ParsedQuicVersionVectorToString(supported_versions)); + return base::Value(std::move(dict)); } base::Value NetLogQuicPushPromiseReceivedParams( @@ -313,12 +312,11 @@ spdy::SpdyStreamId stream_id, spdy::SpdyStreamId promised_stream_id, NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("headers", - ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); - dict.SetIntKey("id", stream_id); - dict.SetIntKey("promised_stream_id", promised_stream_id); - return dict; + base::Value::Dict dict; + dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); + dict.Set("id", static_cast<int>(stream_id)); + dict.Set("promised_stream_id", static_cast<int>(promised_stream_id)); + return base::Value(std::move(dict)); } // TODO(fayang): Remove this when necessary data is collected. @@ -3279,44 +3277,43 @@ base::Value QuicChromiumClientSession::GetInfoAsValue( const std::set<HostPortPair>& aliases) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("version", - ParsedQuicVersionToString(connection()->version())); - dict.SetIntKey("open_streams", GetNumActiveStreams()); + base::Value::Dict dict; + dict.Set("version", ParsedQuicVersionToString(connection()->version())); + dict.Set("open_streams", static_cast<int>(GetNumActiveStreams())); - std::vector<base::Value> stream_list; + base::Value::List stream_list; auto* stream_list_ptr = &stream_list; PerformActionOnActiveStreams([stream_list_ptr](quic::QuicStream* stream) { - stream_list_ptr->emplace_back(base::NumberToString(stream->id())); + stream_list_ptr->Append(base::NumberToString(stream->id())); return true; }); - dict.SetKey("active_streams", base::Value(std::move(stream_list))); + dict.Set("active_streams", std::move(stream_list)); - dict.SetIntKey("total_streams", num_total_streams_); - dict.SetStringKey("peer_address", peer_address().ToString()); - dict.SetStringKey("network_isolation_key", - session_key_.network_isolation_key().ToDebugString()); - dict.SetStringKey("connection_id", connection_id().ToString()); + dict.Set("total_streams", static_cast<int>(num_total_streams_)); + dict.Set("peer_address", peer_address().ToString()); + dict.Set("network_isolation_key", + session_key_.network_isolation_key().ToDebugString()); + dict.Set("connection_id", connection_id().ToString()); if (!connection()->client_connection_id().IsEmpty()) { - dict.SetStringKey("client_connection_id", - connection()->client_connection_id().ToString()); + dict.Set("client_connection_id", + connection()->client_connection_id().ToString()); } - dict.SetBoolKey("connected", connection()->connected()); + dict.Set("connected", connection()->connected()); const quic::QuicConnectionStats& stats = connection()->GetStats(); - dict.SetIntKey("packets_sent", stats.packets_sent); - dict.SetIntKey("packets_received", stats.packets_received); - dict.SetIntKey("packets_lost", stats.packets_lost); + dict.Set("packets_sent", static_cast<int>(stats.packets_sent)); + dict.Set("packets_received", static_cast<int>(stats.packets_received)); + dict.Set("packets_lost", static_cast<int>(stats.packets_lost)); SSLInfo ssl_info; - std::vector<base::Value> alias_list; + base::Value::List alias_list; for (const auto& alias : aliases) { - alias_list.emplace_back(alias.ToString()); + alias_list.Append(alias.ToString()); } - dict.SetKey("aliases", base::Value(std::move(alias_list))); + dict.Set("aliases", std::move(alias_list)); - return dict; + return base::Value(std::move(dict)); } bool QuicChromiumClientSession::gquic_zero_rtt_disabled() const {
diff --git a/net/quic/quic_event_logger.cc b/net/quic/quic_event_logger.cc index 3c7fc02e..27509320 100644 --- a/net/quic/quic_event_logger.cc +++ b/net/quic/quic_event_logger.cc
@@ -18,11 +18,11 @@ base::Value NetLogQuicPacketParams(const quic::QuicSocketAddress& self_address, const quic::QuicSocketAddress& peer_address, size_t packet_size) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("self_address", self_address.ToString()); - dict.SetStringKey("peer_address", peer_address.ToString()); - dict.SetIntKey("size", packet_size); - return dict; + base::Value::Dict dict; + dict.Set("self_address", self_address.ToString()); + dict.Set("peer_address", peer_address.ToString()); + dict.Set("size", static_cast<int>(packet_size)); + return base::Value(std::move(dict)); } base::Value NetLogQuicPacketSentParams(quic::QuicPacketNumber packet_number, @@ -30,34 +30,33 @@ quic::TransmissionType transmission_type, quic::EncryptionLevel encryption_level, quic::QuicTime sent_time) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("transmission_type", - quic::TransmissionTypeToString(transmission_type)); - dict.SetKey("packet_number", NetLogNumberValue(packet_number.ToUint64())); - dict.SetIntKey("size", packet_length); - dict.SetKey("sent_time_us", NetLogNumberValue(sent_time.ToDebuggingValue())); - dict.SetStringKey("encryption_level", - quic::EncryptionLevelToString(encryption_level)); - return dict; + base::Value::Dict dict; + dict.Set("transmission_type", + quic::TransmissionTypeToString(transmission_type)); + dict.Set("packet_number", NetLogNumberValue(packet_number.ToUint64())); + dict.Set("size", packet_length); + dict.Set("sent_time_us", NetLogNumberValue(sent_time.ToDebuggingValue())); + dict.Set("encryption_level", quic::EncryptionLevelToString(encryption_level)); + return base::Value(std::move(dict)); } base::Value NetLogQuicPacketLostParams(quic::QuicPacketNumber packet_number, quic::TransmissionType transmission_type, quic::QuicTime detection_time) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("transmission_type", - quic::TransmissionTypeToString(transmission_type)); - dict.SetKey("packet_number", NetLogNumberValue(packet_number.ToUint64())); - dict.SetKey("detection_time_us", - NetLogNumberValue(detection_time.ToDebuggingValue())); - return dict; + base::Value::Dict dict; + dict.Set("transmission_type", + quic::TransmissionTypeToString(transmission_type)); + dict.Set("packet_number", NetLogNumberValue(packet_number.ToUint64())); + dict.Set("detection_time_us", + NetLogNumberValue(detection_time.ToDebuggingValue())); + return base::Value(std::move(dict)); } base::Value NetLogQuicDuplicatePacketParams( quic::QuicPacketNumber packet_number) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("packet_number", NetLogNumberValue(packet_number.ToUint64())); - return dict; + base::Value::Dict dict; + dict.Set("packet_number", NetLogNumberValue(packet_number.ToUint64())); + return base::Value(std::move(dict)); } base::Value NetLogReceivedQuicPacketHeaderParams( @@ -65,72 +64,69 @@ const quic::ParsedQuicVersion& session_version, const quic::QuicConnectionId& connection_id, const quic::QuicConnectionId& client_connection_id) { - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; quic::ParsedQuicVersion version = session_version; if (header.version_flag && header.version != quic::ParsedQuicVersion::Unsupported()) { version = header.version; if (version != session_version) { - dict.SetStringKey("version", quic::ParsedQuicVersionToString(version)); + dict.Set("version", quic::ParsedQuicVersionToString(version)); } } - dict.SetStringKey("connection_id", connection_id.ToString()); + dict.Set("connection_id", connection_id.ToString()); if (!client_connection_id.IsEmpty()) { - dict.SetStringKey("client_connection_id", client_connection_id.ToString()); + dict.Set("client_connection_id", client_connection_id.ToString()); } if (version.HasIetfInvariantHeader()) { if (header.destination_connection_id_included == quic::CONNECTION_ID_PRESENT && header.destination_connection_id != client_connection_id && !header.destination_connection_id.IsEmpty()) { - dict.SetStringKey("destination_connection_id", - header.destination_connection_id.ToString()); + dict.Set("destination_connection_id", + header.destination_connection_id.ToString()); } if (header.source_connection_id_included == quic::CONNECTION_ID_PRESENT && header.source_connection_id != connection_id && !header.source_connection_id.IsEmpty()) { - dict.SetStringKey("source_connection_id", - header.source_connection_id.ToString()); + dict.Set("source_connection_id", header.source_connection_id.ToString()); } } else { if (header.destination_connection_id_included == quic::CONNECTION_ID_PRESENT && header.destination_connection_id != connection_id && !header.destination_connection_id.IsEmpty()) { - dict.SetStringKey("destination_connection_id", - header.destination_connection_id.ToString()); + dict.Set("destination_connection_id", + header.destination_connection_id.ToString()); } - dict.SetIntKey("reset_flag", header.reset_flag); - dict.SetIntKey("version_flag", header.version_flag); + dict.Set("reset_flag", header.reset_flag); + dict.Set("version_flag", header.version_flag); } - dict.SetKey("packet_number", - NetLogNumberValue(header.packet_number.ToUint64())); - dict.SetStringKey("header_format", - quic::PacketHeaderFormatToString(header.form)); + dict.Set("packet_number", NetLogNumberValue(header.packet_number.ToUint64())); + dict.Set("header_format", quic::PacketHeaderFormatToString(header.form)); if (header.form == quic::IETF_QUIC_LONG_HEADER_PACKET) { - dict.SetStringKey("long_header_type", quic::QuicLongHeaderTypeToString( - header.long_packet_type)); + dict.Set("long_header_type", + quic::QuicLongHeaderTypeToString(header.long_packet_type)); } - return dict; + return base::Value(std::move(dict)); } base::Value NetLogQuicStreamFrameParams(const quic::QuicStreamFrame& frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", frame.stream_id); - dict.SetBoolKey("fin", frame.fin); - dict.SetKey("offset", NetLogNumberValue(frame.offset)); - dict.SetIntKey("length", frame.data_length); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(frame.stream_id)); + dict.Set("fin", frame.fin); + dict.Set("offset", NetLogNumberValue(frame.offset)); + dict.Set("length", frame.data_length); + return base::Value(std::move(dict)); } base::Value NetLogQuicAckFrameParams(const quic::QuicAckFrame* frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("largest_observed", - NetLogNumberValue(frame->largest_acked.ToUint64())); - dict.SetKey("delta_time_largest_observed_us", - NetLogNumberValue(frame->ack_delay_time.ToMicroseconds())); + base::Value::Dict dict; + dict.Set("largest_observed", + NetLogNumberValue(frame->largest_acked.ToUint64())); + dict.Set("delta_time_largest_observed_us", + NetLogNumberValue(frame->ack_delay_time.ToMicroseconds())); - base::Value missing(base::Value::Type::LIST); + base::Value::List missing; quic::QuicPacketNumber smallest_observed; if (!frame->packets.Empty()) { // V34 and above express acked packets, but only print @@ -145,38 +141,38 @@ } else { smallest_observed = frame->largest_acked; } - dict.SetKey("smallest_observed", - NetLogNumberValue(smallest_observed.ToUint64())); - dict.SetKey("missing_packets", std::move(missing)); + dict.Set("smallest_observed", + NetLogNumberValue(smallest_observed.ToUint64())); + dict.Set("missing_packets", std::move(missing)); - base::Value received(base::Value::Type::LIST); - const quic::PacketTimeVector& received_times = frame->received_packet_times; - for (auto it = received_times.begin(); it != received_times.end(); ++it) { - base::Value info(base::Value::Type::DICTIONARY); - info.SetKey("packet_number", NetLogNumberValue(it->first.ToUint64())); - info.SetKey("received", NetLogNumberValue(it->second.ToDebuggingValue())); + base::Value::List received; + for (const auto& packet_time : frame->received_packet_times) { + base::Value::Dict info; + info.Set("packet_number", NetLogNumberValue(packet_time.first.ToUint64())); + info.Set("received", + NetLogNumberValue(packet_time.second.ToDebuggingValue())); received.Append(std::move(info)); } - dict.SetKey("received_packet_times", std::move(received)); + dict.Set("received_packet_times", std::move(received)); - return dict; + return base::Value(std::move(dict)); } base::Value NetLogQuicRstStreamFrameParams( const quic::QuicRstStreamFrame* frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", frame->stream_id); - dict.SetIntKey("quic_rst_stream_error", frame->error_code); - dict.SetKey("offset", NetLogNumberValue(frame->byte_offset)); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(frame->stream_id)); + dict.Set("quic_rst_stream_error", static_cast<int>(frame->error_code)); + dict.Set("offset", NetLogNumberValue(frame->byte_offset)); + return base::Value(std::move(dict)); } base::Value NetLogQuicConnectionCloseFrameParams( const quic::QuicConnectionCloseFrame* frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("quic_error", frame->quic_error_code); + base::Value::Dict dict; + dict.Set("quic_error", frame->quic_error_code); if (frame->wire_error_code != frame->quic_error_code) { - dict.SetIntKey("quic_wire_error", frame->wire_error_code); + dict.Set("quic_wire_error", static_cast<int>(frame->wire_error_code)); } std::string close_type; switch (frame->close_type) { @@ -190,110 +186,106 @@ close_type = "Application"; break; } - dict.SetStringKey("close_type", close_type); + dict.Set("close_type", close_type); if (frame->transport_close_frame_type != 0) { - dict.SetKey("transport_close_frame_type", - NetLogNumberValue(frame->transport_close_frame_type)); + dict.Set("transport_close_frame_type", + NetLogNumberValue(frame->transport_close_frame_type)); } - dict.SetStringKey("details", frame->error_details); - return dict; + dict.Set("details", frame->error_details); + return base::Value(std::move(dict)); } base::Value NetLogQuicWindowUpdateFrameParams( const quic::QuicWindowUpdateFrame& frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", frame.stream_id); - dict.SetKey("byte_offset", NetLogNumberValue(frame.max_data)); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(frame.stream_id)); + dict.Set("byte_offset", NetLogNumberValue(frame.max_data)); + return base::Value(std::move(dict)); } base::Value NetLogQuicBlockedFrameParams(const quic::QuicBlockedFrame& frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", frame.stream_id); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(frame.stream_id)); + return base::Value(std::move(dict)); } base::Value NetLogQuicGoAwayFrameParams(const quic::QuicGoAwayFrame* frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("quic_error", frame->error_code); - dict.SetIntKey("last_good_stream_id", frame->last_good_stream_id); - dict.SetStringKey("reason_phrase", frame->reason_phrase); - return dict; + base::Value::Dict dict; + dict.Set("quic_error", frame->error_code); + dict.Set("last_good_stream_id", static_cast<int>(frame->last_good_stream_id)); + dict.Set("reason_phrase", frame->reason_phrase); + return base::Value(std::move(dict)); } base::Value NetLogQuicStopWaitingFrameParams( const quic::QuicStopWaitingFrame* frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("least_unacked", - NetLogNumberValue(frame->least_unacked.ToUint64())); - return dict; + base::Value::Dict dict; + dict.Set("least_unacked", NetLogNumberValue(frame->least_unacked.ToUint64())); + return base::Value(std::move(dict)); } base::Value NetLogQuicVersionNegotiationPacketParams( const quic::QuicVersionNegotiationPacket* packet) { - base::Value dict(base::Value::Type::DICTIONARY); - base::Value versions(base::Value::Type::LIST); - for (auto it = packet->versions.begin(); it != packet->versions.end(); ++it) { - versions.Append(ParsedQuicVersionToString(*it)); + base::Value::Dict dict; + base::Value::List versions; + for (const auto& version : packet->versions) { + versions.Append(ParsedQuicVersionToString(version)); } - dict.SetKey("versions", std::move(versions)); - return dict; + dict.Set("versions", std::move(versions)); + return base::Value(std::move(dict)); } base::Value NetLogQuicPublicResetPacketParams( const IPEndPoint& server_hello_address, const quic::QuicSocketAddress& public_reset_address) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("server_hello_address", server_hello_address.ToString()); - dict.SetStringKey("public_reset_address", public_reset_address.ToString()); - return dict; + base::Value::Dict dict; + dict.Set("server_hello_address", server_hello_address.ToString()); + dict.Set("public_reset_address", public_reset_address.ToString()); + return base::Value(std::move(dict)); } base::Value NetLogQuicPathData(const quic::QuicPathFrameBuffer& buffer) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("data", NetLogBinaryValue(buffer)); - return dict; + base::Value::Dict dict; + dict.Set("data", NetLogBinaryValue(buffer)); + return base::Value(std::move(dict)); } base::Value NetLogQuicCryptoHandshakeMessageParams( const quic::CryptoHandshakeMessage* message) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("quic_crypto_handshake_message", message->DebugString()); - return dict; + base::Value::Dict dict; + dict.Set("quic_crypto_handshake_message", message->DebugString()); + return base::Value(std::move(dict)); } base::Value NetLogQuicTransportParametersParams( const quic::TransportParameters& transport_parameters) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("quic_transport_parameters", - transport_parameters.ToString()); - return dict; + base::Value::Dict dict; + dict.Set("quic_transport_parameters", transport_parameters.ToString()); + return base::Value(std::move(dict)); } base::Value NetLogQuicZeroRttRejectReason(int reason) { - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; const char* reason_detail = SSL_early_data_reason_string( static_cast<ssl_early_data_reason_t>(reason)); if (reason_detail) { - dict.SetStringKey("reason", reason_detail); + dict.Set("reason", reason_detail); } else { - dict.SetStringKey("reason", - "Unknown reason " + base::NumberToString(reason)); + dict.Set("reason", "Unknown reason " + base::NumberToString(reason)); } - return dict; + return base::Value(std::move(dict)); } base::Value NetLogQuicOnConnectionClosedParams( quic::QuicErrorCode error, std::string error_details, quic::ConnectionCloseSource source) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("quic_error", error); - dict.SetStringKey("details", error_details); - dict.SetBoolKey("from_peer", source == quic::ConnectionCloseSource::FROM_PEER - ? true - : false); - return dict; + base::Value::Dict dict; + dict.Set("quic_error", error); + dict.Set("details", error_details); + dict.Set("from_peer", + source == quic::ConnectionCloseSource::FROM_PEER ? true : false); + return base::Value(std::move(dict)); } base::Value NetLogQuicCertificateVerifiedParams( @@ -302,77 +294,76 @@ // More fields could be logged in the future. std::vector<std::string> dns_names; cert->GetSubjectAltName(&dns_names, nullptr); - base::Value dict(base::Value::Type::DICTIONARY); - base::Value subjects(base::Value::Type::LIST); + base::Value::Dict dict; + base::Value::List subjects; for (auto& dns_name : dns_names) { subjects.Append(std::move(dns_name)); } - dict.SetKey("subjects", std::move(subjects)); - return dict; + dict.Set("subjects", std::move(subjects)); + return base::Value(std::move(dict)); } base::Value NetLogQuicCryptoFrameParams(const quic::QuicCryptoFrame* frame, bool has_buffer) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("encryption_level", - quic::EncryptionLevelToString(frame->level)); - dict.SetIntKey("data_length", frame->data_length); - dict.SetKey("offset", NetLogNumberValue(frame->offset)); + base::Value::Dict dict; + dict.Set("encryption_level", quic::EncryptionLevelToString(frame->level)); + dict.Set("data_length", frame->data_length); + dict.Set("offset", NetLogNumberValue(frame->offset)); if (has_buffer) { - dict.SetKey("bytes", NetLogBinaryValue( - reinterpret_cast<const void*>(frame->data_buffer), - frame->data_length)); + dict.Set("bytes", NetLogBinaryValue( + reinterpret_cast<const void*>(frame->data_buffer), + frame->data_length)); } - return dict; + return base::Value(std::move(dict)); } base::Value NetLogQuicStopSendingFrameParams( const quic::QuicStopSendingFrame& frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", frame.stream_id); - dict.SetIntKey("quic_rst_stream_error", frame.error_code); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(frame.stream_id)); + dict.Set("quic_rst_stream_error", static_cast<int>(frame.error_code)); + return base::Value(std::move(dict)); } base::Value NetLogQuicStreamsBlockedFrameParams( const quic::QuicStreamsBlockedFrame& frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_count", frame.stream_count); - dict.SetBoolKey("is_unidirectional", frame.unidirectional); - return dict; + base::Value::Dict dict; + dict.Set("stream_count", static_cast<int>(frame.stream_count)); + dict.Set("is_unidirectional", frame.unidirectional); + return base::Value(std::move(dict)); } base::Value NetLogQuicMaxStreamsFrameParams( const quic::QuicMaxStreamsFrame& frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_count", frame.stream_count); - dict.SetBoolKey("is_unidirectional", frame.unidirectional); - return dict; + base::Value::Dict dict; + dict.Set("stream_count", static_cast<int>(frame.stream_count)); + dict.Set("is_unidirectional", frame.unidirectional); + return base::Value(std::move(dict)); } base::Value NetLogQuicNewConnectionIdFrameParams( const quic::QuicNewConnectionIdFrame* frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("connection_id", frame->connection_id.ToString()); - dict.SetKey("sequence_number", NetLogNumberValue(frame->sequence_number)); - dict.SetKey("retire_prior_to", NetLogNumberValue(frame->retire_prior_to)); - return dict; + base::Value::Dict dict; + dict.Set("connection_id", frame->connection_id.ToString()); + dict.Set("sequence_number", NetLogNumberValue(frame->sequence_number)); + dict.Set("retire_prior_to", NetLogNumberValue(frame->retire_prior_to)); + return base::Value(std::move(dict)); } base::Value NetLogQuicRetireConnectionIdFrameParams( const quic::QuicRetireConnectionIdFrame* frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("sequence_number", NetLogNumberValue(frame->sequence_number)); - return dict; + base::Value::Dict dict; + dict.Set("sequence_number", NetLogNumberValue(frame->sequence_number)); + return base::Value(std::move(dict)); } base::Value NetLogQuicNewTokenFrameParams( const quic::QuicNewTokenFrame* frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("token", NetLogBinaryValue( - reinterpret_cast<const void*>(frame->token.data()), - frame->token.length())); - return dict; + base::Value::Dict dict; + dict.Set("token", + NetLogBinaryValue(reinterpret_cast<const void*>(frame->token.data()), + frame->token.length())); + return base::Value(std::move(dict)); } } // namespace
diff --git a/net/quic/quic_http3_logger.cc b/net/quic/quic_http3_logger.cc index 438b767..ad77d25 100644 --- a/net/quic/quic_http3_logger.cc +++ b/net/quic/quic_http3_logger.cc
@@ -23,36 +23,36 @@ namespace { base::Value NetLogSettingsParams(const quic::SettingsFrame& frame) { - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; for (auto setting : frame.values) { - dict.SetIntKey( + dict.Set( quic::H3SettingsToString( static_cast<quic::Http3AndQpackSettingsIdentifiers>(setting.first)), - setting.second); + static_cast<int>(setting.second)); } - return dict; + return base::Value(std::move(dict)); } base::Value NetLogPriorityUpdateParams(const quic::PriorityUpdateFrame& frame) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("type", frame.prioritized_element_type == - quic::PrioritizedElementType::REQUEST_STREAM - ? "request_stream" - : "push_stream"); - dict.SetKey("prioritized_element_id", - NetLogNumberValue(frame.prioritized_element_id)); - dict.SetStringKey("priority_field_value", frame.priority_field_value); - return dict; + base::Value::Dict dict; + dict.Set("type", frame.prioritized_element_type == + quic::PrioritizedElementType::REQUEST_STREAM + ? "request_stream" + : "push_stream"); + dict.Set("prioritized_element_id", + NetLogNumberValue(frame.prioritized_element_id)); + dict.Set("priority_field_value", frame.priority_field_value); + return base::Value(std::move(dict)); } base::Value NetLogTwoIntParams(base::StringPiece name1, uint64_t value1, base::StringPiece name2, uint64_t value2) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey(name1, NetLogNumberValue(value1)); - dict.SetKey(name2, NetLogNumberValue(value2)); - return dict; + base::Value::Dict dict; + dict.Set(name1, NetLogNumberValue(value1)); + dict.Set(name2, NetLogNumberValue(value2)); + return base::Value(std::move(dict)); } base::Value NetLogThreeIntParams(base::StringPiece name1, @@ -61,17 +61,17 @@ uint64_t value2, base::StringPiece name3, uint64_t value3) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey(name1, NetLogNumberValue(value1)); - dict.SetKey(name2, NetLogNumberValue(value2)); - dict.SetKey(name3, NetLogNumberValue(value3)); - return dict; + base::Value::Dict dict; + dict.Set(name1, NetLogNumberValue(value1)); + dict.Set(name2, NetLogNumberValue(value2)); + dict.Set(name3, NetLogNumberValue(value3)); + return base::Value(std::move(dict)); } -base::ListValue ElideQuicHeaderListForNetLog( +base::Value::List ElideQuicHeaderListForNetLog( const quic::QuicHeaderList& headers, NetLogCaptureMode capture_mode) { - base::ListValue headers_list; + base::Value::List headers_list; for (const auto& header : headers) { base::StringPiece key = header.first; base::StringPiece value = header.second; @@ -235,12 +235,12 @@ net_log_.AddEvent( NetLogEventType::HTTP3_HEADERS_DECODED, [stream_id, &headers](NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("stream_id", - NetLogNumberValue(static_cast<uint64_t>(stream_id))); - dict.SetKey("headers", - ElideQuicHeaderListForNetLog(headers, capture_mode)); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", + NetLogNumberValue(static_cast<uint64_t>(stream_id))); + dict.Set("headers", + ElideQuicHeaderListForNetLog(headers, capture_mode)); + return base::Value(std::move(dict)); }); } @@ -311,12 +311,12 @@ net_log_.AddEvent( NetLogEventType::HTTP3_HEADERS_SENT, [stream_id, &header_block](NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("stream_id", - NetLogNumberValue(static_cast<uint64_t>(stream_id))); - dict.SetKey("headers", - ElideHttp2HeaderBlockForNetLog(header_block, capture_mode)); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", + NetLogNumberValue(static_cast<uint64_t>(stream_id))); + dict.Set("headers", + ElideHttp2HeaderBlockForNetLog(header_block, capture_mode)); + return base::Value(std::move(dict)); }); }
diff --git a/net/quic/quic_http_stream.cc b/net/quic/quic_http_stream.cc index fc5c7a8..3964b05d 100644 --- a/net/quic/quic_http_stream.cc +++ b/net/quic/quic_http_stream.cc
@@ -39,10 +39,10 @@ base::Value NetLogQuicPushStreamParams(quic::QuicStreamId stream_id, const GURL& url) { - base::DictionaryValue dict; - dict.SetInteger("stream_id", stream_id); - dict.SetString("url", url.spec()); - return std::move(dict); + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("url", url.spec()); + return base::Value(std::move(dict)); } void NetLogQuicPushStream(const NetLogWithSource& net_log1,
diff --git a/net/quic/quic_http_stream_test.cc b/net/quic/quic_http_stream_test.cc index 02be5be9..8f0471f 100644 --- a/net/quic/quic_http_stream_test.cc +++ b/net/quic/quic_http_stream_test.cc
@@ -129,7 +129,7 @@ if (!params.is_dict()) { return false; } - const base::Value* headers = params.FindListKey("headers"); + const base::Value::List* headers = params.GetDict().FindList("headers"); if (!headers) { return false; } @@ -137,24 +137,21 @@ std::string header_prefix = base::StrCat({key, ": "}); std::string expected_header = base::StrCat({header_prefix, expected_value}); - auto header_list = headers->GetListDeprecated(); - auto header_it = header_list.begin(); bool header_found = false; - while (header_it != header_list.end()) { - if (!header_it->is_string()) { + for (const auto& header_value : *headers) { + const std::string* header = header_value.GetIfString(); + if (!header) { return false; } - const std::string& header = header_it->GetString(); - if (base::StartsWith(header, header_prefix)) { + if (base::StartsWith(*header, header_prefix)) { if (header_found) { return false; } - if (header != expected_header) { + if (*header != expected_header) { return false; } header_found = true; } - ++header_it; } return header_found; }
diff --git a/net/quic/quic_http_utils.cc b/net/quic/quic_http_utils.cc index a7641cd..49f7925 100644 --- a/net/quic/quic_http_utils.cc +++ b/net/quic/quic_http_utils.cc
@@ -31,8 +31,8 @@ NetLogCaptureMode capture_mode) { base::Value dict = Http2HeaderBlockNetLogParams(headers, capture_mode); DCHECK(dict.is_dict()); - dict.SetIntKey("quic_priority", static_cast<int>(priority)); - dict.SetIntKey("quic_stream_id", static_cast<int>(stream_id)); + dict.GetDict().Set("quic_priority", static_cast<int>(priority)); + dict.GetDict().Set("quic_stream_id", static_cast<int>(stream_id)); return dict; } @@ -41,8 +41,8 @@ const spdy::Http2HeaderBlock* headers, NetLogCaptureMode capture_mode) { base::Value dict = Http2HeaderBlockNetLogParams(headers, capture_mode); - dict.SetIntKey("quic_stream_id", static_cast<int>(stream_id)); - dict.SetBoolKey("fin", fin_received); + dict.GetDict().Set("quic_stream_id", static_cast<int>(stream_id)); + dict.GetDict().Set("fin", fin_received); return dict; }
diff --git a/net/quic/quic_stream_factory.cc b/net/quic/quic_stream_factory.cc index 42eb4bb5..22108d7 100644 --- a/net/quic/quic_stream_factory.cc +++ b/net/quic/quic_stream_factory.cc
@@ -122,14 +122,14 @@ base::Value NetLogQuicStreamFactoryJobParams( const QuicStreamFactory::QuicSessionAliasKey* key) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("host", key->server_id().host()); - dict.SetIntKey("port", key->server_id().port()); - dict.SetStringKey("privacy_mode", PrivacyModeToDebugString( - key->session_key().privacy_mode())); - dict.SetStringKey("network_isolation_key", - key->session_key().network_isolation_key().ToDebugString()); - return dict; + base::Value::Dict dict; + dict.Set("host", key->server_id().host()); + dict.Set("port", key->server_id().port()); + dict.Set("privacy_mode", + PrivacyModeToDebugString(key->session_key().privacy_mode())); + dict.Set("network_isolation_key", + key->session_key().network_isolation_key().ToDebugString()); + return base::Value(std::move(dict)); } std::string QuicPlatformNotificationToString( @@ -1436,9 +1436,8 @@ DCHECK(all_sessions_.empty()); } -std::unique_ptr<base::Value> QuicStreamFactory::QuicStreamFactoryInfoToValue() - const { - std::unique_ptr<base::ListValue> list(new base::ListValue()); +base::Value QuicStreamFactory::QuicStreamFactoryInfoToValue() const { + base::Value::List list; for (auto it = active_sessions_.begin(); it != active_sessions_.end(); ++it) { const quic::QuicServerId& server_id = it->first.server_id(); @@ -1452,10 +1451,10 @@ hosts.insert(HostPortPair(alias_it->server_id().host(), alias_it->server_id().port())); } - list->Append(session->GetInfoAsValue(hosts)); + list.Append(session->GetInfoAsValue(hosts)); } } - return std::move(list); + return base::Value(std::move(list)); } void QuicStreamFactory::ClearCachedStatesInCryptoConfig(
diff --git a/net/quic/quic_stream_factory.h b/net/quic/quic_stream_factory.h index d175b15..0dad149 100644 --- a/net/quic/quic_stream_factory.h +++ b/net/quic/quic_stream_factory.h
@@ -298,7 +298,7 @@ // It sends connection close packet when closing connections. void CloseAllSessions(int error, quic::QuicErrorCode quic_error); - std::unique_ptr<base::Value> QuicStreamFactoryInfoToValue() const; + base::Value QuicStreamFactoryInfoToValue() const; // Delete cached state objects in |crypto_config_|. If |origin_filter| is not // null, only objects on matching origins will be deleted.
diff --git a/net/spdy/header_coalescer.cc b/net/spdy/header_coalescer.cc index cc5b91f0..e76c3e4 100644 --- a/net/spdy/header_coalescer.cc +++ b/net/spdy/header_coalescer.cc
@@ -27,14 +27,14 @@ const char* error_message) { net_log.AddEvent(NetLogEventType::HTTP2_SESSION_RECV_INVALID_HEADER, [&](NetLogCaptureMode capture_mode) { - base::DictionaryValue dict; - dict.SetKey("header_name", NetLogStringValue(header_name)); - dict.SetKey("header_value", - NetLogStringValue(ElideHeaderValueForNetLog( - capture_mode, std::string(header_name), - std::string(header_value)))); - dict.SetString("error", error_message); - return dict; + base::Value::Dict dict; + dict.Set("header_name", NetLogStringValue(header_name)); + dict.Set("header_value", + NetLogStringValue(ElideHeaderValueForNetLog( + capture_mode, std::string(header_name), + std::string(header_value)))); + dict.Set("error", error_message); + return base::Value(std::move(dict)); }); }
diff --git a/net/spdy/spdy_log_util.cc b/net/spdy/spdy_log_util.cc index 2aa7049..2ca19f30 100644 --- a/net/spdy/spdy_log_util.cc +++ b/net/spdy/spdy_log_util.cc
@@ -25,10 +25,10 @@ {"[", base::NumberToString(debug_data.size()), " bytes were stripped]"})); } -base::ListValue ElideHttp2HeaderBlockForNetLog( +base::Value::List ElideHttp2HeaderBlockForNetLog( const spdy::Http2HeaderBlock& headers, NetLogCaptureMode capture_mode) { - base::ListValue headers_list; + base::Value::List headers_list; for (const auto& header : headers) { base::StringPiece key = base::StringViewToStringPiece(header.first); base::StringPiece value = base::StringViewToStringPiece(header.second); @@ -42,10 +42,9 @@ base::Value Http2HeaderBlockNetLogParams(const spdy::Http2HeaderBlock* headers, NetLogCaptureMode capture_mode) { - base::DictionaryValue dict; - dict.SetKey("headers", - ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); - return std::move(dict); + base::Value::Dict dict; + dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); + return base::Value(std::move(dict)); } } // namespace net
diff --git a/net/spdy/spdy_log_util.h b/net/spdy/spdy_log_util.h index 98b9aba..16ad6be 100644 --- a/net/spdy/spdy_log_util.h +++ b/net/spdy/spdy_log_util.h
@@ -6,17 +6,13 @@ #define NET_SPDY_SPDY_LOG_UTIL_H_ #include "base/strings/string_piece.h" +#include "base/values.h" #include "net/base/net_export.h" #include "net/http/http_log_util.h" #include "net/log/net_log.h" #include "net/log/net_log_capture_mode.h" #include "net/third_party/quiche/src/quiche/spdy/core/spdy_header_block.h" -namespace base { -class ListValue; -class Value; -} // namespace base - namespace net { // Given an HTTP/2 GOAWAY frame |debug_data|, returns the elided version @@ -25,8 +21,8 @@ NetLogCaptureMode capture_mode, base::StringPiece debug_data); -// Given a spdy::Http2HeaderBlock, return its base::ListValue representation. -NET_EXPORT_PRIVATE base::ListValue ElideHttp2HeaderBlockForNetLog( +// Given a spdy::Http2HeaderBlock, return its base::Value::List representation. +NET_EXPORT_PRIVATE base::Value::List ElideHttp2HeaderBlockForNetLog( const spdy::Http2HeaderBlock& headers, NetLogCaptureMode capture_mode);
diff --git a/net/spdy/spdy_log_util_unittest.cc b/net/spdy/spdy_log_util_unittest.cc index 1f767a0c..4186734 100644 --- a/net/spdy/spdy_log_util_unittest.cc +++ b/net/spdy/spdy_log_util_unittest.cc
@@ -37,30 +37,27 @@ headers["foo"] = "bar"; headers["cookie"] = "name=value"; - base::ListValue list = + base::Value::List list = ElideHttp2HeaderBlockForNetLog(headers, NetLogCaptureMode::kDefault); - ASSERT_FALSE(list.is_none()); - ASSERT_EQ(2u, list.GetListDeprecated().size()); + ASSERT_EQ(2u, list.size()); - ASSERT_TRUE(list.GetListDeprecated()[0].is_string()); - EXPECT_EQ("foo: bar", list.GetListDeprecated()[0].GetString()); + ASSERT_TRUE(list[0].is_string()); + EXPECT_EQ("foo: bar", list[0].GetString()); - ASSERT_TRUE(list.GetListDeprecated()[1].is_string()); - EXPECT_EQ("cookie: [10 bytes were stripped]", - list.GetListDeprecated()[1].GetString()); + ASSERT_TRUE(list[1].is_string()); + EXPECT_EQ("cookie: [10 bytes were stripped]", list[1].GetString()); list = ElideHttp2HeaderBlockForNetLog(headers, NetLogCaptureMode::kIncludeSensitive); - ASSERT_FALSE(list.is_none()); - ASSERT_EQ(2u, list.GetListDeprecated().size()); + ASSERT_EQ(2u, list.size()); - ASSERT_TRUE(list.GetListDeprecated()[0].is_string()); - EXPECT_EQ("foo: bar", list.GetListDeprecated()[0].GetString()); + ASSERT_TRUE(list[0].is_string()); + EXPECT_EQ("foo: bar", list[0].GetString()); - ASSERT_TRUE(list.GetListDeprecated()[1].is_string()); - EXPECT_EQ("cookie: name=value", list.GetListDeprecated()[1].GetString()); + ASSERT_TRUE(list[1].is_string()); + EXPECT_EQ("cookie: name=value", list[1].GetString()); } TEST(SpdyLogUtilTest, Http2HeaderBlockNetLogParams) { @@ -73,38 +70,34 @@ ASSERT_TRUE(dict); ASSERT_TRUE(dict->is_dict()); - ASSERT_EQ(1u, dict->DictSize()); + ASSERT_EQ(1u, dict->GetDict().size()); - auto* header_list = dict->FindKey("headers"); + auto* header_list = dict->GetDict().FindList("headers"); ASSERT_TRUE(header_list); - ASSERT_TRUE(header_list->is_list()); - ASSERT_EQ(2u, header_list->GetListDeprecated().size()); + ASSERT_EQ(2u, header_list->size()); - ASSERT_TRUE(header_list->GetListDeprecated()[0].is_string()); - EXPECT_EQ("foo: bar", header_list->GetListDeprecated()[0].GetString()); + ASSERT_TRUE((*header_list)[0].is_string()); + EXPECT_EQ("foo: bar", (*header_list)[0].GetString()); - ASSERT_TRUE(header_list->GetListDeprecated()[1].is_string()); - EXPECT_EQ("cookie: [10 bytes were stripped]", - header_list->GetListDeprecated()[1].GetString()); + ASSERT_TRUE((*header_list)[1].is_string()); + EXPECT_EQ("cookie: [10 bytes were stripped]", (*header_list)[1].GetString()); dict = base::Value::ToUniquePtrValue(Http2HeaderBlockNetLogParams( &headers, NetLogCaptureMode::kIncludeSensitive)); ASSERT_TRUE(dict); ASSERT_TRUE(dict->is_dict()); - ASSERT_EQ(1u, dict->DictSize()); + ASSERT_EQ(1u, dict->GetDict().size()); - header_list = dict->FindKey("headers"); + header_list = dict->GetDict().FindList("headers"); ASSERT_TRUE(header_list); - ASSERT_TRUE(header_list->is_list()); - ASSERT_EQ(2u, header_list->GetListDeprecated().size()); + ASSERT_EQ(2u, header_list->size()); - ASSERT_TRUE(header_list->GetListDeprecated()[0].is_string()); - EXPECT_EQ("foo: bar", header_list->GetListDeprecated()[0].GetString()); + ASSERT_TRUE((*header_list)[0].is_string()); + EXPECT_EQ("foo: bar", (*header_list)[0].GetString()); - ASSERT_TRUE(header_list->GetListDeprecated()[1].is_string()); - EXPECT_EQ("cookie: name=value", - header_list->GetListDeprecated()[1].GetString()); + ASSERT_TRUE((*header_list)[1].is_string()); + EXPECT_EQ("cookie: name=value", (*header_list)[1].GetString()); } // Regression test for https://crbug.com/800282. @@ -114,17 +107,16 @@ headers["O\xe2"] = "bar"; headers["\xde\xad"] = "\xbe\xef"; - base::ListValue list = + base::Value::List list = ElideHttp2HeaderBlockForNetLog(headers, NetLogCaptureMode::kDefault); - base::Value::ConstListView list_view = list.GetListDeprecated(); - ASSERT_EQ(3u, list_view.size()); - ASSERT_TRUE(list_view[0].is_string()); - EXPECT_EQ("%ESCAPED:\xE2\x80\x8B foo: bar%81", list_view[0].GetString()); - ASSERT_TRUE(list_view[1].is_string()); - EXPECT_EQ("%ESCAPED:\xE2\x80\x8B O%E2: bar", list_view[1].GetString()); - ASSERT_TRUE(list_view[2].is_string()); - EXPECT_EQ("%ESCAPED:\xE2\x80\x8B %DE%AD: %BE%EF", list_view[2].GetString()); + ASSERT_EQ(3u, list.size()); + ASSERT_TRUE(list[0].is_string()); + EXPECT_EQ("%ESCAPED:\xE2\x80\x8B foo: bar%81", list[0].GetString()); + ASSERT_TRUE(list[1].is_string()); + EXPECT_EQ("%ESCAPED:\xE2\x80\x8B O%E2: bar", list[1].GetString()); + ASSERT_TRUE(list[2].is_string()); + EXPECT_EQ("%ESCAPED:\xE2\x80\x8B %DE%AD: %BE%EF", list[2].GetString()); } } // namespace net
diff --git a/net/spdy/spdy_network_transaction_unittest.cc b/net/spdy/spdy_network_transaction_unittest.cc index 498da62c..acf28bf 100644 --- a/net/spdy/spdy_network_transaction_unittest.cc +++ b/net/spdy/spdy_network_transaction_unittest.cc
@@ -272,7 +272,7 @@ std::unique_ptr<base::Value> value( session_->spdy_session_pool()->SpdySessionPoolInfoToValue()); CHECK(value && value->is_list()); - return value->GetListDeprecated().size(); + return value->GetList().size(); } HttpNetworkTransaction* trans() { return trans_.get(); } @@ -4906,27 +4906,24 @@ NetLogEventPhase::NONE); ASSERT_TRUE(entries[pos].HasParams()); - auto* header_list = entries[pos].params.FindKey("headers"); + auto* header_list = entries[pos].params.GetDict().FindList("headers"); ASSERT_TRUE(header_list); - ASSERT_TRUE(header_list->is_list()); - ASSERT_EQ(5u, header_list->GetListDeprecated().size()); + ASSERT_EQ(5u, header_list->size()); - ASSERT_TRUE(header_list->GetListDeprecated()[0].is_string()); - EXPECT_EQ(":method: GET", header_list->GetListDeprecated()[0].GetString()); + ASSERT_TRUE((*header_list)[0].is_string()); + EXPECT_EQ(":method: GET", (*header_list)[0].GetString()); - ASSERT_TRUE(header_list->GetListDeprecated()[1].is_string()); - EXPECT_EQ(":authority: www.example.org", - header_list->GetListDeprecated()[1].GetString()); + ASSERT_TRUE((*header_list)[1].is_string()); + EXPECT_EQ(":authority: www.example.org", (*header_list)[1].GetString()); - ASSERT_TRUE(header_list->GetListDeprecated()[2].is_string()); - EXPECT_EQ(":scheme: https", header_list->GetListDeprecated()[2].GetString()); + ASSERT_TRUE((*header_list)[2].is_string()); + EXPECT_EQ(":scheme: https", (*header_list)[2].GetString()); - ASSERT_TRUE(header_list->GetListDeprecated()[3].is_string()); - EXPECT_EQ(":path: /", header_list->GetListDeprecated()[3].GetString()); + ASSERT_TRUE((*header_list)[3].is_string()); + EXPECT_EQ(":path: /", (*header_list)[3].GetString()); - ASSERT_TRUE(header_list->GetListDeprecated()[4].is_string()); - EXPECT_EQ("user-agent: Chrome", - header_list->GetListDeprecated()[4].GetString()); + ASSERT_TRUE((*header_list)[4].is_string()); + EXPECT_EQ("user-agent: Chrome", (*header_list)[4].GetString()); } // Since we buffer the IO from the stream to the renderer, this test verifies @@ -10505,14 +10502,13 @@ ASSERT_LT(pos, entries.size()); const base::Value& params = entries[pos].params; - const base::Value* const settings = params.FindKey("settings"); + const base::Value::List* const settings = + params.GetDict().FindList("settings"); ASSERT_TRUE(settings); - ASSERT_TRUE(settings->is_list()); - base::Value::ConstListView list = settings->GetListDeprecated(); - ASSERT_FALSE(list.empty()); + ASSERT_FALSE(settings->empty()); // Get last setting parameter. - const base::Value& greased_setting = list[list.size() - 1]; + const base::Value& greased_setting = (*settings)[settings->size() - 1]; ASSERT_TRUE(greased_setting.is_string()); base::StringPiece greased_setting_string(greased_setting.GetString());
diff --git a/net/spdy/spdy_session.cc b/net/spdy/spdy_session.cc index 0733e87..148ac4f 100644 --- a/net/spdy/spdy_session.cc +++ b/net/spdy/spdy_session.cc
@@ -248,21 +248,20 @@ bool exclusive, NetLogSource source_dependency, NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("headers", - ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); - dict.SetBoolKey("fin", fin); - dict.SetIntKey("stream_id", stream_id); - dict.SetBoolKey("has_priority", has_priority); + base::Value::Dict dict; + dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); + dict.Set("fin", fin); + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("has_priority", has_priority); if (has_priority) { - dict.SetIntKey("parent_stream_id", parent_stream_id); - dict.SetIntKey("weight", weight); - dict.SetBoolKey("exclusive", exclusive); + dict.Set("parent_stream_id", static_cast<int>(parent_stream_id)); + dict.Set("weight", weight); + dict.Set("exclusive", exclusive); } if (source_dependency.IsValid()) { - source_dependency.AddToEventParameters(&dict); + source_dependency.AddToEventParameters(dict); } - return dict; + return base::Value(std::move(dict)); } base::Value NetLogSpdyHeadersReceivedParams( @@ -270,40 +269,39 @@ bool fin, spdy::SpdyStreamId stream_id, NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("headers", - ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); - dict.SetBoolKey("fin", fin); - dict.SetIntKey("stream_id", stream_id); - return dict; + base::Value::Dict dict; + dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); + dict.Set("fin", fin); + dict.Set("stream_id", static_cast<int>(stream_id)); + return base::Value(std::move(dict)); } base::Value NetLogSpdySessionCloseParams(int net_error, const std::string& description) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("net_error", net_error); - dict.SetStringKey("description", description); - return dict; + base::Value::Dict dict; + dict.Set("net_error", net_error); + dict.Set("description", description); + return base::Value(std::move(dict)); } base::Value NetLogSpdySessionParams(const HostPortProxyPair& host_pair) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("host", host_pair.first.ToString()); - dict.SetStringKey("proxy", ProxyServerToPacResultElement(host_pair.second)); - return dict; + base::Value::Dict dict; + dict.Set("host", host_pair.first.ToString()); + dict.Set("proxy", ProxyServerToPacResultElement(host_pair.second)); + return base::Value(std::move(dict)); } base::Value NetLogSpdyInitializedParams(NetLogSource source) { - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; if (source.IsValid()) { - source.AddToEventParameters(&dict); + source.AddToEventParameters(dict); } - dict.SetStringKey("protocol", NextProtoToString(kProtoHTTP2)); - return dict; + dict.Set("protocol", NextProtoToString(kProtoHTTP2)); + return base::Value(std::move(dict)); } base::Value NetLogSpdySendSettingsParams(const spdy::SettingsMap* settings) { - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; std::vector<base::Value> settings_list; for (auto it = settings->begin(); it != settings->end(); ++it) { const spdy::SpdySettingsId id = it->first; @@ -312,83 +310,80 @@ base::StringPrintf("[id:%u (%s) value:%u]", id, spdy::SettingsIdToString(id).c_str(), value)); } - dict.SetKey("settings", base::Value(std::move(settings_list))); - return dict; + dict.Set("settings", base::Value(std::move(settings_list))); + return base::Value(std::move(dict)); } base::Value NetLogSpdyRecvAcceptChParams(spdy::AcceptChOriginValuePair entry) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("origin", entry.origin); - dict.SetStringKey("accept_ch", entry.value); - return dict; + base::Value::Dict dict; + dict.Set("origin", entry.origin); + dict.Set("accept_ch", entry.value); + return base::Value(std::move(dict)); } base::Value NetLogSpdyRecvSettingParams(spdy::SpdySettingsId id, uint32_t value) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey( - "id", - base::StringPrintf("%u (%s)", id, spdy::SettingsIdToString(id).c_str())); - dict.SetIntKey("value", value); - return dict; + base::Value::Dict dict; + dict.Set("id", base::StringPrintf("%u (%s)", id, + spdy::SettingsIdToString(id).c_str())); + dict.Set("value", static_cast<int>(value)); + return base::Value(std::move(dict)); } base::Value NetLogSpdyWindowUpdateFrameParams(spdy::SpdyStreamId stream_id, uint32_t delta) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", static_cast<int>(stream_id)); - dict.SetIntKey("delta", delta); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("delta", static_cast<int>(delta)); + return base::Value(std::move(dict)); } base::Value NetLogSpdySessionWindowUpdateParams(int32_t delta, int32_t window_size) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("delta", delta); - dict.SetIntKey("window_size", window_size); - return dict; + base::Value::Dict dict; + dict.Set("delta", delta); + dict.Set("window_size", window_size); + return base::Value(std::move(dict)); } base::Value NetLogSpdyDataParams(spdy::SpdyStreamId stream_id, int size, bool fin) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", static_cast<int>(stream_id)); - dict.SetIntKey("size", size); - dict.SetBoolKey("fin", fin); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("size", size); + dict.Set("fin", fin); + return base::Value(std::move(dict)); } base::Value NetLogSpdyRecvRstStreamParams(spdy::SpdyStreamId stream_id, spdy::SpdyErrorCode error_code) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", static_cast<int>(stream_id)); - dict.SetStringKey( - "error_code", - base::StringPrintf("%u (%s)", error_code, ErrorCodeToString(error_code))); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("error_code", base::StringPrintf("%u (%s)", error_code, + ErrorCodeToString(error_code))); + return base::Value(std::move(dict)); } base::Value NetLogSpdySendRstStreamParams(spdy::SpdyStreamId stream_id, spdy::SpdyErrorCode error_code, const std::string& description) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", static_cast<int>(stream_id)); - dict.SetStringKey( - "error_code", - base::StringPrintf("%u (%s)", error_code, ErrorCodeToString(error_code))); - dict.SetStringKey("description", description); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("error_code", base::StringPrintf("%u (%s)", error_code, + ErrorCodeToString(error_code))); + dict.Set("description", description); + return base::Value(std::move(dict)); } base::Value NetLogSpdyPingParams(spdy::SpdyPingId unique_id, bool is_ack, const char* type) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("unique_id", static_cast<int>(unique_id)); - dict.SetStringKey("type", type); - dict.SetBoolKey("is_ack", is_ack); - return dict; + base::Value::Dict dict; + dict.Set("unique_id", static_cast<int>(unique_id)); + dict.Set("type", type); + dict.Set("is_ack", is_ack); + return base::Value(std::move(dict)); } base::Value NetLogSpdyRecvGoAwayParams(spdy::SpdyStreamId last_stream_id, @@ -397,16 +392,15 @@ spdy::SpdyErrorCode error_code, base::StringPiece debug_data, NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("last_accepted_stream_id", static_cast<int>(last_stream_id)); - dict.SetIntKey("active_streams", active_streams); - dict.SetIntKey("unclaimed_streams", unclaimed_streams); - dict.SetStringKey( - "error_code", - base::StringPrintf("%u (%s)", error_code, ErrorCodeToString(error_code))); - dict.SetKey("debug_data", - ElideGoAwayDebugDataForNetLog(capture_mode, debug_data)); - return dict; + base::Value::Dict dict; + dict.Set("last_accepted_stream_id", static_cast<int>(last_stream_id)); + dict.Set("active_streams", active_streams); + dict.Set("unclaimed_streams", unclaimed_streams); + dict.Set("error_code", base::StringPrintf("%u (%s)", error_code, + ErrorCodeToString(error_code))); + dict.Set("debug_data", + ElideGoAwayDebugDataForNetLog(capture_mode, debug_data)); + return base::Value(std::move(dict)); } base::Value NetLogSpdyPushPromiseReceivedParams( @@ -414,20 +408,19 @@ spdy::SpdyStreamId stream_id, spdy::SpdyStreamId promised_stream_id, NetLogCaptureMode capture_mode) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("headers", - ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); - dict.SetIntKey("id", stream_id); - dict.SetIntKey("promised_stream_id", promised_stream_id); - return dict; + base::Value::Dict dict; + dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode)); + dict.Set("id", static_cast<int>(stream_id)); + dict.Set("promised_stream_id", static_cast<int>(promised_stream_id)); + return base::Value(std::move(dict)); } base::Value NetLogSpdyAdoptedPushStreamParams(spdy::SpdyStreamId stream_id, const GURL& url) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", stream_id); - dict.SetStringKey("url", url.spec()); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("url", url.spec()); + return base::Value(std::move(dict)); } base::Value NetLogSpdySessionStalledParams(size_t num_active_streams, @@ -435,25 +428,25 @@ size_t num_pushed_streams, size_t max_concurrent_streams, const std::string& url) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("num_active_streams", num_active_streams); - dict.SetIntKey("num_created_streams", num_created_streams); - dict.SetIntKey("num_pushed_streams", num_pushed_streams); - dict.SetIntKey("max_concurrent_streams", max_concurrent_streams); - dict.SetStringKey("url", url); - return dict; + base::Value::Dict dict; + dict.Set("num_active_streams", static_cast<int>(num_active_streams)); + dict.Set("num_created_streams", static_cast<int>(num_created_streams)); + dict.Set("num_pushed_streams", static_cast<int>(num_pushed_streams)); + dict.Set("max_concurrent_streams", static_cast<int>(max_concurrent_streams)); + dict.Set("url", url); + return base::Value(std::move(dict)); } base::Value NetLogSpdyPriorityParams(spdy::SpdyStreamId stream_id, spdy::SpdyStreamId parent_stream_id, int weight, bool exclusive) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", stream_id); - dict.SetIntKey("parent_stream_id", parent_stream_id); - dict.SetIntKey("weight", weight); - dict.SetBoolKey("exclusive", exclusive); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("parent_stream_id", static_cast<int>(parent_stream_id)); + dict.Set("weight", weight); + dict.Set("exclusive", exclusive); + return base::Value(std::move(dict)); } base::Value NetLogSpdyGreasedFrameParams(spdy::SpdyStreamId stream_id, @@ -461,13 +454,13 @@ uint8_t flags, size_t length, RequestPriority priority) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", stream_id); - dict.SetIntKey("type", type); - dict.SetIntKey("flags", flags); - dict.SetIntKey("length", length); - dict.SetStringKey("priority", RequestPriorityToString(priority)); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("type", type); + dict.Set("flags", flags); + dict.Set("length", static_cast<int>(length)); + dict.Set("priority", RequestPriorityToString(priority)); + return base::Value(std::move(dict)); } // Helper function to return the total size of an array of objects @@ -1614,47 +1607,46 @@ } base::Value SpdySession::GetInfoAsValue() const { - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; - dict.SetIntKey("source_id", net_log_.source().id); + dict.Set("source_id", static_cast<int>(net_log_.source().id)); - dict.SetStringKey("host_port_pair", host_port_pair().ToString()); + dict.Set("host_port_pair", host_port_pair().ToString()); if (!pooled_aliases_.empty()) { - base::Value alias_list(base::Value::Type::LIST); + base::Value::List alias_list; for (const auto& alias : pooled_aliases_) { alias_list.Append(alias.host_port_pair().ToString()); } - dict.SetKey("aliases", std::move(alias_list)); + dict.Set("aliases", std::move(alias_list)); } - dict.SetStringKey("proxy", - ProxyServerToProxyUri(host_port_proxy_pair().second)); - dict.SetStringKey("network_isolation_key", - spdy_session_key_.network_isolation_key().ToDebugString()); + dict.Set("proxy", ProxyServerToProxyUri(host_port_proxy_pair().second)); + dict.Set("network_isolation_key", + spdy_session_key_.network_isolation_key().ToDebugString()); - dict.SetIntKey("active_streams", active_streams_.size()); + dict.Set("active_streams", static_cast<int>(active_streams_.size())); - dict.SetIntKey("unclaimed_pushed_streams", - pool_->push_promise_index()->CountStreamsForSession(this)); + dict.Set("unclaimed_pushed_streams", + static_cast<int>( + pool_->push_promise_index()->CountStreamsForSession(this))); - dict.SetStringKey("negotiated_protocol", - NextProtoToString(socket_->GetNegotiatedProtocol())); + dict.Set("negotiated_protocol", + NextProtoToString(socket_->GetNegotiatedProtocol())); - dict.SetIntKey("error", error_on_close_); - dict.SetIntKey("max_concurrent_streams", max_concurrent_streams_); + dict.Set("error", error_on_close_); + dict.Set("max_concurrent_streams", static_cast<int>(max_concurrent_streams_)); - dict.SetIntKey("streams_initiated_count", streams_initiated_count_); - dict.SetIntKey("streams_pushed_count", streams_pushed_count_); - dict.SetIntKey("streams_pushed_and_claimed_count", - streams_pushed_and_claimed_count_); - dict.SetIntKey("streams_abandoned_count", streams_abandoned_count_); + dict.Set("streams_initiated_count", streams_initiated_count_); + dict.Set("streams_pushed_count", streams_pushed_count_); + dict.Set("streams_pushed_and_claimed_count", + streams_pushed_and_claimed_count_); + dict.Set("streams_abandoned_count", streams_abandoned_count_); DCHECK(buffered_spdy_framer_.get()); - dict.SetIntKey("frames_received", buffered_spdy_framer_->frames_received()); + dict.Set("frames_received", buffered_spdy_framer_->frames_received()); - dict.SetIntKey("send_window_size", session_send_window_size_); - dict.SetIntKey("recv_window_size", session_recv_window_size_); - dict.SetIntKey("unacked_recv_window_bytes", - session_unacked_recv_window_bytes_); - return dict; + dict.Set("send_window_size", session_send_window_size_); + dict.Set("recv_window_size", session_recv_window_size_); + dict.Set("unacked_recv_window_bytes", session_unacked_recv_window_bytes_); + return base::Value(std::move(dict)); } bool SpdySession::IsReused() const {
diff --git a/net/spdy/spdy_session_pool.cc b/net/spdy/spdy_session_pool.cc index e368a5ba..da633e2 100644 --- a/net/spdy/spdy_session_pool.cc +++ b/net/spdy/spdy_session_pool.cc
@@ -479,7 +479,7 @@ std::unique_ptr<base::Value> SpdySessionPool::SpdySessionPoolInfoToValue() const { - auto list = std::make_unique<base::ListValue>(); + base::Value::List list; for (auto it = available_sessions_.begin(); it != available_sessions_.end(); ++it) { @@ -488,9 +488,9 @@ const SpdySessionKey& key = it->first; const SpdySessionKey& session_key = it->second->spdy_session_key(); if (key == session_key) - list->Append(it->second->GetInfoAsValue()); + list.Append(it->second->GetInfoAsValue()); } - return std::move(list); + return std::make_unique<base::Value>(std::move(list)); } void SpdySessionPool::OnIPAddressChanged() {
diff --git a/net/spdy/spdy_session_unittest.cc b/net/spdy/spdy_session_unittest.cc index 0ca1291..54a53a5 100644 --- a/net/spdy/spdy_session_unittest.cc +++ b/net/spdy/spdy_session_unittest.cc
@@ -2247,26 +2247,26 @@ // makes |source| an invalid source on failure. bool NetLogSourceFromEventParameters(const base::Value* event_params, NetLogSource* source) { - const base::Value* source_dict = nullptr; + const base::Value::Dict* source_dict = nullptr; int source_id = -1; int source_type = static_cast<int>(NetLogSourceType::COUNT); if (!event_params) { *source = NetLogSource(); return false; } - source_dict = event_params->FindDictKey("source_dependency"); + source_dict = event_params->GetDict().FindDict("source_dependency"); if (!source_dict) { *source = NetLogSource(); return false; } absl::optional<int> opt_int; - opt_int = source_dict->FindIntKey("id"); + opt_int = source_dict->FindInt("id"); if (!opt_int) { *source = NetLogSource(); return false; } source_id = opt_int.value(); - opt_int = source_dict->FindIntKey("type"); + opt_int = source_dict->FindInt("type"); if (!opt_int) { *source = NetLogSource(); return false;
diff --git a/net/spdy/spdy_stream.cc b/net/spdy/spdy_stream.cc index 255bcaf..b0471f2 100644 --- a/net/spdy/spdy_stream.cc +++ b/net/spdy/spdy_stream.cc
@@ -38,31 +38,31 @@ base::Value NetLogSpdyStreamErrorParams(spdy::SpdyStreamId stream_id, int net_error, base::StringPiece description) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", static_cast<int>(stream_id)); - dict.SetStringKey("net_error", ErrorToShortString(net_error)); - dict.SetStringKey("description", description); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("net_error", ErrorToShortString(net_error)); + dict.Set("description", description); + return base::Value(std::move(dict)); } base::Value NetLogSpdyStreamWindowUpdateParams(spdy::SpdyStreamId stream_id, int32_t delta, int32_t window_size) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", stream_id); - dict.SetIntKey("delta", delta); - dict.SetIntKey("window_size", window_size); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("delta", delta); + dict.Set("window_size", window_size); + return base::Value(std::move(dict)); } base::Value NetLogSpdyDataParams(spdy::SpdyStreamId stream_id, int size, bool fin) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("stream_id", static_cast<int>(stream_id)); - dict.SetIntKey("size", size); - dict.SetBoolKey("fin", fin); - return dict; + base::Value::Dict dict; + dict.Set("stream_id", static_cast<int>(stream_id)); + dict.Set("size", size); + dict.Set("fin", fin); + return base::Value(std::move(dict)); } } // namespace
diff --git a/net/test/url_request/url_request_test_job_backed_by_file.cc b/net/test/url_request/url_request_test_job_backed_by_file.cc index 176cb90..fac551a 100644 --- a/net/test/url_request/url_request_test_job_backed_by_file.cc +++ b/net/test/url_request/url_request_test_job_backed_by_file.cc
@@ -156,7 +156,7 @@ std::unique_ptr<SourceStream> URLRequestTestJobBackedByFile::SetUpSourceStream() { std::unique_ptr<SourceStream> source = URLRequestJob::SetUpSourceStream(); - if (!base::LowerCaseEqualsASCII(file_path_.Extension(), ".svgz")) + if (!base::EqualsCaseInsensitiveASCII(file_path_.Extension(), ".svgz")) return source; return GzipSourceStream::Create(std::move(source), SourceStream::TYPE_GZIP);
diff --git a/net/tools/content_decoder_tool/content_decoder_tool.cc b/net/tools/content_decoder_tool/content_decoder_tool.cc index 4bef0f4..e2b6120f 100644 --- a/net/tools/content_decoder_tool/content_decoder_tool.cc +++ b/net/tools/content_decoder_tool/content_decoder_tool.cc
@@ -70,13 +70,13 @@ std::make_unique<StdinSourceStream>(input_stream)); for (const auto& content_encoding : base::Reversed(content_encodings)) { std::unique_ptr<SourceStream> downstream; - if (base::LowerCaseEqualsASCII(content_encoding, kBrotli)) { + if (base::EqualsCaseInsensitiveASCII(content_encoding, kBrotli)) { downstream = CreateBrotliSourceStream(std::move(upstream)); - } else if (base::LowerCaseEqualsASCII(content_encoding, kDeflate)) { + } else if (base::EqualsCaseInsensitiveASCII(content_encoding, kDeflate)) { downstream = GzipSourceStream::Create(std::move(upstream), SourceStream::TYPE_DEFLATE); - } else if (base::LowerCaseEqualsASCII(content_encoding, kGZip) || - base::LowerCaseEqualsASCII(content_encoding, kXGZip)) { + } else if (base::EqualsCaseInsensitiveASCII(content_encoding, kGZip) || + base::EqualsCaseInsensitiveASCII(content_encoding, kXGZip)) { downstream = GzipSourceStream::Create(std::move(upstream), SourceStream::TYPE_GZIP); } else {
diff --git a/services/network/public/cpp/BUILD.gn b/services/network/public/cpp/BUILD.gn index 81ec15a..23c6ab8 100644 --- a/services/network/public/cpp/BUILD.gn +++ b/services/network/public/cpp/BUILD.gn
@@ -36,6 +36,8 @@ "client_hints.h", "constants.cc", "constants.h", + "content_language_parser.cc", + "content_language_parser.h", "content_security_policy/content_security_policy.cc", "content_security_policy/content_security_policy.h", "content_security_policy/csp_context.cc", @@ -129,6 +131,8 @@ "trust_token_operation_authorization.h", "url_util.cc", "url_util.h", + "variants_header_parser.cc", + "variants_header_parser.h", "weak_wrapper_shared_url_loader_factory.cc", "weak_wrapper_shared_url_loader_factory.h", "web_sandbox_flags.cc", @@ -407,6 +411,7 @@ sources = [ "bfcache_opt_in_parser_unittest.cc", "client_hints_unittest.cc", + "content_language_parser_unittest.cc", "content_security_policy/content_security_policy_unittest.cc", "content_security_policy/csp_context_unittest.cc", "content_security_policy/csp_source_list_unittest.cc", @@ -454,6 +459,7 @@ "transferable_directory_unittest.cc", "url_loader_completion_status_mojom_traits_unittest.cc", "url_request_mojom_traits_unittest.cc", + "variants_header_parser_unittest.cc", "web_sandbox_flags_unittests.cc", "x_frame_options_parser_unittest.cc", ]
diff --git a/services/network/public/cpp/content_language_parser.cc b/services/network/public/cpp/content_language_parser.cc new file mode 100644 index 0000000..0d8dc6b --- /dev/null +++ b/services/network/public/cpp/content_language_parser.cc
@@ -0,0 +1,40 @@ +// Copyright 2022 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 "services/network/public/cpp/content_language_parser.h" + +#include <utility> +#include <vector> + +#include "base/strings/string_util.h" +#include "net/http/structured_headers.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace network { + +absl::optional<std::vector<std::string>> ParseContentLanguages( + const std::string& header) { + // Content-Language is a sh-dictionary of tokens to header; see: + // https://httpwg.org/specs/rfc7231.html#rfc.section.3.1.3.2. + absl::optional<net::structured_headers::List> maybe_list = + net::structured_headers::ParseList(base::ToLowerASCII(header)); + if (!maybe_list.has_value()) + return absl::nullopt; + + for (const auto& list_item : maybe_list.value()) { + // Make sure not a nested list. + if (list_item.member.size() != 1u) + return absl::nullopt; + if (!list_item.member[0].item.is_token()) + return absl::nullopt; + } + + std::vector<std::string> result; + for (const auto& list_item : maybe_list.value()) { + const std::string& token_value = list_item.member[0].item.GetString(); + result.push_back(token_value); + } + return absl::make_optional(std::move(result)); +} + +} // namespace network \ No newline at end of file
diff --git a/services/network/public/cpp/content_language_parser.h b/services/network/public/cpp/content_language_parser.h new file mode 100644 index 0000000..6dcf8ce --- /dev/null +++ b/services/network/public/cpp/content_language_parser.h
@@ -0,0 +1,28 @@ +// Copyright 2022 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 SERVICES_NETWORK_PUBLIC_CPP_CONTENT_LANGUAGE_PARSER_H_ +#define SERVICES_NETWORK_PUBLIC_CPP_CONTENT_LANGUAGE_PARSER_H_ + +#include <vector> + +#include "base/component_export.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace network { + +// Parses `Content-Language` headers and returns the parsed representations of +// content languages. The parsed representations are used to pass content +// language headers between processes. +// +// Returns base::nullopt if parsing failed and the header should be ignored; +// otherwise returns a (possibly empty) list of string. See +// https://datatracker.ietf.org/doc/html/rfc3282#section-2. +COMPONENT_EXPORT(NETWORK_CPP) +absl::optional<std::vector<std::string>> ParseContentLanguages( + const std::string& header); + +} // namespace network + +#endif // SERVICES_NETWORK_PUBLIC_CPP_CONTENT_LANGUAGE_PARSER_H_
diff --git a/services/network/public/cpp/content_language_parser_unittest.cc b/services/network/public/cpp/content_language_parser_unittest.cc new file mode 100644 index 0000000..f685cb9d --- /dev/null +++ b/services/network/public/cpp/content_language_parser_unittest.cc
@@ -0,0 +1,46 @@ +// Copyright 2022 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 "services/network/public/cpp/content_language_parser.h" +#include <iostream> + +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::UnorderedElementsAre; + +namespace network { + +TEST(ContentLanguageTest, ParseContentLanguages) { + absl::optional<std::vector<std::string>> result; + + // Empty is OK. + result = ParseContentLanguages(" "); + ASSERT_TRUE(result.has_value()); + EXPECT_TRUE(result.value().empty()); + + // Normal case. + result = ParseContentLanguages("en, zh "); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), std::vector<std::string>({"en", "zh"})); + + // Must be a list of tokens, not other things. + result = ParseContentLanguages("\"en\", \"zh\""); + EXPECT_FALSE(result.has_value()); + + // Parameters to the tokens are ignored. + result = ParseContentLanguages("en;q=1.0, zh"); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), std::vector<std::string>({"en", "zh"})); + + // Matching is case-insensitive. + result = ParseContentLanguages("de-DE, en-CA "); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), std::vector<std::string>({"de-de", "en-ca"})); + + result = ParseContentLanguages("en, fr (This is a dictionary)"); + ASSERT_FALSE(result.has_value()); +} + +} // namespace network
diff --git a/services/network/public/cpp/corb/corb_impl.cc b/services/network/public/cpp/corb/corb_impl.cc index ee70b09..90c9dba 100644 --- a/services/network/public/cpp/corb/corb_impl.cc +++ b/services/network/public/cpp/corb/corb_impl.cc
@@ -308,31 +308,31 @@ // Checking for image/svg+xml and application/dash+xml early ensures that they // won't get classified as MimeType::kXml by the presence of the "+xml" // suffix. - if (base::LowerCaseEqualsASCII(mime_type, kImageSvg) || - base::LowerCaseEqualsASCII(mime_type, kDashVideo)) + if (base::EqualsCaseInsensitiveASCII(mime_type, kImageSvg) || + base::EqualsCaseInsensitiveASCII(mime_type, kDashVideo)) return MimeType::kOthers; // See also https://mimesniff.spec.whatwg.org/#html-mime-type - if (base::LowerCaseEqualsASCII(mime_type, kTextHtml)) + if (base::EqualsCaseInsensitiveASCII(mime_type, kTextHtml)) return MimeType::kHtml; // See also https://mimesniff.spec.whatwg.org/#json-mime-type constexpr auto kCaseInsensitive = base::CompareCase::INSENSITIVE_ASCII; - if (base::LowerCaseEqualsASCII(mime_type, kAppJson) || - base::LowerCaseEqualsASCII(mime_type, kTextJson) || - base::LowerCaseEqualsASCII(mime_type, kJsonProtobuf) || + if (base::EqualsCaseInsensitiveASCII(mime_type, kAppJson) || + base::EqualsCaseInsensitiveASCII(mime_type, kTextJson) || + base::EqualsCaseInsensitiveASCII(mime_type, kJsonProtobuf) || base::EndsWith(mime_type, kJsonSuffix, kCaseInsensitive)) { return MimeType::kJson; } // See also https://mimesniff.spec.whatwg.org/#xml-mime-type - if (base::LowerCaseEqualsASCII(mime_type, kAppXml) || - base::LowerCaseEqualsASCII(mime_type, kTextXml) || + if (base::EqualsCaseInsensitiveASCII(mime_type, kAppXml) || + base::EqualsCaseInsensitiveASCII(mime_type, kTextXml) || base::EndsWith(mime_type, kXmlSuffix, kCaseInsensitive)) { return MimeType::kXml; } - if (base::LowerCaseEqualsASCII(mime_type, kTextPlain)) + if (base::EqualsCaseInsensitiveASCII(mime_type, kTextPlain)) return MimeType::kPlain; if (base::Contains(GetNeverSniffedMimeTypes(), @@ -780,7 +780,7 @@ case MimeType::kOthers: // Stylesheets shouldn't be sniffed for JSON parser breakers - see // https://crbug.com/809259. - if (base::LowerCaseEqualsASCII(response.mime_type, "text/css")) + if (base::EqualsCaseInsensitiveASCII(response.mime_type, "text/css")) return Decision::kAllow; return Decision::kSniffMore; @@ -833,7 +833,7 @@ if (response.headers) { std::string value; response.headers->GetNormalizedHeader("accept-ranges", &value); - if (!value.empty() && !base::LowerCaseEqualsASCII(value, "none")) { + if (!value.empty() && !base::EqualsCaseInsensitiveASCII(value, "none")) { return true; } } @@ -879,13 +879,13 @@ // https://mimesniff.spec.whatwg.org/#audio-or-video-mime-type. if (base::StartsWith(mime_type, "audio", kCaseInsensitive) || base::StartsWith(mime_type, "video", kCaseInsensitive) || - base::LowerCaseEqualsASCII(mime_type, "application/ogg") || - base::LowerCaseEqualsASCII(mime_type, "application/dash+xml")) { + base::EqualsCaseInsensitiveASCII(mime_type, "application/ogg") || + base::EqualsCaseInsensitiveASCII(mime_type, "application/dash+xml")) { return kPublic; } // CSS files are assumed public and must be sent with text/css. - if (base::LowerCaseEqualsASCII(mime_type, "text/css")) { + if (base::EqualsCaseInsensitiveASCII(mime_type, "text/css")) { return kPublic; } return kOther; @@ -1091,7 +1091,7 @@ std::string nosniff_header; response.headers->GetNormalizedHeader("x-content-type-options", &nosniff_header); - return base::LowerCaseEqualsASCII(nosniff_header, "nosniff"); + return base::EqualsCaseInsensitiveASCII(nosniff_header, "nosniff"); } // static
diff --git a/services/network/public/cpp/corb/orb_impl.cc b/services/network/public/cpp/corb/orb_impl.cc index 574e7b7..7ea329b 100644 --- a/services/network/public/cpp/corb/orb_impl.cc +++ b/services/network/public/cpp/corb/orb_impl.cc
@@ -31,7 +31,7 @@ // This function returns true for image formats that are not recognized by // net::SniffMimeTypeFromLocalData. This helps to allow such images. - return base::LowerCaseEqualsASCII(mime_type, "image/svg+xml"); + return base::EqualsCaseInsensitiveASCII(mime_type, "image/svg+xml"); } bool IsAudioOrVideoMimeType(base::StringPiece mime_type) { @@ -59,7 +59,7 @@ // (sniffing audio/video in the OpaqueResponseBlockingAnalyzer::Sniff method // below) because net::SniffMimeTypeFromLocalData may return // "application/ogg". - if (base::LowerCaseEqualsASCII(mime_type, "application/ogg")) + if (base::EqualsCaseInsensitiveASCII(mime_type, "application/ogg")) return true; // TODO(lukasza): Address this departure from the spec (which doesn't @@ -69,18 +69,19 @@ // modify ORB spec to match this implementation. If there is too much // web-compatibility risk, then ORB might need to fully parse DASH/HLS // manifests. - if (base::LowerCaseEqualsASCII(mime_type, "application/dash+xml")) + if (base::EqualsCaseInsensitiveASCII(mime_type, "application/dash+xml")) return true; - if (base::LowerCaseEqualsASCII(mime_type, "application/vnd.apple.mpegurl")) + if (base::EqualsCaseInsensitiveASCII(mime_type, + "application/vnd.apple.mpegurl")) return true; - if (base::LowerCaseEqualsASCII(mime_type, "text/vtt")) + if (base::EqualsCaseInsensitiveASCII(mime_type, "text/vtt")) return true; return false; } bool IsTextCssMimeType(base::StringPiece mime_type) { - return base::LowerCaseEqualsASCII(mime_type, "text/css"); + return base::EqualsCaseInsensitiveASCII(mime_type, "text/css"); } // ORB spec says that "An opaque-safelisted MIME type" is a JavaScript MIME type
diff --git a/services/network/public/cpp/features.cc b/services/network/public/cpp/features.cc index 5110718..081e8d7 100644 --- a/services/network/public/cpp/features.cc +++ b/services/network/public/cpp/features.cc
@@ -289,5 +289,11 @@ // Read as much of the net::URLRequest as there is space in the Mojo data pipe. const base::Feature kOptimizeNetworkBuffers{"OptimizeNetworkBuffers", base::FEATURE_DISABLED_BY_DEFAULT}; + +// Enables support for the `Variants` response header and reduce +// accept-language. https://github.com/Tanych/accept-language +const base::Feature kReduceAcceptLanguage{"ReduceAcceptLanguage", + base::FEATURE_DISABLED_BY_DEFAULT}; + } // namespace features } // namespace network
diff --git a/services/network/public/cpp/features.h b/services/network/public/cpp/features.h index cc8aea4..4222ac17 100644 --- a/services/network/public/cpp/features.h +++ b/services/network/public/cpp/features.h
@@ -122,6 +122,9 @@ extern const base::FeatureParam<std::string> kCacheTransparencyPervasivePayloads; +COMPONENT_EXPORT(NETWORK_CPP) +extern const base::Feature kReduceAcceptLanguage; + } // namespace features } // namespace network
diff --git a/services/network/public/cpp/parsed_headers.cc b/services/network/public/cpp/parsed_headers.cc index b9ea67f7..2074f4a 100644 --- a/services/network/public/cpp/parsed_headers.cc +++ b/services/network/public/cpp/parsed_headers.cc
@@ -10,6 +10,7 @@ #include "net/reporting/reporting_header_parser.h" #include "services/network/public/cpp/bfcache_opt_in_parser.h" #include "services/network/public/cpp/client_hints.h" +#include "services/network/public/cpp/content_language_parser.h" #include "services/network/public/cpp/content_security_policy/content_security_policy.h" #include "services/network/public/cpp/cross_origin_embedder_policy_parser.h" #include "services/network/public/cpp/cross_origin_opener_policy_parser.h" @@ -17,6 +18,7 @@ #include "services/network/public/cpp/link_header_parser.h" #include "services/network/public/cpp/origin_agent_cluster_parser.h" #include "services/network/public/cpp/timing_allow_origin_parser.h" +#include "services/network/public/cpp/variants_header_parser.h" #include "services/network/public/cpp/x_frame_options_parser.h" namespace network { @@ -79,6 +81,17 @@ } #endif + if (base::FeatureList::IsEnabled(network::features::kReduceAcceptLanguage)) { + std::string variants; + if (headers->GetNormalizedHeader("Variants", &variants)) { + parsed_headers->variants_headers = ParseVariantsHeaders(variants); + } + std::string content_language; + if (headers->GetNormalizedHeader("Content-Language", &content_language)) { + parsed_headers->content_language = + ParseContentLanguages(content_language); + } + } return parsed_headers; }
diff --git a/services/network/public/cpp/variants_header_parser.cc b/services/network/public/cpp/variants_header_parser.cc new file mode 100644 index 0000000..8fe5515 --- /dev/null +++ b/services/network/public/cpp/variants_header_parser.cc
@@ -0,0 +1,60 @@ +// Copyright 2022 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 "services/network/public/cpp/variants_header_parser.h" + +#include <utility> +#include <vector> + +#include "base/containers/flat_set.h" +#include "base/no_destructor.h" +#include "net/http/structured_headers.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace network { +// Add Support Variants for existing content negotiation mechanisms, See +// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-variants-06#appendix-A. +// For reduce accept-language fingerprinting, we only care about accept-language +// header. +SupportedVariantsNameSet MakeSupportedVariantsNameSet() { + return {"accept-language"}; +} + +const SupportedVariantsNameSet& GetSupportedVariantsNameSet() { + static const base::NoDestructor<SupportedVariantsNameSet> set( + MakeSupportedVariantsNameSet()); + return *set; +} + +absl::optional<std::vector<mojom::VariantsHeaderPtr>> ParseVariantsHeaders( + const std::string& header) { + // Variants is a sh-dictionary of tokens to header; see: + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-variants-06#section-2 + absl::optional<net::structured_headers::Dictionary> maybe_dictionary = + net::structured_headers::ParseDictionary(base::ToLowerASCII(header)); + if (!maybe_dictionary.has_value()) + return absl::nullopt; + + std::vector<mojom::VariantsHeaderPtr> parsed_headers; + + // Now filter only supported variants. + const SupportedVariantsNameSet& supported_set = GetSupportedVariantsNameSet(); + for (const auto& dictionary_pair : maybe_dictionary.value()) { + if (!supported_set.count(dictionary_pair.first)) + continue; + + std::vector<std::string> parsed_values; + for (const auto& member : dictionary_pair.second.member) { + if (!member.item.is_token()) + continue; + parsed_values.push_back(member.item.GetString()); + } + auto parsed = mojom::VariantsHeader::New(dictionary_pair.first, + std::move(parsed_values)); + parsed_headers.push_back(std::move(parsed)); + } + return absl::make_optional(std::move(parsed_headers)); +} + +} // namespace network \ No newline at end of file
diff --git a/services/network/public/cpp/variants_header_parser.h b/services/network/public/cpp/variants_header_parser.h new file mode 100644 index 0000000..aba0350 --- /dev/null +++ b/services/network/public/cpp/variants_header_parser.h
@@ -0,0 +1,31 @@ +// Copyright 2022 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 SERVICES_NETWORK_PUBLIC_CPP_VARIANTS_HEADER_PARSER_H_ +#define SERVICES_NETWORK_PUBLIC_CPP_VARIANTS_HEADER_PARSER_H_ + +#include <vector> + +#include "base/component_export.h" +#include "services/network/public/mojom/variants_header.mojom.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace network { + +using SupportedVariantsNameSet = base::flat_set<std::string>; + +// Parses `Variants` headers and returns the parsed representations of them. +// The parsed representations are used to pass Variants headers between +// processes. +// +// Returns base::nullopt if parsing failed and the header should be ignored; +// otherwise returns a (possibly empty) list of Variant representations. See +// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-variants-06. +COMPONENT_EXPORT(NETWORK_CPP) +absl::optional<std::vector<mojom::VariantsHeaderPtr>> ParseVariantsHeaders( + const std::string& header); + +} // namespace network + +#endif // SERVICES_NETWORK_PUBLIC_CPP_VARIANTS_HEADER_PARSER_H_ \ No newline at end of file
diff --git a/services/network/public/cpp/variants_header_parser_unittest.cc b/services/network/public/cpp/variants_header_parser_unittest.cc new file mode 100644 index 0000000..fae6e96d --- /dev/null +++ b/services/network/public/cpp/variants_header_parser_unittest.cc
@@ -0,0 +1,85 @@ +// Copyright 2022 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 "services/network/public/cpp/variants_header_parser.h" +#include <iostream> + +#include "net/http/http_response_headers.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::UnorderedElementsAre; + +namespace network { + +TEST(VariantsHeaderTest, ParseVariantsHeader) { + absl::optional<std::vector<mojom::VariantsHeaderPtr>> result; + + // Empty is OK. + result = ParseVariantsHeaders(" "); + EXPECT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), 0UL); + + // Normal case. + result = ParseVariantsHeaders("accept-language=(en)"); + EXPECT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), 1UL); + EXPECT_EQ(result.value()[0]->name, "accept-language"); + EXPECT_EQ(result.value()[0]->available_values, + (std::vector<std::string>){"en"}); + + // Case with no values. + result = ParseVariantsHeaders("Accept-Language;de;en;jp"); + EXPECT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), 1UL); + EXPECT_EQ(result.value()[0]->name, "accept-language"); + EXPECT_EQ(result.value()[0]->available_values, (std::vector<std::string>){}); + + // Value list is empty + result = ParseVariantsHeaders("accept-language=()"); + EXPECT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), 1UL); + EXPECT_EQ(result.value()[0]->name, "accept-language"); + EXPECT_EQ(result.value()[0]->available_values, (std::vector<std::string>){}); + + // Must be a list of tokens, not other things. + result = ParseVariantsHeaders( + "\"accept-language=(en)\", \"accept-encoding=(gzip)\""); + EXPECT_FALSE(result.has_value()); + + // Unknown tokens are fine, since this meant to be extensible. + result = + ParseVariantsHeaders("accept-language=(en), accept-encoding=(gzip)"); + EXPECT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), 1UL); + EXPECT_EQ(result.value()[0]->name, "accept-language"); + EXPECT_EQ(result.value()[0]->available_values, + (std::vector<std::string>){"en"}); + + // Matching is case-insensitive. + result = ParseVariantsHeaders("Accept-Language=(en)"); + EXPECT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), 1UL); + EXPECT_EQ(result.value()[0]->name, "accept-language"); + EXPECT_EQ(result.value()[0]->available_values, + (std::vector<std::string>){"en"}); + + // Matching can find a one or more tokens. + result = ParseVariantsHeaders("Accept-Language=(en de zh)"); + EXPECT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), 1UL); + EXPECT_EQ(result.value()[0]->name, "accept-language"); + EXPECT_EQ(result.value()[0]->available_values, + std::vector<std::string>({"en", "de", "zh"})); + + // Only matching first comes value pair. + result = ParseVariantsHeaders("accept-language=(en), accept-language=(de)"); + EXPECT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), 1UL); + EXPECT_EQ(result.value()[0]->name, "accept-language"); + EXPECT_EQ(result.value()[0]->available_values, + std::vector<std::string>({"de"})); +} + +} // namespace network
diff --git a/services/network/public/mojom/BUILD.gn b/services/network/public/mojom/BUILD.gn index ec490ec..35fcfde 100644 --- a/services/network/public/mojom/BUILD.gn +++ b/services/network/public/mojom/BUILD.gn
@@ -288,6 +288,7 @@ "url_loader_network_service_observer.mojom", "url_request.mojom", "url_response_head.mojom", + "variants_header.mojom", "web_bundle_handle.mojom", "web_client_hints_types.mojom", "web_sandbox_flags.mojom",
diff --git a/services/network/public/mojom/parsed_headers.mojom b/services/network/public/mojom/parsed_headers.mojom index 8ecea65..be0e0b1d 100644 --- a/services/network/public/mojom/parsed_headers.mojom +++ b/services/network/public/mojom/parsed_headers.mojom
@@ -10,6 +10,7 @@ import "services/network/public/mojom/cross_origin_opener_policy.mojom"; import "services/network/public/mojom/link_header.mojom"; import "services/network/public/mojom/timing_allow_origin.mojom"; +import "services/network/public/mojom/variants_header.mojom"; import "services/network/public/mojom/web_client_hints_types.mojom"; import "services/network/public/mojom/x_frame_options.mojom"; @@ -87,4 +88,26 @@ // header. Will be null if that header was not present in the response. // URLs are represented here as strings, and have not been validated. map<string,string>? reporting_endpoints; + + // The parsed Variants response header. + // + // Indicates that representations are available for a given resource at the + // time that the response is produced, by enumerating the request header + // fields that it varies on, along with a representation of the values that + // are available for each. + // + // If Structured Header parsing fails or a member's value does have the + // structure outlined as defined, the client MUST treat the representation as + // having no Variants header field. + // + // Variants header only contains Accept-Language values. Please update the + // description if it extends to support other header values. Also, it only be + // populated when kReduceAcceptLanguage feature enabled. + // + // For more information, see: + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-variants-06#section-2. + array<VariantsHeader>? variants_headers; + + // The parsed value of the Content-Language header. + array<string>? content_language; };
diff --git a/services/network/public/mojom/variants_header.mojom b/services/network/public/mojom/variants_header.mojom new file mode 100644 index 0000000..c5fa149 --- /dev/null +++ b/services/network/public/mojom/variants_header.mojom
@@ -0,0 +1,14 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module network.mojom; + +// Holds the parsed representation of the Variants header. +// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-variants-06#section-2 +struct VariantsHeader { + // The name of representation of in Variants header. + string name; + // The `available_values` of the representation. + array<string> available_values; +}; \ No newline at end of file
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 4cde762..567a47d 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -7028,27 +7028,6 @@ ] } ], - "SafeBrowsingSendSampledPingsForProtegoAllowlistDomains": [ - { - "platforms": [ - "android", - "ios", - "linux", - "mac", - "windows", - "chromeos", - "chromeos_lacros" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "SafeBrowsingSendSampledPingsForProtegoAllowlistDomains" - ] - } - ] - } - ], "ScrollUnification": [ { "platforms": [
diff --git a/third_party/blink/renderer/core/css/css_selector.cc b/third_party/blink/renderer/core/css/css_selector.cc index aefc69cb..b8125240 100644 --- a/third_party/blink/renderer/core/css/css_selector.cc +++ b/third_party/blink/renderer/core/css/css_selector.cc
@@ -339,8 +339,8 @@ case kPseudoListBox: case kPseudoMultiSelectFocus: case kPseudoHostHasAppearance: - case kPseudoPopupOpen: case kPseudoSlotted: + case kPseudoTopLayer: case kPseudoVideoPersistent: case kPseudoVideoPersistentAncestor: case kPseudoXrOverlay: @@ -452,7 +452,6 @@ {"placeholder", CSSSelector::kPseudoPlaceholder}, {"placeholder-shown", CSSSelector::kPseudoPlaceholderShown}, {"playing", CSSSelector::kPseudoPlaying}, - {"popup-open", CSSSelector::kPseudoPopupOpen}, {"read-only", CSSSelector::kPseudoReadOnly}, {"read-write", CSSSelector::kPseudoReadWrite}, {"required", CSSSelector::kPseudoRequired}, @@ -465,6 +464,7 @@ {"start", CSSSelector::kPseudoStart}, {"target", CSSSelector::kPseudoTarget}, {"target-text", CSSSelector::kPseudoTargetText}, + {"top-layer", CSSSelector::kPseudoTopLayer}, {"valid", CSSSelector::kPseudoValid}, {"vertical", CSSSelector::kPseudoVertical}, {"visited", CSSSelector::kPseudoVisited}, @@ -553,7 +553,7 @@ !RuntimeEnabledFeatures::CSSPseudoPlayingPausedEnabled()) return CSSSelector::kPseudoUnknown; - if (match->type == CSSSelector::kPseudoPopupOpen && + if (match->type == CSSSelector::kPseudoTopLayer && !RuntimeEnabledFeatures::HTMLPopupAttributeEnabled()) return CSSSelector::kPseudoUnknown; @@ -749,7 +749,6 @@ case kPseudoPictureInPicture: case kPseudoPlaceholderShown: case kPseudoPlaying: - case kPseudoPopupOpen: case kPseudoReadOnly: case kPseudoReadWrite: case kPseudoRelativeLeftmost: @@ -761,6 +760,7 @@ case kPseudoStart: case kPseudoState: case kPseudoTarget: + case kPseudoTopLayer: case kPseudoUnknown: case kPseudoValid: case kPseudoVertical:
diff --git a/third_party/blink/renderer/core/css/css_selector.h b/third_party/blink/renderer/core/css/css_selector.h index 91c4463..9d01bb76 100644 --- a/third_party/blink/renderer/core/css/css_selector.h +++ b/third_party/blink/renderer/core/css/css_selector.h
@@ -280,7 +280,7 @@ kPseudoListBox, kPseudoMultiSelectFocus, kPseudoHostHasAppearance, - kPseudoPopupOpen, + kPseudoTopLayer, kPseudoSlotted, kPseudoVideoPersistent, kPseudoVideoPersistentAncestor,
diff --git a/third_party/blink/renderer/core/css/parser/css_proto_converter.cc b/third_party/blink/renderer/core/css/parser/css_proto_converter.cc index 41ebdf6..0da5a8e 100644 --- a/third_party/blink/renderer/core/css/parser/css_proto_converter.cc +++ b/third_party/blink/renderer/core/css/parser/css_proto_converter.cc
@@ -104,7 +104,6 @@ "past", "placeholder", "placeholder-shown", - "popup-open", "read-only", "read-write", "required", @@ -115,6 +114,7 @@ "single-button", "start", "target", + "top-layer", "valid", "vertical", "visited",
diff --git a/third_party/blink/renderer/core/css/popup.css b/third_party/blink/renderer/core/css/popup.css index bf6e09b..5b3703d 100644 --- a/third_party/blink/renderer/core/css/popup.css +++ b/third_party/blink/renderer/core/css/popup.css
@@ -9,9 +9,9 @@ @namespace "http://www.w3.org/1999/xhtml"; -[popup=popup i]:not(:popup-open), -[popup=hint i]:not(:popup-open), -[popup=async i]:not(:popup-open) { +[popup=popup i]:not(:top-layer), +[popup=hint i]:not(:top-layer), +[popup=async i]:not(:top-layer) { display: none; }
diff --git a/third_party/blink/renderer/core/css/rule_feature_set.cc b/third_party/blink/renderer/core/css/rule_feature_set.cc index 84c26e0..75f9ec99 100644 --- a/third_party/blink/renderer/core/css/rule_feature_set.cc +++ b/third_party/blink/renderer/core/css/rule_feature_set.cc
@@ -176,7 +176,7 @@ case CSSSelector::kPseudoListBox: case CSSSelector::kPseudoMultiSelectFocus: case CSSSelector::kPseudoHostHasAppearance: - case CSSSelector::kPseudoPopupOpen: + case CSSSelector::kPseudoTopLayer: case CSSSelector::kPseudoSlotted: case CSSSelector::kPseudoVideoPersistent: case CSSSelector::kPseudoVideoPersistentAncestor: @@ -648,7 +648,7 @@ case CSSSelector::kPseudoInRange: case CSSSelector::kPseudoOutOfRange: case CSSSelector::kPseudoDefined: - case CSSSelector::kPseudoPopupOpen: + case CSSSelector::kPseudoTopLayer: case CSSSelector::kPseudoVideoPersistent: case CSSSelector::kPseudoVideoPersistentAncestor: case CSSSelector::kPseudoXrOverlay:
diff --git a/third_party/blink/renderer/core/css/selector_checker.cc b/third_party/blink/renderer/core/css/selector_checker.cc index 73bc0b2..1e5ad9a 100644 --- a/third_party/blink/renderer/core/css/selector_checker.cc +++ b/third_party/blink/renderer/core/css/selector_checker.cc
@@ -1393,7 +1393,7 @@ } break; } - case CSSSelector::kPseudoPopupOpen: + case CSSSelector::kPseudoTopLayer: if (element.HasValidPopupAttribute()) { return element.popupOpen(); }
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index 4f70a364..2b61ea8 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -2485,7 +2485,7 @@ } GetPopupData()->setOpen(true); GetDocument().AddToTopLayer(this); - PseudoStateChanged(CSSSelector::kPseudoPopupOpen); + PseudoStateChanged(CSSSelector::kPseudoTopLayer); GetPopupData()->setPreviouslyFocusedElement( should_restore_focus ? GetDocument().FocusedElement() : nullptr); SetPopupFocusOnShow(); @@ -2527,7 +2527,7 @@ GetPopupData()->setInvoker(nullptr); GetPopupData()->setNeedsRepositioningForSelectMenu(false); GetDocument().RemoveFromTopLayer(this); - PseudoStateChanged(CSSSelector::kPseudoPopupOpen); + PseudoStateChanged(CSSSelector::kPseudoTopLayer); // Queue the hide event. Event* event = Event::CreateBubble(event_type_names::kHide); event->SetTarget(this);
diff --git a/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc b/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc index e4a6b94..5e87de6 100644 --- a/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc +++ b/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc
@@ -94,9 +94,7 @@ } // https://w3c.github.io/webappsec-csp/#effective-directive-for-inline-check -// TODO(hiroshige): The following two methods are slightly different. -// Investigate the correct behavior and merge them. -CSPDirectiveName GetDirectiveTypeForAllowInlineFromInlineType( +CSPDirectiveName EffectiveDirectiveForInlineCheck( ContentSecurityPolicy::InlineType inline_type) { // 1. Switch on type: [spec text] switch (inline_type) { @@ -124,24 +122,6 @@ } } -CSPDirectiveName GetDirectiveTypeForAllowHashFromInlineType( - ContentSecurityPolicy::InlineType inline_type) { - switch (inline_type) { - case ContentSecurityPolicy::InlineType::kScript: - return CSPDirectiveName::ScriptSrcElem; - - case ContentSecurityPolicy::InlineType::kNavigation: - case ContentSecurityPolicy::InlineType::kScriptAttribute: - return CSPDirectiveName::ScriptSrcAttr; - - case ContentSecurityPolicy::InlineType::kStyleAttribute: - return CSPDirectiveName::StyleSrcAttr; - - case ContentSecurityPolicy::InlineType::kStyle: - return CSPDirectiveName::StyleSrcElem; - } -} - CSPOperativeDirective OperativeDirective( const network::mojom::blink::ContentSecurityPolicy& csp, CSPDirectiveName type, @@ -669,8 +649,7 @@ const String& context_url, const WTF::OrdinalNumber& context_line, ReportingDisposition reporting_disposition) { - CSPDirectiveName type = - GetDirectiveTypeForAllowInlineFromInlineType(inline_type); + CSPDirectiveName type = EffectiveDirectiveForInlineCheck(inline_type); CSPOperativeDirective directive = OperativeDirective(csp, type); if (IsMatchingNoncePresent(directive.source_list, nonce)) @@ -910,7 +889,7 @@ const network::mojom::blink::CSPHashSource& hash_value, const ContentSecurityPolicy::InlineType inline_type) { CSPDirectiveName directive_type = - GetDirectiveTypeForAllowHashFromInlineType(inline_type); + EffectiveDirectiveForInlineCheck(inline_type); const network::mojom::blink::CSPSourceList* operative_directive = OperativeDirective(csp, directive_type).source_list;
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc index 3aa3ab51..a9be638 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
@@ -380,7 +380,7 @@ DEFINE_STRING_MAPPING(PseudoIsHtml) DEFINE_STRING_MAPPING(PseudoListBox) DEFINE_STRING_MAPPING(PseudoMultiSelectFocus) - DEFINE_STRING_MAPPING(PseudoPopupOpen) + DEFINE_STRING_MAPPING(PseudoTopLayer) DEFINE_STRING_MAPPING(PseudoHostHasAppearance) DEFINE_STRING_MAPPING(PseudoVideoPersistent) DEFINE_STRING_MAPPING(PseudoVideoPersistentAncestor)
diff --git a/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc b/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc index a66185e..8bccb29 100644 --- a/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc +++ b/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc
@@ -65,7 +65,6 @@ class CryptoResultImpl::Resolver final : public ScriptPromiseResolver { public: static Resolver* Create(ScriptState* script_state, CryptoResultImpl* result) { - DCHECK(script_state->ContextIsValid()); Resolver* resolver = MakeGarbageCollected<Resolver>(script_state, result); resolver->KeepAliveWhilePending(); return resolver; @@ -114,7 +113,7 @@ cancel_(base::MakeRefCounted<CryptoResultCancel>()) { // Sync cancellation state. if (ExecutionContext::From(script_state)->IsContextDestroyed()) - cancel_->Cancel(); + Cancel(); } CryptoResultImpl::~CryptoResultImpl() { @@ -245,9 +244,7 @@ } void CryptoResultImpl::Cancel() { - DCHECK(cancel_); cancel_->Cancel(); - cancel_ = nullptr; ClearResolver(); }
diff --git a/third_party/blink/renderer/platform/network/http_parsers.cc b/third_party/blink/renderer/platform/network/http_parsers.cc index e23658d..1601a21 100644 --- a/third_party/blink/renderer/platform/network/http_parsers.cc +++ b/third_party/blink/renderer/platform/network/http_parsers.cc
@@ -238,6 +238,12 @@ } } +blink::VariantsHeaderPtr ConvertToBlink(const VariantsHeaderPtr& in) { + DCHECK(in); + return blink::VariantsHeader::New(ConvertToBlink(in->name), + ConvertToBlink(in->available_values)); +} + blink::ParsedHeadersPtr ConvertToBlink(const ParsedHeadersPtr& in) { DCHECK(in); return blink::ParsedHeaders::New( @@ -254,6 +260,12 @@ ConvertToBlink(in->timing_allow_origin), in->bfcache_opt_in_unload, in->reporting_endpoints.has_value() ? absl::make_optional(ConvertToBlink(in->reporting_endpoints.value())) + : absl::nullopt, + in->variants_headers.has_value() + ? absl::make_optional(ConvertToBlink(in->variants_headers.value())) + : absl::nullopt, + in->content_language.has_value() + ? absl::make_optional(ConvertToBlink(in->content_language.value())) : absl::nullopt); }
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index def987a..4a755ea5 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1233,7 +1233,6 @@ }, { name: "HighlightOverlayPainting", - status: "stable", }, { name: "HrefTranslate",
diff --git a/third_party/blink/tools/blinkpy/common/net/web.py b/third_party/blink/tools/blinkpy/common/net/web.py index 02af1e4..8315076 100644 --- a/third_party/blink/tools/blinkpy/common/net/web.py +++ b/third_party/blink/tools/blinkpy/common/net/web.py
@@ -26,6 +26,9 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import gzip + +import six from six.moves import urllib from blinkpy.common.net.network_transaction import NetworkTransaction @@ -41,8 +44,22 @@ return self.http_error_301(req, fp, 301, msg, headers) def get_binary(self, url, return_none_on_404=False): - return NetworkTransaction(return_none_on_404=return_none_on_404).run( - lambda: self.request('GET', url).read()) + def make_request(): + response = self.request('GET', + url, + headers={'Accept-Encoding': 'gzip'}) + if response.headers.get('Content-Encoding') == 'gzip': + # Wrap the HTTP response, which is not fully file-like. + # Unfortunately, `six` does not provide `io.BufferedRandom`, so + # we need to read the entire payload up-front (may pose a + # performance issue). + buf = six.BytesIO(response.read()) + gzip_decoder = gzip.GzipFile(fileobj=buf) + return gzip_decoder.read() + return response.read() + + return NetworkTransaction( + return_none_on_404=return_none_on_404).run(make_request) def request(self, method, url, data=None, headers=None): opener = urllib.request.build_opener(Web._HTTPRedirectHandler2)
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng index ff766fb..2be408d 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng +++ b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng
@@ -628,6 +628,7 @@ crbug.com/1108830 external/wpt/css/css-pseudo/marker-word-break.html [ Failure ] crbug.com/1012289 external/wpt/css/css-pseudo/marker-unicode-bidi-default.html [ Failure ] crbug.com/1012289 external/wpt/css/css-pseudo/marker-unicode-bidi-normal.html [ Failure ] +crbug.com/1136817 external/wpt/css/css-pseudo/target-text-004.html [ Pass ] crbug.com/1136817 external/wpt/css/css-pseudo/target-text-007.html [ Failure ] crbug.com/1035708 wpt_internal/css/css-pseudo/spelling-error-color-001.html [ Failure ] crbug.com/1035708 wpt_internal/css/css-pseudo/spelling-error-color-002.html [ Failure ] @@ -1766,120 +1767,6 @@ # HighlightOverlayPainting is only implemented in ng crbug.com/1147859 virtual/css-highlight-overlay-painting/* [ Skip ] -crbug.com/1147859 dark-mode/colors/selection.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-001.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-002.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-003.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-005.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-006.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-007.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-008.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-009.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-010.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-011.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-012.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-013.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-014.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-015.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-016.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-017.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-018.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-below-selection.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-001.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-002.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-003.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-004.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-005.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-inheritance-001.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-inheritance-002.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-001.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-003.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-004.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-005.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-006.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-007.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-overlapping-highlights-001.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-overlapping-highlights-002.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-prioritization-001.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-prioritization-002.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-002.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-003.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-text-shadow.tentative.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/highlight-painting-003.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/highlight-painting-currentcolor-004.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/highlight-paired-cascade-004.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/target-text-001.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/target-text-002.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/target-text-003.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/target-text-004.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/target-text-005.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/target-text-006.html [ Failure ] -crbug.com/1147859 external/wpt/css/css-pseudo/target-text-text-decoration-001.html [ Failure ] -crbug.com/1147859 paint/markers/document-markers-font-8px.html [ Failure ] -crbug.com/1147859 paint/markers/document-markers-zoom-125.html [ Failure ] -crbug.com/1147859 paint/markers/document-markers-zoom-150.html [ Failure ] -crbug.com/1147859 paint/markers/document-markers-zoom-175.html [ Failure ] -crbug.com/1147859 paint/markers/document-markers-zoom-200.html [ Failure ] -crbug.com/1147859 paint/markers/document-markers-zoom-2000.html [ Failure ] -crbug.com/1147859 paint/markers/document-markers-zoom-250.html [ Failure ] -crbug.com/1147859 paint/markers/document-markers.html [ Failure ] -crbug.com/1147859 paint/markers/first-letter.html [ Failure ] -crbug.com/1147859 paint/markers/grammar-markers-hidpi.html [ Failure ] -crbug.com/1147859 paint/markers/grammar-markers.html [ Failure ] -crbug.com/1147859 paint/markers/inline-spelling-markers-hidpi-composited.html [ Failure ] -crbug.com/1147859 paint/markers/inline-spelling-markers-hidpi.html [ Failure ] -crbug.com/1147859 paint/markers/marker-early-break-bug.html [ Failure ] -crbug.com/1147859 paint/markers/markers-zoomed.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-001.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-002.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-003.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-005.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-006.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-007.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-008.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-009.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-010.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-011.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-012.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-013.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-014.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-015.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-016.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-017.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-018.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-below-selection.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-001.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-002.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-003.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-004.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-005.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-001.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-003.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-004.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-005.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-006.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-007.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-overlapping-highlights-001.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-overlapping-highlights-002.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-prioritization-001.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-prioritization-002.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-002.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-003.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-text-shadow.tentative.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/highlight-painting-003.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/highlight-painting-currentcolor-004.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/highlight-paired-cascade-004.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/target-text-001.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/target-text-002.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/target-text-003.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/target-text-004.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/target-text-005.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/target-text-006.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/external/wpt/css/css-pseudo/target-text-text-decoration-001.html [ Failure ] -crbug.com/1147859 virtual/css-highlight-inheritance/wpt_internal/css/css-pseudo/target-text-002.html [ Failure ] -crbug.com/1147859 virtual/dark-mode-default/dark-mode/colors/selection.html [ Failure ] -crbug.com/1147859 virtual/dark-mode-increase-text-contrast/dark-mode/colors/selection.html [ Failure ] -crbug.com/1147859 wpt_internal/css/css-pseudo/target-text-002.html [ Failure ] crbug.com/1303102 external/wpt/css/css-images/object-view-box* [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 8b7255d..708c48f 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1749,10 +1749,14 @@ crbug.com/1163437 external/wpt/css/css-pseudo/grammar-spelling-errors-002.html [ Failure ] crbug.com/1147859 external/wpt/css/css-pseudo/highlight-painting-001.html [ Failure ] crbug.com/1147859 external/wpt/css/css-pseudo/highlight-painting-002.html [ Failure ] +crbug.com/1147859 external/wpt/css/css-pseudo/highlight-painting-003.html [ Failure ] crbug.com/1147859 external/wpt/css/css-pseudo/highlight-painting-004.html [ Failure ] crbug.com/1295264 crbug.com/1147859 external/wpt/css/css-pseudo/highlight-painting-currentcolor-001.html [ Failure ] crbug.com/1295264 crbug.com/1147859 external/wpt/css/css-pseudo/highlight-painting-currentcolor-002.html [ Failure ] crbug.com/1295264 external/wpt/css/css-pseudo/highlight-pseudos-currentcolor-visited-computed-001.html [ Failure ] +crbug.com/1179938 external/wpt/css/css-pseudo/highlight-painting-currentcolor-003.html [ Failure ] +crbug.com/1179938 external/wpt/css/css-pseudo/highlight-painting-currentcolor-004.html [ Failure ] +crbug.com/1179938 external/wpt/css/css-pseudo/highlight-painting-currentcolor-005.html [ Failure ] crbug.com/1024156 external/wpt/css/css-pseudo/highlight-pseudos-inheritance-computed-001.html [ Failure ] crbug.com/1024156 external/wpt/css/css-pseudo/highlight-pseudos-currentcolor-inheritance-computed-001.html [ Failure ] crbug.com/995106 external/wpt/css/css-pseudo/first-letter-exclude-inline-marker.html [ Failure ] @@ -1772,16 +1776,12 @@ crbug.com/1035708 wpt_internal/css/css-pseudo/grammar-error-color-dynamic-003.html [ Failure ] crbug.com/1035708 wpt_internal/css/css-pseudo/grammar-error-color-dynamic-004.html [ Failure ] crbug.com/1147859 external/wpt/css/css-pseudo/target-text-004.html [ Failure ] +crbug.com/1179938 external/wpt/css/css-pseudo/target-text-006.html [ Failure ] crbug.com/1035708 external/wpt/css/css-pseudo/target-text-dynamic-001.html [ Failure ] crbug.com/1035708 external/wpt/css/css-pseudo/target-text-dynamic-002.html [ Failure ] crbug.com/1035708 external/wpt/css/css-pseudo/target-text-dynamic-003.html [ Failure ] crbug.com/1035708 external/wpt/css/css-pseudo/target-text-dynamic-004.html [ Failure ] - -# CSS highlight painting (HighlightOverlayPainting) -crbug.com/1147859 [ Mac ] external/wpt/css/css-highlight-api/painting/custom-highlight-painting-text-decoration-001.html [ Failure ] -crbug.com/1147859 [ Mac ] external/wpt/css/css-pseudo/highlight-painting-003.html [ Failure ] -crbug.com/1321106 external/wpt/css/css-text-decor/text-decoration-color-selection-001.html [ Failure ] -crbug.com/1321114 paint/markers/suggestion-marker-basic.html [ Failure ] +crbug.com/1179938 external/wpt/css/css-pseudo/target-text-text-decoration-001.html [ Failure ] crbug.com/1205953 external/wpt/css/css-will-change/will-change-fixpos-cb-position-1.html [ Failure ] crbug.com/1207788 external/wpt/css/css-will-change/will-change-stacking-context-mask-1.html [ Failure ] @@ -3112,6 +3112,73 @@ crbug.com/1035708 virtual/css-highlight-inheritance/wpt_internal/css/css-pseudo/spelling-error-color-dynamic-003.html [ Pass ] crbug.com/1035708 virtual/css-highlight-inheritance/wpt_internal/css/css-pseudo/spelling-error-color-dynamic-004.html [ Pass ] +# virtual/css-highlight-overlay-painting/ +crbug.com/1295264 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-overlapping-highlights-001.html [ Failure ] +crbug.com/1295264 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-overlapping-highlights-002.html [ Failure ] +crbug.com/1147859 [ Mac ] virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-text-decoration-001.html [ Failure ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/grammar-error-color-001.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/grammar-error-color-002.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/spelling-error-color-001.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/spelling-error-color-002.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-001.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-002.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-003.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-005.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-006.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-007.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-008.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-009.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-010.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-011.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-012.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-013.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-014.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-015.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-016.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-017.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-018.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-below-selection.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-001.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-002.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-003.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-004.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-005.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-iframe-006.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-inheritance-001.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-inheritance-002.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-inheritance-003.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-001.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-002.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-003.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-004.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-005.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-006.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-invalidation-007.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-prioritization-001.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-prioritization-002.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-001.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-002.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-003.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-004.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-005.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-006.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-staticrange-007.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-highlight-api/painting/custom-highlight-painting-text-shadow.tentative.html [ Pass ] +crbug.com/1147859 [ Mac11 ] virtual/css-highlight-overlay-painting/external/wpt/css/css-pseudo/highlight-painting-003.html [ Failure ] +crbug.com/1147859 [ Win ] virtual/css-highlight-overlay-painting/external/wpt/css/css-pseudo/highlight-painting-003.html [ Pass ] +crbug.com/1147859 [ Linux ] virtual/css-highlight-overlay-painting/external/wpt/css/css-pseudo/highlight-painting-003.html [ Pass ] +crbug.com/1147859 [ Fuchsia ] virtual/css-highlight-overlay-painting/external/wpt/css/css-pseudo/highlight-painting-003.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-pseudo/highlight-painting-currentcolor-003.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-pseudo/highlight-painting-currentcolor-004.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-pseudo/target-text-006.html [ Pass ] +crbug.com/1147859 virtual/css-highlight-overlay-painting/external/wpt/css/css-pseudo/target-text-text-decoration-001.html [ Pass ] +crbug.com/1251193 crbug.com/1024156 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/grammar-error-color-dynamic-001.html [ Failure ] +crbug.com/1251193 crbug.com/1024156 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/grammar-error-color-dynamic-003.html [ Failure ] +crbug.com/1251193 crbug.com/1024156 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/grammar-error-color-dynamic-004.html [ Failure ] +crbug.com/1251193 crbug.com/1024156 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/spelling-error-color-dynamic-001.html [ Failure ] +crbug.com/1251193 crbug.com/1024156 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/spelling-error-color-dynamic-003.html [ Failure ] +crbug.com/1251193 crbug.com/1024156 virtual/css-highlight-overlay-painting/wpt_internal/css/css-pseudo/spelling-error-color-dynamic-004.html [ Failure ] + crbug.com/825270 external/wpt/payment-request/delegate-request.https.sub.html [ Failure ] crbug.com/1105958 external/wpt/payment-request/payment-is-showing.https.html [ Failure Timeout ] @@ -5487,9 +5554,6 @@ # Wpt importer Sheriff 2020-12-11 crbug.com/626703 [ Linux ] wpt_internal/storage/estimate-usage-details-filesystem.https.tentative.any.html [ Failure Pass ] -# Wpt importer sheriff 2020-12-23 -crbug.com/1161590 external/wpt/html/semantics/forms/textfieldselection/select-event.html [ Pass Timeout ] - # Wpt importer sheriff 2021-01-05 crbug.com/1163175 external/wpt/css/css-pseudo/first-letter-punctuation-and-space.html [ Failure ] @@ -5935,7 +5999,10 @@ crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-004.html [ Failure ] crbug.com/1163437 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-below-grammar.html [ Failure ] crbug.com/1147859 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-below-target-text.html [ Failure ] -crbug.com/1147859 [ Linux ] external/wpt/css/css-highlight-api/painting/custom-highlight-painting-004-2.html [ Failure ] +crbug.com/1274174 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-text-decoration-001.html [ Pass ] +crbug.com/1274174 external/wpt/css/css-highlight-api/painting/custom-highlight-painting-text-decoration-dynamic-001.html [ Pass ] +crbug.com/1147859 [ Linux ] external/wpt/css/css-highlight-api/painting/* [ Failure ] +crbug.com/1147859 [ Linux ] virtual/css-highlight-inheritance/external/wpt/css/css-highlight-api/painting/* [ Failure ] crbug.com/1147859 [ Linux ] paint/custom-highlight-only-inheritance.html [ Failure ] # Green Mac11 Test @@ -6951,3 +7018,8 @@ # Sheriff 2022-05-26 crbug.com/1322004 http/tests/inspector-protocol/attribution-reporting/insecure-subresource.js [ Pass Timeout ] crbug.com/1329596 virtual/gpu-rasterization/images/jpeg-with-non-interleaved-dc-channels.html [ Failure Pass ] + +# Sheriff 2022-05-27 +crbug.com/1325307 fast/css-grid-layout/grid-auto-repeat-huge-grid-003.html [ Skip ] +crbug.com/1325307 fast/css-grid-layout/grid-auto-repeat-huge-grid-009.html [ Skip ] +crbug.com/1325307 fast/css-grid-layout/grid-auto-repeat-huge-grid-010.html [ Skip ]
diff --git a/third_party/blink/web_tests/external/wpt/WebCryptoAPI/algorithm-discards-context.https.window.js b/third_party/blink/web_tests/external/wpt/WebCryptoAPI/algorithm-discards-context.https.window.js new file mode 100644 index 0000000..e648bc2f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/WebCryptoAPI/algorithm-discards-context.https.window.js
@@ -0,0 +1,213 @@ +// META: title=WebCryptoAPI: Properties discard the context in algorithm normalization + +let nextTest = 0; +let tests = {}; +function closeChild(testId) { + if (tests[testId]) { + let {child, t} = tests[testId]; + delete tests[testId]; + document.body.removeChild(child); + t.done(); + } +} + +function runInChild(t, childScript) { + let testId = nextTest++; + const preamble = ` +let testId = ${testId}; +function closeChildOnAccess(obj, key) { + const oldValue = obj[key]; + Object.defineProperty(obj, key, {get: () => { + top.closeChild(testId); + return oldValue; + }}); +} +`; + childScript = preamble + childScript; + + let child = document.createElement("iframe"); + tests[testId] = {t, child}; + document.body.appendChild(child); + let script = document.createElement("script"); + script.textContent = childScript; + child.contentDocument.body.appendChild(script); +} + +async_test((t) => { + const childScript = ` +let algorithm = {name: "AES-GCM", length: 128}; +closeChildOnAccess(algorithm, "name"); +crypto.subtle.generateKey(algorithm, true, ["encrypt", "decrypt"]);`; + runInChild(t, childScript); +}, "Context is discarded in generateKey"); + +async_test((t) => { + const childScript = ` +let algorithm = {name: "AES-GCM"}; +closeChildOnAccess(algorithm, "name"); +crypto.subtle.importKey("raw", new Uint8Array(16), algorithm, true, + ["encrypt", "decrypt"]);`; + runInChild(t, childScript); +}, "Context is discarded in importKey"); + +async_test((t) => { + const childScript = ` +(async () => { + let key = await crypto.subtle.generateKey( + {name: "AES-GCM", length: 128}, true, ["encrypt", "decrypt"]); + let algorithm = {name: "AES-GCM", iv: new Uint8Array(12)}; + closeChildOnAccess(algorithm, "name"); + crypto.subtle.encrypt(algorithm, key, new Uint8Array()); +})();`; + runInChild(t, childScript); +}, "Context is discarded in encrypt"); + +async_test((t) => { + const childScript = ` +(async () => { + let key = await crypto.subtle.generateKey( + {name: "AES-GCM", length: 128}, true, ["encrypt", "decrypt"]); + let algorithm = {name: "AES-GCM", iv: new Uint8Array(12)}; + let encrypted = await crypto.subtle.encrypt(algorithm, key, new Uint8Array()); + closeChildOnAccess(algorithm, "name"); + crypto.subtle.decrypt(algorithm, key, encrypted); +})();`; + runInChild(t, childScript); +}, "Context is discarded in decrypt"); + +async_test((t) => { + const childScript = ` +let algorithm = {name: "SHA-256"}; +closeChildOnAccess(algorithm, "name"); +crypto.subtle.digest(algorithm, new Uint8Array());`; + runInChild(t, childScript); +}, "Context is discarded in digest"); + +async_test((t) => { + const childScript = ` +(async () => { + let key = await crypto.subtle.generateKey( + {name: "ECDSA", namedCurve: "P-256"}, true, ["sign", "verify"]); + let algorithm = {name: "ECDSA", hash: "SHA-256"}; + closeChildOnAccess(algorithm, "name"); + crypto.subtle.sign(algorithm, key.privateKey, new Uint8Array()); +})();`; + runInChild(t, childScript); +}, "Context is discarded in sign"); + +async_test((t) => { + const childScript = ` +(async () => { + let key = await crypto.subtle.generateKey( + {name: "ECDSA", namedCurve: "P-256"}, true, ["sign", "verify"]); + let algorithm = {name: "ECDSA", hash: "SHA-256"}; + let data = new Uint8Array(); + let signature = await crypto.subtle.sign(algorithm, key.privateKey, data); + closeChildOnAccess(algorithm, "name"); + crypto.subtle.verify(algorithm, key.publicKey, signature, data); +})();`; + runInChild(t, childScript); +}, "Context is discarded in verify"); + +async_test((t) => { + const childScript = ` +(async () => { + let key = await crypto.subtle.importKey( + "raw", new Uint8Array(16), "HKDF", false, ["deriveBits"]); + let algorithm = { + name: "HKDF", + hash: "SHA-256", + salt: new Uint8Array(), + info: new Uint8Array(), + }; + closeChildOnAccess(algorithm, "name"); + crypto.subtle.deriveBits(algorithm, key, 16); +})();`; + runInChild(t, childScript); +}, "Context is discarded in deriveBits"); + +async_test((t) => { + const childScript = ` +(async () => { + let key = await crypto.subtle.importKey( + "raw", new Uint8Array(16), "HKDF", false, ["deriveKey"]); + let algorithm = { + name: "HKDF", + hash: "SHA-256", + salt: new Uint8Array(), + info: new Uint8Array(), + }; + let derivedAlgorithm = {name: "AES-GCM", length: 128}; + closeChildOnAccess(algorithm, "name"); + crypto.subtle.deriveKey(algorithm, key, derivedAlgorithm, true, + ["encrypt", "decrypt"]); +})();`; + runInChild(t, childScript); +}, "Context is discarded in deriveKey"); + +async_test((t) => { + const childScript = ` +(async () => { + let key = await crypto.subtle.importKey( + "raw", new Uint8Array(16), "HKDF", false, ["deriveKey"]); + let algorithm = { + name: "HKDF", + hash: "SHA-256", + salt: new Uint8Array(), + info: new Uint8Array(), + }; + let derivedAlgorithm = {name: "AES-GCM", length: 128}; + closeChildOnAccess(derivedAlgorithm, "name"); + crypto.subtle.deriveKey(algorithm, key, derivedAlgorithm, true, + ["encrypt", "decrypt"]); +})();`; + runInChild(t, childScript); +}, "Context is discarded in deriveKey (2)"); + +async_test((t) => { + const childScript = ` +(async () => { + let wrapKey = await crypto.subtle.generateKey( + {name: "AES-GCM", length: 128}, true, ["wrapKey", "unwrapKey"]); + let key = await crypto.subtle.generateKey( + {name: "AES-GCM", length: 128}, true, ["encrypt", "decrypt"]); + let wrapAlgorithm = {name: "AES-GCM", iv: new Uint8Array(12)}; + closeChildOnAccess(wrapAlgorithm, "name"); + crypto.subtle.wrapKey("raw", key, wrapKey, wrapAlgorithm); +})();`; + runInChild(t, childScript); +}, "Context is discarded in wrapKey"); + +async_test((t) => { + const childScript = ` +(async () => { + let wrapKey = await crypto.subtle.generateKey( + {name: "AES-GCM", length: 128}, true, ["wrapKey", "unwrapKey"]); + let keyAlgorithm = {name: "AES-GCM", length: 128}; + let keyUsages = ["encrypt", "decrypt"]; + let key = await crypto.subtle.generateKey(keyAlgorithm, true, keyUsages); + let wrapAlgorithm = {name: "AES-GCM", iv: new Uint8Array(12)}; + let wrapped = await crypto.subtle.wrapKey("raw", key, wrapKey, wrapAlgorithm); + closeChildOnAccess(wrapAlgorithm, "name"); + crypto.subtle.unwrapKey( + "raw", wrapped, wrapKey, wrapAlgorithm, keyAlgorithm, true, keyUsages); +})();`; + runInChild(t, childScript); +}, "Context is discarded in unwrapKey"); + +async_test((t) => { + const childScript = ` +(async () => { + let wrapKey = await crypto.subtle.generateKey( + {name: "AES-GCM", length: 128}, true, ["wrapKey", "unwrapKey"]); + let keyAlgorithm = {name: "AES-GCM", length: 128}; + let keyUsages = ["encrypt", "decrypt"]; + let key = await crypto.subtle.generateKey(keyAlgorithm, true, keyUsages); + let wrapAlgorithm = {name: "AES-GCM", iv: new Uint8Array(12)}; + let wrapped = await crypto.subtle.wrapKey("raw", key, wrapKey, wrapAlgorithm); + closeChildOnAccess(keyAlgorithm, "name"); + crypto.subtle.unwrapKey( + "raw", wrapped, wrapKey, wrapAlgorithm, keyAlgorithm, true, keyUsages); +})();`; + runInChild(t, childScript); +}, "Context is discarded in unwrapKey (2)");
diff --git a/third_party/blink/web_tests/external/wpt/css/css-pseudo/target-text-text-decoration-001-ref.html b/third_party/blink/web_tests/external/wpt/css/css-pseudo/target-text-text-decoration-001-ref.html index 0ee37b1..b15f74c 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-pseudo/target-text-text-decoration-001-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-pseudo/target-text-text-decoration-001-ref.html
@@ -4,8 +4,6 @@ <style> div { text-decoration: solid underline magenta; - color: initial; - background: transparent; } </style> <p>The test passes if the following line has a magenta underline.</p>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-pseudo/target-text-text-decoration-001.html b/third_party/blink/web_tests/external/wpt/css/css-pseudo/target-text-text-decoration-001.html index d90d5d9..1709ce70 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-pseudo/target-text-text-decoration-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-pseudo/target-text-text-decoration-001.html
@@ -7,8 +7,6 @@ <style> ::target-text { text-decoration: solid underline magenta; - color: initial; - background: transparent; } </style> <p>The test passes if the following line has a magenta underline.</p>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/select-event.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/select-event.html index cb54b64..c3a65f73 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/select-event.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/textfieldselection/select-event.html
@@ -59,12 +59,14 @@ } ]; - function initialize(el, t) { +function waitForRender() { + return new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); +} + +function initialize(el) { el.setRangeText("foobar", 0, el.value.length, "start"); // Make sure to flush async dispatches - return new Promise(resolve => { - t.step_timeout(resolve, 200); - }); + return waitForRender(); } els.forEach((el) => { @@ -74,7 +76,7 @@ // promise_test instead of async_test is important because these need to happen in sequence (to test that events // fire if and only if the selection changes). promise_test(async t => { - await initialize(el, t); + await initialize(el); const watcher = new EventWatcher(t, el, "select"); @@ -89,30 +91,25 @@ return promise; }, `${elLabel}: ${action.label}`); - promise_test(t => { + promise_test(async t => { el.onselect = t.unreached_func("the select event must not fire the second time"); action.action(el); - return new Promise(resolve => { - t.step_timeout(() => { - el.onselect = null; - resolve(); - }, 200); - }); + await waitForRender(); + el.onselect = null; }, `${elLabel}: ${action.label} a second time (must not fire select)`); promise_test(async t => { const element = el.cloneNode(true); - - element.onselect = e => { - element.onselect = null; - }; + let fired = false; + element.addEventListener('select', () => fired = true, { once: true }); action.action(element); - // step_wait properly timeouts before the whole test collapses - await t.step_wait(() => !element.onselect, "event didn't fire", 200, 10); + await waitForRender(); + assert_true(fired, "event didn't fire"); + }, `${elLabel}: ${action.label} disconnected node`); // Intentionally still using promise_test, as assert_unreachable does not @@ -120,28 +117,26 @@ promise_test(async t => { const element = el.cloneNode(true); let fired = false; + element.addEventListener('select', () => fired = true, { once: true }); - element.onselect = () => fired = true; action.action(element); - assert_false(fired, "the select event must not fire synchronously") - await t.step_wait(() => fired, "event didn't fire", 200, 10); + assert_false(fired, "the select event must not fire synchronously"); + await waitForRender(); + assert_true(fired, "event didn't fire"); }, `${elLabel}: ${action.label} event queue`); - promise_test(t => { + promise_test(async t => { const element = el.cloneNode(true); + let selectCount = 0; + element.addEventListener('select', () => ++selectCount); assert_equals(element.selectionEnd, 0); - element.onselect = () => { - element.onselect = t.unreached_func("the select event must not fire twice"); - }; - action.action(element); action.action(element); - return new Promise(resolve => { - t.step_timeout(resolve, 200); - }); + await waitForRender(); + assert_equals(selectCount, 1, "the select event must not fire twice"); }, `${elLabel}: ${action.label} twice in disconnected node (must fire select only once)`); }); });
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html index 927b45c..7a11b57 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-selectmenu-element/selectmenu-parts-structure.tentative.html
@@ -208,13 +208,13 @@ const selectMenu1Popup = document.getElementById("selectMenu1-popup"); const selectMenu1Button = document.getElementById("selectMenu1-button"); const selectMenu1Child2 = document.getElementById("selectMenu1-child2"); - assert_false(selectMenu1Popup.matches(':popup-open')); + assert_false(selectMenu1Popup.matches(':top-layer')); selectMenu1Button.click(); - assert_false(selectMenu1Popup.matches(':popup-open'), "Clicking a button part that is a descendant of the listbox part should have no effect"); + assert_false(selectMenu1Popup.matches(':top-layer'), "Clicking a button part that is a descendant of the listbox part should have no effect"); assert_equals(selectMenu1.value, "one"); await clickOn(selectMenu1); - assert_true(selectMenu1Popup.matches(':popup-open')); + assert_true(selectMenu1Popup.matches(':top-layer')); await clickOn(selectMenu1Child2); assert_equals(selectMenu1.value, "two", "Clicking an <option> should change the value"); }, "To receive button part controller code, an element labeled as a button must not be a descendant of the listbox part in a flat tree traversal"); @@ -226,9 +226,9 @@ const selectMenu2Child2 = document.getElementById("selectMenu2-child2"); const selectMenu2Child4 = document.getElementById("selectMenu2-child4"); - assert_false(selectMenu2Popup.matches(':popup-open')); + assert_false(selectMenu2Popup.matches(':top-layer')); await clickOn(selectMenu2Button); - assert_false(selectMenu2Popup.matches(':popup-open'), "Clicking a button part should not show an invalid listbox part"); + assert_false(selectMenu2Popup.matches(':top-layer'), "Clicking a button part should not show an invalid listbox part"); assert_equals(selectMenu2.value, "three"); await clickOn(selectMenu2Button);
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-anchor-nesting.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-anchor-nesting.tentative.html index d7e5784..c7ebe58 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-anchor-nesting.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-anchor-nesting.tentative.html
@@ -46,15 +46,15 @@ setup({ explicit_done: true }); popup2.showPopup(); - assert_false(popup1.matches(':popup-open')); - assert_true(popup2.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); + assert_true(popup2.matches(':top-layer')); await clickOn(button1); test(t => { // Button1 is the anchor for popup1, and an ancestor of popup2. // Since popup2 is open, but not popup1, button1 should not be // the anchor of any open popup. So popup2 should be closed. - assert_false(popup2.matches(':popup-open')); - assert_true(popup1.matches(':popup-open')); + assert_false(popup2.matches(':top-layer')); + assert_true(popup1.matches(':top-layer')); },'Nested popups (inside anchor elements) do not affect light dismiss'); done();
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-attribute-basic.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-attribute-basic.tentative.html index 9d74476..661c63fe 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-attribute-basic.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-attribute-basic.tentative.html
@@ -22,10 +22,10 @@ const isVisible = !!(popup.offsetWidth || popup.offsetHeight || popup.getClientRects().length); if (isVisible) { assert_not_equals(window.getComputedStyle(popup).display,'none'); - assert_equals(isPopup,popup.matches(':popup-open')); + assert_equals(isPopup,popup.matches(':top-layer')); } else { assert_equals(window.getComputedStyle(popup).display,'none'); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); } return isVisible; } @@ -138,17 +138,17 @@ test(() => { const popup = createPopup(); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); popup.setAttribute('popup','hint'); // Change popup type - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); popup.setAttribute('popup','async'); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); popup.setAttribute('popup','invalid'); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); },'Changing attribute values should close open popups'); @@ -157,11 +157,11 @@ const popup = createPopup(); popup.setAttribute('popup',type); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); popup.remove(); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); document.body.appendChild(popup); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); },`Removing a visible popup=${type} element from the document should close the popup`); }); </script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-defaultopen-2.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-defaultopen-2.tentative.html index 1e54e469..bf44092c 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-defaultopen-2.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-defaultopen-2.tentative.html
@@ -16,8 +16,8 @@ requestAnimationFrame(() => { requestAnimationFrame(() => { test(function(){ - assert_true(p1.matches(':popup-open'),'The first (outermost) popup should be the one that opens in this case'); - assert_false(p2.matches(':popup-open'),'The inner popup should not be open'); + assert_true(p1.matches(':top-layer'),'The first (outermost) popup should be the one that opens in this case'); + assert_false(p2.matches(':top-layer'),'The inner popup should not be open'); }, "The defaultopen attribute should cause only the first popup to open"); }); });
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-defaultopen.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-defaultopen.tentative.html index 50bf825..12cf5452 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-defaultopen.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-defaultopen.tentative.html
@@ -18,25 +18,25 @@ requestAnimationFrame(() => { requestAnimationFrame(() => { test(function(){ - assert_true(p1.matches(':popup-open'),'defaultopen should open the popup'); + assert_true(p1.matches(':top-layer'),'defaultopen should open the popup'); assert_true(p1.hasAttribute('defaultopen')); assert_true(p1.defaultOpen,'defaultopen should be reflected in the IDL attribute'); - assert_false(p2.matches(':popup-open'), 'Only the first popup with defaultopen should be open on load'); + assert_false(p2.matches(':top-layer'), 'Only the first popup with defaultopen should be open on load'); assert_true(p2.hasAttribute('defaultopen'),'defaultopen should be present/true, even if not opened'); assert_true(p2.defaultOpen,'defaultopen should be present/true, even if not opened'); - assert_false(p2b.matches(':popup-open'),'Only the first popup/hint with defaultopen should be open on load'); - assert_true(p4.matches(':popup-open'),'defaultopen should open all async popups'); - assert_true(p5.matches(':popup-open'),'defaultopen should open all async popups'); + assert_false(p2b.matches(':top-layer'),'Only the first popup/hint with defaultopen should be open on load'); + assert_true(p4.matches(':top-layer'),'defaultopen should open all async popups'); + assert_true(p5.matches(':top-layer'),'defaultopen should open all async popups'); - assert_false(p3.matches(':popup-open')); + assert_false(p3.matches(':top-layer')); p3.setAttribute('defaultopen',''); - assert_false(p3.matches(':popup-open'), 'Changing defaultopen should not affect open status'); + assert_false(p3.matches(':top-layer'), 'Changing defaultopen should not affect open status'); assert_true(p3.hasAttribute('defaultopen')); assert_true(p3.defaultOpen,'defaultopen should still reflect to IDL'); p1.removeAttribute('defaultopen'); - assert_true(p1.matches(':popup-open'),'removing defaultopen should not close the popup'); + assert_true(p1.matches(':top-layer'),'removing defaultopen should not close the popup'); assert_false(p1.hasAttribute('defaultopen'),'...but it should reflect to IDL'); p1.hidePopup();
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-events.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-events.tentative.html index 9390ea3c..7be1dae 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-events.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-events.tentative.html
@@ -31,26 +31,26 @@ let showCount = 0; let hideCount = 0; await new Promise(resolve => window.addEventListener('load',() => resolve())); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); document.addEventListener('show',() => ++showCount); document.addEventListener('hide',() => ++hideCount); assert_equals(0,showCount); assert_equals(0,hideCount); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); await waitUntilChange(() => showCount); assert_equals(1,showCount); assert_equals(0,hideCount); await requestAnimationFramePromise(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); popup.hidePopup(); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); await waitUntilChange(() => hideCount); assert_equals(1,showCount); assert_equals(1,hideCount); await requestAnimationFramePromise(); // No additional events after animation frame - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); assert_equals(1,showCount); assert_equals(1,hideCount); }, 'Show and hide events get properly dispatched for popups');
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-focus.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-focus.tentative.html index 6fccb0f..0612313 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-focus.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-focus.tentative.html
@@ -132,7 +132,7 @@ expectedFocusedElement = priorFocus; } assert_true(!!expectedFocusedElement); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); // Directly show and hide the popup: priorFocus.focus(); @@ -156,7 +156,7 @@ assert_equals(document.activeElement, expectedFocusedElement, `${testName} activated by popup.showPopup()`); assert_equals(popup.popup, 'popup', 'All popups in this test should start as popup=popup'); popup.popup = 'hint'; - assert_false(popup.matches(':popup-open'), 'Changing the popup type should hide the popup'); + assert_false(popup.matches(':top-layer'), 'Changing the popup type should hide the popup'); assert_equals(document.activeElement, priorFocus, 'prior element should get focus when the type is changed'); popup.popup = 'popup'; @@ -165,7 +165,7 @@ popup.showPopup(); assert_equals(document.activeElement, expectedFocusedElement, `${testName} activated by popup.showPopup()`); popup.remove(); - assert_false(popup.matches(':popup-open'), 'Removing the popup should hide it'); + assert_false(popup.matches(':top-layer'), 'Removing the popup should hide it'); if (!popup.hasAttribute('data-no-focus')) { assert_not_equals(document.activeElement, priorFocus, 'prior element should *not* get focus when the popup is removed from the document'); } @@ -177,7 +177,7 @@ assert_equals(document.activeElement, expectedFocusedElement, `${testName} activated by popup.showPopup()`); const dialog = document.body.appendChild(document.createElement('dialog')); dialog.showModal(); - assert_false(popup.matches(':popup-open'), 'Opening a modal dialog should hide the popup'); + assert_false(popup.matches(':top-layer'), 'Opening a modal dialog should hide the popup'); assert_not_equals(document.activeElement, priorFocus, 'prior element should *not* get focus when a modal dialog is shown'); dialog.close(); dialog.remove(); @@ -186,20 +186,20 @@ const button = addInvoker(t, popup); priorFocus.focus(); button.click(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); assert_equals(document.activeElement, expectedFocusedElement, `${testName} activated by button.click()`); // Make sure we can directly focus the (already open) popup: popup.focus(); assert_equals(document.activeElement, popup.hasAttribute('tabindex') ? popup : expectedFocusedElement, `${testName} directly focus with popup.focus()`); button.click(); // Button is set to toggle the popup - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); assert_equals(document.activeElement, priorFocus, 'prior element should get focus on button-toggled hide'); }, "Popup focus test: " + testName); promise_test(async t => { const priorFocus = addPriorFocus(t); - assert_false(popup.matches(':popup-open'), 'popup should start out hidden'); + assert_false(popup.matches(':top-layer'), 'popup should start out hidden'); let button = addInvoker(t, popup); assert_equals(button.getAttribute('togglepopup'), popup.id, 'This test assumes the button uses `togglepopup`.'); assert_not_equals(button, priorFocus, 'Stranger things have happened'); @@ -207,9 +207,9 @@ priorFocus.focus(); assert_equals(document.activeElement, priorFocus); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); await clickOn(button); // This will not light dismiss, but will "toggle" the popup. - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); assert_equals(document.activeElement, priorFocus, 'Focus should return to prior focus'); // Same thing, but the button is contained within the popup @@ -218,12 +218,12 @@ popup.appendChild(button); priorFocus.focus(); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); if (!popup.hasAttribute('data-no-focus')) { assert_not_equals(document.activeElement, priorFocus, 'focus should shift for this element'); } await clickOn(button); - assert_false(popup.matches(':popup-open'), 'clicking button should hide the popup'); + assert_false(popup.matches(':top-layer'), 'clicking button should hide the popup'); assert_equals(document.activeElement, priorFocus, 'Contained button should return focus to the previously focused element'); // Same thing, but the button is unrelated (no togglepopup) @@ -231,9 +231,9 @@ document.body.appendChild(button); priorFocus.focus(); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); await clickOn(button); // This will light dismiss the popup, focus the prior focus, then focus this button. - assert_false(popup.matches(':popup-open'), 'clicking button should hide the popup (via light dismiss)'); + assert_false(popup.matches(':top-layer'), 'clicking button should hide the popup (via light dismiss)'); assert_equals(document.activeElement, button, 'Focus should go to unrelated button on light dismiss'); }, "Popup button click focus test: " + testName); @@ -243,12 +243,12 @@ return; } const priorFocus = addPriorFocus(t); - assert_false(popup.matches(':popup-open'), 'popup should start out hidden'); + assert_false(popup.matches(':top-layer'), 'popup should start out hidden'); // Move the prior focus out of the document priorFocus.focus(); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); const newFocus = document.activeElement; assert_not_equals(newFocus, priorFocus, 'focus should shift for this element'); priorFocus.remove(); @@ -260,11 +260,11 @@ // Move the prior focus inside the (already open) popup priorFocus.focus(); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); assert_false(popup.contains(priorFocus), 'Start with a non-contained prior focus'); popup.appendChild(priorFocus); // Move inside the popup assert_true(popup.contains(priorFocus)); - assert_true(popup.matches(':popup-open'), 'popup should stay open'); + assert_true(popup.matches(':top-layer'), 'popup should stay open'); popup.hidePopup(); assert_not_equals(document.activeElement, priorFocus, 'focused element is display:none inside the popup'); document.body.appendChild(priorFocus); // Put it back
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-inside-display-none.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-inside-display-none.tentative.html index d72f0aa..2230d77 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-inside-display-none.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-inside-display-none.tentative.html
@@ -13,6 +13,6 @@ <script> const popup = document.querySelector('[popup]'); popup.showPopup(); - if (!popup.matches(':popup-open')) + if (!popup.matches(':top-layer')) document.body.appendChild(document.createTextNode('FAIL')); </script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-invoking-attribute.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-invoking-attribute.tentative.html index 49056f8..2cac8d1 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-invoking-attribute.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-invoking-attribute.tentative.html
@@ -139,7 +139,7 @@ const otherId = expectedId !== 1 ? 1 : 2; function assert_popup(num,state,message) { assert_true(num>0,`Invalid expectedId ${num}`); - assert_equals((num===1 ? popup1 : popup2).matches(':popup-open'),state,message || ""); + assert_equals((num===1 ? popup1 : popup2).matches(':top-layer'),state,message || ""); } assert_popup(expectedId,false); assert_popup(otherId,false); @@ -205,7 +205,7 @@ popup.addEventListener('hide',() => ++hideCount); async function assertState(expectOpen,expectShow,expectHide) { - assert_equals(popup.matches(':popup-open'),expectOpen,'Popup open state is incorrect'); + assert_equals(popup.matches(':top-layer'),expectOpen,'Popup open state is incorrect'); await new Promise(resolve => requestAnimationFrame(resolve)); assert_equals(showCount,expectShow,'Show count is incorrect'); assert_equals(hideCount,expectHide,'Hide count is incorrect');
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-light-dismiss-on-scroll.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-light-dismiss-on-scroll.tentative.html index bafa50dae..10276edb 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-light-dismiss-on-scroll.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-light-dismiss-on-scroll.tentative.html
@@ -39,7 +39,7 @@ const popups = document.querySelectorAll('[popup]'); function assertAll(showing) { for(let popup of popups) { - assert_equals(popup.matches(':popup-open'),showing); + assert_equals(popup.matches(':top-layer'),showing); } } async_test(t => {
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-light-dismiss.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-light-dismiss.tentative.html index e3c05fa..568a515 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-light-dismiss.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-light-dismiss.tentative.html
@@ -54,34 +54,34 @@ e.preventDefault(); // 'hide' should not be cancellable. }); promise_test(async () => { - assert_false(popup1.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); popup1.showPopup(); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); let p1HideCount = popup1HideCount; await clickOn(outside); - assert_false(popup1.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); assert_equals(popup1HideCount,p1HideCount+1); },'Clicking outside a popup will dismiss the popup'); promise_test(async () => { - assert_false(popup1.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); popup1.showPopup(); await waitForRender(); p1HideCount = popup1HideCount; await clickOn(inside1); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); assert_equals(popup1HideCount,p1HideCount); popup1.hidePopup(); },'Clicking inside a popup does not close that popup'); promise_test(async () => { - assert_false(popup1.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); popup1.showPopup(); await clickOn(inside1After); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); await sendTab(); assert_equals(document.activeElement,afterp1,'Focus should move to a button outside the popup'); - assert_false(popup1.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); },'Moving focus outside the popup will dismiss the popup'); promise_test(async () => { @@ -91,13 +91,13 @@ p1HideCount = popup1HideCount; let p2HideCount = popup2HideCount; await clickOn(inside2); - assert_true(popup1.matches(':popup-open'),'popup1 should be open'); - assert_true(popup2.matches(':popup-open'),'popup2 should be open'); + assert_true(popup1.matches(':top-layer'),'popup1 should be open'); + assert_true(popup2.matches(':top-layer'),'popup2 should be open'); assert_equals(popup1HideCount,p1HideCount,'popup1'); assert_equals(popup2HideCount,p2HideCount,'popup2'); popup1.hidePopup(); - assert_false(popup1.matches(':popup-open')); - assert_false(popup2.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); + assert_false(popup2.matches(':top-layer')); },'Clicking inside a child popup shouldn\'t close either popup'); promise_test(async () => { @@ -107,64 +107,64 @@ p1HideCount = popup1HideCount; p2HideCount = popup2HideCount; await clickOn(inside1); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); assert_equals(popup1HideCount,p1HideCount); - assert_false(popup2.matches(':popup-open')); + assert_false(popup2.matches(':top-layer')); assert_equals(popup2HideCount,p2HideCount+1); popup1.hidePopup(); },'Clicking inside a parent popup should close child popup'); promise_test(async () => { await clickOn(button1show); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); await waitForRender(); p1HideCount = popup1HideCount; await clickOn(button1show); - assert_true(popup1.matches(':popup-open'),'popup1 should stay open'); + assert_true(popup1.matches(':top-layer'),'popup1 should stay open'); assert_equals(popup1HideCount,p1HideCount,'popup1 should not get hidden and reshown'); popup1.hidePopup(); // Cleanup - assert_false(popup1.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); },'Clicking on invoking element, after using it for activation, shouldn\'t close its popup'); promise_test(async () => { popup1.showPopup(); // Directly show the popup - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); await waitForRender(); p1HideCount = popup1HideCount; await clickOn(button1show); - assert_true(popup1.matches(':popup-open'),'popup1 should stay open'); + assert_true(popup1.matches(':top-layer'),'popup1 should stay open'); assert_equals(popup1HideCount,p1HideCount,'popup1 should not get hidden and reshown'); popup1.hidePopup(); // Cleanup - assert_false(popup1.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); },'Clicking on invoking element, even if it wasn\'t used for activation, shouldn\'t close its popup'); promise_test(async () => { popup1.showPopup(); // Directly show the popup - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); await waitForRender(); p1HideCount = popup1HideCount; await clickOn(button1toggle); - assert_false(popup1.matches(':popup-open'),'popup1 should be hidden by togglepopup'); + assert_false(popup1.matches(':top-layer'),'popup1 should be hidden by togglepopup'); assert_equals(popup1HideCount,p1HideCount+1,'popup1 should get hidden only once by togglepopup'); },'Clicking on togglepopup element, even if it wasn\'t used for activation, should hide it exactly once'); promise_test(async () => { popup1.showPopup(); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); await waitForRender(); p1HideCount = popup1HideCount; await clickOn(popup1anchor); - assert_true(popup1.matches(':popup-open'),'popup1 not open'); + assert_true(popup1.matches(':top-layer'),'popup1 not open'); assert_equals(popup1HideCount,p1HideCount); popup1.hidePopup(); // Cleanup - assert_false(popup1.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); },'Clicking on anchor element (that isn\'t an invoking element) shouldn\'t close its popup'); promise_test(async () => { popup1.showPopup(); popup2.showPopup(); // Popup1 is an ancestral element for popup2. - assert_true(popup1.matches(':popup-open')); - assert_true(popup2.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); + assert_true(popup2.matches(':top-layer')); const drag_actions = new test_driver.Actions(); // Drag *from* popup2 *to* popup1 (its ancestor). await drag_actions.pointerMove(0,0,{origin: popup2}) @@ -172,10 +172,10 @@ .pointerMove(0,0,{origin: popup1}) .pointerUp({button: drag_actions.ButtonType.LEFT}) .send(); - assert_true(popup1.matches(':popup-open'),'popup1 should be open'); - assert_true(popup2.matches(':popup-open'),'popup1 should be open'); + assert_true(popup1.matches(':top-layer'),'popup1 should be open'); + assert_true(popup2.matches(':top-layer'),'popup1 should be open'); popup1.hidePopup(); - assert_false(popup2.matches(':popup-open')); + assert_false(popup2.matches(':top-layer')); },'Dragging from an open popup outside an open popup should leave the popup open'); </script> @@ -198,28 +198,28 @@ const button3 = document.querySelector('#b3'); promise_test(async () => { await clickOn(button3); - assert_true(popup3.matches(':popup-open'),'invoking element should open popup'); + assert_true(popup3.matches(':top-layer'),'invoking element should open popup'); popup4.showPopup(); - assert_true(popup4.matches(':popup-open')); - assert_true(popup3.matches(':popup-open')); + assert_true(popup4.matches(':top-layer')); + assert_true(popup3.matches(':top-layer')); popup3.hidePopup(); // Cleanup - assert_false(popup3.matches(':popup-open')); - assert_false(popup4.matches(':popup-open')); + assert_false(popup3.matches(':top-layer')); + assert_false(popup4.matches(':top-layer')); },'An invoking element should be part of the ancestor chain'); promise_test(async () => { await clickOn(button3); - assert_true(popup3.matches(':popup-open')); - assert_false(popup4.matches(':popup-open')); - assert_false(popup5.matches(':popup-open')); + assert_true(popup3.matches(':top-layer')); + assert_false(popup4.matches(':top-layer')); + assert_false(popup5.matches(':top-layer')); popup5.showPopup(); - assert_true(popup3.matches(':popup-open')); - assert_false(popup4.matches(':popup-open')); - assert_true(popup5.matches(':popup-open')); + assert_true(popup3.matches(':top-layer')); + assert_false(popup4.matches(':top-layer')); + assert_true(popup5.matches(':top-layer')); popup3.hidePopup(); - assert_false(popup3.matches(':popup-open')); - assert_false(popup4.matches(':popup-open')); - assert_false(popup5.matches(':popup-open')); + assert_false(popup3.matches(':top-layer')); + assert_false(popup4.matches(':top-layer')); + assert_false(popup5.matches(':top-layer')); },'An invoking element that was not used to invoke the popup can still be part of the ancestor chain'); </script> @@ -243,7 +243,7 @@ await new test_driver.Actions() .scroll(0, 0, 0, 50, {origin: popup6}) .send(); - assert_true(popup6.matches(':popup-open'),'popup6 should stay open'); + assert_true(popup6.matches(':top-layer'),'popup6 should stay open'); assert_equals(popup6.scrollTop,50,'popup6 should be scrolled'); popup6.hidePopup(); },'Scrolling within a popup should not close the popup'); @@ -267,18 +267,18 @@ } promise_test(async () => { button7.click(); - assert_true(popup7.matches(':popup-open'),'invoking element should open popup'); + assert_true(popup7.matches(':top-layer'),'invoking element should open popup'); inside7.click(); - assert_true(popup7.matches(':popup-open')); + assert_true(popup7.matches(':top-layer')); popup7.hidePopup(); },'Clicking inside a shadow DOM popup does not close that popup'); promise_test(async () => { button7.click(); inside7.click(); - assert_true(popup7.matches(':popup-open')); + assert_true(popup7.matches(':top-layer')); await clickOn(outside); - assert_false(popup7.matches(':popup-open')); + assert_false(popup7.matches(':top-layer')); },'Clicking outside a shadow DOM popup should close that popup'); </script> @@ -292,13 +292,13 @@ const popup8 = document.querySelector('#p8'); const inside8After = document.querySelector('#inside8after'); const popup8Anchor = document.querySelector('#p8anchor'); - assert_false(popup8.matches(':popup-open')); + assert_false(popup8.matches(':top-layer')); popup8.showPopup(); await clickOn(inside8After); - assert_true(popup8.matches(':popup-open')); + assert_true(popup8.matches(':top-layer')); await sendTab(); assert_equals(document.activeElement,popup8Anchor,'Focus should move to the anchor element'); - assert_true(popup8.matches(':popup-open'),'popup should stay open'); + assert_true(popup8.matches(':top-layer'),'popup should stay open'); popup8.hidePopup(); },'Moving focus back to the anchor element should not dismiss the popup'); </script> @@ -313,13 +313,13 @@ const popup9 = document.querySelector('#p9'); const inside9After = document.querySelector('#inside9after'); const popup9Invoker = document.querySelector('#b9after'); - assert_false(popup9.matches(':popup-open')); + assert_false(popup9.matches(':top-layer')); popup9Invoker.click(); // Trigger via the button await clickOn(inside9After); - assert_true(popup9.matches(':popup-open')); + assert_true(popup9.matches(':top-layer')); await sendTab(); assert_equals(document.activeElement,popup9Invoker,'Focus should move to the invoking element'); - assert_true(popup9.matches(':popup-open'),'popup should stay open'); + assert_true(popup9.matches(':top-layer'),'popup should stay open'); popup9.hidePopup(); },'Moving focus back to the active trigger element should not dismiss the popup'); @@ -327,13 +327,13 @@ const popup9 = document.querySelector('#p9'); const inside9After = document.querySelector('#inside9after'); const popup9Invoker = document.querySelector('#b9after'); - assert_false(popup9.matches(':popup-open')); + assert_false(popup9.matches(':top-layer')); popup9.showPopup(); // Trigger directly await clickOn(inside9After); - assert_true(popup9.matches(':popup-open')); + assert_true(popup9.matches(':top-layer')); await sendTab(); assert_equals(document.activeElement,popup9Invoker,'Focus should move to the invoking element'); - assert_true(popup9.matches(':popup-open'),'popup should stay open - even though the trigger wasn\'t used, it points to this popup'); + assert_true(popup9.matches(':top-layer'),'popup should stay open - even though the trigger wasn\'t used, it points to this popup'); },'Moving focus back to an inactive trigger element should also *not* dismiss the popup'); </script> @@ -365,51 +365,51 @@ const convPopup4 = document.querySelector('#convoluted_p4'); promise_test(async () => { convPopup1.showPopup(); // Programmatically open p1 - assert_true(convPopup1.matches(':popup-open')); + assert_true(convPopup1.matches(':top-layer')); convPopup1.querySelector('button').click(); // Click to invoke p2 - assert_true(convPopup1.matches(':popup-open')); - assert_true(convPopup2.matches(':popup-open')); + assert_true(convPopup1.matches(':top-layer')); + assert_true(convPopup2.matches(':top-layer')); convPopup2.querySelector('button').click(); // Click to invoke p3 - assert_true(convPopup1.matches(':popup-open')); - assert_true(convPopup2.matches(':popup-open')); - assert_true(convPopup3.matches(':popup-open')); + assert_true(convPopup1.matches(':top-layer')); + assert_true(convPopup2.matches(':top-layer')); + assert_true(convPopup3.matches(':top-layer')); convPopup3.querySelector('button').click(); // Click to invoke p4 - assert_true(convPopup1.matches(':popup-open')); - assert_true(convPopup2.matches(':popup-open')); - assert_true(convPopup3.matches(':popup-open')); - assert_true(convPopup4.matches(':popup-open')); + assert_true(convPopup1.matches(':top-layer')); + assert_true(convPopup2.matches(':top-layer')); + assert_true(convPopup3.matches(':top-layer')); + assert_true(convPopup4.matches(':top-layer')); convPopup4.firstElementChild.click(); // Click within p4 - assert_true(convPopup1.matches(':popup-open')); - assert_true(convPopup2.matches(':popup-open')); - assert_true(convPopup3.matches(':popup-open')); - assert_true(convPopup4.matches(':popup-open')); + assert_true(convPopup1.matches(':top-layer')); + assert_true(convPopup2.matches(':top-layer')); + assert_true(convPopup3.matches(':top-layer')); + assert_true(convPopup4.matches(':top-layer')); convPopup1.hidePopup(); - assert_false(convPopup1.matches(':popup-open')); - assert_false(convPopup2.matches(':popup-open')); - assert_false(convPopup3.matches(':popup-open')); - assert_false(convPopup4.matches(':popup-open')); + assert_false(convPopup1.matches(':top-layer')); + assert_false(convPopup2.matches(':top-layer')); + assert_false(convPopup3.matches(':top-layer')); + assert_false(convPopup4.matches(':top-layer')); },'Ensure circular/convoluted ancestral relationships are functional'); promise_test(async () => { convPopup1.showPopup(); // Programmatically open p1 convPopup1.querySelector('button').click(); // Click to invoke p2 - assert_true(convPopup1.matches(':popup-open')); - assert_true(convPopup2.matches(':popup-open')); - assert_false(convPopup3.matches(':popup-open')); - assert_false(convPopup4.matches(':popup-open')); + assert_true(convPopup1.matches(':top-layer')); + assert_true(convPopup2.matches(':top-layer')); + assert_false(convPopup3.matches(':top-layer')); + assert_false(convPopup4.matches(':top-layer')); convPopup4.showPopup(); // Programmatically open p4 - assert_true(convPopup1.matches(':popup-open'),'popup1 stays open because it is a DOM ancestor of popup4'); - assert_false(convPopup2.matches(':popup-open'),'popup2 closes because it isn\'t connected to popup4 via active invokers'); - assert_true(convPopup4.matches(':popup-open')); + assert_true(convPopup1.matches(':top-layer'),'popup1 stays open because it is a DOM ancestor of popup4'); + assert_false(convPopup2.matches(':top-layer'),'popup2 closes because it isn\'t connected to popup4 via active invokers'); + assert_true(convPopup4.matches(':top-layer')); convPopup4.firstElementChild.click(); // Click within p4 - assert_true(convPopup1.matches(':popup-open'),'nothing changes'); - assert_false(convPopup2.matches(':popup-open')); - assert_true(convPopup4.matches(':popup-open')); + assert_true(convPopup1.matches(':top-layer'),'nothing changes'); + assert_false(convPopup2.matches(':top-layer')); + assert_true(convPopup4.matches(':top-layer')); convPopup1.hidePopup(); - assert_false(convPopup1.matches(':popup-open')); - assert_false(convPopup2.matches(':popup-open')); - assert_false(convPopup3.matches(':popup-open')); - assert_false(convPopup4.matches(':popup-open')); + assert_false(convPopup1.matches(':top-layer')); + assert_false(convPopup2.matches(':top-layer')); + assert_false(convPopup3.matches(':top-layer')); + assert_false(convPopup4.matches(':top-layer')); },'Ensure circular/convoluted ancestral relationships are functional, with a direct showPopup()'); </script> @@ -431,30 +431,30 @@ popup.showPopup(); hint.showPopup(); async.showPopup(); - assert_true(popup.matches(':popup-open')); - assert_true(hint.matches(':popup-open')); - assert_true(async.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); + assert_true(hint.matches(':top-layer')); + assert_true(async.matches(':top-layer')); // The hint was opened last, so clicking it shouldn't close anything: await clickOn(hint); - assert_true(popup.matches(':popup-open'),'popup should stay open'); - assert_true(hint.matches(':popup-open'),'hint should stay open'); - assert_true(async.matches(':popup-open'),'async does not light dismiss'); + assert_true(popup.matches(':top-layer'),'popup should stay open'); + assert_true(hint.matches(':top-layer'),'hint should stay open'); + assert_true(async.matches(':top-layer'),'async does not light dismiss'); // Clicking outside should close the hint and popup, but not the async: await clickOn(outside); - assert_false(popup.matches(':popup-open'),'popup should close'); - assert_false(hint.matches(':popup-open'),'hint should close'); - assert_true(async.matches(':popup-open'),'async does not light dismiss'); + assert_false(popup.matches(':top-layer'),'popup should close'); + assert_false(hint.matches(':top-layer'),'hint should close'); + assert_true(async.matches(':top-layer'),'async does not light dismiss'); async.hidePopup(); - assert_false(async.matches(':popup-open')); + assert_false(async.matches(':top-layer')); popup.showPopup(); hint.showPopup(); - assert_true(popup.matches(':popup-open')); - assert_true(hint.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); + assert_true(hint.matches(':top-layer')); // Clicking on the popup should close the hint: await clickOn(popup); - assert_true(popup.matches(':popup-open'),'popup should stay open'); - assert_false(hint.matches(':popup-open'),'hint should light dismiss'); + assert_true(popup.matches(':top-layer'),'popup should stay open'); + assert_false(hint.matches(':top-layer'),'hint should light dismiss'); popup.hidePopup(); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); },'Light dismiss of mixed popup types'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-not-keyboard-focusable.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-not-keyboard-focusable.tentative.html index 39d9839..4deb76d 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-not-keyboard-focusable.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-not-keyboard-focusable.tentative.html
@@ -23,12 +23,12 @@ b1.focus(); assert_equals(document.activeElement,b1); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); assert_equals(document.activeElement,b1); // Tab once await new test_driver.send_keys(document.body,'\uE004'); // Tab assert_equals(document.activeElement, b2, 'Keyboard focus should skip the open popup'); - assert_false(popup.matches(':popup-open'),'changing focus should close the popup'); + assert_false(popup.matches(':top-layer'),'changing focus should close the popup'); // Add a focusable button to the popup and make sure we can focus that const button = document.createElement('button'); @@ -39,8 +39,8 @@ // Tab once await new test_driver.send_keys(document.body,'\uE004'); // Tab assert_equals(document.activeElement, button, 'Keyboard focus should go to the contained button'); - assert_true(popup.matches(':popup-open'),'changing focus to the popup should leave it showing'); + assert_true(popup.matches(':top-layer'),'changing focus to the popup should leave it showing'); popup.hidePopup(); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); }, "Popup should not be keyboard focusable"); </script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-removal-2.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-removal-2.tentative.html index 0204c3c9..02e7429 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-removal-2.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-removal-2.tentative.html
@@ -16,13 +16,13 @@ const frame2Doc = document.getElementById('frame2').contentDocument; const popup = frame1Doc.querySelector('[popup]'); assert_true(!!popup); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); frame2Doc.body.appendChild(popup); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); }, 'Moving popup between documents shouldn\'t cause issues'); }; </script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-removal.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-removal.tentative.html index 02201dc2..525448e 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-removal.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-removal.tentative.html
@@ -16,9 +16,9 @@ }); } const popup = document.querySelector('[popup]'); - assert_false(popup.matches(':popup-open')); + assert_false(popup.matches(':top-layer')); popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); popup.remove(); // Shouldn't cause any issues document.body.click(); // Shouldn't cause light dismiss problems await loadCompleted(); // The document should finish loading
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-shadow-dom.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-shadow-dom.tentative.html index 922bf16..8df874d 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-shadow-dom.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-shadow-dom.tentative.html
@@ -58,7 +58,7 @@ test(function() { const popup = getPopupReferences('test1')[0]; popup.showPopup(); - assert_true(popup.matches(':popup-open')); + assert_true(popup.matches(':top-layer')); assert_true(popupVisible(popup)); }, "Popups located inside shadow DOM can still be shown"); </script> @@ -84,12 +84,12 @@ test(function() { const [popup1,popup2] = getPopupReferences('test2'); popup1.showPopup(); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); assert_true(popupVisible(popup1)); popup2.showPopup(); - assert_false(popup1.matches(':popup-open'), 'popup1 open'); // P1 was closed by P2 + assert_false(popup1.matches(':top-layer'), 'popup1 open'); // P1 was closed by P2 assert_false(popupVisible(popup1), 'popup1 visible'); - assert_true(popup2.matches(':popup-open'), 'popup2 open'); // P2 is open + assert_true(popup2.matches(':top-layer'), 'popup2 open'); // P2 is open assert_true(popupVisible(popup2), 'popup2 visible'); }, "anchor references do not cross shadow boundaries"); </script> @@ -113,18 +113,18 @@ test(function() { const [popup1,popup2] = getPopupReferences('test3'); popup1.showPopup(); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); assert_true(popupVisible(popup1)); // Showing popup2 should not close popup1, since it is a flat // tree ancestor of popup2's anchor button. popup2.showPopup(); - assert_true(popup2.matches(':popup-open')); + assert_true(popup2.matches(':top-layer')); assert_true(popupVisible(popup2)); - assert_true(popup1.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); assert_true(popupVisible(popup1)); popup1.hidePopup(); - assert_false(popup2.matches(':popup-open')); - assert_false(popup1.matches(':popup-open')); + assert_false(popup2.matches(':top-layer')); + assert_false(popup1.matches(':top-layer')); }, "anchor references use the flat tree not the DOM tree"); </script> @@ -150,13 +150,13 @@ popup1.showPopup(); popup2.showPopup(); // Both 1 and 2 should be open at this point. - assert_true(popup1.matches(':popup-open'), 'popup1 not open'); + assert_true(popup1.matches(':top-layer'), 'popup1 not open'); assert_true(popupVisible(popup1)); - assert_true(popup2.matches(':popup-open'), 'popup2 not open'); + assert_true(popup2.matches(':top-layer'), 'popup2 not open'); assert_true(popupVisible(popup2)); // This should hide both of them. popup1.hidePopup(); - assert_false(popup2.matches(':popup-open')); + assert_false(popup2.matches(':top-layer')); assert_false(popupVisible(popup2)); }, "The popup stack is preserved across shadow-inclusive ancestors"); </script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-stacking.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-stacking.tentative.html index 160a4a5..2cf540c 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-stacking.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-stacking.tentative.html
@@ -89,18 +89,18 @@ const clickToActivate = example.querySelector('.clickme'); test(function() { assert_true(!!descr && !!ancestor && !!child); - assert_false(ancestor.matches(':popup-open')); - assert_false(child.matches(':popup-open')); + assert_false(ancestor.matches(':top-layer')); + assert_false(child.matches(':top-layer')); ancestor.showPopup(); if (clickToActivate) clickToActivate.click(); else child.showPopup(); - assert_true(child.matches(':popup-open')); - assert_true(ancestor.matches(':popup-open')); + assert_true(child.matches(':top-layer')); + assert_true(ancestor.matches(':top-layer')); ancestor.hidePopup(); - assert_false(ancestor.matches(':popup-open')); - assert_false(child.matches(':popup-open')); + assert_false(ancestor.matches(':top-layer')); + assert_false(child.matches(':top-layer')); },descr); } @@ -109,7 +109,7 @@ function assertState(...states) { assert_equals(popups.length,states.length); for(let i=0;i<popups.length;++i) { - assert_equals(popups[i].matches(':popup-open'),states[i],`Popup #${i+1} incorrect state`); + assert_equals(popups[i].matches(':top-layer'),states[i],`Popup #${i+1} incorrect state`); } } test(function() {
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-top-layer-interactions.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-top-layer-interactions.tentative.html index 53ded3e..69cc436 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-top-layer-interactions.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-top-layer-interactions.tentative.html
@@ -22,7 +22,7 @@ createElement: () => Object.assign(document.createElement('div'), {popup: 'popup'}), trigger: function() {this.element.showPopup()}, close: function() {this.element.hidePopup()}, - isTopLayer: function() {return this.element.matches(':popup-open')}, + isTopLayer: function() {return this.element.matches(':top-layer')}, }, { type: types.modalDialog,
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-types.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-types.tentative.html index 74a1b916..e3d24ac 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-types.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popups/popup-types.tentative.html
@@ -12,10 +12,10 @@ <script> function assert_state_1(popupOpen,hintOpen,asyncOpen,async2Open) { - assert_equals(popup.matches(':popup-open'),popupOpen,'popup open state is incorrect'); - assert_equals(hint.matches(':popup-open'),hintOpen,'hint open state is incorrect'); - assert_equals(async.matches(':popup-open'),asyncOpen,'async open state is incorrect'); - assert_equals(async2.matches(':popup-open'),async2Open,'async2 open state is incorrect'); + assert_equals(popup.matches(':top-layer'),popupOpen,'popup open state is incorrect'); + assert_equals(hint.matches(':top-layer'),hintOpen,'hint open state is incorrect'); + assert_equals(async.matches(':top-layer'),asyncOpen,'async open state is incorrect'); + assert_equals(async2.matches(':top-layer'),async2Open,'async2 open state is incorrect'); } test(() => { assert_state_1(false,false,false,false); @@ -67,10 +67,10 @@ <div id=hint2 popup=hint anchor=anchorid>Hint anchored to popup</div> <script> function assert_state_2(popup1Open,popup2Open,popup3Open,hintOpen) { - assert_equals(popup1.matches(':popup-open'),popup1Open,'popup1 open state is incorrect'); - assert_equals(popup2.matches(':popup-open'),popup2Open,'popup2 open state is incorrect'); - assert_equals(popup3.matches(':popup-open'),popup3Open,'popup3 open state is incorrect'); - assert_equals(hint2.matches(':popup-open'),hintOpen,'hint2 open state is incorrect'); + assert_equals(popup1.matches(':top-layer'),popup1Open,'popup1 open state is incorrect'); + assert_equals(popup2.matches(':top-layer'),popup2Open,'popup2 open state is incorrect'); + assert_equals(popup3.matches(':top-layer'),popup3Open,'popup3 open state is incorrect'); + assert_equals(hint2.matches(':top-layer'),hintOpen,'hint2 open state is incorrect'); } test(() => { assert_state_2(false,false,false,false);
diff --git a/third_party/blink/web_tests/html/popup/popup-light-dismiss-keyboard.html b/third_party/blink/web_tests/html/popup/popup-light-dismiss-keyboard.html index e507d72..a905bd9 100644 --- a/third_party/blink/web_tests/html/popup/popup-light-dismiss-keyboard.html +++ b/third_party/blink/web_tests/html/popup/popup-light-dismiss-keyboard.html
@@ -36,10 +36,10 @@ popup1.showPopup(); popup2.showPopup(); eventSender.keyDown("Escape"); - assert_true(popup1.matches(':popup-open')); - assert_false(popup2.matches(':popup-open')); + assert_true(popup1.matches(':top-layer')); + assert_false(popup2.matches(':top-layer')); eventSender.keyDown("Escape"); - assert_false(popup1.matches(':popup-open')); - assert_false(popup2.matches(':popup-open')); + assert_false(popup1.matches(':top-layer')); + assert_false(popup2.matches(':top-layer')); },'Escape key should close top level popup'); </script>
diff --git a/third_party/blink/web_tests/images/directly-composited-image-orientation.html b/third_party/blink/web_tests/images/directly-composited-image-orientation.html index 84cc5e4..9162eab 100644 --- a/third_party/blink/web_tests/images/directly-composited-image-orientation.html +++ b/third_party/blink/web_tests/images/directly-composited-image-orientation.html
@@ -29,58 +29,58 @@ <body> <!-- The images should rotate respecting their EXIF orientation because image-orientation: from-image is specified. --> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-1-ul.jpg"> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-2-ur.jpg"> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-3-lr.jpg"> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-4-lol.jpg"> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-5-lu.jpg"> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-6-ru.jpg"> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-7-rl.jpg"> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-8-llo.jpg"> - <link rel="preload" as="image" href="../external/wpt/css/css-images/image-orientation/support/exif-orientation-9-u.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-1-ul.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-2-ur.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-3-lr.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-4-lol.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-5-lu.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-6-ru.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-7-rl.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-8-llo.jpg"> + <link rel="preload" as="image" href="support/exif-orientation-9-u.jpg"> <div> <img class="orientation-normal" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-1-ul.jpg"/> + src="support/exif-orientation-1-ul.jpg"/> </div> <div> <img class="orientation-normal" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-2-ur.jpg"/> + src="support/exif-orientation-2-ur.jpg"/> </div> <div> <img class="orientation-normal" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-3-lr.jpg"/> + src="support/exif-orientation-3-lr.jpg"/> </div> <div> <img class="orientation-normal" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-4-lol.jpg"/> + src="support/exif-orientation-4-lol.jpg"/> </div> <div> <img class="orientation-swapped" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-5-lu.jpg"/> + src="support/exif-orientation-5-lu.jpg"/> </div> <div> <img class="orientation-swapped" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-6-ru.jpg"/> + src="support/exif-orientation-6-ru.jpg"/> </div> <div> <img class="orientation-swapped" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-7-rl.jpg"/> + src="support/exif-orientation-7-rl.jpg"/> </div> <div> <img class="orientation-swapped" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-8-llo.jpg"/> + src="support/exif-orientation-8-llo.jpg"/> </div> <div> <img class="orientation-normal" - src="../external/wpt/css/css-images/image-orientation/support/exif-orientation-9-u.jpg"/> + src="support/exif-orientation-9-u.jpg"/> </div> </body>
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-1-ul.jpg b/third_party/blink/web_tests/images/support/exif-orientation-1-ul.jpg new file mode 100644 index 0000000..5125ede0 --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-1-ul.jpg Binary files differ
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-2-ur.jpg b/third_party/blink/web_tests/images/support/exif-orientation-2-ur.jpg new file mode 100644 index 0000000..20c4b79 --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-2-ur.jpg Binary files differ
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-3-lr.jpg b/third_party/blink/web_tests/images/support/exif-orientation-3-lr.jpg new file mode 100644 index 0000000..818e573 --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-3-lr.jpg Binary files differ
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-4-lol.jpg b/third_party/blink/web_tests/images/support/exif-orientation-4-lol.jpg new file mode 100644 index 0000000..ec8caf84 --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-4-lol.jpg Binary files differ
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-5-lu.jpg b/third_party/blink/web_tests/images/support/exif-orientation-5-lu.jpg new file mode 100644 index 0000000..06f0f663 --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-5-lu.jpg Binary files differ
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-6-ru.jpg b/third_party/blink/web_tests/images/support/exif-orientation-6-ru.jpg new file mode 100644 index 0000000..08d03f0 --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-6-ru.jpg Binary files differ
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-7-rl.jpg b/third_party/blink/web_tests/images/support/exif-orientation-7-rl.jpg new file mode 100644 index 0000000..28a9d07a --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-7-rl.jpg Binary files differ
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-8-llo.jpg b/third_party/blink/web_tests/images/support/exif-orientation-8-llo.jpg new file mode 100644 index 0000000..c396925e --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-8-llo.jpg Binary files differ
diff --git a/third_party/blink/web_tests/images/support/exif-orientation-9-u.jpg b/third_party/blink/web_tests/images/support/exif-orientation-9-u.jpg new file mode 100644 index 0000000..7d41aea --- /dev/null +++ b/third_party/blink/web_tests/images/support/exif-orientation-9-u.jpg Binary files differ
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem-expected.txt deleted file mode 100644 index d9979f1..0000000 --- a/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL javascript: navigation using <a href target=_blank> should be refused due to missing unsafe-hashes assert_unreached: Should not have run javascript: URL Reached unreachable code -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem-expected.txt deleted file mode 100644 index c0ad830..0000000 --- a/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL javascript: navigation using <a href target=_blank> should be refused due to wrong hash assert_unreached: Should not have run javascript: URL Reached unreachable code -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/html/semantics/forms/textfieldselection/select-event-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/html/semantics/forms/textfieldselection/select-event-expected.txt index 11a2360a9..3940b927 100644 --- a/third_party/blink/web_tests/platform/generic/external/wpt/html/semantics/forms/textfieldselection/select-event-expected.txt +++ b/third_party/blink/web_tests/platform/generic/external/wpt/html/semantics/forms/textfieldselection/select-event-expected.txt
@@ -32,18 +32,18 @@ FAIL textarea: setRangeText() twice in disconnected node (must fire select only once) assert_equals: expected 0 but got 15 PASS textarea: selectionStart out of range PASS textarea: selectionStart out of range a second time (must not fire select) -FAIL textarea: selectionStart out of range disconnected node step_wait_func: event didn't fire Timed out waiting on condition -FAIL textarea: selectionStart out of range event queue step_wait_func: event didn't fire Timed out waiting on condition +FAIL textarea: selectionStart out of range disconnected node assert_true: event didn't fire expected true got false +FAIL textarea: selectionStart out of range event queue assert_true: event didn't fire expected true got false FAIL textarea: selectionStart out of range twice in disconnected node (must fire select only once) assert_equals: expected 0 but got 6 PASS textarea: selectionEnd out of range PASS textarea: selectionEnd out of range a second time (must not fire select) -FAIL textarea: selectionEnd out of range disconnected node step_wait_func: event didn't fire Timed out waiting on condition -FAIL textarea: selectionEnd out of range event queue step_wait_func: event didn't fire Timed out waiting on condition +FAIL textarea: selectionEnd out of range disconnected node assert_true: event didn't fire expected true got false +FAIL textarea: selectionEnd out of range event queue assert_true: event didn't fire expected true got false FAIL textarea: selectionEnd out of range twice in disconnected node (must fire select only once) assert_equals: expected 0 but got 6 PASS textarea: setSelectionRange out of range PASS textarea: setSelectionRange out of range a second time (must not fire select) -FAIL textarea: setSelectionRange out of range disconnected node step_wait_func: event didn't fire Timed out waiting on condition -FAIL textarea: setSelectionRange out of range event queue step_wait_func: event didn't fire Timed out waiting on condition +FAIL textarea: setSelectionRange out of range disconnected node assert_true: event didn't fire expected true got false +FAIL textarea: setSelectionRange out of range event queue assert_true: event didn't fire expected true got false FAIL textarea: setSelectionRange out of range twice in disconnected node (must fire select only once) assert_equals: expected 0 but got 6 PASS input type text: select() PASS input type text: select() a second time (must not fire select)
diff --git a/third_party/blink/web_tests/platform/linux/dark-mode/colors/selection-expected.png b/third_party/blink/web_tests/platform/linux/dark-mode/colors/selection-expected.png index 231145c4..644446fa 100644 --- a/third_party/blink/web_tests/platform/linux/dark-mode/colors/selection-expected.png +++ b/third_party/blink/web_tests/platform/linux/dark-mode/colors/selection-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/editing/selection/line-wrap-2-expected.png b/third_party/blink/web_tests/platform/linux/editing/selection/line-wrap-2-expected.png index a9106581..ea678ec 100644 --- a/third_party/blink/web_tests/platform/linux/editing/selection/line-wrap-2-expected.png +++ b/third_party/blink/web_tests/platform/linux/editing/selection/line-wrap-2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/paint/markers/document-markers-zoom-2000-expected.png b/third_party/blink/web_tests/platform/linux/paint/markers/document-markers-zoom-2000-expected.png index fc548fb..81a9e407 100644 --- a/third_party/blink/web_tests/platform/linux/paint/markers/document-markers-zoom-2000-expected.png +++ b/third_party/blink/web_tests/platform/linux/paint/markers/document-markers-zoom-2000-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/svg/text/text-selection-deco-01-b-expected.png b/third_party/blink/web_tests/platform/linux/svg/text/text-selection-deco-01-b-expected.png index 6bfd44f..22db64d 100644 --- a/third_party/blink/web_tests/platform/linux/svg/text/text-selection-deco-01-b-expected.png +++ b/third_party/blink/web_tests/platform/linux/svg/text/text-selection-deco-01-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/svg/text/text-selection-text-03-b-expected.png b/third_party/blink/web_tests/platform/linux/svg/text/text-selection-text-03-b-expected.png index 6c8d1f9..f7fdebd2 100644 --- a/third_party/blink/web_tests/platform/linux/svg/text/text-selection-text-03-b-expected.png +++ b/third_party/blink/web_tests/platform/linux/svg/text/text-selection-text-03-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/dark-mode-default/dark-mode/colors/selection-expected.png b/third_party/blink/web_tests/platform/linux/virtual/dark-mode-default/dark-mode/colors/selection-expected.png index 432e3d6..a488bdd9 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/dark-mode-default/dark-mode/colors/selection-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/dark-mode-default/dark-mode/colors/selection-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/dark-mode-increase-text-contrast/dark-mode/colors/selection-expected.png b/third_party/blink/web_tests/platform/linux/virtual/dark-mode-increase-text-contrast/dark-mode/colors/selection-expected.png index 2fd8929..6d51f1d5 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/dark-mode-increase-text-contrast/dark-mode/colors/selection-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/dark-mode-increase-text-contrast/dark-mode/colors/selection-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/text-antialias/selection/khmer-selection-expected.png b/third_party/blink/web_tests/platform/linux/virtual/text-antialias/selection/khmer-selection-expected.png index 4ba52e7..4dae189 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/text-antialias/selection/khmer-selection-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/text-antialias/selection/khmer-selection-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/editing/selection/line-wrap-2-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/editing/selection/line-wrap-2-expected.png index 6468907..b0e106b 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.13/editing/selection/line-wrap-2-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.13/editing/selection/line-wrap-2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/paint/markers/document-markers-font-8px-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/paint/markers/document-markers-font-8px-expected.png index 422df4c..1547a596 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.13/paint/markers/document-markers-font-8px-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.13/paint/markers/document-markers-font-8px-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/paint/markers/document-markers-zoom-2000-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/paint/markers/document-markers-zoom-2000-expected.png index b723e3e..52f9143 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.13/paint/markers/document-markers-zoom-2000-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.13/paint/markers/document-markers-zoom-2000-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/svg/text/text-selection-deco-01-b-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/svg/text/text-selection-deco-01-b-expected.png index 8005621..eead15c 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.13/svg/text/text-selection-deco-01-b-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.13/svg/text/text-selection-deco-01-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/svg/text/text-selection-text-03-b-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/svg/text/text-selection-text-03-b-expected.png index 9ec97f6..416870c 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.13/svg/text/text-selection-text-03-b-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.13/svg/text/text-selection-text-03-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/virtual/text-antialias/selection/khmer-selection-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/virtual/text-antialias/selection/khmer-selection-expected.png index 43c4731..89a1690e 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.13/virtual/text-antialias/selection/khmer-selection-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.13/virtual/text-antialias/selection/khmer-selection-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/editing/selection/line-wrap-2-expected.png b/third_party/blink/web_tests/platform/mac/editing/selection/line-wrap-2-expected.png index 9d089a7..f79c9b86 100644 --- a/third_party/blink/web_tests/platform/mac/editing/selection/line-wrap-2-expected.png +++ b/third_party/blink/web_tests/platform/mac/editing/selection/line-wrap-2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/html/semantics/forms/textfieldselection/select-event-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/html/semantics/forms/textfieldselection/select-event-expected.txt index 60e2cc21..1caa1e0 100644 --- a/third_party/blink/web_tests/platform/mac/external/wpt/html/semantics/forms/textfieldselection/select-event-expected.txt +++ b/third_party/blink/web_tests/platform/mac/external/wpt/html/semantics/forms/textfieldselection/select-event-expected.txt
@@ -32,18 +32,18 @@ FAIL textarea: setRangeText() twice in disconnected node (must fire select only once) assert_equals: expected 0 but got 15 PASS textarea: selectionStart out of range PASS textarea: selectionStart out of range a second time (must not fire select) -FAIL textarea: selectionStart out of range disconnected node step_wait_func: event didn't fire Timed out waiting on condition -FAIL textarea: selectionStart out of range event queue step_wait_func: event didn't fire Timed out waiting on condition +FAIL textarea: selectionStart out of range disconnected node assert_true: event didn't fire expected true got false +FAIL textarea: selectionStart out of range event queue assert_true: event didn't fire expected true got false FAIL textarea: selectionStart out of range twice in disconnected node (must fire select only once) assert_equals: expected 0 but got 6 PASS textarea: selectionEnd out of range PASS textarea: selectionEnd out of range a second time (must not fire select) -FAIL textarea: selectionEnd out of range disconnected node step_wait_func: event didn't fire Timed out waiting on condition -FAIL textarea: selectionEnd out of range event queue step_wait_func: event didn't fire Timed out waiting on condition +FAIL textarea: selectionEnd out of range disconnected node assert_true: event didn't fire expected true got false +FAIL textarea: selectionEnd out of range event queue assert_true: event didn't fire expected true got false FAIL textarea: selectionEnd out of range twice in disconnected node (must fire select only once) assert_equals: expected 0 but got 6 PASS textarea: setSelectionRange out of range PASS textarea: setSelectionRange out of range a second time (must not fire select) -FAIL textarea: setSelectionRange out of range disconnected node step_wait_func: event didn't fire Timed out waiting on condition -FAIL textarea: setSelectionRange out of range event queue step_wait_func: event didn't fire Timed out waiting on condition +FAIL textarea: setSelectionRange out of range disconnected node assert_true: event didn't fire expected true got false +FAIL textarea: setSelectionRange out of range event queue assert_true: event didn't fire expected true got false FAIL textarea: setSelectionRange out of range twice in disconnected node (must fire select only once) assert_equals: expected 0 but got 6 PASS input type text: select() PASS input type text: select() a second time (must not fire select)
diff --git a/third_party/blink/web_tests/platform/mac/paint/markers/document-markers-font-8px-expected.png b/third_party/blink/web_tests/platform/mac/paint/markers/document-markers-font-8px-expected.png index fe00a90..1e0b12d 100644 --- a/third_party/blink/web_tests/platform/mac/paint/markers/document-markers-font-8px-expected.png +++ b/third_party/blink/web_tests/platform/mac/paint/markers/document-markers-font-8px-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/paint/markers/document-markers-zoom-2000-expected.png b/third_party/blink/web_tests/platform/mac/paint/markers/document-markers-zoom-2000-expected.png index 9627203b..f0b7adb1 100644 --- a/third_party/blink/web_tests/platform/mac/paint/markers/document-markers-zoom-2000-expected.png +++ b/third_party/blink/web_tests/platform/mac/paint/markers/document-markers-zoom-2000-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/svg/text/text-selection-deco-01-b-expected.png b/third_party/blink/web_tests/platform/mac/svg/text/text-selection-deco-01-b-expected.png index ee87b3b..c1b9339 100644 --- a/third_party/blink/web_tests/platform/mac/svg/text/text-selection-deco-01-b-expected.png +++ b/third_party/blink/web_tests/platform/mac/svg/text/text-selection-deco-01-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/svg/text/text-selection-text-03-b-expected.png b/third_party/blink/web_tests/platform/mac/svg/text/text-selection-text-03-b-expected.png index 17c6e79..6d3823b4 100644 --- a/third_party/blink/web_tests/platform/mac/svg/text/text-selection-text-03-b-expected.png +++ b/third_party/blink/web_tests/platform/mac/svg/text/text-selection-text-03-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/text-antialias/selection/khmer-selection-expected.png b/third_party/blink/web_tests/platform/mac/virtual/text-antialias/selection/khmer-selection-expected.png index 343126b..ce97e889 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/text-antialias/selection/khmer-selection-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/text-antialias/selection/khmer-selection-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/editing/selection/line-wrap-2-expected.png b/third_party/blink/web_tests/platform/win/editing/selection/line-wrap-2-expected.png index 46e3bdb..450abb2 100644 --- a/third_party/blink/web_tests/platform/win/editing/selection/line-wrap-2-expected.png +++ b/third_party/blink/web_tests/platform/win/editing/selection/line-wrap-2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/paint/markers/document-markers-zoom-2000-expected.png b/third_party/blink/web_tests/platform/win/paint/markers/document-markers-zoom-2000-expected.png index cb1fa3f..7dba21f1 100644 --- a/third_party/blink/web_tests/platform/win/paint/markers/document-markers-zoom-2000-expected.png +++ b/third_party/blink/web_tests/platform/win/paint/markers/document-markers-zoom-2000-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/svg/text/text-selection-deco-01-b-expected.png b/third_party/blink/web_tests/platform/win/svg/text/text-selection-deco-01-b-expected.png index 15b6be2b..a498ad2 100644 --- a/third_party/blink/web_tests/platform/win/svg/text/text-selection-deco-01-b-expected.png +++ b/third_party/blink/web_tests/platform/win/svg/text/text-selection-deco-01-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/svg/text/text-selection-text-03-b-expected.png b/third_party/blink/web_tests/platform/win/svg/text/text-selection-text-03-b-expected.png index 3fe7ec3..d236f98 100644 --- a/third_party/blink/web_tests/platform/win/svg/text/text-selection-text-03-b-expected.png +++ b/third_party/blink/web_tests/platform/win/svg/text/text-selection-text-03-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/text-antialias/selection/khmer-selection-expected.png b/third_party/blink/web_tests/platform/win/virtual/text-antialias/selection/khmer-selection-expected.png index 4c5de446..884ccb4 100644 --- a/third_party/blink/web_tests/platform/win/virtual/text-antialias/selection/khmer-selection-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/text-antialias/selection/khmer-selection-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win7/virtual/text-antialias/selection/khmer-selection-expected.png b/third_party/blink/web_tests/platform/win7/virtual/text-antialias/selection/khmer-selection-expected.png index bea9b0c6..3669edc3 100644 --- a/third_party/blink/web_tests/platform/win7/virtual/text-antialias/selection/khmer-selection-expected.png +++ b/third_party/blink/web_tests/platform/win7/virtual/text-antialias/selection/khmer-selection-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/popup-disabled/popup-disabled.html b/third_party/blink/web_tests/virtual/popup-disabled/popup-disabled.html index 2c702e5..1e2a0a00 100644 --- a/third_party/blink/web_tests/virtual/popup-disabled/popup-disabled.html +++ b/third_party/blink/web_tests/virtual/popup-disabled/popup-disabled.html
@@ -18,7 +18,7 @@ const elements = document.getElementById('elements'); test(() => { - assert_throws_dom("SyntaxError",() => {elements.matches(':popup-open')},"The :popup-open pseudo class shouldn't be available"); + assert_throws_dom("SyntaxError",() => {elements.matches(':top-layer')},"The :top-layer pseudo class shouldn't be available"); },'Basic tests'); for(let el of elements.children) {
diff --git a/tools/clang/scripts/update.py b/tools/clang/scripts/update.py index 3f89c4b..43cf1e36 100755 --- a/tools/clang/scripts/update.py +++ b/tools/clang/scripts/update.py
@@ -35,7 +35,7 @@ # https://chromium.googlesource.com/chromium/src/+/main/docs/updating_clang.md # Reverting problematic clang rolls is safe, though. # This is the output of `git describe` and is usable as a commit-ish. -CLANG_REVISION = 'llvmorg-15-init-11359-gca27f3e3' +CLANG_REVISION = 'llvmorg-15-init-10717-ge00cbbec' CLANG_SUB_REVISION = 1 PACKAGE_VERSION = '%s-%s' % (CLANG_REVISION, CLANG_SUB_REVISION)
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index e69156c..30ece6d7 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -1096,7 +1096,6 @@ 'linux-perfetto-rel': 'perfetto_release_trybot', 'linux-rel': 'gpu_tests_release_trybot_no_symbols_use_dummy_lastchange_code_coverage_do_typecheck', 'linux-rel-ml': 'gpu_tests_release_trybot_no_symbols_use_dummy_lastchange_code_coverage_do_typecheck', - 'linux-rel-orchestrator-pool': 'gpu_tests_release_trybot_no_symbols_use_dummy_lastchange_code_coverage_do_typecheck', 'linux-rel-warmed': 'gpu_tests_release_trybot_no_symbols_use_dummy_lastchange_code_coverage', 'linux-viz-rel': 'release_trybot', 'linux-wayland-rel': 'gpu_tests_wayland_release_trybot_no_symbols_use_dummy_lastchange_code_coverage',
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.linux.json b/tools/mb/mb_config_expectations/tryserver.chromium.linux.json index 80370f7..610320ed 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.linux.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.linux.json
@@ -509,21 +509,6 @@ "use_goma": true } }, - "linux-rel-orchestrator-pool": { - "gn_args": { - "coverage_instrumentation_input_file": "//.code-coverage/files_to_instrument.txt", - "dcheck_always_on": true, - "devtools_skip_typecheck": false, - "ffmpeg_branding": "Chrome", - "is_component_build": false, - "is_debug": false, - "proprietary_codecs": true, - "symbol_level": 0, - "use_clang_coverage": true, - "use_dummy_lastchange": true, - "use_goma": true - } - }, "linux-rel-warmed": { "gn_args": { "coverage_instrumentation_input_file": "//.code-coverage/files_to_instrument.txt",
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 4d01194..7e6dc49a 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -34583,6 +34583,9 @@ <int value="1657" label="BOOKMARKMANAGERPRIVATE_OPENINNEWTAB"/> <int value="1658" label="BOOKMARKMANAGERPRIVATE_OPENINNEWWINDOW"/> <int value="1659" label="WMDESKSPRIVATE_REMOVEDESKANDCLOSEWINDOWS"/> + <int value="1660" label="SHAREDSTORAGEPRIVATE_GET"/> + <int value="1661" label="SHAREDSTORAGEPRIVATE_SET"/> + <int value="1662" label="SHAREDSTORAGEPRIVATE_REMOVE"/> </enum> <enum name="ExtensionIconState"> @@ -35210,6 +35213,7 @@ <int value="235" label="kSpeechRecognitionPrivate"/> <int value="236" label="kChromeOSDiagnostics"/> <int value="237" label="kChromeOSTelemetrySerialNumber"/> + <int value="238" label="kSharedStoragePrivate"/> </enum> <enum name="ExtensionPointEnableState">
diff --git a/tools/metrics/histograms/metadata/android/histograms.xml b/tools/metrics/histograms/metadata/android/histograms.xml index 1bbd6fd..018187f9 100644 --- a/tools/metrics/histograms/metadata/android/histograms.xml +++ b/tools/metrics/histograms/metadata/android/histograms.xml
@@ -2877,7 +2877,7 @@ </histogram> <histogram name="Android.PrepareMenu.OpenWebApkVisibilityCheck" units="ms" - expires_after="2022-06-01"> + expires_after="2023-06-01"> <owner>hartmanng@chromium.org</owner> <owner> src/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS
diff --git a/tools/metrics/histograms/metadata/chromeos/histograms.xml b/tools/metrics/histograms/metadata/chromeos/histograms.xml index 2d6b6a5..eb51b59b 100644 --- a/tools/metrics/histograms/metadata/chromeos/histograms.xml +++ b/tools/metrics/histograms/metadata/chromeos/histograms.xml
@@ -683,8 +683,9 @@ </histogram> <histogram name="ChromeOS.DiagnosticsUi.InitialScreen" - enum="CrosDiagnosticsNavigationView" expires_after="2022-10-04"> - <owner>gavindodd@chromium.org</owner> + units="CrosDiagnosticsNavigationView" expires_after="2022-10-04"> + <owner>ashleydp@google.com</owner> + <owner>gavinwill@chromium.org</owner> <owner>zentaro@chromium.org</owner> <owner>cros-peripherals@google.com</owner> <summary> @@ -694,7 +695,8 @@ <histogram name="ChromeOS.DiagnosticsUi.MemoryRoutineDuration" units="s" expires_after="2022-10-04"> - <owner>gavindodd@chromium.org</owner> + <owner>ashleydp@google.com</owner> + <owner>gavinwill@chromium.org</owner> <owner>zentaro@chromium.org</owner> <owner>cros-peripherals@google.com</owner> <summary> @@ -705,7 +707,8 @@ <histogram name="ChromeOS.DiagnosticsUi.OpenDuration" units="ms" expires_after="2022-10-04"> - <owner>gavindodd@chromium.org</owner> + <owner>ashleydp@google.com</owner> + <owner>gavinwill@chromium.org</owner> <owner>zentaro@chromium.org</owner> <owner>cros-peripherals@google.com</owner> <summary> @@ -716,7 +719,8 @@ <histogram name="ChromeOS.DiagnosticsUi.RoutineCount" units="routines" expires_after="2022-10-04"> - <owner>gavindodd@chromium.org</owner> + <owner>ashleydp@google.com</owner> + <owner>gavinwill@chromium.org</owner> <owner>zentaro@chromium.org</owner> <owner>cros-peripherals@google.com</owner> <summary> @@ -727,8 +731,9 @@ </histogram> <histogram name="ChromeOS.DiagnosticsUi.{RoutineType}Result" - enum="CrosDiagnosticsRoutineResult" expires_after="2022-06-15"> - <owner>gavindodd@chromium.org</owner> + enum="CrosDiagnosticsRoutineResult" expires_after="2023-06-15"> + <owner>ashleydp@google.com</owner> + <owner>gavinwill@chromium.org</owner> <owner>zentaro@chromium.org</owner> <owner>cros-peripherals@google.com</owner> <summary>Records the result of the {RoutineType} Routine.</summary>
diff --git a/tools/metrics/histograms/metadata/cross_device/histograms.xml b/tools/metrics/histograms/metadata/cross_device/histograms.xml index 0b2a681..6bf88a7 100644 --- a/tools/metrics/histograms/metadata/cross_device/histograms.xml +++ b/tools/metrics/histograms/metadata/cross_device/histograms.xml
@@ -2316,9 +2316,8 @@ <summary> The duration of time between when the user locks their screen or wakes their device (either opening a clamshell device or waking up a tablet), and when - the user is first provided a visible indication of Smart Lock's status (the - Smart Lock icon presents as either yellow or green, with a tooltip - explaining the status). + the user is first provided a visible indication of Smart Lock's status after + Smart Lock has communicated with the phone. Suffixed by the type of status which the user is first presented with. View the base histogram to see results for all status types aggregated together,
diff --git a/tools/metrics/histograms/metadata/tab/histograms.xml b/tools/metrics/histograms/metadata/tab/histograms.xml index 85537858..4d85ae2 100644 --- a/tools/metrics/histograms/metadata/tab/histograms.xml +++ b/tools/metrics/histograms/metadata/tab/histograms.xml
@@ -1927,7 +1927,7 @@ </histogram> <histogram name="Tabs.PersistedTabData.Storage.SaveTime.File" units="ms" - expires_after="2022-05-22"> + expires_after="2023-05-22"> <owner>yusufo@chromium.org</owner> <owner>nyquist@chromium.org</owner> <owner>dtrainor@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/web_apk/histograms.xml b/tools/metrics/histograms/metadata/web_apk/histograms.xml index 37cfed4..b4c176d 100644 --- a/tools/metrics/histograms/metadata/web_apk/histograms.xml +++ b/tools/metrics/histograms/metadata/web_apk/histograms.xml
@@ -153,7 +153,7 @@ </histogram> <histogram name="WebApk.Launch.NetworkError" enum="NetErrorCodes" - expires_after="2022-06-01"> + expires_after="2023-06-01"> <owner>hartmanng@chromium.org</owner> <owner> src/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS
diff --git a/tools/perf/chrome-health-run-daily.sh b/tools/perf/chrome-health-run-daily.sh index 4f0b50f..dca0e6403 100644 --- a/tools/perf/chrome-health-run-daily.sh +++ b/tools/perf/chrome-health-run-daily.sh
@@ -7,9 +7,8 @@ pinnedReleaseMinusOne=93c720db8323b3ec10d056025ab95c23a31997c9 #101.0.4951.41 pinnedMain=6ee574c7eb5719153bbe0d1eff07fd0acbd864cc #refs/heads/main@{#966041} +# NOTE: If you are doing active development in this branch, the rest of this script may not work (it will attempt to check out different branches) cd ~/chromium/src - -gclient sync --with_branch_heads --with_tags git fetch # Current release branch
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 76e1b2a..0b3281a 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,16 +5,16 @@ "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm64/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "win": { - "hash": "6dbca97e80dcaeed2cdce3bcd4c7f1ed43d3ac70", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/a2ba21403c0a958883480c4191c8b5d48a350806/trace_processor_shell.exe" + "hash": "7318b13e41d1be2d8329f70f152b28444c8b37e5", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/26f1ca3b42a13a5dc179334f972ad8847aded023/trace_processor_shell.exe" }, "linux_arm": { "hash": "58893933be305d3bfe0a72ebebcacde2ac3ca893", "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "mac": { - "hash": "9c416e7a683a5ff76551bcd9c32d023d27154d76", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/a2ba21403c0a958883480c4191c8b5d48a350806/trace_processor_shell" + "hash": "143c4ce23f9389069250ea96f424eb19989cf325", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/26f1ca3b42a13a5dc179334f972ad8847aded023/trace_processor_shell" }, "mac_arm64": { "hash": "e1ad4861384b06d911a65f035317914b8cc975c6",
diff --git a/tools/perf/core/shard_maps/timing_data/fuchsia-perf-atlas-fyi_timing.json b/tools/perf/core/shard_maps/timing_data/fuchsia-perf-atlas-fyi_timing.json index 947d7ab..bd454a1f 100644 --- a/tools/perf/core/shard_maps/timing_data/fuchsia-perf-atlas-fyi_timing.json +++ b/tools/perf/core/shard_maps/timing_data/fuchsia-perf-atlas-fyi_timing.json
@@ -261,10 +261,6 @@ }, { "duration": "8.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { - "duration": "8.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, {
diff --git a/tools/perf/core/shard_maps/timing_data/linux-perf-fyi_timing.json b/tools/perf/core/shard_maps/timing_data/linux-perf-fyi_timing.json index b8463e50e..8f83c6e 100644 --- a/tools/perf/core/shard_maps/timing_data/linux-perf-fyi_timing.json +++ b/tools/perf/core/shard_maps/timing_data/linux-perf-fyi_timing.json
@@ -164,10 +164,6 @@ "name": "system_health.common_desktop/browse:tools:docs_scrolling" }, { - "duration": "71.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { "duration": "9.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" },
diff --git a/tools/perf/core/shard_maps/timing_data/linux-perf-pgo_timing.json b/tools/perf/core/shard_maps/timing_data/linux-perf-pgo_timing.json index 933c600..63b5b61 100644 --- a/tools/perf/core/shard_maps/timing_data/linux-perf-pgo_timing.json +++ b/tools/perf/core/shard_maps/timing_data/linux-perf-pgo_timing.json
@@ -3468,10 +3468,6 @@ "name": "system_health.common_desktop/browse:tools:docs_scrolling" }, { - "duration": "71.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { "duration": "4.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, @@ -3781,10 +3777,6 @@ }, { "duration": "1.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "1.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4132,10 +4124,6 @@ "name": "v8.browsing_desktop-future/browse:tools:docs_scrolling" }, { - "duration": "75.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { "duration": "11.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, @@ -4236,10 +4224,6 @@ "name": "v8.browsing_desktop/browse:tools:docs_scrolling" }, { - "duration": "74.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { "duration": "10.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" },
diff --git a/tools/perf/core/shard_maps/timing_data/linux-perf_timing.json b/tools/perf/core/shard_maps/timing_data/linux-perf_timing.json index 933c600..63b5b61 100644 --- a/tools/perf/core/shard_maps/timing_data/linux-perf_timing.json +++ b/tools/perf/core/shard_maps/timing_data/linux-perf_timing.json
@@ -3468,10 +3468,6 @@ "name": "system_health.common_desktop/browse:tools:docs_scrolling" }, { - "duration": "71.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { "duration": "4.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, @@ -3781,10 +3777,6 @@ }, { "duration": "1.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "1.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4132,10 +4124,6 @@ "name": "v8.browsing_desktop-future/browse:tools:docs_scrolling" }, { - "duration": "75.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { "duration": "11.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, @@ -4236,10 +4224,6 @@ "name": "v8.browsing_desktop/browse:tools:docs_scrolling" }, { - "duration": "74.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { "duration": "10.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" },
diff --git a/tools/perf/core/shard_maps/timing_data/mac-laptop_high_end-perf-pgo_timing.json b/tools/perf/core/shard_maps/timing_data/mac-laptop_high_end-perf-pgo_timing.json index 0831df09..f7e0584 100644 --- a/tools/perf/core/shard_maps/timing_data/mac-laptop_high_end-perf-pgo_timing.json +++ b/tools/perf/core/shard_maps/timing_data/mac-laptop_high_end-perf-pgo_timing.json
@@ -3693,10 +3693,6 @@ }, { "duration": "4.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { - "duration": "4.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, { @@ -4013,10 +4009,6 @@ }, { "duration": "2.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "2.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4377,10 +4369,6 @@ }, { "duration": "5.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { - "duration": "5.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, { @@ -4489,10 +4477,6 @@ }, { "duration": "4.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { - "duration": "4.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" }, {
diff --git a/tools/perf/core/shard_maps/timing_data/mac-laptop_high_end-perf_timing.json b/tools/perf/core/shard_maps/timing_data/mac-laptop_high_end-perf_timing.json index 0831df09..f7e0584 100644 --- a/tools/perf/core/shard_maps/timing_data/mac-laptop_high_end-perf_timing.json +++ b/tools/perf/core/shard_maps/timing_data/mac-laptop_high_end-perf_timing.json
@@ -3693,10 +3693,6 @@ }, { "duration": "4.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { - "duration": "4.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, { @@ -4013,10 +4009,6 @@ }, { "duration": "2.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "2.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4377,10 +4369,6 @@ }, { "duration": "5.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { - "duration": "5.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, { @@ -4489,10 +4477,6 @@ }, { "duration": "4.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { - "duration": "4.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" }, {
diff --git a/tools/perf/core/shard_maps/timing_data/mac-laptop_low_end-perf-pgo_timing.json b/tools/perf/core/shard_maps/timing_data/mac-laptop_low_end-perf-pgo_timing.json index 9a129c2..189b0e0 100644 --- a/tools/perf/core/shard_maps/timing_data/mac-laptop_low_end-perf-pgo_timing.json +++ b/tools/perf/core/shard_maps/timing_data/mac-laptop_low_end-perf-pgo_timing.json
@@ -3432,10 +3432,6 @@ "name": "system_health.common_desktop/browse:tools:docs_scrolling" }, { - "duration": "79.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { "duration": "11.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, @@ -3737,10 +3733,6 @@ }, { "duration": "4.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "4.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4080,10 +4072,6 @@ "name": "v8.browsing_desktop-future/browse:tools:docs_scrolling" }, { - "duration": "94.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { "duration": "24.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, @@ -4176,10 +4164,6 @@ "name": "v8.browsing_desktop/browse:tools:docs_scrolling" }, { - "duration": "95.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { "duration": "25.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" },
diff --git a/tools/perf/core/shard_maps/timing_data/mac-laptop_low_end-perf_timing.json b/tools/perf/core/shard_maps/timing_data/mac-laptop_low_end-perf_timing.json index 9a129c2..189b0e0 100644 --- a/tools/perf/core/shard_maps/timing_data/mac-laptop_low_end-perf_timing.json +++ b/tools/perf/core/shard_maps/timing_data/mac-laptop_low_end-perf_timing.json
@@ -3432,10 +3432,6 @@ "name": "system_health.common_desktop/browse:tools:docs_scrolling" }, { - "duration": "79.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { "duration": "11.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, @@ -3737,10 +3733,6 @@ }, { "duration": "4.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "4.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4080,10 +4072,6 @@ "name": "v8.browsing_desktop-future/browse:tools:docs_scrolling" }, { - "duration": "94.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { "duration": "24.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, @@ -4176,10 +4164,6 @@ "name": "v8.browsing_desktop/browse:tools:docs_scrolling" }, { - "duration": "95.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { "duration": "25.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" },
diff --git a/tools/perf/core/shard_maps/timing_data/mac-m1_mini_2020-perf-pgo_timing.json b/tools/perf/core/shard_maps/timing_data/mac-m1_mini_2020-perf-pgo_timing.json index a2d5939..99d7883 100644 --- a/tools/perf/core/shard_maps/timing_data/mac-m1_mini_2020-perf-pgo_timing.json +++ b/tools/perf/core/shard_maps/timing_data/mac-m1_mini_2020-perf-pgo_timing.json
@@ -3597,10 +3597,6 @@ }, { "duration": "3.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { - "duration": "3.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, { @@ -3917,10 +3913,6 @@ }, { "duration": "1.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "1.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4281,10 +4273,6 @@ }, { "duration": "5.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { - "duration": "5.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, { @@ -4393,10 +4381,6 @@ }, { "duration": "5.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { - "duration": "5.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" }, {
diff --git a/tools/perf/core/shard_maps/timing_data/mac-m1_mini_2020-perf_timing.json b/tools/perf/core/shard_maps/timing_data/mac-m1_mini_2020-perf_timing.json index a2d5939..99d7883 100644 --- a/tools/perf/core/shard_maps/timing_data/mac-m1_mini_2020-perf_timing.json +++ b/tools/perf/core/shard_maps/timing_data/mac-m1_mini_2020-perf_timing.json
@@ -3597,10 +3597,6 @@ }, { "duration": "3.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { - "duration": "3.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, { @@ -3917,10 +3913,6 @@ }, { "duration": "1.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "1.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4281,10 +4273,6 @@ }, { "duration": "5.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { - "duration": "5.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, { @@ -4393,10 +4381,6 @@ }, { "duration": "5.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { - "duration": "5.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" }, {
diff --git a/tools/perf/core/shard_maps/timing_data/win-10-perf-pgo_timing.json b/tools/perf/core/shard_maps/timing_data/win-10-perf-pgo_timing.json index 6310f8c..20b0061 100644 --- a/tools/perf/core/shard_maps/timing_data/win-10-perf-pgo_timing.json +++ b/tools/perf/core/shard_maps/timing_data/win-10-perf-pgo_timing.json
@@ -3476,10 +3476,6 @@ "name": "system_health.common_desktop/browse:tools:docs_scrolling" }, { - "duration": "75.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { "duration": "7.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, @@ -3789,10 +3785,6 @@ }, { "duration": "2.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "2.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4140,10 +4132,6 @@ "name": "v8.browsing_desktop-future/browse:tools:docs_scrolling" }, { - "duration": "97.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { "duration": "13.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, @@ -4244,10 +4232,6 @@ "name": "v8.browsing_desktop/browse:tools:docs_scrolling" }, { - "duration": "87.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { "duration": "17.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" },
diff --git a/tools/perf/core/shard_maps/timing_data/win-10-perf_timing.json b/tools/perf/core/shard_maps/timing_data/win-10-perf_timing.json index 6310f8c..20b0061 100644 --- a/tools/perf/core/shard_maps/timing_data/win-10-perf_timing.json +++ b/tools/perf/core/shard_maps/timing_data/win-10-perf_timing.json
@@ -3476,10 +3476,6 @@ "name": "system_health.common_desktop/browse:tools:docs_scrolling" }, { - "duration": "75.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { "duration": "7.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, @@ -3789,10 +3785,6 @@ }, { "duration": "2.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "2.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4140,10 +4132,6 @@ "name": "v8.browsing_desktop-future/browse:tools:docs_scrolling" }, { - "duration": "97.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { "duration": "13.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, @@ -4244,10 +4232,6 @@ "name": "v8.browsing_desktop/browse:tools:docs_scrolling" }, { - "duration": "87.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { "duration": "17.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" },
diff --git a/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf-pgo_timing.json b/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf-pgo_timing.json index afc51a3d..b00ea33 100644 --- a/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf-pgo_timing.json +++ b/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf-pgo_timing.json
@@ -3889,10 +3889,6 @@ }, { "duration": "11.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { - "duration": "11.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, { @@ -4217,10 +4213,6 @@ }, { "duration": "6.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "6.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4589,10 +4581,6 @@ }, { "duration": "23.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { - "duration": "23.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, { @@ -4709,10 +4697,6 @@ }, { "duration": "33.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { - "duration": "33.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" }, {
diff --git a/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf_hp-candidate_timing.json b/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf_hp-candidate_timing.json index f88b5aa..2bdfa6c 100644 --- a/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf_hp-candidate_timing.json +++ b/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf_hp-candidate_timing.json
@@ -56,10 +56,6 @@ "name": "v8.browsing_desktop/browse:tools:docs_scrolling" }, { - "duration": "78.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { "duration": "53.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" },
diff --git a/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf_timing.json b/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf_timing.json index afc51a3d..b00ea33 100644 --- a/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf_timing.json +++ b/tools/perf/core/shard_maps/timing_data/win-10_laptop_low_end-perf_timing.json
@@ -3889,10 +3889,6 @@ }, { "duration": "11.0", - "name": "system_health.common_desktop/browse:tools:earth:2020" - }, - { - "duration": "11.0", "name": "system_health.common_desktop/browse:tools:gmail-compose:2020" }, { @@ -4217,10 +4213,6 @@ }, { "duration": "6.0", - "name": "system_health.memory_desktop/browse:tools:earth:2020" - }, - { - "duration": "6.0", "name": "system_health.memory_desktop/browse:tools:gmail-compose:2020" }, { @@ -4589,10 +4581,6 @@ }, { "duration": "23.0", - "name": "v8.browsing_desktop-future/browse:tools:earth:2020" - }, - { - "duration": "23.0", "name": "v8.browsing_desktop-future/browse:tools:gmail-compose:2020" }, { @@ -4709,10 +4697,6 @@ }, { "duration": "33.0", - "name": "v8.browsing_desktop/browse:tools:earth:2020" - }, - { - "duration": "33.0", "name": "v8.browsing_desktop/browse:tools:gmail-compose:2020" }, {
diff --git a/tools/perf/expectations.config b/tools/perf/expectations.config index dc3bf47..299bf436 100644 --- a/tools/perf/expectations.config +++ b/tools/perf/expectations.config
@@ -316,7 +316,6 @@ crbug.com/1190750 [ linux ] system_health.common_desktop/long_running:tools:gmail-background [ Skip ] crbug.com/1190750 [ win ] system_health.common_desktop/long_running:tools:gmail-background [ Skip ] crbug.com/1190750 [ mac ] system_health.common_desktop/long_running:tools:gmail-background [ Skip ] -crbug.com/1196039 [ desktop ] system_health.common_desktop/browse:tools:earth:2020 [ Skip ] crbug.com/1174108 [ win-laptop ] system_health.common_desktop/browse:tools:autocad:2021 [ Skip ] crbug.com/1211795 [ mac ] system_health.common_desktop/browse:tools:autocad:2021 [ Skip ] crbug.com/1277966 [ win-laptop ] system_health.common_desktop/browse:tools:maps:2019 [ Skip ] @@ -331,7 +330,6 @@ crbug.com/1297360 [ fuchsia-chrome ] system_health.common_desktop/browse:tools:photoshop:2021 [ Skip ] crbug.com/1297360 [ fuchsia-chrome ] system_health.common_desktop/browse:media:youtube:2019 [ Skip ] crbug.com/1297360 [ fuchsia-chrome ] system_health.common_desktop/browse:tools:sheets:2019 [ Skip ] -crbug.com/1297360 [ fuchsia-chrome ] system_health.common_desktop/browse:tools:earth:2020 [ Skip ] crbug.com/1306274 [ fuchsia-chrome ] system_health.common_desktop/browse:media:imgur [ Skip ] crbug.com/1306280 [ fuchsia-chrome ] system_health.common_desktop/load:media:google_images:2018 [ Skip ] crbug.com/1302694 [ mac ] system_health.common_desktop/browse:tools:photoshop:2021 [ Skip ] @@ -499,8 +497,7 @@ crbug.com/903417 [ mac ] system_health.memory_desktop/long_running:tools:gmail-foreground [ Skip ] crbug.com/1216366 [ win-laptop ] system_health.memory_desktop/load:tools:drive:2019 [ Skip ] -# Memory dumps don't work at the moment for Google Earth and AutoCAD, see the issue. -crbug.com/1057035 system_health.memory_desktop/browse:tools:earth:2020 [ Skip ] +# Memory dumps don't work at the moment for WebAssembly apps. crbug.com/1057035 system_health.memory_desktop/browse:tools:autocad:2021 [ Skip ] crbug.com/1057035 system_health.memory_desktop/browse:tools:photoshop:2021 [ Skip ] crbug.com/1057035 system_health.memory_desktop/browse:tools:photoshop_warm:2021 [ Skip ] @@ -558,9 +555,7 @@ crbug.com/1111593 [ linux ] v8.browsing_desktop/browse:tools:gmail-compose:2020 [ Skip ] crbug.com/1149983 [ win-laptop ] v8.browsing_desktop/browse:tools:maps:2019 [ Skip ] crbug.com/1167686 [ linux ] v8.browsing_desktop/browse:tools:maps:2019 [ Skip ] -crbug.com/1174106 [ win-laptop ] v8.browsing_desktop/browse:tools:earth:2020 [ Skip ] crbug.com/1174108 [ win-laptop ] v8.browsing_desktop/browse:tools:autocad:2021 [ Skip ] -crbug.com/1196039 [ desktop ] v8.browsing_desktop/browse:tools:earth:2020 [ Skip ] crbug.com/1211795 [ mac ] v8.browsing_desktop/browse:tools:sheets:2019 [ Skip ] crbug.com/1211795 [ mac ] v8.browsing_desktop/browse:media:googleplaystore:2021 [ Skip ] crbug.com/1211795 [ mac ] v8.browsing_desktop/browse:social:twitter:2018 [ Skip ] @@ -593,9 +588,7 @@ crbug.com/1111593 [ linux ] v8.browsing_desktop-future/browse:tools:gmail-compose:2020 [ Skip ] crbug.com/1149983 [ win-laptop ] v8.browsing_desktop-future/browse:tools:maps:2019 [ Skip ] crbug.com/1167686 [ linux ] v8.browsing_desktop-future/browse:tools:maps:2019 [ Skip ] -crbug.com/1174106 [ win-laptop ] v8.browsing_desktop-future/browse:tools:earth:2020 [ Skip ] crbug.com/1174108 [ win-laptop ] v8.browsing_desktop-future/browse:tools:autocad:2021 [ Skip ] -crbug.com/1196039 [ desktop ] v8.browsing_desktop-future/browse:tools:earth:2020 [ Skip ] crbug.com/1211795 [ mac ] v8.browsing_desktop-future/browse:tools:sheets:2019 [ Skip ] crbug.com/1211795 [ mac ] v8.browsing_desktop-future/browse:media:googleplaystore:2021 [ Skip ] crbug.com/1211795 [ mac ] v8.browsing_desktop-future/browse:social:twitter:2018 [ Skip ]
diff --git a/tools/perf/page_sets/data/system_health_desktop.json b/tools/perf/page_sets/data/system_health_desktop.json index e0eece08..59c5ae0 100644 --- a/tools/perf/page_sets/data/system_health_desktop.json +++ b/tools/perf/page_sets/data/system_health_desktop.json
@@ -1,8 +1,5 @@ { "archives": { - "browse:media:earth:2020": { - "DEFAULT": "system_health_desktop_27ca4caf21.wprgo" - }, "browse:media:flickr_infinite_scroll": { "DEFAULT": "system_health_desktop_057.wprgo" }, @@ -127,9 +124,6 @@ "browse:tools:earth": { "DEFAULT": "system_health_desktop_050.wprgo" }, - "browse:tools:earth:2020": { - "DEFAULT": "system_health_desktop_df060e3191.wprgo" - }, "browse:tools:gmail-compose:2020": { "DEFAULT": "system_health_desktop_1d2b5dbaab.wprgo" },
diff --git a/tools/perf/page_sets/system_health/browsing_stories.py b/tools/perf/page_sets/system_health/browsing_stories.py index 76a865c9..f29b3eb 100644 --- a/tools/perf/page_sets/system_health/browsing_stories.py +++ b/tools/perf/page_sets/system_health/browsing_stories.py
@@ -910,79 +910,6 @@ action_runner.Wait(5) -class EarthDesktopStory2020(_MediaBrowsingStory): - """Load Google Earth and search for the Empire State Building. Watch the - Empire State Building for a few seconds. - """ - NAME = 'browse:tools:earth:2020' - URL = 'https://earth.google.com/web/' - SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY - TAGS = [ - story_tags.YEAR_2020, story_tags.WEBASSEMBLY, story_tags.WEBGL, - story_tags.KEYBOARD_INPUT - ] - - def __init__(self, story_set, take_memory_measurement): - super(EarthDesktopStory2020, self).__init__(story_set, - take_memory_measurement) - - # This script sets values in localStorage that suggest that Google Earth has - # already been visited before. Thereby we can avoid the tutorial at startup. - self.script_to_evaluate_on_commit = ''' - localStorage.setItem('earth.out_of_box.url:', - 'https://www.google.com/earth/clientassets/oobe/rev0/oobe_r0__$[hl].kml'); - localStorage.setItem('earth.out_of_box.major_revision:', '0'); - localStorage.setItem('earth.out_of_box.client_version:', '9.3.99.1'); - ''' - - def _DidLoadDocument(self, action_runner): - - CHECK_LOADED = ( - 'document.querySelector("body > earth-app").shadowRoot' - '.querySelector("#earthRelativeElements > earth-view-status")' - '.shadowRoot.querySelector("#percentageText").textContent === {{target}}' - ) - - action_runner.WaitForJavaScriptCondition(CHECK_LOADED, target="100%") - - search_selector = ('(() => document.querySelector("body > earth-app")' - '.shadowRoot.querySelector("#toolbar").shadowRoot' - '.querySelector("#search"))()') - action_runner.ClickElement(element_function=search_selector) - - search_text_selector = ( - '(() => document.querySelector("body > earth-app")' - '.shadowRoot.querySelector("#drawerContainer").shadowRoot' - '.querySelector("#search").shadowRoot.querySelector("#omnibox")' - '.shadowRoot.querySelector("#queryInput"))()') - - action_runner.WaitForElement(element_function=search_text_selector) - action_runner.ClickElement(element_function=search_text_selector) - - action_runner.EnterText('Empire State Building') - action_runner.PressKey('Return') - # Wait for 20 seconds so that the Empire State Building is reached and fully - # loaded. - action_runner.Wait(20) - - compass_selector = ( - '(() => document.querySelector("body > earth-app").shadowRoot' - '.querySelector("#compass").shadowRoot' - '.querySelector("#compassIcon"))()') - - action_runner.ClickElement(element_function=compass_selector) - action_runner.Wait(5) - - zoom_2d_selector = ( - '(() => document.querySelector("body > earth-app").shadowRoot' - '.querySelector("#hoverButton").shadowRoot' - '.querySelector("#hoverButton"))()') - action_runner.ClickElement(element_function=zoom_2d_selector) - # Wait for 5 seconds to load everything. We cannot wait for 100% because of - # the non-deterministic nature of the benchmark. - action_runner.Wait(5) - - class YouTubeTVDesktopStory2019(_MediaBrowsingStory): """Load a typical YouTube TV video then navigate to a next few videos. Stop and watch each video for a few seconds.
diff --git a/tools/perf/system_health_stories.csv b/tools/perf/system_health_stories.csv index 6cb095d7..5fe4440 100644 --- a/tools/perf/system_health_stories.csv +++ b/tools/perf/system_health_stories.csv
@@ -52,7 +52,6 @@ browse:tech:discourse_infinite_scroll:2018,,"desktop,mobile","2018,infinite_scroll" browse:tools:autocad:2021,"AutoCAD desktop story,",desktop,"2021,keyboard_input,wasm,webgl" browse:tools:docs_scrolling,Google Docs scrolling story:,desktop,"2020,javascript_heavy" -browse:tools:earth:2020,Load Google Earth and search for the Empire State Building. Watch the,desktop,"2020,keyboard_input,wasm,webgl" browse:tools:gmail-compose:2020,,desktop,2020 browse:tools:gmail-labelclick:2020,,desktop,2020 browse:tools:gmail-openconversation:2020,,desktop,2020
diff --git a/ui/accessibility/platform/ax_platform_node_base.cc b/ui/accessibility/platform/ax_platform_node_base.cc index 9337f50..d8edd27 100644 --- a/ui/accessibility/platform/ax_platform_node_base.cc +++ b/ui/accessibility/platform/ax_platform_node_base.cc
@@ -1233,7 +1233,7 @@ switch (static_cast<ax::mojom::DescriptionFrom>(desc_from)) { case ax::mojom::DescriptionFrom::kAriaDescription: // Descriptions are exposed via each platform's usual description field. - // Also, only aria-description is exposed via tha "description" object + // Also, only aria-description is exposed via the "description" object // attribute, in order to match Firefox. AddAttributeToList(ax::mojom::StringAttribute::kDescription, "description", attributes); @@ -1242,11 +1242,8 @@ case ax::mojom::DescriptionFrom::kButtonLabel: from = "button-label"; break; - case ax::mojom::DescriptionFrom::kPopupElement: - from = "popup-element"; - break; case ax::mojom::DescriptionFrom::kRelatedElement: - // Both @title an aria-describedby=tooltip get "tooltip". + // aria-describedby=tooltip is mapped to "tooltip". from = IsDescribedByTooltip() ? "tooltip" : "aria-describedby"; break; case ax::mojom::DescriptionFrom::kRubyAnnotation: @@ -1262,7 +1259,11 @@ from = "table-caption"; break; case ax::mojom::DescriptionFrom::kTitle: - // Both @title an aria-describedby=tooltip get "tooltip". + case ax::mojom::DescriptionFrom::kPopupElement: + // The following types of markup are mapped to "tooltip": + // * The title attribute. + // * A related popup=hint related via togglepopup/showpopup/hidepopup. + // * A tooltip related via aria-describedby (see kRelatedElement above). from = "tooltip"; break; case ax::mojom::DescriptionFrom::kNone:
diff --git a/ui/aura/gestures/gesture_recognizer_unittest.cc b/ui/aura/gestures/gesture_recognizer_unittest.cc index 8f728b8..17600f7 100644 --- a/ui/aura/gestures/gesture_recognizer_unittest.cc +++ b/ui/aura/gestures/gesture_recognizer_unittest.cc
@@ -4806,5 +4806,42 @@ EXPECT_0_EVENTS(delegate->events()); } +// Verifies that destructing a `GestureRecognizerImpl` instance with gesture +// providers works as expected (https://crbug.com/1325256). +TEST_F(GestureRecognizerTest, ResetGestureRecognizerWithGestureProvider) { + TimedEvents tes; + const int kTouchId = 4; + std::unique_ptr<GestureEventConsumeDelegate> delegate( + new GestureEventConsumeDelegate()); + std::unique_ptr<aura::Window> window(CreateTestWindowWithDelegate( + delegate.get(), /*id=*/-2345, /*bounds=*/gfx::Rect(0, 0, 50, 50), + /*parent=*/root_window())); + + // Touch press then release on `window`. + constexpr gfx::Point touch_location(/*x=*/10, /*y=*/20); + ui::TouchEvent press( + ui::ET_TOUCH_PRESSED, touch_location, /*time_stamp=*/tes.Now(), + ui::PointerDetails(ui::EventPointerType::kTouch, kTouchId)); + delegate->Reset(); + DispatchEventUsingWindowDispatcher(&press); + EXPECT_TRUE(delegate->tap_down()); + delegate->Reset(); + ui::TouchEvent release( + ui::ET_TOUCH_RELEASED, touch_location, + /*time_stamp=*/press.time_stamp() + base::Milliseconds(50), + ui::PointerDetails(ui::EventPointerType::kTouch, kTouchId)); + DispatchEventUsingWindowDispatcher(&release); + EXPECT_FALSE(delegate->tap_down()); + + // Check that the gesture recognizer owns one gesture provider. + EXPECT_EQ(1u, static_cast<ui::GestureRecognizerImpl*>( + aura::Env::GetInstance()->gesture_recognizer()) + ->consumer_gesture_provider_.size()); + + // Destroy the current gesture recognizer. + aura::Env::GetInstance()->SetGestureRecognizer( + std::make_unique<ui::GestureRecognizerImpl>()); +} + } // namespace test } // namespace aura
diff --git a/ui/aura/test/aura_test_helper.cc b/ui/aura/test/aura_test_helper.cc index 6c469e8b..b34ac0a 100644 --- a/ui/aura/test/aura_test_helper.cc +++ b/ui/aura/test/aura_test_helper.cc
@@ -94,7 +94,6 @@ // Reset aura::Env to eliminate test dependency (https://crbug.com/586514). EnvTestHelper env_helper(env); - env_helper.ResetEnvForTesting(); // Unit tests generally don't want to query the system, rather use the state // from RootWindow. env_helper.SetInputStateLookup(nullptr);
diff --git a/ui/aura/test/env_test_helper.h b/ui/aura/test/env_test_helper.h index 1712ab2..0b769e4 100644 --- a/ui/aura/test/env_test_helper.h +++ b/ui/aura/test/env_test_helper.h
@@ -38,10 +38,6 @@ env_->env_controller_->touch_ids_down_ = 0; } - // Reset aura::Env to eliminate potential test dependency. - // (https://crbug.com/586514) - void ResetEnvForTesting() { env_->is_touch_down_ = false; } - void SetGestureRecognizer( std::unique_ptr<ui::GestureRecognizer> gesture_recognizer) { env_->gesture_recognizer_ = std::move(gesture_recognizer);
diff --git a/ui/events/gestures/gesture_recognizer_impl.cc b/ui/events/gestures/gesture_recognizer_impl.cc index e48876dd..8d67ff2e 100644 --- a/ui/events/gestures/gesture_recognizer_impl.cc +++ b/ui/events/gestures/gesture_recognizer_impl.cc
@@ -62,7 +62,13 @@ GestureRecognizerImpl::GestureRecognizerImpl() = default; -GestureRecognizerImpl::~GestureRecognizerImpl() = default; +GestureRecognizerImpl::~GestureRecognizerImpl() { + // The gesture recognizer impl observes the gesture providers that are owned + // by `consumer_gesture_provider_`. Clear `consumer_gesture_provider_` + // explicitly so that the notifications sent by gesture providers during + // destruction are handled properly. + consumer_gesture_provider_.clear(); +} // Checks if this finger is already down, if so, returns the current target. // Otherwise, returns nullptr.
diff --git a/ui/events/gestures/gesture_recognizer_impl.h b/ui/events/gestures/gesture_recognizer_impl.h index d03d63889..fa757fb 100644 --- a/ui/events/gestures/gesture_recognizer_impl.h +++ b/ui/events/gestures/gesture_recognizer_impl.h
@@ -21,6 +21,8 @@ namespace aura::test { FORWARD_DECLARE_TEST(GestureRecognizerTest, DestroyGestureProviderAuraBeforeAck); +FORWARD_DECLARE_TEST(GestureRecognizerTest, + ResetGestureRecognizerWithGestureProvider); } // namespace aura::test namespace ui { @@ -83,6 +85,8 @@ private: FRIEND_TEST_ALL_PREFIXES(aura::test::GestureRecognizerTest, DestroyGestureProviderAuraBeforeAck); + FRIEND_TEST_ALL_PREFIXES(aura::test::GestureRecognizerTest, + ResetGestureRecognizerWithGestureProvider); // Sets up the target consumer for gestures based on the touch-event. void SetupTargets(const TouchEvent& event, GestureConsumer* consumer);
diff --git a/ui/gl/gl_display_manager.h b/ui/gl/gl_display_manager.h index 1bdff3a..966a871 100644 --- a/ui/gl/gl_display_manager.h +++ b/ui/gl/gl_display_manager.h
@@ -11,6 +11,8 @@ #include "base/check.h" #include "base/no_destructor.h" +#include "base/synchronization/lock.h" +#include "base/thread_annotations.h" #include "ui/gl/gl_display.h" #include "ui/gl/gl_export.h" #include "ui/gl/gpu_preference.h" @@ -41,6 +43,7 @@ GLDisplayManager& operator=(const GLDisplayManager&) = delete; GLDisplayPlatform* GetDisplay(uint64_t system_device_id) { + base::AutoLock auto_lock(lock_); for (const auto& display : displays_) { if (display->system_device_id() == system_device_id) { return display.get(); @@ -82,7 +85,9 @@ GLDisplayManager() = default; virtual ~GLDisplayManager() = default; - std::vector<std::unique_ptr<GLDisplayPlatform>> displays_; + mutable base::Lock lock_; + std::vector<std::unique_ptr<GLDisplayPlatform>> displays_ GUARDED_BY(lock_); + std::map<GpuPreference, uint64_t> gpu_preference_map_; };
diff --git a/ui/gl/gl_surface_egl.cc b/ui/gl/gl_surface_egl.cc index 2e6ce0254..d3df5378 100644 --- a/ui/gl/gl_surface_egl.cc +++ b/ui/gl/gl_surface_egl.cc
@@ -294,7 +294,7 @@ } EGLDisplay GetPlatformANGLEDisplay( - EGLDisplayPlatform native_display, + GLDisplayEGL* gl_display, EGLenum platform_type, const std::vector<std::string>& enabled_features, const std::vector<std::string>& disabled_features, @@ -335,7 +335,7 @@ GetAttribArrayFromStringVector(enabled_features); std::vector<const char*> disabled_features_attribs = GetAttribArrayFromStringVector(disabled_features); - if (GLSurfaceEGL::GetGLDisplayEGL()->egl_angle_feature_control_supported) { + if (gl_display->egl_angle_feature_control_supported) { if (!enabled_features_attribs.empty()) { display_attribs.push_back(EGL_FEATURE_OVERRIDES_ENABLED_ANGLE); display_attribs.push_back( @@ -349,8 +349,7 @@ } // TODO(dbehr) Add an attrib to Angle to pass EGL platform. - if (GLSurfaceEGL::GetGLDisplayEGL() - ->IsANGLEDisplayPowerPreferenceSupported()) { + if (gl_display->IsANGLEDisplayPowerPreferenceSupported()) { GpuPreference pref = GLSurface::AdjustGpuPreference(GpuPreference::kDefault); switch (pref) { @@ -376,17 +375,18 @@ // EGLAttribs (pointers) instead of EGLints into the display return eglGetPlatformDisplay( EGL_PLATFORM_ANGLE_ANGLE, - reinterpret_cast<void*>(native_display.GetDisplay()), + reinterpret_cast<void*>(gl_display->GetNativeDisplay()), &display_attribs[0]); } EGLDisplay GetDisplayFromType( DisplayType display_type, - EGLDisplayPlatform native_display, + GLDisplayEGL* gl_display, const std::vector<std::string>& enabled_angle_features, const std::vector<std::string>& disabled_angle_features, bool disable_all_angle_features, uint64_t system_device_id) { + DCHECK(gl_display); std::vector<EGLAttrib> extra_display_attribs; if (disable_all_angle_features) { extra_display_attribs.push_back(EGL_FEATURE_ALL_DISABLED_ANGLE); @@ -404,7 +404,8 @@ } switch (display_type) { case DEFAULT: - case SWIFT_SHADER: + case SWIFT_SHADER: { + EGLDisplayPlatform native_display = gl_display->native_display; if (native_display.GetPlatform() != 0) { return eglGetPlatformDisplay( native_display.GetPlatform(), @@ -412,14 +413,15 @@ } else { return eglGetDisplay(native_display.GetDisplay()); } + } case ANGLE_D3D9: return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_D3D11: return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_D3D11_NULL: @@ -427,19 +429,19 @@ extra_display_attribs.push_back( EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_OPENGL: return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_OPENGL_EGL: extra_display_attribs.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE); extra_display_attribs.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_EGL_ANGLE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_OPENGL_NULL: @@ -447,19 +449,19 @@ extra_display_attribs.push_back( EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_OPENGLES: return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_OPENGLES_EGL: extra_display_attribs.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE); extra_display_attribs.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_EGL_ANGLE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_OPENGLES_NULL: @@ -467,17 +469,17 @@ extra_display_attribs.push_back( EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_NULL: return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_NULL_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_NULL_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_VULKAN: return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_VULKAN_NULL: @@ -485,14 +487,14 @@ extra_display_attribs.push_back( EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_D3D11on12: extra_display_attribs.push_back(EGL_PLATFORM_ANGLE_D3D11ON12_ANGLE); extra_display_attribs.push_back(EGL_TRUE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_SWIFTSHADER: @@ -500,12 +502,12 @@ extra_display_attribs.push_back( EGL_PLATFORM_ANGLE_DEVICE_TYPE_SWIFTSHADER_ANGLE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_METAL: return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); case ANGLE_METAL_NULL: @@ -513,7 +515,7 @@ extra_display_attribs.push_back( EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE); return GetPlatformANGLEDisplay( - native_display, EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE, + gl_display, EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE, enabled_angle_features, disabled_angle_features, extra_display_attribs); default: @@ -1311,7 +1313,7 @@ for (size_t disp_index = 0; disp_index < init_displays.size(); ++disp_index) { DisplayType display_type = init_displays[disp_index]; EGLDisplay display = GetDisplayFromType( - display_type, gl_display->native_display, enabled_angle_features, + display_type, gl_display, enabled_angle_features, disabled_angle_features, disable_all_angle_features, system_device_id); if (display == EGL_NO_DISPLAY) { LOG(ERROR) << "EGL display query failed with error "
diff --git a/ui/webui/resources/cr_elements/cr_nav_menu_item_style.ts b/ui/webui/resources/cr_elements/cr_nav_menu_item_style.ts deleted file mode 100644 index 010ff13..0000000 --- a/ui/webui/resources/cr_elements/cr_nav_menu_item_style.ts +++ /dev/null
@@ -1,9 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'chrome://resources/cr_elements/shared_vars_css.m.js'; - -const styleElement = document.createElement('dom-module'); -styleElement.innerHTML = `{__html_template__}`; -styleElement.register('cr-nav-menu-item-style'); \ No newline at end of file
diff --git a/ui/webui/resources/cr_elements/search_highlight_style_css.ts b/ui/webui/resources/cr_elements/search_highlight_style_css.ts deleted file mode 100644 index c4814019..0000000 --- a/ui/webui/resources/cr_elements/search_highlight_style_css.ts +++ /dev/null
@@ -1,9 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import './shared_vars_css.m.js'; - -const styleMod = document.createElement('dom-module'); -styleMod.innerHTML = `{__html_template__}`; -styleMod.register('search-highlight-style');