diff --git a/DEPS b/DEPS index 1f02de98..c1cc91f 100644 --- a/DEPS +++ b/DEPS
@@ -121,11 +121,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'acc763e8795c694d0fb7c74a412b1805446754ff', + 'skia_revision': 'aec8c7e280cbd0590655887e9e2dff7f3822f34e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '90efb11e6eb215ccee50b035bd095e747dc57416', + 'v8_revision': '012576206f4785ac36cbcc35e73c0fa835813d62', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -133,7 +133,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '7f6b3674978d1852e06263821c99403e3259d397', + 'angle_revision': 'cb9609fe58c2464aa01f70404479de91dbf80f17', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling build tools # and whatever else without interference from each other. @@ -181,7 +181,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': 'a923c2a6de79f0f209157ab09849d695a98f4470', + 'catapult_revision': 'ecf56e8e03cd13d93319c53330ea950f7ae7e51d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -679,7 +679,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '3d335bee0f8d8fa3c56c89d38270afbe012a7b68', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '61c192b19b7974f3ced48ec339cd0bdea81702a7', 'condition': 'checkout_linux', }, @@ -1036,7 +1036,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '5a17545b5ab9cf380fc06c00e5080e2179c96762', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '8a5b9a8ad6fa8d06ac3f63a091303eead859cfd0', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78', @@ -1199,7 +1199,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'a2b35635aaef3e9301d69f77f9a0a3fd99291b08', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '9fe758e78833aa46691b8102bd03b81f77d8660f', + Var('webrtc_git') + '/src.git' + '@' + '5f8b5fdb62d38699e814ff181f511d1038fbf48e', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1230,7 +1230,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@03fe76f2cf15376da09677808a7801f7ce821015', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@dbf3245a78dbbb86910070cb2649f9a2fe5fd804', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/browser/aw_form_database_service.cc b/android_webview/browser/aw_form_database_service.cc index bf5fb76c..488bfb32 100644 --- a/android_webview/browser/aw_form_database_service.cc +++ b/android_webview/browser/aw_form_database_service.cc
@@ -84,7 +84,7 @@ base::IgnoreResult(&awds::GetCountOfValuesContainedBetween), autofill_data_, base::Time(), base::Time::Max(), this)); { - base::ThreadRestrictions::ScopedAllowWait wait; + base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; has_form_data_completion_.Wait(); } return has_form_data_result_;
diff --git a/android_webview/browser/cookie_manager.cc b/android_webview/browser/cookie_manager.cc index cbdf1d7ed..ae12327 100644 --- a/android_webview/browser/cookie_manager.cc +++ b/android_webview/browser/cookie_manager.cc
@@ -247,7 +247,10 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); ExecCookieTask(base::BindOnce( std::move(task), BoolCallbackAdapter(SignalEventClosure(&completion)))); - base::ThreadRestrictions::ScopedAllowWait wait; + + // Waiting is necessary when implementing synchronous APIs for the WebView + // embedder. + base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope wait; completion.Wait(); } @@ -258,7 +261,7 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); ExecCookieTask(base::BindOnce( std::move(task), IntCallbackAdapter(SignalEventClosure(&completion)))); - base::ThreadRestrictions::ScopedAllowWait wait; + base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope wait; completion.Wait(); } @@ -270,7 +273,7 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); ExecCookieTask( base::BindOnce(std::move(task), SignalEventClosure(&completion))); - base::ThreadRestrictions::ScopedAllowWait wait; + base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope wait; completion.Wait(); }
diff --git a/ash/components/fast_ink/fast_ink_view.cc b/ash/components/fast_ink/fast_ink_view.cc index 42506e8..cf3c73a 100644 --- a/ash/components/fast_ink/fast_ink_view.cc +++ b/ash/components/fast_ink/fast_ink_view.cc
@@ -213,6 +213,8 @@ } void ReclaimResources( const std::vector<viz::ReturnedResource>& resources) override { + if (delete_pending_) + return; for (auto& entry : resources) { auto it = exported_resources_.find(entry.id); DCHECK(it != exported_resources_.end());
diff --git a/ash/system/message_center/unified_message_center_view.cc b/ash/system/message_center/unified_message_center_view.cc index a67a0769..969db1a7 100644 --- a/ash/system/message_center/unified_message_center_view.cc +++ b/ash/system/message_center/unified_message_center_view.cc
@@ -13,6 +13,7 @@ #include "ash/system/message_center/unified_message_list_view.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/unified/sign_out_button.h" +#include "ash/system/unified/unified_system_tray_model.h" #include "ash/system/unified/unified_system_tray_view.h" #include "base/metrics/user_metrics.h" #include "ui/base/l10n/l10n_util.h" @@ -114,11 +115,12 @@ UnifiedSystemTrayView* parent, UnifiedSystemTrayModel* model) : parent_(parent), + model_(model), stacking_counter_(new StackingNotificationCounterView()), scroll_bar_(new MessageCenterScrollBar(this)), scroller_(new views::ScrollView()), message_list_view_(new UnifiedMessageListView(this, model)), - position_from_bottom_(kClearAllButtonRowHeight) { + last_scroll_position_from_bottom_(kClearAllButtonRowHeight) { message_list_view_->Init(); AddChildView(stacking_counter_); @@ -135,6 +137,9 @@ } UnifiedMessageCenterView::~UnifiedMessageCenterView() { + model_->set_notification_target_mode( + UnifiedSystemTrayModel::NotificationTargetMode::LAST_NOTIFICATION); + RemovedFromWidget(); } @@ -145,7 +150,7 @@ void UnifiedMessageCenterView::ListPreferredSizeChanged() { UpdateVisibility(); PreferredSizeChanged(); - ScrollToPositionFromBottom(); + ScrollToTarget(); Layout(); if (GetWidget() && !GetWidget()->IsClosed()) @@ -185,7 +190,7 @@ scroller_->SetBoundsRect(GetContentsBounds()); } - ScrollToPositionFromBottom(); + ScrollToTarget(); NotifyHeightBelowScroll(); } @@ -197,9 +202,13 @@ } void UnifiedMessageCenterView::OnMessageCenterScrolled() { - position_from_bottom_ = + last_scroll_position_from_bottom_ = scroll_bar_->GetMaxPosition() - scroller_->GetVisibleRect().y(); + // Reset the target if user scrolls the list manually. + model_->set_notification_target_mode( + UnifiedSystemTrayModel::NotificationTargetMode::LAST_POSITION); + const bool was_visible = stacking_counter_->visible(); stacking_counter_->SetCount(GetStackedNotificationCount()); if (was_visible != stacking_counter_->visible()) { @@ -239,33 +248,59 @@ session_controller->ShouldShowNotificationTray() && (!session_controller->IsScreenLocked() || AshMessageCenterLockScreenController::IsEnabled())); - // When notification list went invisible, |position_from_bottom_| should be - // reset. - if (!visible()) - position_from_bottom_ = kClearAllButtonRowHeight; + // When notification list went invisible, the last notification should be + // targeted next time. + if (!visible()) { + model_->set_notification_target_mode( + UnifiedSystemTrayModel::NotificationTargetMode::LAST_NOTIFICATION); + } } -void UnifiedMessageCenterView::ScrollToPositionFromBottom() { +void UnifiedMessageCenterView::ScrollToTarget() { // Following logic doesn't work when the view is invisible, because it uses // the height of |scroller_|. if (!visible()) return; - // If the last notification is taller than |scroller_|, we should align the - // top of the notification with the top of |scroller_|. - const int last_notification_offset = - message_list_view_->GetLastNotificationHeight() - scroller_->height() + - kUnifiedNotificationCenterSpacing; - if (position_from_bottom_ == kClearAllButtonRowHeight && - last_notification_offset > 0) { - position_from_bottom_ += last_notification_offset; + int position; + switch (model_->notification_target_mode()) { + case UnifiedSystemTrayModel::NotificationTargetMode::LAST_POSITION: + // Restore the previous scrolled position with matching the distance from + // the bottom. + position = + scroll_bar_->GetMaxPosition() - last_scroll_position_from_bottom_; + break; + case UnifiedSystemTrayModel::NotificationTargetMode::NOTIFICATION_ID: + FALLTHROUGH; + case UnifiedSystemTrayModel::NotificationTargetMode::LAST_NOTIFICATION: { + const gfx::Rect& target_rect = + (model_->notification_target_mode() == + UnifiedSystemTrayModel::NotificationTargetMode::NOTIFICATION_ID) + ? message_list_view_->GetNotificationBounds( + model_->notification_target_id()) + : message_list_view_->GetLastNotificationBounds(); + + const int last_notification_offset = target_rect.height() - + scroller_->height() + + kUnifiedNotificationCenterSpacing; + if (last_notification_offset > 0) { + // If the target notification is taller than |scroller_|, we should + // align the top of the notification with the top of |scroller_|. + position = target_rect.y(); + } else { + // Otherwise, we align the bottom of the notification with the bottom of + // |scroller_|; + position = target_rect.bottom() - scroller_->height(); + + if (model_->notification_target_mode() == + UnifiedSystemTrayModel::NotificationTargetMode::LAST_NOTIFICATION) { + position += kUnifiedNotificationCenterSpacing; + } + } + } } - if (position_from_bottom_ > scroll_bar_->GetMaxPosition()) - position_from_bottom_ = scroll_bar_->GetMaxPosition(); - - scroller_->ScrollToPosition( - scroll_bar_, scroll_bar_->GetMaxPosition() - position_from_bottom_); + scroller_->ScrollToPosition(scroll_bar_, position); } int UnifiedMessageCenterView::GetStackedNotificationCount() const {
diff --git a/ash/system/message_center/unified_message_center_view.h b/ash/system/message_center/unified_message_center_view.h index f03ddc1..f9b7bee 100644 --- a/ash/system/message_center/unified_message_center_view.h +++ b/ash/system/message_center/unified_message_center_view.h
@@ -87,21 +87,22 @@ void UpdateVisibility(); - // Scroll the notification list to |position_from_bottom_|. - void ScrollToPositionFromBottom(); + // Scroll the notification list to the target position. + void ScrollToTarget(); // Notifies height below scroll to |parent_| so that it can update // TopCornerBorder. void NotifyHeightBelowScroll(); UnifiedSystemTrayView* const parent_; + UnifiedSystemTrayModel* const model_; StackingNotificationCounterView* const stacking_counter_; MessageCenterScrollBar* const scroll_bar_; views::ScrollView* const scroller_; UnifiedMessageListView* const message_list_view_; // Position from the bottom of scroll contents in dip. - int position_from_bottom_; + int last_scroll_position_from_bottom_; views::FocusManager* focus_manager_ = nullptr;
diff --git a/ash/system/message_center/unified_message_center_view_unittest.cc b/ash/system/message_center/unified_message_center_view_unittest.cc index e202313..5385537 100644 --- a/ash/system/message_center/unified_message_center_view_unittest.cc +++ b/ash/system/message_center/unified_message_center_view_unittest.cc
@@ -152,6 +152,8 @@ int size_changed_count() const { return size_changed_count_; } + UnifiedSystemTrayModel* model() { return model_.get(); } + private: int id_ = 0; int size_changed_count_ = 0; @@ -311,7 +313,7 @@ message_view_bounds.height()); // Top of the second notification aligns with the top of MessageCenterView. - EXPECT_EQ(0, message_view_bounds.y()); + EXPECT_EQ(kStackingNotificationCounterHeight, message_view_bounds.y()); } TEST_F(UnifiedMessageCenterViewTest, ScrollPositionWhenResized) { @@ -438,4 +440,80 @@ EXPECT_LT(0, message_center_view()->height_below_scroll()); } +TEST_F(UnifiedMessageCenterViewTest, + HeightBelowScrollWithTargetingFirstNotification) { + std::vector<std::string> ids; + for (size_t i = 0; i < 10; ++i) + ids.push_back(AddNotification()); + // Set the first notification as the target. + model()->SetTargetNotification(ids[0]); + + CreateMessageCenterView(); + EXPECT_TRUE(message_center_view()->visible()); + + EXPECT_GT(GetMessageListView()->bounds().height(), + message_center_view()->bounds().height()); + message_center_view()->OnMessageCenterScrolled(); + + EXPECT_EQ(0, GetScroller()->GetVisibleRect().y()); + EXPECT_EQ( + GetMessageListView()->height() - GetScroller()->GetVisibleRect().height(), + message_center_view()->height_below_scroll()); +} + +TEST_F(UnifiedMessageCenterViewTest, + HeightBelowScrollWithTargetingNotification) { + std::vector<std::string> ids; + for (size_t i = 0; i < 10; ++i) + ids.push_back(AddNotification()); + // Set the second last notification as the target. + model()->SetTargetNotification(ids[8]); + + CreateMessageCenterView(); + EXPECT_TRUE(message_center_view()->visible()); + + EXPECT_GT(GetMessageListView()->bounds().height(), + message_center_view()->bounds().height()); + message_center_view()->OnMessageCenterScrolled(); + + EXPECT_EQ(GetMessageListView()->GetLastNotificationBounds().height(), + message_center_view()->height_below_scroll()); +} + +TEST_F(UnifiedMessageCenterViewTest, + HeightBelowScrollWithTargetingLastNotification) { + std::vector<std::string> ids; + for (size_t i = 0; i < 10; ++i) + ids.push_back(AddNotification()); + // Set the second last notification as the target. + model()->SetTargetNotification(ids[9]); + + CreateMessageCenterView(); + EXPECT_TRUE(message_center_view()->visible()); + + EXPECT_GT(GetMessageListView()->bounds().height(), + message_center_view()->bounds().height()); + message_center_view()->OnMessageCenterScrolled(); + + EXPECT_EQ(0, message_center_view()->height_below_scroll()); +} + +TEST_F(UnifiedMessageCenterViewTest, + HeightBelowScrollWithTargetingInvalidNotification) { + std::vector<std::string> ids; + for (size_t i = 0; i < 10; ++i) + ids.push_back(AddNotification()); + // Set the second last notification as the target. + model()->SetTargetNotification("INVALID_ID"); + + CreateMessageCenterView(); + EXPECT_TRUE(message_center_view()->visible()); + + EXPECT_GT(GetMessageListView()->bounds().height(), + message_center_view()->bounds().height()); + message_center_view()->OnMessageCenterScrolled(); + + EXPECT_EQ(0, message_center_view()->height_below_scroll()); +} + } // namespace ash
diff --git a/ash/system/message_center/unified_message_list_view.cc b/ash/system/message_center/unified_message_list_view.cc index 389657a..7e50c21a 100644 --- a/ash/system/message_center/unified_message_list_view.cc +++ b/ash/system/message_center/unified_message_list_view.cc
@@ -210,12 +210,6 @@ StartAnimation(); } -int UnifiedMessageListView::GetLastNotificationHeight() const { - if (!has_children()) - return 0; - return child_at(child_count() - 1)->bounds().height(); -} - int UnifiedMessageListView::CountNotificationsAboveY(int y_offset) const { for (int i = 0; i < child_count(); ++i) { if (child_at(i)->bounds().bottom() >= y_offset) @@ -244,6 +238,26 @@ } } +gfx::Rect UnifiedMessageListView::GetNotificationBounds( + const std::string& notification_id) const { + if (!notification_id.empty()) { + for (int i = 0; i < child_count(); i++) { + if (GetContainer(i)->GetNotificationId() == notification_id) + return GetContainer(i)->bounds(); + } + } + + // Fallback to the last notification. + return GetLastNotificationBounds(); +} + +gfx::Rect UnifiedMessageListView::GetLastNotificationBounds() const { + if (child_count() == 0) + return gfx::Rect(); + + return GetContainer(child_count() - 1)->bounds(); +} + gfx::Size UnifiedMessageListView::CalculatePreferredSize() const { return gfx::Size(kTrayMenuWidth, gfx::Tween::IntValueBetween(GetCurrentValue(), start_height_,
diff --git a/ash/system/message_center/unified_message_list_view.h b/ash/system/message_center/unified_message_list_view.h index 32f3908..998b4a49 100644 --- a/ash/system/message_center/unified_message_list_view.h +++ b/ash/system/message_center/unified_message_list_view.h
@@ -46,9 +46,13 @@ // removed from MessageCenter at the beginning of the animation. void ClearAllWithAnimation(); - // Get the height of the notification at the bottom. If no notification is - // added, it returns 0. - int GetLastNotificationHeight() const; + // Return the bounds of the specified notification view. If the given id is + // invalid, return an empty rect. + gfx::Rect GetNotificationBounds(const std::string& id) const; + + // Return the bounds of the last notification view. If there is no view, + // return an empty rect. + gfx::Rect GetLastNotificationBounds() const; // Count the number of notifications whose bottom position is above // |y_offset|. O(n) where n is number of notifications.
diff --git a/ash/system/unified/unified_system_tray.cc b/ash/system/unified/unified_system_tray.cc index 3818ca5..8e38db3 100644 --- a/ash/system/unified/unified_system_tray.cc +++ b/ash/system/unified/unified_system_tray.cc
@@ -243,6 +243,11 @@ SetEnabled(enabled); } +void UnifiedSystemTray::SetTargetNotification( + const std::string& notification_id) { + model_->SetTargetNotification(notification_id); +} + bool UnifiedSystemTray::PerformAction(const ui::Event& event) { if (bubble_) { CloseBubble();
diff --git a/ash/system/unified/unified_system_tray.h b/ash/system/unified/unified_system_tray.h index 077266b..f224389 100644 --- a/ash/system/unified/unified_system_tray.h +++ b/ash/system/unified/unified_system_tray.h
@@ -78,6 +78,10 @@ // open when disabling, also close it. void SetTrayEnabled(bool enabled); + // Set the target notification, which is visible in the viewport when the + // message center opens. + void SetTargetNotification(const std::string& notification_id); + // Sets the height of the system tray bubble from the edge of the work area // so that the notification popups don't overlap with the tray. Pass 0 if no // bubble is shown.
diff --git a/ash/system/unified/unified_system_tray_model.cc b/ash/system/unified/unified_system_tray_model.cc index 8e61bcd..5dd97842 100644 --- a/ash/system/unified/unified_system_tray_model.cc +++ b/ash/system/unified/unified_system_tray_model.cc
@@ -99,6 +99,13 @@ : base::Optional<bool>(it->second); } +void UnifiedSystemTrayModel::SetTargetNotification( + const std::string& notification_id) { + DCHECK(!notification_id.empty()); + notification_target_id_ = notification_id; + notification_target_mode_ = NotificationTargetMode::NOTIFICATION_ID; +} + void UnifiedSystemTrayModel::SetNotificationExpanded( const std::string& notification_id, bool expanded) {
diff --git a/ash/system/unified/unified_system_tray_model.h b/ash/system/unified/unified_system_tray_model.h index a5a9359..a5691ee 100644 --- a/ash/system/unified/unified_system_tray_model.h +++ b/ash/system/unified/unified_system_tray_model.h
@@ -16,6 +16,16 @@ // SystemTrayModel. class ASH_EXPORT UnifiedSystemTrayModel { public: + enum class NotificationTargetMode { + // Notification list scrolls to the last notification. + LAST_NOTIFICATION, + // Notification list scrolls to the last scroll position. + LAST_POSITION, + // Notification list scrolls to the specified notification defined by + // |SetTargetNotification(notification_id)|. + NOTIFICATION_ID, + }; + class Observer { public: virtual ~Observer() {} @@ -49,6 +59,10 @@ // Clears all changes by SetNotificatinExpanded(). void ClearNotificationChanges(); + // Set the notification id of the target. This sets target mode as + // NOTIFICATION_ID. + void SetTargetNotification(const std::string& notification_id); + float display_brightness() const { return display_brightness_; } float keyboard_brightness() const { return keyboard_brightness_; } @@ -56,12 +70,32 @@ expanded_on_open_ = expanded_on_open; } + void set_notification_target_mode(NotificationTargetMode mode) { + notification_target_mode_ = mode; + } + + NotificationTargetMode notification_target_mode() const { + return notification_target_mode_; + } + + const std::string& notification_target_id() const { + return notification_target_id_; + } + private: class DBusObserver; void DisplayBrightnessChanged(float brightness, bool by_user); void KeyboardBrightnessChanged(float brightness, bool by_user); + // Target mode which is used to decide the scroll position of the message + // center on opening. See the comment in |NotificationTargetMode|. + NotificationTargetMode notification_target_mode_ = + NotificationTargetMode::LAST_NOTIFICATION; + // Set the notification id of the target. This id is used if the target mode + // is NOTIFICATION_ID. + std::string notification_target_id_; + // If UnifiedSystemTray bubble is expanded on its open. It's expanded by // default, and if a user collapses manually, it remembers previous state. bool expanded_on_open_ = true;
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index 34485b7..5ede3b9 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h
@@ -365,8 +365,6 @@ // Allowed usage: friend class SimpleThread; - friend class android_webview::AwFormDatabaseService; - friend class android_webview::CookieManager; friend class base::GetAppOutputScopedAllowBaseSyncPrimitives; friend class content::BrowserMainLoop; friend class content::BrowserProcessSubThread; @@ -418,6 +416,9 @@ friend class ::NativeDesktopMediaList; friend class ::StartupTimeBomb; friend class android::JavaHandlerThread; + friend class android_webview:: + AwFormDatabaseService; // http://crbug.com/904431 + friend class android_webview::CookieManager; friend class audio::OutputDevice; friend class base::MessageLoopImpl; friend class base::ScopedAllowThreadRecallForStackSamplingProfiler; @@ -438,8 +439,8 @@ // Usage that should be fixed: friend class ::chromeos::BlockingMethodCaller; // http://crbug.com/125360 friend class base::Thread; // http://crbug.com/918039 - friend class cc::CompletionEvent; // http://crbug.com/902653 - friend class cc::SingleThreadTaskGraphRunner; // http://crbug.com/902823 + friend class cc::CompletionEvent; // http://crbug.com/902653 + friend class cc::SingleThreadTaskGraphRunner; // http://crbug.com/902823 friend class content:: BrowserGpuChannelHostFactory; // http://crbug.com/125248 friend class content::CategorizedWorkerPool; // http://crbug.com/902823
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 826e194..adc63b3c 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -4d54ec8046e1222e119eca44d87bd8414ce43e5b \ No newline at end of file +7fb0692d9161011a6fd3b8abf5d3d83b7ffeee89 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 7fdbdb6..c198749 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -3f82cdd0060d732bdb12f35d65db0497f6b10d37 \ No newline at end of file +0c76458159f1a91ec777356c92d5fe7be4bc5681 \ No newline at end of file
diff --git a/chrome/VERSION b/chrome/VERSION index 8da05cb..143fe25f 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=73 MINOR=0 -BUILD=3654 +BUILD=3655 PATCH=0
diff --git a/chrome/android/java/res/layout-sw600dp/location_status.xml b/chrome/android/java/res/layout-sw600dp/location_status.xml deleted file mode 100644 index d443fefd..0000000 --- a/chrome/android/java/res/layout-sw600dp/location_status.xml +++ /dev/null
@@ -1,47 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2018 The Chromium Authors. All rights reserved. - Use of this source code is governed by a BSD-style license that can be - found in the LICENSE file. --> - -<!-- Layout for the LocationBar's StatusView for devices with >600dp min width --> -<merge - xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto"> - - <org.chromium.chrome.browser.omnibox.status.StatusView - android:id="@+id/location_bar_status" - android:layout_width="wrap_content" - android:layout_height="match_parent"> - - <FrameLayout android:id="@+id/location_bar_icon" - android:layout_width="@dimen/location_bar_icon_width" - android:layout_height="match_parent" - android:layout_gravity="start|center_vertical"> - - <ImageView android:id="@+id/navigation_button" - style="@style/LocationBarButton" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:layout_gravity="center_vertical" - android:src="@drawable/ic_omnibox_page" - android:scaleType="center" - android:contentDescription="@string/accessibility_toolbar_btn_site_info" /> - - <org.chromium.ui.widget.ChromeImageButton - android:id="@+id/security_button" - style="@style/LocationBarButton" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:scaleType="center" - android:layout_gravity="center" - android:alpha="0" - android:visibility="invisible" - app:tint="@color/dark_mode_tint" /> - - </FrameLayout> - - <include layout="@layout/location_bar_status" /> - - </org.chromium.chrome.browser.omnibox.status.StatusView> - -</merge>
diff --git a/chrome/android/java/res/layout/location_bar_status.xml b/chrome/android/java/res/layout/location_bar_status.xml deleted file mode 100644 index 2ca2613..0000000 --- a/chrome/android/java/res/layout/location_bar_status.xml +++ /dev/null
@@ -1,35 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2016 The Chromium Authors. All rights reserved. - Use of this source code is governed by a BSD-style license that can be - found in the LICENSE file. --> - -<!-- The location bar verbose status. --> -<merge xmlns:android="http://schemas.android.com/apk/res/android"> - - <TextView android:id="@+id/location_bar_verbose_status" - android:layout_width="wrap_content" - android:layout_height="match_parent" - android:paddingEnd="8dp" - android:gravity="center_vertical" - android:textAlignment="viewStart" - android:textAppearance="@style/TextAppearance.OmniboxVerboseStatus" - android:ellipsize="end" - android:maxLines="1" - android:visibility="gone" /> - - <!-- Separator is going to be shown or hidden together with the status defined above. --> - <View android:id="@+id/location_bar_verbose_status_separator" - android:layout_width="@dimen/location_bar_status_separator_width" - android:layout_height="24dp" - android:layout_gravity="center_vertical" - android:background="#1f000000" - android:visibility="gone" /> - - <!-- This space follows the verbose status and compliments the space that follows - the status. --> - <Space android:id="@+id/location_bar_verbose_status_extra_space" - android:layout_width="@dimen/location_bar_status_separator_spacer" - android:layout_height="match_parent" - android:visibility="gone" /> - -</merge>
diff --git a/chrome/android/java/res/layout/location_status.xml b/chrome/android/java/res/layout/location_status.xml index 417b9d2..ea736de2 100644 --- a/chrome/android/java/res/layout/location_status.xml +++ b/chrome/android/java/res/layout/location_status.xml
@@ -2,8 +2,6 @@ <!-- Copyright 2018 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> - -<!-- Layout for the LocationBar's StatusView for most devices --> <merge xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> @@ -13,35 +11,40 @@ android:layout_width="wrap_content" android:layout_height="match_parent"> - <FrameLayout android:id="@+id/location_bar_icon" + <org.chromium.ui.widget.ChromeImageButton + android:id="@+id/location_bar_status_icon" + style="@style/LocationBarButton" android:layout_width="@dimen/location_bar_start_icon_width" android:layout_height="match_parent" - android:paddingEnd="4dp" - android:visibility="gone" > - - <ImageView android:id="@+id/navigation_button" - style="@style/LocationBarButton" - android:layout_width="match_parent" - android:layout_height="match_parent" android:layout_gravity="center" - android:scaleType="center" - android:contentDescription="@string/accessibility_toolbar_btn_site_info" /> + android:contentDescription="@string/accessibility_toolbar_btn_site_info" + android:scaleType="center" /> - <org.chromium.ui.widget.ChromeImageButton - android:id="@+id/security_button" - style="@style/LocationBarButton" - android:layout_width="match_parent" + <TextView android:id="@+id/location_bar_verbose_status" + android:layout_width="wrap_content" android:layout_height="match_parent" - android:scaleType="center" - android:layout_gravity="center" - android:alpha="0" - android:visibility="invisible" - app:tint="@color/dark_mode_tint" /> + android:paddingEnd="8dp" + android:gravity="center_vertical" + android:textAlignment="viewStart" + android:textAppearance="@style/TextAppearance.OmniboxVerboseStatus" + android:ellipsize="end" + android:maxLines="1" + android:visibility="gone" /> - </FrameLayout> + <!-- Separator is going to be shown or hidden together with the status defined above. --> + <View android:id="@+id/location_bar_verbose_status_separator" + android:layout_width="@dimen/location_bar_status_separator_width" + android:layout_height="24dp" + android:layout_gravity="center_vertical" + android:background="@color/black_alpha_12" + android:visibility="gone" /> - <include layout="@layout/location_bar_status" /> + <!-- This space follows the verbose status and compliments the space that follows + the status. --> + <Space android:id="@+id/location_bar_verbose_status_extra_space" + android:layout_width="@dimen/location_bar_status_separator_spacer" + android:layout_height="match_parent" + android:visibility="gone" /> </org.chromium.chrome.browser.omnibox.status.StatusView> - </merge>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java index b963ef2..de13e60 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java
@@ -80,6 +80,8 @@ "org.chromium.chrome.browser.webapp_splash_screen_url"; public static final String EXTRA_IS_ICON_GENERATED = "org.chromium.chrome.browser.is_icon_generated"; + public static final String EXTRA_IS_ICON_ADAPTIVE = + "org.chromium.chrome.browser.webapp_icon_adaptive"; public static final String EXTRA_VERSION = "org.chromium.chrome.browser.webapp_shortcut_version"; public static final String REUSE_URL_MATCHING_TAB_ELSE_NEW_TAB = @@ -124,13 +126,13 @@ // We subtract 1 from the scaling factor to give the amount we need to increase by, then divide // it by two to get the amount of padding that we will add to both sides. private static final float MASKABLE_SAFE_ZONE_RATIO = 4.0f / 5.0f; - private static final float ADAPTABLE_SAFE_ZONE_RATIO = 66.0f / 108.0f; + private static final float ADAPTIVE_SAFE_ZONE_RATIO = 66.0f / 108.0f; - private static final float MASKABLE_TO_ADAPTABLE_SCALING_FACTOR = - MASKABLE_SAFE_ZONE_RATIO / ADAPTABLE_SAFE_ZONE_RATIO; + private static final float MASKABLE_TO_ADAPTIVE_SCALING_FACTOR = + MASKABLE_SAFE_ZONE_RATIO / ADAPTIVE_SAFE_ZONE_RATIO; private static final float MASKABLE_ICON_PADDING_RATIO = - (MASKABLE_TO_ADAPTABLE_SCALING_FACTOR - 1.0f) / 2.0f; + (MASKABLE_TO_ADAPTIVE_SCALING_FACTOR - 1.0f) / 2.0f; // True when Android O's ShortcutManager.requestPinShortcut() is supported. private static boolean sIsRequestPinShortcutSupported; @@ -146,13 +148,13 @@ * Request Android to add a shortcut to the home screen. * @param title Title of the shortcut. * @param icon Image that represents the shortcut. - * @param iconAdaptable Whether to create an Android Adaptable icon. + * @param isIconAdaptive Whether to create an Android Adaptive icon. * @param shortcutIntent Intent to fire when the shortcut is activated. */ public void addShortcutToHomescreen( - String title, Bitmap icon, boolean iconAdaptable, Intent shortcutIntent) { + String title, Bitmap icon, boolean isIconAdaptive, Intent shortcutIntent) { if (isRequestPinShortcutSupported()) { - addShortcutWithShortcutManager(title, icon, iconAdaptable, shortcutIntent); + addShortcutWithShortcutManager(title, icon, isIconAdaptive, shortcutIntent); return; } Intent intent = createAddToHomeIntent(title, icon, shortcutIntent); @@ -186,7 +188,7 @@ @CalledByNative private static void addWebapp(final String id, final String url, final String scopeUrl, final String userTitle, final String name, final String shortName, final String iconUrl, - final Bitmap icon, boolean iconAdaptable, @WebDisplayMode final int displayMode, + final Bitmap icon, boolean isIconAdaptive, @WebDisplayMode final int displayMode, final int orientation, final int source, final long themeColor, final long backgroundColor, final String splashScreenUrl, final long callbackPointer) { new AsyncTask<Intent>() { @@ -202,14 +204,14 @@ Intent shortcutIntent = createWebappShortcutIntent(id, sDelegate.getFullscreenAction(), url, nonEmptyScopeUrl, name, shortName, encodedIcon, WEBAPP_SHORTCUT_VERSION, displayMode, orientation, themeColor, - backgroundColor, splashScreenUrl, iconUrl.isEmpty()); + backgroundColor, splashScreenUrl, iconUrl.isEmpty(), isIconAdaptive); shortcutIntent.putExtra(EXTRA_MAC, getEncodedMac(url)); shortcutIntent.putExtra(EXTRA_SOURCE, source); return shortcutIntent; } @Override protected void onPostExecute(final Intent resultIntent) { - sDelegate.addShortcutToHomescreen(userTitle, icon, iconAdaptable, resultIntent); + sDelegate.addShortcutToHomescreen(userTitle, icon, isIconAdaptive, resultIntent); // Store the webapp data so that it is accessible without the intent. Once this // process is complete, call back to native code to start the splash image @@ -233,13 +235,13 @@ @SuppressWarnings("unused") @CalledByNative private static void addShortcut(String id, String url, String userTitle, Bitmap icon, - boolean iconAdaptable, int source) { + boolean isIconAdaptive, int source) { Context context = ContextUtils.getApplicationContext(); final Intent shortcutIntent = createShortcutIntent(url); shortcutIntent.putExtra(EXTRA_ID, id); shortcutIntent.putExtra(EXTRA_SOURCE, source); shortcutIntent.setPackage(context.getPackageName()); - sDelegate.addShortcutToHomescreen(userTitle, icon, iconAdaptable, shortcutIntent); + sDelegate.addShortcutToHomescreen(userTitle, icon, isIconAdaptive, shortcutIntent); if (shouldShowToastWhenAddingShortcut()) { showAddedToHomescreenToast(userTitle); } @@ -354,13 +356,14 @@ * @param backgroundColor Background color of the web app. * @param splashScreenUrl Url of the HTML splash screen. * @param isIconGenerated True if the icon is generated by Chromium. + * @param isIconAdaptive Whether the shortcut icon is Adaptive. * @return Intent for onclick action of the shortcut. * This method must not be called on the UI thread. */ public static Intent createWebappShortcutIntent(String id, String action, String url, String scope, String name, String shortName, String encodedIcon, int version, @WebDisplayMode int displayMode, int orientation, long themeColor, long backgroundColor, - String splashScreenUrl, boolean isIconGenerated) { + String splashScreenUrl, boolean isIconGenerated, boolean isIconAdaptive) { // Create an intent as a launcher icon for a full-screen Activity. Intent shortcutIntent = new Intent(); shortcutIntent.setPackage(ContextUtils.getApplicationContext().getPackageName()) @@ -377,7 +380,8 @@ .putExtra(EXTRA_THEME_COLOR, themeColor) .putExtra(EXTRA_BACKGROUND_COLOR, backgroundColor) .putExtra(EXTRA_SPLASH_SCREEN_URL, splashScreenUrl) - .putExtra(EXTRA_IS_ICON_GENERATED, isIconGenerated); + .putExtra(EXTRA_IS_ICON_GENERATED, isIconGenerated) + .putExtra(EXTRA_IS_ICON_ADAPTIVE, isIconAdaptive); return shortcutIntent; } @@ -390,7 +394,7 @@ */ public static Intent createWebappShortcutIntentForTesting(String id, String url) { return createWebappShortcutIntent(id, null, url, getScopeFromUrl(url), null, null, null, - WEBAPP_SHORTCUT_VERSION, WebDisplayMode.STANDALONE, 0, 0, 0, null, false); + WEBAPP_SHORTCUT_VERSION, WebDisplayMode.STANDALONE, 0, 0, 0, null, false, false); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/mojo/ChromeInterfaceRegistrar.java b/chrome/android/java/src/org/chromium/chrome/browser/mojo/ChromeInterfaceRegistrar.java index 58a8b50..d7a8d70 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/mojo/ChromeInterfaceRegistrar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/mojo/ChromeInterfaceRegistrar.java
@@ -18,8 +18,6 @@ import org.chromium.services.service_manager.InterfaceRegistry; import org.chromium.webshare.mojom.ShareService; -@SuppressWarnings("MultipleTopLevelClassesInFile") - /** Registers mojo interface implementations exposed to C++ code at the Chrome layer. */ class ChromeInterfaceRegistrar { @CalledByNative
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java index 3acaa60..e8044731 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java
@@ -43,11 +43,9 @@ import org.chromium.chrome.browser.omnibox.UrlBar.ScrollType; import org.chromium.chrome.browser.omnibox.UrlBarCoordinator.SelectionState; import org.chromium.chrome.browser.omnibox.geo.GeolocationHeader; -import org.chromium.chrome.browser.omnibox.status.StatusView; import org.chromium.chrome.browser.omnibox.status.StatusViewCoordinator; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteCoordinator; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteCoordinator.AutocompleteDelegate; -import org.chromium.chrome.browser.omnibox.suggestions.OmniboxSuggestion; import org.chromium.chrome.browser.omnibox.suggestions.OmniboxSuggestionsList; import org.chromium.chrome.browser.preferences.privacy.PrivacyPreferencesManager; import org.chromium.chrome.browser.profiles.Profile; @@ -571,28 +569,12 @@ return mToolbarDataProvider; } - private static @StatusView.NavigationButtonType int suggestionTypeToNavigationButtonType( - OmniboxSuggestion suggestion) { - if (suggestion.isUrlSuggestion()) { - return StatusView.NavigationButtonType.PAGE; - } else { - return StatusView.NavigationButtonType.MAGNIFIER; - } - } - - // Updates the navigation button based on the URL string - private void updateNavigationButton() { - @StatusView.NavigationButtonType - int type = StatusView.NavigationButtonType.EMPTY; - if (mIsTablet && mAutocompleteCoordinator.getSuggestionCount() > 0) { - // If there are suggestions showing, show the icon for the default suggestion. - type = suggestionTypeToNavigationButtonType( - mAutocompleteCoordinator.getSuggestionAt(0)); - } else if (mIsTablet) { - type = StatusView.NavigationButtonType.PAGE; - } - - mStatusViewCoordinator.setNavigationButtonType(type); + /** + * Updates the navigation button based on the URL string. + */ + protected void updateNavigationButton() { + mStatusViewCoordinator.setNavigationButtonType( + StatusViewCoordinator.NavigationButtonType.EMPTY); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java index 69576a2..9536f728 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java
@@ -19,6 +19,8 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.download.DownloadUtils; import org.chromium.chrome.browser.ntp.NewTabPage; +import org.chromium.chrome.browser.omnibox.status.StatusViewCoordinator; +import org.chromium.chrome.browser.omnibox.suggestions.OmniboxSuggestion; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.toolbar.top.ToolbarTablet; import org.chromium.chrome.browser.widget.animation.CancelAwareAnimatorListener; @@ -111,7 +113,7 @@ protected void onFinishInflate() { super.onFinishInflate(); - mLocationBarIcon = findViewById(R.id.location_bar_icon); + mLocationBarIcon = findViewById(R.id.location_bar_status_icon); mBookmarkButton = findViewById(R.id.bookmark_button); mSaveOfflineButton = findViewById(R.id.save_offline_button); @@ -261,6 +263,29 @@ } @Override + protected void updateNavigationButton() { + @StatusViewCoordinator.NavigationButtonType + int type = StatusViewCoordinator.NavigationButtonType.PAGE; + + if (mAutocompleteCoordinator.getSuggestionCount() > 0) { + // If there are suggestions showing, show the icon for the default suggestion. + type = suggestionTypeToNavigationButtonType( + mAutocompleteCoordinator.getSuggestionAt(0)); + } + + mStatusViewCoordinator.setNavigationButtonType(type); + } + + private static @StatusViewCoordinator.NavigationButtonType + int suggestionTypeToNavigationButtonType(OmniboxSuggestion suggestion) { + if (suggestion.isUrlSuggestion()) { + return StatusViewCoordinator.NavigationButtonType.PAGE; + } else { + return StatusViewCoordinator.NavigationButtonType.MAGNIFIER; + } + } + + @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = getMeasuredWidth();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediator.java index f307d35b..978e64e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediator.java
@@ -11,8 +11,6 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.modelutil.PropertyModel; -import org.chromium.chrome.browser.omnibox.status.StatusView.NavigationButtonType; -import org.chromium.chrome.browser.omnibox.status.StatusView.StatusButtonType; /** * Contains the controller logic of the Status component. @@ -32,6 +30,12 @@ private int mVerboseStatusTextMinWidth; private @DrawableRes int mSecurityIconRes; + private @DrawableRes int mSecurityIconTintRes; + private @StringRes int mSecurityIconDescriptionRes; + private @DrawableRes int mNavigationIconRes; + private @DrawableRes int mNavigationIconTintRes; + + private boolean mTestingIsSecurityButtonShown; StatusMediator(PropertyModel model) { mModel = model; @@ -47,23 +51,8 @@ /** * Specify navigation button image type. */ - void setNavigationButtonType(@NavigationButtonType int buttonType) { - @DrawableRes - int imageRes = 0; - - switch (buttonType) { - case NavigationButtonType.PAGE: - imageRes = R.drawable.ic_omnibox_page; - break; - case NavigationButtonType.MAGNIFIER: - imageRes = R.drawable.omnibox_search; - break; - case NavigationButtonType.EMPTY: - break; - default: - assert false : "Invalid navigation button type"; - } - mModel.set(StatusProperties.NAVIGATION_ICON_RES, imageRes); + void setNavigationButtonType(@DrawableRes int imageRes) { + mNavigationIconRes = imageRes; updateLocationBarIcon(); } @@ -93,7 +82,6 @@ * Specify icon displayed by the security chip. */ void setSecurityIconResource(@DrawableRes int securityIcon) { - if (mSecurityIconRes == securityIcon) return; mSecurityIconRes = securityIcon; updateLocationBarIcon(); } @@ -102,14 +90,16 @@ * Specify tint of icon displayed by the security chip. */ void setSecurityIconTint(@ColorRes int tintList) { - mModel.set(StatusProperties.SECURITY_ICON_TINT_RES, tintList); + mSecurityIconTintRes = tintList; + updateLocationBarIcon(); } /** * Specify tint of icon displayed by the security chip. */ void setSecurityIconDescription(@StringRes int desc) { - mModel.set(StatusProperties.SECURITY_ICON_DESCRIPTION_RES, desc); + mSecurityIconDescriptionRes = desc; + updateLocationBarIcon(); } /** @@ -249,10 +239,18 @@ @ColorRes int tintColor = mDarkTheme ? R.color.dark_mode_tint : R.color.light_mode_tint; - mModel.set(StatusProperties.NAVIGATION_ICON_TINT_RES, tintColor); mModel.set(StatusProperties.SEPARATOR_COLOR_RES, separatorColor); - + mNavigationIconTintRes = tintColor; if (textColor != 0) mModel.set(StatusProperties.VERBOSE_STATUS_TEXT_COLOR_RES, textColor); + + updateLocationBarIcon(); + } + + /** + * Reports whether security icon is shown. + */ + boolean testIsSecurityButtonShown() { + return mTestingIsSecurityButtonShown; } /** @@ -268,16 +266,26 @@ */ private void updateLocationBarIcon() { if (mUrlHasFocus && mTabletMode) { - mModel.set(StatusProperties.STATUS_BUTTON_TYPE, StatusButtonType.NAVIGATION_ICON); + mModel.set(StatusProperties.STATUS_ICON_RES, mNavigationIconRes); + mModel.set(StatusProperties.STATUS_ICON_TINT_RES, mNavigationIconTintRes); + mModel.set(StatusProperties.STATUS_ICON_DESCRIPTION_RES, + R.string.accessibility_toolbar_btn_site_info); + mModel.set(StatusProperties.STATUS_ICON_ACCESSIBILITY_TOAST_RES, 0); + mTestingIsSecurityButtonShown = false; return; } if (!mUrlHasFocus && mSecurityIconRes != 0) { - mModel.set(StatusProperties.SECURITY_ICON_RES, mSecurityIconRes); - mModel.set(StatusProperties.STATUS_BUTTON_TYPE, StatusButtonType.SECURITY_ICON); + mModel.set(StatusProperties.STATUS_ICON_RES, mSecurityIconRes); + mModel.set(StatusProperties.STATUS_ICON_TINT_RES, mSecurityIconTintRes); + mModel.set(StatusProperties.STATUS_ICON_DESCRIPTION_RES, mSecurityIconDescriptionRes); + mModel.set( + StatusProperties.STATUS_ICON_ACCESSIBILITY_TOAST_RES, R.string.menu_page_info); + mTestingIsSecurityButtonShown = true; return; } - mModel.set(StatusProperties.STATUS_BUTTON_TYPE, StatusButtonType.NONE); + mTestingIsSecurityButtonShown = false; + mModel.set(StatusProperties.STATUS_ICON_RES, 0); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusProperties.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusProperties.java index 7ef2a67..e86d7a18 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusProperties.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusProperties.java
@@ -16,58 +16,47 @@ */ class StatusProperties { /** Enables / disables animations. */ - public static final WritableBooleanPropertyKey ANIMATIONS_ENABLED = - new WritableBooleanPropertyKey(); + static final WritableBooleanPropertyKey ANIMATIONS_ENABLED = new WritableBooleanPropertyKey(); /** Specifies navigation icon resource type .*/ - public static final WritableIntPropertyKey NAVIGATION_ICON_RES = new WritableIntPropertyKey(); + static final WritableIntPropertyKey STATUS_ICON_RES = new WritableIntPropertyKey(); /** Specifies color tint for navigation icon. */ - public static final WritableIntPropertyKey NAVIGATION_ICON_TINT_RES = + static final WritableIntPropertyKey STATUS_ICON_TINT_RES = new WritableIntPropertyKey(); + + /** Specifies accessibility string presented to user upon long click on security icon. */ + public static final WritableIntPropertyKey STATUS_ICON_ACCESSIBILITY_TOAST_RES = new WritableIntPropertyKey(); /** Specifies string resource holding content description for security icon. */ - public static final WritableIntPropertyKey SECURITY_ICON_DESCRIPTION_RES = - new WritableIntPropertyKey(); - - /** Specifies resource displayed by security chip. */ - public static final WritableIntPropertyKey SECURITY_ICON_RES = new WritableIntPropertyKey(); - - /** Specifies color tint list for icon displayed by security chip. */ - public static final WritableIntPropertyKey SECURITY_ICON_TINT_RES = - new WritableIntPropertyKey(); + static final WritableIntPropertyKey STATUS_ICON_DESCRIPTION_RES = new WritableIntPropertyKey(); /** Specifies status separator color. */ - public static final WritableIntPropertyKey SEPARATOR_COLOR_RES = new WritableIntPropertyKey(); - - /** Specifies current selection of the location bar button type. */ - public static final WritableIntPropertyKey STATUS_BUTTON_TYPE = new WritableIntPropertyKey(); + static final WritableIntPropertyKey SEPARATOR_COLOR_RES = new WritableIntPropertyKey(); /** Specifies object to receive status click events. */ - public static final WritableObjectPropertyKey<View.OnClickListener> STATUS_CLICK_LISTENER = + static final WritableObjectPropertyKey<View.OnClickListener> STATUS_CLICK_LISTENER = new WritableObjectPropertyKey<>(); - /** Specifies verbose status text color. */ - public static final WritableIntPropertyKey VERBOSE_STATUS_TEXT_COLOR_RES = + static final WritableIntPropertyKey VERBOSE_STATUS_TEXT_COLOR_RES = new WritableIntPropertyKey(); /** Specifies content of the verbose status text field. */ - public static final WritableIntPropertyKey VERBOSE_STATUS_TEXT_STRING_RES = + static final WritableIntPropertyKey VERBOSE_STATUS_TEXT_STRING_RES = new WritableIntPropertyKey(); /** Specifies whether verbose status text view is visible. */ - public static final WritableBooleanPropertyKey VERBOSE_STATUS_TEXT_VISIBLE = + static final WritableBooleanPropertyKey VERBOSE_STATUS_TEXT_VISIBLE = new WritableBooleanPropertyKey(); /** Specifies width of the verbose status text view. */ - public static final WritableIntPropertyKey VERBOSE_STATUS_TEXT_WIDTH = - new WritableIntPropertyKey(); + static final WritableIntPropertyKey VERBOSE_STATUS_TEXT_WIDTH = new WritableIntPropertyKey(); public static final PropertyKey[] ALL_KEYS = new PropertyKey[] {ANIMATIONS_ENABLED, - NAVIGATION_ICON_RES, NAVIGATION_ICON_TINT_RES, SECURITY_ICON_RES, - SECURITY_ICON_DESCRIPTION_RES, SECURITY_ICON_TINT_RES, SEPARATOR_COLOR_RES, - STATUS_BUTTON_TYPE, STATUS_CLICK_LISTENER, VERBOSE_STATUS_TEXT_COLOR_RES, - VERBOSE_STATUS_TEXT_STRING_RES, VERBOSE_STATUS_TEXT_VISIBLE, VERBOSE_STATUS_TEXT_WIDTH}; + STATUS_ICON_ACCESSIBILITY_TOAST_RES, STATUS_ICON_RES, STATUS_ICON_TINT_RES, + STATUS_ICON_DESCRIPTION_RES, SEPARATOR_COLOR_RES, STATUS_CLICK_LISTENER, + VERBOSE_STATUS_TEXT_COLOR_RES, VERBOSE_STATUS_TEXT_STRING_RES, + VERBOSE_STATUS_TEXT_VISIBLE, VERBOSE_STATUS_TEXT_WIDTH}; private StatusProperties() {} }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusView.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusView.java index 93e1b36..f4c15b6e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusView.java
@@ -6,20 +6,16 @@ import static org.chromium.chrome.browser.toolbar.top.ToolbarPhone.URL_FOCUS_CHANGE_ANIMATION_DURATION_MS; -import android.animation.Animator; -import android.animation.AnimatorListenerAdapter; -import android.animation.AnimatorSet; -import android.animation.ObjectAnimator; import android.content.Context; -import android.content.res.ColorStateList; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.TransitionDrawable; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; -import android.support.annotation.IntDef; import android.support.annotation.StringRes; -import android.support.v7.content.res.AppCompatResources; import android.util.AttributeSet; import android.view.View; -import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; @@ -27,43 +23,13 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.util.AccessibilityUtil; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; +import org.chromium.chrome.browser.widget.TintedDrawable; /** * StatusView is a location bar's view displaying status (icons and/or text). */ public class StatusView extends LinearLayout { - /** - * Specifies the types of buttons shown to signify different types of navigation elements. - */ - @IntDef({NavigationButtonType.PAGE, NavigationButtonType.MAGNIFIER, NavigationButtonType.EMPTY}) - @Retention(RetentionPolicy.SOURCE) - public @interface NavigationButtonType { - int PAGE = 0; - int MAGNIFIER = 1; - int EMPTY = 2; - } - - /** - * Specifies which button should be shown in location bar, if any. - */ - @IntDef({StatusButtonType.NONE, StatusButtonType.SECURITY_ICON, - StatusButtonType.NAVIGATION_ICON}) - @Retention(RetentionPolicy.SOURCE) - public @interface StatusButtonType { - /** No button should be shown. */ - int NONE = 0; - /** Security button should be shown (includes offline icon). */ - int SECURITY_ICON = 1; - /** Navigation button should be shown. */ - int NAVIGATION_ICON = 2; - } - - private View mLocationBarIcon; - private ImageView mNavigationButton; - private ImageButton mSecurityButton; + private ImageView mIconView; private TextView mVerboseStatusTextView; private View mSeparatorView; private View mStatusExtraSpace; @@ -71,83 +37,9 @@ private boolean mAnimationsEnabled; - private StatusViewAnimator mLocationBarIconActiveAnimator; - private StatusViewAnimator mLocationBarSecurityButtonShowAnimator; - private StatusViewAnimator mLocationBarNavigationIconShowAnimator; - private StatusViewAnimator mLocationBarClearAnimator; - - private @StringRes int mSecurityIconAccessibilityDescription; - - /** - * Class animating transition between FrameLayout children. - * Can take any number of child components; ensures that the - * - component supplied as first (the 'target' component) will be visible and - * - every other supplied component will be made invisible at the end of animation. - */ - private final class StatusViewAnimator { - private final AnimatorSet mAnimator; - // Target view that will be displayed at the end of animation. - private final View[] mTargetViews; - // Set of source views that should be made invisible at the end. - private final View[] mSourceViews; - - /** - * Adapter updating start and end states of animated elements. - * Ensures that target elements are made visible and source elements - * are no longer presented at the end of animation. - */ - private final class StatusViewAnimatorAdapter extends AnimatorListenerAdapter { - @Override - public void onAnimationEnd(Animator animation) { - for (View source : mSourceViews) { - source.setVisibility(View.INVISIBLE); - } - } - - @Override - public void onAnimationStart(Animator animation) { - for (View target : mTargetViews) { - target.setVisibility(View.VISIBLE); - } - } - } - - public StatusViewAnimator(View[] targets, View[] sources) { - mAnimator = new AnimatorSet(); - mTargetViews = targets; - mSourceViews = sources; - - AnimatorSet.Builder b = null; - - // Phase in these objects - for (View view : targets) { - if (b == null) { - b = mAnimator.play(ObjectAnimator.ofFloat(view, View.ALPHA, 1)); - } else { - b.with(ObjectAnimator.ofFloat(view, View.ALPHA, 1)); - } - } - - // Phase out these objects - for (View view : sources) { - if (b == null) { - b = mAnimator.play(ObjectAnimator.ofFloat(view, View.ALPHA, 0)); - } else { - b.with(ObjectAnimator.ofFloat(view, View.ALPHA, 0)); - } - } - mAnimator.addListener(new StatusViewAnimatorAdapter()); - } - - public void cancel() { - if (mAnimator.isRunning()) mAnimator.cancel(); - } - - public void animate(long duration) { - mAnimator.setDuration(duration); - mAnimator.start(); - } - } + private @DrawableRes int mIconRes; + private @ColorRes int mIconTintRes; + private @StringRes int mAccessibilityToast; public StatusView(Context context, AttributeSet attributes) { super(context, attributes); @@ -157,58 +49,69 @@ protected void onFinishInflate() { super.onFinishInflate(); - mNavigationButton = findViewById(R.id.navigation_button); - mSecurityButton = findViewById(R.id.security_button); + mIconView = findViewById(R.id.location_bar_status_icon); mVerboseStatusTextView = findViewById(R.id.location_bar_verbose_status); mSeparatorView = findViewById(R.id.location_bar_verbose_status_separator); mStatusExtraSpace = findViewById(R.id.location_bar_verbose_status_extra_space); - mLocationBarIcon = findViewById(R.id.location_bar_icon); - assert mNavigationButton != null : "Missing navigation type view."; - configureLocationBarIconAnimations(); configureAccessibilityDescriptions(); } /** + * Start animating transition of status icon. + */ + private void animateStatusIcon() { + Drawable sourceIcon = mIconView.getDrawable(); + + if (sourceIcon == null) { + sourceIcon = new ColorDrawable(Color.TRANSPARENT); + } + + Drawable targetIcon = null; + if (mIconRes != 0 && mIconTintRes != 0) { + targetIcon = + TintedDrawable.constructTintedDrawable(getContext(), mIconRes, mIconTintRes); + } else if (mIconRes != 0) { + targetIcon = ApiCompatibilityUtils.getDrawable(getContext().getResources(), mIconRes); + } else { + targetIcon = new ColorDrawable(Color.TRANSPARENT); + } + + TransitionDrawable newImage = + new TransitionDrawable(new Drawable[] {sourceIcon, targetIcon}); + + mIconView.setImageDrawable(newImage); + + // Note: crossfade controls blending, not animation. + newImage.setCrossFadeEnabled(true); + // TODO(ender): Consider simply leaving animations on. It looks so nice! + newImage.startTransition(mAnimationsEnabled ? URL_FOCUS_CHANGE_ANIMATION_DURATION_MS : 0); + } + + /** * Specify object to receive click events. * * @param listener Instance of View.OnClickListener or null. */ - public void setStatusClickListener(View.OnClickListener listener) { - mNavigationButton.setOnClickListener(listener); - mSecurityButton.setOnClickListener(listener); + void setStatusClickListener(View.OnClickListener listener) { + mIconView.setOnClickListener(listener); mVerboseStatusTextView.setOnClickListener(listener); } /** - * Configure animations used to cross-fade status icon. - */ - void configureLocationBarIconAnimations() { - // Animation presenting Security button and hiding all others. - mLocationBarSecurityButtonShowAnimator = new StatusViewAnimator( - new View[] {mSecurityButton}, new View[] {mNavigationButton}); - - // Animation presenting Navigation button and hiding all others. - mLocationBarNavigationIconShowAnimator = new StatusViewAnimator( - new View[] {mNavigationButton}, new View[] {mSecurityButton}); - - // Animation clearing up all location bar icons. - mLocationBarClearAnimator = new StatusViewAnimator( - new View[] {}, new View[] {mNavigationButton, mSecurityButton}); - } - - /** * Configure accessibility toasts. */ void configureAccessibilityDescriptions() { - mSecurityButton.setOnLongClickListener(new View.OnLongClickListener() { + View.OnLongClickListener listener = new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { + if (mAccessibilityToast == 0) return false; Context context = getContext(); return AccessibilityUtil.showAccessibilityToast( - context, view, context.getResources().getString(R.string.menu_page_info)); + context, view, context.getResources().getString(mAccessibilityToast)); } - }); + }; + mIconView.setOnLongClickListener(listener); } /** @@ -219,94 +122,42 @@ } /** - * Specify status bar button type. - */ - void setStatusButtonType(@StatusButtonType int type) { - // Terminate any animation currently taking place. - // We won't be terminating animation that is currently presenting the - // same object - property mechanism will prevent this. - if (mLocationBarIconActiveAnimator != null) { - mLocationBarIconActiveAnimator.cancel(); - } - - switch (type) { - case StatusButtonType.SECURITY_ICON: - mLocationBarIconActiveAnimator = mLocationBarSecurityButtonShowAnimator; - mLocationBarIcon.setVisibility(View.VISIBLE); - break; - case StatusButtonType.NAVIGATION_ICON: - mLocationBarIconActiveAnimator = mLocationBarNavigationIconShowAnimator; - mLocationBarIcon.setVisibility(View.VISIBLE); - break; - case StatusButtonType.NONE: - default: - mLocationBarIconActiveAnimator = mLocationBarClearAnimator; - // TODO(ender): This call should only be invoked once animation completes. Fix - // animation system and hide the view once icons are invisible. - mLocationBarIcon.setVisibility(View.GONE); - return; - } - - mLocationBarIconActiveAnimator.animate( - mAnimationsEnabled ? URL_FOCUS_CHANGE_ANIMATION_DURATION_MS : 0); - } - - /** * Specify navigation button image. */ - void setNavigationIcon(@DrawableRes int imageRes) { - if (imageRes != 0) { - mNavigationButton.setImageResource(imageRes); - } else { - mNavigationButton.setImageDrawable(null); - } + void setStatusIcon(@DrawableRes int imageRes) { + mIconRes = imageRes; + animateStatusIcon(); } /** * Specify navigation icon tint color. */ - void setNavigationIconTint(@ColorRes int colorRes) { - ColorStateList list = null; - if (colorRes != 0) { - list = AppCompatResources.getColorStateList(getContext(), colorRes); - } - ApiCompatibilityUtils.setImageTintList(mNavigationButton, list); + void setStatusIconTint(@ColorRes int colorRes) { + // TODO(ender): combine icon and tint into a single class describing icon properties to + // avoid multi-step crossfade animation configuration. + // This is technically still invisible, since animations only begin after all operations in + // UI thread (including status icon configuration) are complete, but can be avoided + // entirely, making the code also more intuitive. + mIconTintRes = colorRes; + animateStatusIcon(); } /** - * Specify security icon image. + * Specify accessibility string presented to user upon long click. */ - void setSecurityIcon(@DrawableRes int imageRes) { - if (imageRes != 0) { - mSecurityButton.setImageResource(imageRes); - } else { - mSecurityButton.setImageDrawable(null); - } - } - - /** - * Specify security icon tint color. - */ - void setSecurityIconTint(@ColorRes int colorRes) { - // Note: There's no need to apply this each time icon changes: - // Subsequent calls to setImageDrawable will automatically - // mutate the drawable and apply the specified tint and tint mode. - ColorStateList list = null; - if (colorRes != 0) { - list = AppCompatResources.getColorStateList(getContext(), colorRes); - } - ApiCompatibilityUtils.setImageTintList(mSecurityButton, list); + void setStatusIconAccessibilityToast(@StringRes int description) { + mAccessibilityToast = description; } /** * Specify content description for security icon. */ - void setSecurityIconDescription(@StringRes int descriptionRes) { + void setStatusIconDescription(@StringRes int descriptionRes) { String description = null; if (descriptionRes != 0) { description = getResources().getString(descriptionRes); } - mSecurityButton.setContentDescription(description); + mIconView.setContentDescription(description); } /** @@ -349,17 +200,10 @@ mVerboseStatusTextView.setMaxWidth(width); } - // TODO(ender): replace these with methods manipulating views directly. - // Do not depend on these when creating new code! - View getNavigationButton() { - return mNavigationButton; - } - + // TODO(ender): The final last purpose of this method is to allow + // ToolbarButtonInProductHelpController set up help bubbles. This dependency is about to + // change. Do not depend on this method when creating new code. View getSecurityButton() { - return mSecurityButton; - } - - TextView getVerboseStatusTextView() { - return mVerboseStatusTextView; + return mIconView; } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusViewBinder.java index 823fe49..df7a8db00 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusViewBinder.java
@@ -12,25 +12,21 @@ * StatusViewBinder observes StatusModel changes and triggers StatusView updates. */ class StatusViewBinder implements ViewBinder<PropertyModel, StatusView, PropertyKey> { - public StatusViewBinder() {} + StatusViewBinder() {} @Override public void bind(PropertyModel model, StatusView view, PropertyKey propertyKey) { if (StatusProperties.ANIMATIONS_ENABLED.equals(propertyKey)) { view.setAnimationsEnabled(model.get(StatusProperties.ANIMATIONS_ENABLED)); - } else if (StatusProperties.STATUS_BUTTON_TYPE.equals(propertyKey)) { - view.setStatusButtonType(model.get(StatusProperties.STATUS_BUTTON_TYPE)); - } else if (StatusProperties.NAVIGATION_ICON_RES.equals(propertyKey)) { - view.setNavigationIcon(model.get(StatusProperties.NAVIGATION_ICON_RES)); - } else if (StatusProperties.NAVIGATION_ICON_TINT_RES.equals(propertyKey)) { - view.setNavigationIconTint(model.get(StatusProperties.NAVIGATION_ICON_TINT_RES)); - } else if (StatusProperties.SECURITY_ICON_RES.equals(propertyKey)) { - view.setSecurityIcon(model.get(StatusProperties.SECURITY_ICON_RES)); - } else if (StatusProperties.SECURITY_ICON_TINT_RES.equals(propertyKey)) { - view.setSecurityIconTint(model.get(StatusProperties.SECURITY_ICON_TINT_RES)); - } else if (StatusProperties.SECURITY_ICON_DESCRIPTION_RES.equals(propertyKey)) { - view.setSecurityIconDescription( - model.get(StatusProperties.SECURITY_ICON_DESCRIPTION_RES)); + } else if (StatusProperties.STATUS_ICON_RES.equals(propertyKey)) { + view.setStatusIcon(model.get(StatusProperties.STATUS_ICON_RES)); + } else if (StatusProperties.STATUS_ICON_ACCESSIBILITY_TOAST_RES.equals(propertyKey)) { + view.setStatusIconAccessibilityToast( + model.get(StatusProperties.STATUS_ICON_ACCESSIBILITY_TOAST_RES)); + } else if (StatusProperties.STATUS_ICON_TINT_RES.equals(propertyKey)) { + view.setStatusIconTint(model.get(StatusProperties.STATUS_ICON_TINT_RES)); + } else if (StatusProperties.STATUS_ICON_DESCRIPTION_RES.equals(propertyKey)) { + view.setStatusIconDescription(model.get(StatusProperties.STATUS_ICON_DESCRIPTION_RES)); } else if (StatusProperties.SEPARATOR_COLOR_RES.equals(propertyKey)) { view.setSeparatorColor(model.get(StatusProperties.SEPARATOR_COLOR_RES)); } else if (StatusProperties.STATUS_CLICK_LISTENER.equals(propertyKey)) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusViewCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusViewCoordinator.java index f811ad4..8e4c04b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusViewCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusViewCoordinator.java
@@ -8,22 +8,35 @@ import android.content.Context; import android.content.res.Resources; import android.support.annotation.DrawableRes; +import android.support.annotation.IntDef; import android.view.View; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; import org.chromium.chrome.browser.modelutil.PropertyModel; import org.chromium.chrome.browser.modelutil.PropertyModelChangeProcessor; -import org.chromium.chrome.browser.omnibox.status.StatusView.NavigationButtonType; -import org.chromium.chrome.browser.omnibox.status.StatusView.StatusButtonType; import org.chromium.chrome.browser.page_info.PageInfoController; import org.chromium.chrome.browser.toolbar.ToolbarDataProvider; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + /** * A component for displaying a status icon (e.g. security icon or navigation icon) and optional * verbose status text. */ public class StatusViewCoordinator implements View.OnClickListener { + /** + * Specifies the types of buttons shown to signify different types of navigation elements. + */ + @IntDef({NavigationButtonType.PAGE, NavigationButtonType.MAGNIFIER, NavigationButtonType.EMPTY}) + @Retention(RetentionPolicy.SOURCE) + public @interface NavigationButtonType { + int PAGE = 0; + int MAGNIFIER = 1; + int EMPTY = 2; + } + private final StatusView mStatusView; private final StatusMediator mMediator; private final PropertyModel mModel; @@ -42,9 +55,8 @@ mStatusView = statusView; mModel = new PropertyModel.Builder(StatusProperties.ALL_KEYS) - .with(StatusProperties.NAVIGATION_ICON_TINT_RES, + .with(StatusProperties.STATUS_ICON_TINT_RES, R.color.locationbar_status_separator_color) - .with(StatusProperties.STATUS_BUTTON_TYPE, StatusButtonType.NONE) .build(); PropertyModelChangeProcessor.create(mModel, mStatusView, new StatusViewBinder()); @@ -126,7 +138,7 @@ */ @VisibleForTesting public boolean isSecurityButtonShown() { - return mModel.get(StatusProperties.STATUS_BUTTON_TYPE) == StatusButtonType.SECURITY_ICON; + return mMediator.testIsSecurityButtonShown(); } /** @@ -135,7 +147,7 @@ @VisibleForTesting @DrawableRes public int getSecurityIconResourceId() { - return mModel.get(StatusProperties.SECURITY_ICON_RES); + return mModel.get(StatusProperties.STATUS_ICON_RES); } /** @@ -143,7 +155,21 @@ * @param buttonType The type of navigation button to be shown. */ public void setNavigationButtonType(@NavigationButtonType int buttonType) { - mMediator.setNavigationButtonType(buttonType); + @DrawableRes + int imageRes = 0; + switch (buttonType) { + case NavigationButtonType.PAGE: + imageRes = R.drawable.ic_omnibox_page; + break; + case NavigationButtonType.MAGNIFIER: + imageRes = R.drawable.omnibox_search; + break; + case NavigationButtonType.EMPTY: + break; + default: + assert false : "Invalid navigation button type"; + } + mMediator.setNavigationButtonType(imageRes); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkInfo.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkInfo.java index 5ddc4cd1..47b6d632 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkInfo.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkInfo.java
@@ -357,7 +357,7 @@ boolean forceNavigation, boolean useTransparentSplash, ShareData shareData) { super(id, url, scope, primaryIcon, name, shortName, displayMode, orientation, source, themeColor, backgroundColor, null /* splash_screen_url */, - false /* isIconGenerated */, forceNavigation); + false /* isIconGenerated */, false /* isIconAdaptive */, forceNavigation); mBadgeIcon = badgeIcon; mSplashIcon = splashIcon; mApkPackageName = webApkPackageName;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDataStorage.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDataStorage.java index 6704ec23..ee27e33 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDataStorage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDataStorage.java
@@ -50,6 +50,7 @@ static final String KEY_SOURCE = "source"; static final String KEY_ACTION = "action"; static final String KEY_IS_ICON_GENERATED = "is_icon_generated"; + static final String KEY_IS_ICON_ADAPTIVE = "is_icon_adaptive"; static final String KEY_VERSION = "version"; static final String KEY_WEBAPK_PACKAGE_NAME = "webapk_package_name"; @@ -210,7 +211,8 @@ mPreferences.getString(KEY_ACTION, null), mPreferences.getString(KEY_URL, null), mPreferences.getString(KEY_SCOPE, null), mPreferences.getString(KEY_NAME, null), mPreferences.getString(KEY_SHORT_NAME, null), - mPreferences.getString(KEY_ICON, null), version, + mPreferences.getString(KEY_ICON, null), + version, mPreferences.getInt(KEY_DISPLAY_MODE, WebDisplayMode.STANDALONE), mPreferences.getInt(KEY_ORIENTATION, ScreenOrientationValues.DEFAULT), mPreferences.getLong( @@ -218,7 +220,8 @@ mPreferences.getLong( KEY_BACKGROUND_COLOR, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING), mPreferences.getString(KEY_SPLASH_SCREEN_URL, ""), - mPreferences.getBoolean(KEY_IS_ICON_GENERATED, false)); + mPreferences.getBoolean(KEY_IS_ICON_GENERATED, false), + mPreferences.getBoolean(KEY_IS_ICON_ADAPTIVE, false)); } /** @@ -282,6 +285,8 @@ ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING)); editor.putBoolean(KEY_IS_ICON_GENERATED, IntentUtils.safeGetBooleanExtra( shortcutIntent, ShortcutHelper.EXTRA_IS_ICON_GENERATED, false)); + editor.putBoolean(KEY_IS_ICON_ADAPTIVE, IntentUtils.safeGetBooleanExtra( + shortcutIntent, ShortcutHelper.EXTRA_IS_ICON_ADAPTIVE, false)); editor.putString(KEY_ACTION, shortcutIntent.getAction()); String webApkPackageName = IntentUtils.safeGetStringExtra(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappInfo.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappInfo.java index d150b17..f8ad842 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappInfo.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappInfo.java
@@ -73,6 +73,7 @@ private long mBackgroundColor; private Uri mSplashScreenUri; private boolean mIsIconGenerated; + private boolean mIsIconAdaptive; private boolean mForceNavigation; public static WebappInfo createEmpty() { @@ -163,6 +164,8 @@ IntentUtils.safeGetStringExtra(intent, ShortcutHelper.EXTRA_SPLASH_SCREEN_URL); boolean isIconGenerated = IntentUtils.safeGetBooleanExtra(intent, ShortcutHelper.EXTRA_IS_ICON_GENERATED, false); + boolean isIconAdaptive = IntentUtils.safeGetBooleanExtra(intent, + ShortcutHelper.EXTRA_IS_ICON_ADAPTIVE, false); boolean forceNavigation = IntentUtils.safeGetBooleanExtra( intent, ShortcutHelper.EXTRA_FORCE_NAVIGATION, false); @@ -171,7 +174,7 @@ return create(id, url, scope, new Icon(icon), name, shortName, displayMode, orientation, source, themeColor, backgroundColor, splashScreenUrl, isIconGenerated, - forceNavigation); + isIconAdaptive, forceNavigation); } /** @@ -189,13 +192,14 @@ * @param backgroundColor The background color of the webapp. * @param splashScreenUrl URL of the HTML splash screen. * @param isIconGenerated Whether the |icon| was generated by Chromium. + * @param isIconAdaptive Whether the Icon is an Android Adaptive Icon. * @param forceNavigation Whether the webapp should navigate to {@link url} if the * webapp is already open. */ public static WebappInfo create(String id, String url, String scope, Icon icon, String name, String shortName, @WebDisplayMode int displayMode, int orientation, int source, long themeColor, long backgroundColor, String splashScreenUrl, boolean isIconGenerated, - boolean forceNavigation) { + boolean isIconAdaptive, boolean forceNavigation) { if (id == null || url == null) { Log.e(TAG, "Incomplete data provided: " + id + ", " + url); return null; @@ -203,13 +207,13 @@ return new WebappInfo(id, url, scope, icon, name, shortName, displayMode, orientation, source, themeColor, backgroundColor, splashScreenUrl, isIconGenerated, - forceNavigation); + isIconAdaptive, forceNavigation); } protected WebappInfo(String id, String url, String scope, Icon icon, String name, String shortName, @WebDisplayMode int displayMode, int orientation, int source, long themeColor, long backgroundColor, String splashScreenUrl, boolean isIconGenerated, - boolean forceNavigation) { + boolean isIconAdaptive, boolean forceNavigation) { Uri uri = Uri.parse(url); if (TextUtils.isEmpty(scope)) { scope = ShortcutHelper.getScopeFromUrl(url); @@ -229,6 +233,7 @@ mBackgroundColor = backgroundColor; mSplashScreenUri = Uri.parse(splashScreenUrl != null ? splashScreenUrl : ""); mIsIconGenerated = isIconGenerated; + mIsIconAdaptive = isIconAdaptive; mForceNavigation = forceNavigation; mIsInitialized = mUri != null; } @@ -361,6 +366,13 @@ } /** + * Returns whether the {@link #icon} should be used as an Android Adaptive Icon. + */ + public boolean isIconAdaptive() { + return mIsIconAdaptive; + } + + /** * Returns whether the icon was generated by Chromium. */ public boolean isIconGenerated() { @@ -392,6 +404,7 @@ intent.putExtra(ShortcutHelper.EXTRA_BACKGROUND_COLOR, backgroundColor()); intent.putExtra(ShortcutHelper.EXTRA_SPLASH_SCREEN_URL, splashScreenUri().toString()); intent.putExtra(ShortcutHelper.EXTRA_IS_ICON_GENERATED, isIconGenerated()); + intent.putExtra(ShortcutHelper.EXTRA_IS_ICON_ADAPTIVE, isIconAdaptive()); } public static String idFromIntent(Intent intent) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappSplashScreenController.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappSplashScreenController.java index 8072bcbd..f306ccd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappSplashScreenController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappSplashScreenController.java
@@ -234,9 +234,11 @@ Bitmap displayIcon = splashImage; boolean displayIconGenerated = false; + boolean displayIconAdaptive = false; if (displayIcon == null) { displayIcon = webappInfo.icon(); displayIconGenerated = webappInfo.isIconGenerated(); + displayIconAdaptive = webappInfo.isIconAdaptive(); } @SplashLayout.IconClassification int displayIconClassification = @@ -261,8 +263,8 @@ / resources.getDisplayMetrics().density)); } - SplashLayout.createLayout(context, mSplashScreen, displayIcon, displayIconClassification, - webappInfo.name(), + SplashLayout.createLayout(context, mSplashScreen, displayIcon, displayIconAdaptive, + displayIconClassification, webappInfo.name(), ColorUtils.shouldUseLightForegroundOnBackground(backgroundColor)); if (mNativeLoaded) mWebappUma.commitMetrics();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationHandlerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationHandlerTest.java index 921726b..19f8d9c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationHandlerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationHandlerTest.java
@@ -1499,7 +1499,7 @@ private static WebappInfo newWebappInfoFromScope(String scope) { return WebappInfo.create("", "", scope, null, null, null, WebDisplayMode.STANDALONE, 0, 0, - 0, 0, null, false, false); + 0, 0, null, false, false, false); } private static class IntentActivity {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/OmniboxTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/OmniboxTest.java index 5864b48..a67eb91 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/OmniboxTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/OmniboxTest.java
@@ -617,9 +617,6 @@ try { final String testUrl = testServer.getURL("/chrome/test/data/android/omnibox/one.html"); - ImageButton securityButton = (ImageButton) mActivityTestRule.getActivity().findViewById( - R.id.security_button); - mActivityTestRule.loadUrl(testUrl); final LocationBarLayout locationBar = (LocationBarLayout) mActivityTestRule.getActivity().findViewById( @@ -629,12 +626,10 @@ boolean securityIcon = statusViewCoordinator.isSecurityButtonShown(); if (mActivityTestRule.getActivity().isTablet()) { Assert.assertTrue("Omnibox should have a Security icon", securityIcon); - Assert.assertTrue(securityButton.isShown()); Assert.assertEquals( R.drawable.omnibox_info, statusViewCoordinator.getSecurityIconResourceId()); } else { Assert.assertFalse("Omnibox should not have a Security icon", securityIcon); - Assert.assertFalse(securityButton.isShown()); } } finally { testServer.stopAndDestroyServer(); @@ -665,7 +660,7 @@ httpsTestServer.getURL("/chrome/test/data/android/omnibox/one.html"); ImageButton securityButton = (ImageButton) mActivityTestRule.getActivity().findViewById( - R.id.security_button); + R.id.location_bar_status_icon); mActivityTestRule.loadUrl(testHttpsUrl); onSSLStateUpdatedCallbackHelper.waitForCallback(0); @@ -677,8 +672,8 @@ locationBar.getStatusViewCoordinatorForTesting(); boolean securityIcon = statusViewCoordinator.isSecurityButtonShown(); Assert.assertTrue("Omnibox should have a Security icon", securityIcon); - Assert.assertEquals("security_button with wrong resource-id", R.id.security_button, - securityButton.getId()); + Assert.assertEquals("location_bar_status_icon with wrong resource-id", + R.id.location_bar_status_icon, securityButton.getId()); Assert.assertTrue(securityButton.isShown()); Assert.assertEquals(R.drawable.omnibox_https_valid, statusViewCoordinator.getSecurityIconResourceId()); @@ -722,13 +717,13 @@ (LocationBarLayout) mActivityTestRule.getActivity().findViewById( R.id.location_bar); ImageButton securityButton = (ImageButton) mActivityTestRule.getActivity().findViewById( - R.id.security_button); + R.id.location_bar_status_icon); boolean securityIcon = locationBarLayout.getStatusViewCoordinatorForTesting().isSecurityButtonShown(); Assert.assertTrue("Omnibox should have a Security icon", securityIcon); - Assert.assertEquals("security_button with wrong resource-id", R.id.security_button, - securityButton.getId()); + Assert.assertEquals("location_bar_status_icon with wrong resource-id", + R.id.location_bar_status_icon, securityButton.getId()); if (mActivityTestRule.getActivity().isTablet()) { Assert.assertTrue(mActivityTestRule.getActivity()
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappModeTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappModeTest.java index d06fd5d6..cdd9f34 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappModeTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappModeTest.java
@@ -91,7 +91,7 @@ null, WebDisplayMode.STANDALONE, ScreenOrientationValues.PORTRAIT, ShortcutSource.UNKNOWN, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, null, false /* isIconGenerated */, - false /* forceNavigation */); + false /* isIconAdaptive */, false /* forceNavigation */); webappInfo.setWebappIntentExtras(intent); return intent;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappVisibilityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappVisibilityTest.java index b45d56c..a944fffb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappVisibilityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappVisibilityTest.java
@@ -131,7 +131,7 @@ return scopePolicy == WebappScopePolicy.Type.LEGACY ? WebappInfo.create("", webappStartUrlOrScopeUrl, null, null, null, null, displayMode, 0, 0, 0, 0, null, false /* isIconGenerated */, - false /* forceNavigation */) + false /* isIconAdaptive */, false /* forceNavigation */) : WebApkInfo.create("", "", webappStartUrlOrScopeUrl, null, null, null, null, null, displayMode, 0, 0, 0, 0, "", 0, null, "", WebApkInfo.WebApkDistributor.BROWSER, null, null,
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java index 6eef41563..31c5f76 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java
@@ -218,9 +218,11 @@ final long backgroundColor = 3; final String splashScreenUrl = "splashy"; final boolean isIconGenerated = false; + final boolean isIconAdaptive = false; Intent shortcutIntent = ShortcutHelper.createWebappShortcutIntent(id, action, url, scope, name, shortName, encodedIcon, ShortcutHelper.WEBAPP_SHORTCUT_VERSION, displayMode, - orientation, themeColor, backgroundColor, splashScreenUrl, isIconGenerated); + orientation, themeColor, backgroundColor, splashScreenUrl, isIconGenerated, + isIconAdaptive); WebappDataStorage storage = WebappDataStorage.open("test"); storage.updateFromShortcutIntent(shortcutIntent); @@ -242,6 +244,8 @@ mSharedPreferences.getString(WebappDataStorage.KEY_SPLASH_SCREEN_URL, null)); assertEquals(isIconGenerated, mSharedPreferences.getBoolean(WebappDataStorage.KEY_IS_ICON_GENERATED, true)); + assertEquals(isIconAdaptive, + mSharedPreferences.getBoolean(WebappDataStorage.KEY_IS_ICON_ADAPTIVE, true)); // Wipe out the data and ensure that it is all gone. mSharedPreferences.edit() @@ -257,6 +261,7 @@ .remove(WebappDataStorage.KEY_BACKGROUND_COLOR) .remove(WebappDataStorage.KEY_SPLASH_SCREEN_URL) .remove(WebappDataStorage.KEY_IS_ICON_GENERATED) + .remove(WebappDataStorage.KEY_IS_ICON_ADAPTIVE) .apply(); assertEquals(null, mSharedPreferences.getString(WebappDataStorage.KEY_ACTION, null)); @@ -273,6 +278,8 @@ null, mSharedPreferences.getString(WebappDataStorage.KEY_SPLASH_SCREEN_URL, null)); assertEquals(true, mSharedPreferences.getBoolean(WebappDataStorage.KEY_IS_ICON_GENERATED, true)); + assertEquals(true, + mSharedPreferences.getBoolean(WebappDataStorage.KEY_IS_ICON_ADAPTIVE, true)); // Update again from the intent and ensure that the data is restored. storage.updateFromShortcutIntent(shortcutIntent); @@ -294,6 +301,8 @@ mSharedPreferences.getString(WebappDataStorage.KEY_SPLASH_SCREEN_URL, null)); assertEquals(isIconGenerated, mSharedPreferences.getBoolean(WebappDataStorage.KEY_IS_ICON_GENERATED, true)); + assertEquals(isIconAdaptive, + mSharedPreferences.getBoolean(WebappDataStorage.KEY_IS_ICON_GENERATED, true)); } /**
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java index 45f0dcd..b79553ea 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappInfoTest.java
@@ -36,7 +36,8 @@ WebDisplayMode.STANDALONE, ScreenOrientationValues.DEFAULT, ShortcutSource.UNKNOWN, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, SPLASH_SCREEN_URL, - false /* isIconGenerated */, false /* forceNavigation */); + false /* isIconGenerated */, false /* isIconAdaptive */, + false /* forceNavigation */); Assert.assertNotNull(info); } @@ -51,7 +52,8 @@ WebDisplayMode.STANDALONE, ScreenOrientationValues.DEFAULT, ShortcutSource.UNKNOWN, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, SPLASH_SCREEN_URL, - false /* isIconGenerated */, false /* forceNavigation */); + false /* isIconGenerated */, false /* isIconAdaptive */, + false /* forceNavigation */); Assert.assertNotNull(info); } @@ -135,7 +137,8 @@ WebDisplayMode.FULLSCREEN, ScreenOrientationValues.DEFAULT, ShortcutSource.UNKNOWN, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, SPLASH_SCREEN_URL, - false /* isIconGenerated */, false /* forceNavigation */); + false /* isIconGenerated */, false /* isIconAdaptive */, + false /* forceNavigation */); Assert.assertEquals(WebDisplayMode.FULLSCREEN, info.displayMode()); Assert.assertEquals(ScreenOrientationValues.DEFAULT, info.orientation()); Assert.assertEquals(ShortcutSource.UNKNOWN, info.source()); @@ -153,7 +156,7 @@ WebappInfo info = WebappInfo.create(id, url, null, null, name, shortName, WebDisplayMode.STANDALONE, ScreenOrientationValues.DEFAULT, ShortcutSource.UNKNOWN, themeColor, backgroundColor, SPLASH_SCREEN_URL, false /* isIconGenerated */, - false /* forceNavigation */); + false /* isIconAdaptive */, false /* forceNavigation */); Assert.assertEquals(themeColor, info.themeColor()); Assert.assertEquals(backgroundColor, info.backgroundColor()); } @@ -169,7 +172,8 @@ WebDisplayMode.STANDALONE, ScreenOrientationValues.DEFAULT, ShortcutSource.UNKNOWN, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, SPLASH_SCREEN_URL, - false /* isIconGenerated */, false /* forceNavigation */); + false /* isIconGenerated */, false /* isIconAdaptive */, + false /* forceNavigation */); Assert.assertEquals(ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, info.themeColor()); Assert.assertEquals( ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING, info.backgroundColor()); @@ -294,6 +298,61 @@ } } + @Test + public void testIntentAdaptiveIcon() { + String id = "webapp id"; + String name = "longName"; + String shortName = "name"; + String url = "about:blank"; + + // Default value. + { + Intent intent = new Intent(); + intent.putExtra(ShortcutHelper.EXTRA_ID, id); + intent.putExtra(ShortcutHelper.EXTRA_NAME, name); + intent.putExtra(ShortcutHelper.EXTRA_SHORT_NAME, shortName); + intent.putExtra(ShortcutHelper.EXTRA_URL, url); + + Assert.assertFalse(name, WebappInfo.create(intent).isIconAdaptive()); + } + + // Set to true. + { + Intent intent = new Intent(); + intent.putExtra(ShortcutHelper.EXTRA_ID, id); + intent.putExtra(ShortcutHelper.EXTRA_NAME, name); + intent.putExtra(ShortcutHelper.EXTRA_SHORT_NAME, shortName); + intent.putExtra(ShortcutHelper.EXTRA_URL, url); + intent.putExtra(ShortcutHelper.EXTRA_IS_ICON_ADAPTIVE, true); + + Assert.assertTrue(name, WebappInfo.create(intent).isIconAdaptive()); + } + + // Set to false. + { + Intent intent = new Intent(); + intent.putExtra(ShortcutHelper.EXTRA_ID, id); + intent.putExtra(ShortcutHelper.EXTRA_NAME, name); + intent.putExtra(ShortcutHelper.EXTRA_SHORT_NAME, shortName); + intent.putExtra(ShortcutHelper.EXTRA_URL, url); + intent.putExtra(ShortcutHelper.EXTRA_IS_ICON_ADAPTIVE, false); + + Assert.assertFalse(name, WebappInfo.create(intent).isIconAdaptive()); + } + + // Set to something else than a boolean. + { + Intent intent = new Intent(); + intent.putExtra(ShortcutHelper.EXTRA_ID, id); + intent.putExtra(ShortcutHelper.EXTRA_NAME, name); + intent.putExtra(ShortcutHelper.EXTRA_SHORT_NAME, shortName); + intent.putExtra(ShortcutHelper.EXTRA_URL, url); + intent.putExtra(ShortcutHelper.EXTRA_IS_ICON_ADAPTIVE, "true"); + + Assert.assertFalse(name, WebappInfo.create(intent).isIconAdaptive()); + } + } + /** * Test that {@link WebappInfo#shouldForceNavigation()} defaults to false when the * {@link ShortcutHelper#EXTRA_FORCE_NAVIGATION} intent extra is not specified.
diff --git a/chrome/android/profiles/newest.txt b/chrome/android/profiles/newest.txt index 6fa1d84..dc8db26 100644 --- a/chrome/android/profiles/newest.txt +++ b/chrome/android/profiles/newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-73.0.3652.0_rc-r1.afdo.bz2 \ No newline at end of file +chromeos-chrome-amd64-73.0.3654.0_rc-r1.afdo.bz2 \ No newline at end of file
diff --git a/chrome/android/webapk/libs/common/src/org/chromium/webapk/lib/common/splash/SplashLayout.java b/chrome/android/webapk/libs/common/src/org/chromium/webapk/lib/common/splash/SplashLayout.java index 2cd8eadd..4b60512 100644 --- a/chrome/android/webapk/libs/common/src/org/chromium/webapk/lib/common/splash/SplashLayout.java +++ b/chrome/android/webapk/libs/common/src/org/chromium/webapk/lib/common/splash/SplashLayout.java
@@ -8,6 +8,7 @@ import android.content.res.Resources; import android.content.res.Resources.NotFoundException; import android.graphics.Bitmap; +import android.graphics.drawable.Icon; import android.os.Build; import android.support.annotation.IntDef; import android.util.DisplayMetrics; @@ -84,7 +85,8 @@ /** Builds splash screen and attaches it to the parent view. */ public static void createLayout(Context appContext, ViewGroup parentView, Bitmap icon, - @IconClassification int iconClassification, String text, boolean useLightTextColor) { + boolean isIconAdaptive, @IconClassification int iconClassification, String text, + boolean useLightTextColor) { int layoutId = selectLayoutFromIconClassification(iconClassification); ViewGroup layout = (ViewGroup) LayoutInflater.from(appContext).inflate(layoutId, parentView, true); @@ -97,6 +99,13 @@ } ImageView splashIconView = (ImageView) layout.findViewById(R.id.webapp_splash_screen_icon); - if (splashIconView != null) splashIconView.setImageBitmap(icon); + if (splashIconView == null) return; + + // Adaptive icons should only be present on Android O. + if (isIconAdaptive && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + splashIconView.setImageIcon(Icon.createWithAdaptiveBitmap(icon)); + } else { + splashIconView.setImageBitmap(icon); + } } }
diff --git a/chrome/android/webapk/shell_apk/current_version/current_version.gni b/chrome/android/webapk/shell_apk/current_version/current_version.gni index be73da616..59f229b 100644 --- a/chrome/android/webapk/shell_apk/current_version/current_version.gni +++ b/chrome/android/webapk/shell_apk/current_version/current_version.gni
@@ -12,4 +12,4 @@ # //chrome/android/webapk/shell_apk:webapk is changed. This includes # Java files, Android resource files and AndroidManifest.xml. Does not affect # Chrome.apk -current_shell_apk_version = 80 +current_shell_apk_version = 81
diff --git a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashActivity.java b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashActivity.java index a95e972..417a1f4 100644 --- a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashActivity.java +++ b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashActivity.java
@@ -73,8 +73,8 @@ setContentView(layout); int backgroundColor = WebApkUtils.getColor(resources, R.color.background_color); - SplashLayout.createLayout(this, layout, icon, iconClassification, - resources.getString(R.string.name), + SplashLayout.createLayout(this, layout, icon, false /* isIconAdaptive */, + iconClassification, resources.getString(R.string.name), WebApkUtils.shouldUseLightForegroundOnBackground(backgroundColor)); int themeColor = (int) WebApkMetaDataUtils.getLongFromMetaData(
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 350cb0e..c45dd51 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -234,6 +234,8 @@ <include name="IDR_APP_MANAGEMENT_APP_JS" file="resources\app_management\app.js" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML" file="resources\app_management\browser_proxy.html" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_BROWSER_PROXY_JS" file="resources\app_management\browser_proxy.js" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_HTML" file="resources\app_management\chrome_app_permission_view.html" type="BINDATA"/> + <include name="IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_JS" file="resources\app_management\chrome_app_permission_view.js" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_CONSTANTS_HTML" file="resources\app_management\constants.html" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_CONSTANTS_JS" file="resources\app_management\constants.js" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS" file="resources\app_management\fake_page_handler.js" type="BINDATA" />
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc index 495d18b..e875df1 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc
@@ -652,6 +652,8 @@ return true; } +namespace { + // Obtains file size of URL. void GetFileMetadataOnIOThread( scoped_refptr<storage::FileSystemContext> file_system_context, @@ -664,12 +666,16 @@ base::BindOnce(&GetFileMetadataRespondOnUIThread, std::move(callback))); } -// Checks if the available space of the |path| is enough for required |bytes|. -bool CheckLocalDiskSpace(const base::FilePath& path, int64_t bytes) { - return bytes <= base::SysInfo::AmountOfFreeDiskSpace(path) - - cryptohome::kMinFreeSpaceInBytes; +// Gets the available space of the |path|. +int64_t GetLocalDiskSpace(const base::FilePath& path) { + if (!base::PathExists(path)) { + return std::numeric_limits<int64_t>::min(); + } + return base::SysInfo::AmountOfFreeDiskSpace(path); } +} // namespace + bool FileManagerPrivateInternalStartCopyFunction::RunAsync() { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -704,25 +710,16 @@ return false; } - // Check if the destination directory is downloads. If so, secure available - // spece by freeing drive caches. - if (destination_url_.filesystem_id() == - file_manager::util::GetDownloadsMountPointName(GetProfile())) { - return base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce( - &GetFileMetadataOnIOThread, file_system_context, source_url_, - storage::FileSystemOperation::GET_METADATA_FIELD_SIZE, - base::BindOnce(&FileManagerPrivateInternalStartCopyFunction:: - RunAfterGetFileMetadata, - this))); - } - + // Check how much space we need for the copy operation. return base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, + FROM_HERE, {BrowserThread::IO}, base::BindOnce( - &FileManagerPrivateInternalStartCopyFunction::RunAfterFreeDiskSpace, - this, true)); + &GetFileMetadataOnIOThread, file_system_context, source_url_, + storage::FileSystemOperation::GET_METADATA_FIELD_SIZE | + storage::FileSystemOperation::GET_METADATA_FIELD_TOTAL_SIZE, + base::BindOnce(&FileManagerPrivateInternalStartCopyFunction:: + RunAfterGetFileMetadata, + this))); } void FileManagerPrivateInternalStartCopyFunction::RunAfterGetFileMetadata( @@ -736,24 +733,57 @@ return; } - drive::FileSystemInterface* const drive_file_system = - drive::util::GetFileSystemByProfile(GetProfile()); - if (drive_file_system) { - drive_file_system->FreeDiskSpaceIfNeededFor( - file_info.size, - base::Bind( - &FileManagerPrivateInternalStartCopyFunction::RunAfterFreeDiskSpace, - this)); + base::FilePath destination_dir; + if (destination_url_.filesystem_id() == + drive::util::GetDriveMountPointPath(GetProfile()).BaseName().value()) { + // Google Drive's cache is limited by the available space on the local disk. + destination_dir = + file_manager::util::GetMyFilesFolderForProfile(GetProfile()); } else { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, - base::BindOnce( - &CheckLocalDiskSpace, - file_manager::util::GetMyFilesFolderForProfile(GetProfile()), - file_info.size), - base::BindOnce( - &FileManagerPrivateInternalStartCopyFunction::RunAfterFreeDiskSpace, - this)); + destination_dir = destination_url_.path().DirName(); + } + + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::MayBlock()}, + base::BindOnce(&GetLocalDiskSpace, destination_dir), + base::BindOnce( + &FileManagerPrivateInternalStartCopyFunction::RunAfterCheckDiskSpace, + this, file_info.size)); +} + +void FileManagerPrivateInternalStartCopyFunction::RunAfterCheckDiskSpace( + int64_t space_needed, + int64_t space_available) { + if (space_available < 0) { + // It might be a virtual path. In this case we just assume that it has + // enough space. + RunAfterFreeDiskSpace(true); + } else if (destination_url_.filesystem_id() == + file_manager::util::GetDownloadsMountPointName(GetProfile()) || + destination_url_.filesystem_id() == + drive::util::GetDriveMountPointPath(GetProfile()) + .BaseName() + .value()) { + // If the destination directory is local hard drive or Google Drive we + // must leave some additional space to make sure we don't break the system. + if (space_available - cryptohome::kMinFreeSpaceInBytes > space_needed) { + RunAfterFreeDiskSpace(true); + } else { + // Also we can try to secure needed space by freeing Drive caches. + drive::FileSystemInterface* const drive_file_system = + drive::util::GetFileSystemByProfile(GetProfile()); + if (!drive_file_system) { + RunAfterFreeDiskSpace(false); + } else { + drive_file_system->FreeDiskSpaceIfNeededFor( + space_needed, + base::Bind(&FileManagerPrivateInternalStartCopyFunction:: + RunAfterFreeDiskSpace, + this)); + } + } + } else { + RunAfterFreeDiskSpace(space_available > space_needed); } }
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.h b/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.h index 26fea6f..d94c6ed 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.h +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.h
@@ -257,6 +257,10 @@ void RunAfterGetFileMetadata(base::File::Error result, const base::File::Info& file_info); + // Part of RunAsync(). Called after the amount of space on the destination + // is known. + void RunAfterCheckDiskSpace(int64_t space_needed, int64_t space_available); + // Part of RunAsync(). Called after FreeDiskSpaceIfNeededFor() is completed on // IO thread. void RunAfterFreeDiskSpace(bool available);
diff --git a/chrome/browser/chromeos/file_system_provider/provided_file_system.cc b/chrome/browser/chromeos/file_system_provider/provided_file_system.cc index 97eeac2..92546bbb 100644 --- a/chrome/browser/chromeos/file_system_provider/provided_file_system.cc +++ b/chrome/browser/chromeos/file_system_provider/provided_file_system.cc
@@ -214,7 +214,9 @@ new operations::GetActions(event_router_, file_system_info_, entry_paths, callback))); if (!request_id) { - callback.Run(Actions(), base::File::FILE_ERROR_SECURITY); + // If the provider doesn't listen for GetActions requests, treat it as + // having no actions. + callback.Run(Actions(), base::File::FILE_OK); return AbortCallback(); }
diff --git a/chrome/browser/net/reporting_browsertest.cc b/chrome/browser/net/reporting_browsertest.cc index 0f125e43..1575744 100644 --- a/chrome/browser/net/reporting_browsertest.cc +++ b/chrome/browser/net/reporting_browsertest.cc
@@ -19,6 +19,7 @@ #include "content/public/browser/navigation_controller.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" +#include "content/public/common/result_codes.h" #include "content/public/common/url_constants.h" #include "content/public/test/test_navigation_observer.h" #include "net/dns/mock_host_resolver.h" @@ -174,12 +175,15 @@ EXPECT_EQ(*expected, *actual); } -// This test intentionally crashes a render process, and so fails ASan tests. +// These tests intentionally crash a render process, and so fail ASan tests. #if defined(ADDRESS_SANITIZER) #define MAYBE_CrashReport DISABLED_CrashReport +#define MAYBE_CrashReportUnresponsive DISABLED_CrashReportUnresponsive #else #define MAYBE_CrashReport CrashReport +#define MAYBE_CrashReportUnresponsive CrashReportUnresponsive #endif + IN_PROC_BROWSER_TEST_F(ReportingBrowserTest, MAYBE_CrashReport) { content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -218,3 +222,43 @@ EXPECT_EQ(base::StringPrintf("https://example.com:%d/original", port()), url->GetString()); } + +IN_PROC_BROWSER_TEST_F(ReportingBrowserTest, MAYBE_CrashReportUnresponsive) { + content::WebContents* contents = + browser()->tab_strip_model()->GetActiveWebContents(); + content::TestNavigationObserver navigation_observer(contents); + + // Navigate to reporting-enabled page. + NavigateParams params(browser(), GetReportingEnabledURL(), + ui::PAGE_TRANSITION_LINK); + Navigate(¶ms); + + original_response()->WaitForRequest(); + original_response()->Send("HTTP/1.1 200 OK\r\n"); + original_response()->Send(GetReportToHeader()); + original_response()->Send("\r\n"); + original_response()->Done(); + navigation_observer.Wait(); + + // Simulate the page being killed due to being unresponsive. + contents->GetMainFrame()->GetProcess()->Shutdown(content::RESULT_CODE_HUNG); + + upload_response()->WaitForRequest(); + auto response = ParseReportUpload(upload_response()->http_request()->content); + upload_response()->Send("HTTP/1.1 200 OK\r\n"); + upload_response()->Send("\r\n"); + upload_response()->Done(); + + // Verify the contents of the report that we received. + EXPECT_TRUE(response != nullptr); + auto report = response->GetList().begin(); + auto* type = report->FindKeyOfType("type", base::Value::Type::STRING); + auto* url = report->FindKeyOfType("url", base::Value::Type::STRING); + auto* body = report->FindKeyOfType("body", base::Value::Type::DICTIONARY); + auto* reason = body->FindKeyOfType("reason", base::Value::Type::STRING); + + EXPECT_EQ("crash", type->GetString()); + EXPECT_EQ(base::StringPrintf("https://example.com:%d/original", port()), + url->GetString()); + EXPECT_EQ("unresponsive", reason->GetString()); +}
diff --git a/chrome/browser/resources/app_management/BUILD.gn b/chrome/browser/resources/app_management/BUILD.gn index 19b5cdd..2a664556 100644 --- a/chrome/browser/resources/app_management/BUILD.gn +++ b/chrome/browser/resources/app_management/BUILD.gn
@@ -60,6 +60,12 @@ ] } + js_library("chrome_app_permission_view") { + deps = [ + ":fake_page_handler", + ] + } + js_library("constants") { }
diff --git a/chrome/browser/resources/app_management/app.html b/chrome/browser/resources/app_management/app.html index b94366ff..15883d0 100644 --- a/chrome/browser/resources/app_management/app.html +++ b/chrome/browser/resources/app_management/app.html
@@ -2,6 +2,7 @@ <link rel="import" href="actions.html"> <link rel="import" href="browser_proxy.html"> +<link rel="import" href="chrome_app_permission_view.html"> <link rel="import" href="constants.html"> <link rel="import" href="main_view.html"> <link rel="import" href="pwa_permission_view.html"> @@ -26,6 +27,8 @@ </cr-toolbar> <app-management-main-view></app-management-main-view> <app-management-pwa-permission-view></app-management-pwa-permission-view> + <app-management-chrome-app-permission-view> + </app-management-chrome-app-permission-view> <app-management-router></app-management-router> </template> <script src="chrome://apps/app.js"></script>
diff --git a/chrome/browser/resources/app_management/chrome_app_permission_view.html b/chrome/browser/resources/app_management/chrome_app_permission_view.html new file mode 100644 index 0000000..701349e --- /dev/null +++ b/chrome/browser/resources/app_management/chrome_app_permission_view.html
@@ -0,0 +1,25 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="shared_style.html"> +<link rel="import" href="browser_proxy.html"> +<link rel="import" href="shared_style.html"> +<link rel="import" href="util.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html"> + +<dom-module id="app-management-chrome-app-permission-view"> + <template> + <style include="app-management-shared-css"> + + </style> + <div class="permission-view-header"> + <paper-icon-button-light class="icon-arrow-back"> + <button> + <paper-ripple class="circle"></paper-ripple> + </button> + </paper-icon-button-light> + <img class="permission-view-header-icon" src="[[iconUrlFromId_(app_)]]"> + <div class="app-title">[[app_.title]]</div> + </div> + </template> + <script src="chrome_app_permission_view.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/app_management/chrome_app_permission_view.js b/chrome/browser/resources/app_management/chrome_app_permission_view.js new file mode 100644 index 0000000..6973667 --- /dev/null +++ b/chrome/browser/resources/app_management/chrome_app_permission_view.js
@@ -0,0 +1,29 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +Polymer({ + is: 'app-management-chrome-app-permission-view', + + properties: { + /** + * @type {appManagement.mojom.App} + * @private + */ + app_: { + type: Object, + value: function() { + return app_management.FakePageHandler.createApp( + 'ahfgeienlihckogmohjhadlkjgocpleb'); + }, + }, + }, + + /** + * @param {appManagement.mojom.App} app + * @return {string} + * @private + */ + iconUrlFromId_: function(app) { + return app_management.util.getAppIcon(app); + }, +});
diff --git a/chrome/browser/resources/app_management/item.js b/chrome/browser/resources/app_management/item.js index 54841b8..897caed 100644 --- a/chrome/browser/resources/app_management/item.js +++ b/chrome/browser/resources/app_management/item.js
@@ -33,6 +33,6 @@ * @private */ iconUrlFromId_: function(app) { - return `chrome://extension-icon/${app.id}/128/1`; + return app_management.util.getAppIcon(app); }, });
diff --git a/chrome/browser/resources/app_management/pwa_permission_view.html b/chrome/browser/resources/app_management/pwa_permission_view.html index 2fa4145..443f16ca 100644 --- a/chrome/browser/resources/app_management/pwa_permission_view.html +++ b/chrome/browser/resources/app_management/pwa_permission_view.html
@@ -13,19 +13,6 @@ <dom-module id="app-management-pwa-permission-view"> <template> <style include="app-management-shared-css cr-icons paper-button-style"> - #permission-header { - align-items: center; - border-top: var(--card-separator); - display: flex; - } - - #app-title { - flex: 1; - font-size: 16px; - overflow: hidden; - text-overflow: ellipsis; - } - #site-settings-button { color: var(--secondary-text-color); font-size: 12px; @@ -49,14 +36,14 @@ } </style> - <div id="permission-header"> + <div class="permission-view-header"> <paper-icon-button-light class="icon-arrow-back"> <button id="closeButton" aria-label="$i18n{back}"> <paper-ripple class="circle"></paper-ripple> </button> </paper-icon-button-light> <img class="permission-view-header-icon" src="[[iconUrlFromId_(app_)]]"> - <div id="app-title">[[app_.title]]</div> + <div class="app-title">[[app_.title]]</div> <div id="site-settings-button">$i18n{openSiteSettings}</div> <paper-icon-button-light id="site-settings-icon" class="icon-external"> <button aria-label="$i18n{openSiteSettings}"></button>
diff --git a/chrome/browser/resources/app_management/pwa_permission_view.js b/chrome/browser/resources/app_management/pwa_permission_view.js index ef5e5e44..17d27a0 100644 --- a/chrome/browser/resources/app_management/pwa_permission_view.js +++ b/chrome/browser/resources/app_management/pwa_permission_view.js
@@ -38,7 +38,7 @@ * @private */ iconUrlFromId_: function(app) { - return `chrome://extension-icon/${app.id}/128/1`; + return app_management.util.getAppIcon(app); }, /**
diff --git a/chrome/browser/resources/app_management/shared_style.html b/chrome/browser/resources/app_management/shared_style.html index fab54b9..71f6c83 100644 --- a/chrome/browser/resources/app_management/shared_style.html +++ b/chrome/browser/resources/app_management/shared_style.html
@@ -13,6 +13,12 @@ width: var(--card-width); } + .permission-view-header { + align-items: center; + border-top: var(--card-separator); + display: flex; + } + .permission-view-header-icon { height: 26px; margin-inline-end: 8px; @@ -25,15 +31,17 @@ font-weight: var(--secondary-font-weight); } - .secondary-text { - color: var(--secondary-text-color); - font-weight: var(--secondary-font-weight); + .app-title { + flex: 1; + font-size: 16px; + overflow: hidden; + text-overflow: ellipsis; } .permission-row { align-items: center; border-top: var(--card-separator); - display: flex; + display: inline-flex; height: 62px; justify-content: space-between; padding: 0 24px; @@ -47,5 +55,10 @@ align-items: center; display: inline-flex; } + + .secondary-text { + color: var(--secondary-text-color); + font-weight: var(--secondary-font-weight); + } </style> </template>
diff --git a/chrome/browser/resources/app_management/util.js b/chrome/browser/resources/app_management/util.js index 76cb9beb..5b57744 100644 --- a/chrome/browser/resources/app_management/util.js +++ b/chrome/browser/resources/app_management/util.js
@@ -34,8 +34,17 @@ return initialState; } + /** + * @param {appManagement.mojom.App} app + * @return {string} + */ + function getAppIcon(app) { + return `chrome://extension-icon/${app.id}/128/1`; + } + return { createEmptyState: createEmptyState, createInitialState: createInitialState, + getAppIcon: getAppIcon, }; });
diff --git a/chrome/browser/resources/chromeos/zip_archiver/js/background.js b/chrome/browser/resources/chromeos/zip_archiver/js/background.js index 0e4d40a6..72f4590 100644 --- a/chrome/browser/resources/chromeos/zip_archiver/js/background.js +++ b/chrome/browser/resources/chromeos/zip_archiver/js/background.js
@@ -42,12 +42,6 @@ chrome.fileSystemProvider.onReadFileRequested.addListener( unpacker.app.onReadFileRequested); - // Provide a dummy onGetActionsRequested implementation to make FSP happy. - chrome.fileSystemProvider.onGetActionsRequested.addListener( - (options, success, error) => { - success([]); - }); - // Clean all temporary files inside the work directory, just in case the // extension aborted previously without removing ones. unpacker.app.cleanWorkDirectory();
diff --git a/chrome/browser/resources/chromeos/zip_archiver/manifest.json b/chrome/browser/resources/chromeos/zip_archiver/manifest.json index 82619de..bf14acab 100644 --- a/chrome/browser/resources/chromeos/zip_archiver/manifest.json +++ b/chrome/browser/resources/chromeos/zip_archiver/manifest.json
@@ -2,7 +2,7 @@ // chrome-extension://dmboannefpncccogfdikhmhpmdnddgoe "key": "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCxGxJCOLUzHIYc812NFoBC1eV8PhOTuF6he3gSuqzxckUyrDLdl5++DAd1AkQkv6i8SSMWFvDKLg2b+zfCOwk6P7uu3tqNavXXy61Okaq5HKF3xhciNDl4zF6ZlegvE9AhJOTo2eCHVIMS0+YuK5hyno/+xMwN4byvsrOYXQnhcJeOHxkFb9TfVUb3SOBgl4pBZ7+EIMNntEvzY7mxjBzOgnCjBePvwnoMRyAqljCJarz2WSbUOLP3yoCuH9vPKj+0D6hF1woXmd6qBr0ln/7tHdbr1cYmkosfFuJO2y6d00FAJY/G5L6o8JAEBbWG5D0qELt+aBjkG0uos5gcR4ZPAgMBAAECggEBAK3aIjFJU25J6MjQiRvvY5a4O56bnUIb8SDZgAP6pbwZ7R2R9hiaN6AqVMOiptvgHDZAISYU/OerD4b3s0OCCkvYtlcxwh6iSZQ9BvIighFWrpZRqPHVjDktfQuNIS/dZiiy+9Yr0oFmD4jS45idCPgy+K0h6CEUX9GlPTEq24ElECDwQHVyB9LHdenleCdvldIEDxf6/D+zkc/PmCPlZPfwdppK6wgH2GvgqbxV+OoSnNp0XhNinjCN37P5yAo4xEi0UGOxOwkNGkJn0V5bYjH6/JHzmdVH74D40N4/Fcy0bC79oFGeiP0ZzW8AAArfIxbxStodWlBOCsTVtvi4RMECgYEA2pyZRThGx4OH8uXCC94LkdpVjKvLvbUlIVd2zk3UEFpWujgmAI+erkAaE1JSlcJpFNSlfonTX1vQuMgTOfnK7soy4677P1CMQH++GxjMWRIAQsMyx7vLtKOISr5/vQQKAyuFmxzt9xbMOmPzqWxwkuuiF74GtPgE5VXslhvsoyECgYEAz2U7L6YS4u2aMRK4DMDxcf/hZ3BxwHmUl5euknRNcaFJSdv6392y8w3t9Lz7sp8CK56GADXL1bmLrDgg2tlL82f60rtPd6IOoJk10uMmCnyjbZh7aJzuw1CTSs+dwi6qpGUB4YbJn8R2AN79SHxUb4dwVOh4lHeNa415Wka+a28CgYA3Vf5iDB22cO/fpxLYSCtrjvWqtu3KpmiwqOAU1pSAUy2y03WjHLeQ6f7vtx3adKx+rlj5z89mSuppa5OaUEVy7lG1WlyUqUHnLa6kU0GepjTUsW5QKpQktGRSbygMY1JZfRHDsq31ppqpiRVrZFyWg/iyw9IUytcKahaJ5KWgoQKBgFbgY/ugyNaQi3+1BK4rALktZAGNo8jp5SnfWzx0RaCs3GN5J80xNG4GTsCvjYwUebdF74IVBu7fi7e3x2OFlQBAdVxjJHXLx+7UXyyZBG1uKpOVRVTcMFRW42x6Le6S196HhVMwwDMR/BB/WIBNvJz/kjmvLBudPPtpxwTfD5M3AoGBALrrXX4QwqBiq4q09SPKoeOwlV35QETUhQaAKKag9aSrNMONcf77TXUBZ0d9Z+tabHLTGGa6E7q2BL82NdZSZvVeVWA+KaE4ezW2t5KyZqg14Cc0uY9Xys9VkFcVgMqsvtkUzDvAVJcmNAgcrMIEiapUR6LPrneLLXH1ikOt+hM8", "name": "Zip Archiver", - "version": "1.0", + "version": "1.1", "manifest_version": 2, "minimum_chrome_version": "44.0.2400.0", "description": "Zip Archiver - Open and pack ZIP files in Files app.",
diff --git a/chrome/browser/resources/md_bookmarks/list.html b/chrome/browser/resources/md_bookmarks/list.html index 15a02236..271645c 100644 --- a/chrome/browser/resources/md_bookmarks/list.html +++ b/chrome/browser/resources/md_bookmarks/list.html
@@ -25,7 +25,7 @@ #list { @apply --cr-card-elevation; - background-color: #fff; + background-color: var(--cr-card-background-color); border-radius: var(--cr-card-border-radius); margin: 0 auto; max-width: var(--card-max-width);
diff --git a/chrome/browser/resources/md_downloads/item.html b/chrome/browser/resources/md_downloads/item.html index 0236203..07ae040 100644 --- a/chrome/browser/resources/md_downloads/item.html +++ b/chrome/browser/resources/md_downloads/item.html
@@ -48,7 +48,7 @@ } #content { - background: white; + background: var(--cr-card-background-color); border-radius: var(--cr-card-border-radius); display: flex; flex: none;
diff --git a/chrome/browser/resources/md_downloads/toolbar.html b/chrome/browser/resources/md_downloads/toolbar.html index 1d8f572..279617e 100644 --- a/chrome/browser/resources/md_downloads/toolbar.html +++ b/chrome/browser/resources/md_downloads/toolbar.html
@@ -18,7 +18,7 @@ <style include="cr-hidden-style"> :host { align-items: center; - background: var(--google-blue-700); + background: var(--md-toolbar-color); color: white; display: flex; min-height: 56px;
diff --git a/chrome/browser/resources/md_extensions/item.html b/chrome/browser/resources/md_extensions/item.html index 589b4d8..da73f6c 100644 --- a/chrome/browser/resources/md_extensions/item.html +++ b/chrome/browser/resources/md_extensions/item.html
@@ -60,7 +60,7 @@ #card { @apply --cr-card-elevation; - background: white; + background: var(--cr-card-background-color); border-radius: var(--cr-card-border-radius); display: flex; flex-direction: column;
diff --git a/chrome/browser/resources/md_extensions/keyboard_shortcuts.html b/chrome/browser/resources/md_extensions/keyboard_shortcuts.html index e473060..acec5522 100644 --- a/chrome/browser/resources/md_extensions/keyboard_shortcuts.html +++ b/chrome/browser/resources/md_extensions/keyboard_shortcuts.html
@@ -19,7 +19,7 @@ .shortcut-card { @apply --cr-primary-text; @apply --cr-card-elevation; - background-color: white; + background-color: var(--cr-card-background-color); border-radius: var(--cr-card-border-radius); margin: 0 auto 16px auto; padding-bottom: 8px;
diff --git a/chrome/browser/resources/md_history/history_item.html b/chrome/browser/resources/md_history/history_item.html index 9db1c4e..add4ccb 100644 --- a/chrome/browser/resources/md_history/history_item.html +++ b/chrome/browser/resources/md_history/history_item.html
@@ -144,7 +144,7 @@ #background { @apply --cr-card-elevation; - background: #fff; + background: var(--cr-card-background-color); bottom: 0; left: 0; position: absolute;
diff --git a/chrome/browser/resources/md_history/synced_device_card.html b/chrome/browser/resources/md_history/synced_device_card.html index 7518b3e..8dd8bf8 100644 --- a/chrome/browser/resources/md_history/synced_device_card.html +++ b/chrome/browser/resources/md_history/synced_device_card.html
@@ -58,7 +58,7 @@ #history-item-container { @apply --cr-card-elevation; - background: #fff; + background: var(--cr-card-background-color); border-radius: var(--cr-card-border-radius); }
diff --git a/chrome/browser/resources/pdf/index.html b/chrome/browser/resources/pdf/index.html index a14ae79..235875b 100644 --- a/chrome/browser/resources/pdf/index.html +++ b/chrome/browser/resources/pdf/index.html
@@ -37,9 +37,9 @@ <script src="zoom_manager.js"></script> <script src="gesture_detector.js"></script> <script src="pdf_scripting_api.js"></script> -<script src="chrome://resources/js/load_time_data.js"></script> -<script src="chrome://resources/js/util.js"></script> -<script src="chrome://resources/js/promise_resolver.js"></script> +<link rel="import" href="chrome://resources/html/load_time_data.html"> +<link rel="import" href="chrome://resources/html/promise_resolver.html"> +<link rel="import" href="chrome://resources/html/util.html"> <script src="browser_api.js"></script> <script src="metrics.js"></script> <script src="pdf_viewer.js"></script>
diff --git a/chrome/browser/resources/policy.html b/chrome/browser/resources/policy.html index 23d0eef2..d8b96cfe 100644 --- a/chrome/browser/resources/policy.html +++ b/chrome/browser/resources/policy.html
@@ -134,17 +134,35 @@ </div> </td> <td class="value-column"> - <div class="value-container"> - <span class="value"></span> - <a is="action-link" class="toggle-expanded-value"></a> + <div class="value-container collapsible-cell" + data-expandable-row=".expanded-value-container"> + <span class="value cell-text"></span> + <a is="action-link" + class="toggle-expanded-value overflow-link" + data-show="showExpandedValue" + data-hide="hideExpandedValue" + hidden> + </a> </div> </td> <td class="status-column"> - <div class="status elide preformatted"></div> + <div class="status-container collapsible-cell" + data-expandable-row=".expanded-status-container"> + <span class="status preformatted cell-text"></span> + <a is="action-link" + class="toggle-expanded-status overflow-link" + data-show="showExpandedStatus" + data-hide="hideExpandedStatus" + hidden> + </a> + </div> </td> </tr> - <tr class="expanded-value-container"> - <td class="expanded-value" colspan=5></td> + <tr class="expanded-value-container" hidden> + <td class="expanded-text" colspan=6></td> + </tr> + <tr class="expanded-status-container" hidden> + <td class="expanded-text" colspan=6></td> </tr> </tbody> </table>
diff --git a/chrome/browser/resources/policy_android.css b/chrome/browser/resources/policy_android.css index 5e06ea8..e511a0c0 100644 --- a/chrome/browser/resources/policy_android.css +++ b/chrome/browser/resources/policy_android.css
@@ -174,30 +174,18 @@ } div.elide, -span.value { +span.value, +span.status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -button.toggle-expanded-value { +button.overflow-link { padding: 0; } -tbody.has-overflowed-value span.value { - display: none; -} - -tbody:not(.has-overflowed-value) button.toggle-expanded-value { - display: none; -} - -tbody:not(.has-overflowed-value) > tr.expanded-value-container, -tbody:not(.show-overflowed-value) > tr.expanded-value-container { - display: none; -} - -td.expanded-value { +td.expanded-text { white-space: pre; word-wrap: break-word; }
diff --git a/chrome/browser/resources/policy_base.js b/chrome/browser/resources/policy_base.js index de2122e..3f748ff4 100644 --- a/chrome/browser/resources/policy_base.js +++ b/chrome/browser/resources/policy_base.js
@@ -129,9 +129,14 @@ * Initialization function for the cr.ui framework. */ decorate: function() { - this.updateToggleExpandedValueText_(); + const links = this.querySelectorAll('.overflow-link'); + for (let i = 0; i < links.length; i++) { + this.setExpandedText_(links[i], true); + } this.querySelector('.toggle-expanded-value') - .addEventListener('click', this.toggleExpandedValue_.bind(this)); + .addEventListener('click', this.toggleExpanded_); + this.querySelector('.toggle-expanded-status') + .addEventListener('click', this.toggleExpanded_); }, /** @@ -167,7 +172,8 @@ this.querySelector('.source').textContent = loadTimeData.getString(value.source); this.querySelector('.value').textContent = value.value; - this.querySelector('.expanded-value').textContent = value.value; + this.querySelector('.expanded-value-container .expanded-text') + .textContent = value.value; } // Populate the status column. @@ -187,89 +193,98 @@ status = loadTimeData.getString('ok'); } this.querySelector('.status').textContent = status; - + this.querySelector('.expanded-status-container .expanded-text') + .textContent = status; if (isMobilePage()) { // The number of columns which are hidden by the css file for the mobile // (Android) version of this page. /** @const */ const HIDDEN_COLUMNS_IN_MOBILE_VERSION = 2; - - const expandedValue = this.querySelector('.expanded-value'); - expandedValue.setAttribute( - 'colspan', - expandedValue.colSpan - HIDDEN_COLUMNS_IN_MOBILE_VERSION); + const expandedCells = this.querySelector('.expanded-text'); + for (const cell in expandedCells) { + cell.setAttribute( + 'colspan', cell.colSpan - HIDDEN_COLUMNS_IN_MOBILE_VERSION); + } } }, /* - * Get value width of the value container. - * @param {Object} valueContainer Container for the value. + * Get width of a DOM element inside a container. + * @param {Object} container Container for the element. + * @param {string} elemClass Class of the element containing text. * @private */ - getValueWidth_: function(valueContainer) { - return valueContainer.querySelector('.value').offsetWidth; + getElementWidth_: function(container, elemClass) { + return container.querySelector(elemClass).offsetWidth; }, /* - * Update the value width for the value container if necessary. - * @param {Object} valueContainer Container for the value. + * Update the value width for a container if necessary. + * @param {Object} container Container for the DOM element. + * @param {string} elemClass Class of the element containing text. * @private */ - updateValueWidth_: function(valueContainer) { - if (valueContainer.valueWidth == undefined) { - valueContainer.valueWidth = this.getValueWidth_(valueContainer); + updateContainerWidth_: function(container, elemClass) { + if (container.valueWidth == undefined) { + container.valueWidth = this.getElementWidth_(container, elemClass); } }, + /** * Check the table columns for overflow. Most columns are automatically - * elided when overflow occurs. The only action required is to add a tooltip - * that shows the complete content. The value column is an exception. If - * overflow occurs here, the contents is replaced with a link that toggles - * the visibility of an additional row containing the complete value. + * elided when overflow occurs. The only action required is to add a + * tooltip that shows the complete content. The value and status columns + * are exceptions. If overflow occurs here, the contents are replaced links + * that toggle the visibility of additional rows containing the complete + * value and/or status texts. */ checkOverflow: function() { - // Set a tooltip on all overflowed columns except the value column. + // Set a tooltip on all overflowed columns except the columns value and + // status. const divs = this.querySelectorAll('div.elide'); for (let i = 0; i < divs.length; i++) { const div = divs[i]; div.title = div.offsetWidth < div.scrollWidth ? div.textContent : ''; } - - // Cache the width of the value column's contents when it is first shown. - // This is required to be able to check whether the contents would still - // overflow the column once it has been hidden and replaced by a link. - const valueContainer = this.querySelector('.value-container'); - this.updateValueWidth_(valueContainer); - - // Determine whether the contents of the value column overflows. The - // visibility of the contents, replacement link and additional row - // containing the complete value that depend on this are handled by CSS. - if (valueContainer.offsetWidth <= valueContainer.valueWidth) - this.classList.add('has-overflowed-value'); - else - this.classList.remove('has-overflowed-value'); + const collapsibleCells = this.querySelectorAll('.collapsible-cell'); + for (let i = 0; i < collapsibleCells.length; i++) { + const cell = collapsibleCells[i]; + // Cache the width of the column's contents when it is first shown. + // This is required to be able to check whether the contents would still + // overflow the column once it has been hidden and replaced by a link. + this.updateContainerWidth_(cell, '.cell-text'); + // Determine whether the contents of the column overflows. + if (cell.offsetWidth <= cell.valueWidth) { + cell.querySelector('.cell-text').hidden = true; + cell.querySelector('.overflow-link').hidden = false; + } else { + cell.querySelector('.cell-text').hidden = false; + cell.querySelector('.overflow-link').hidden = true; + this.querySelector(cell.dataset.expandableRow).hidden = true; + this.setExpandedText_(cell.querySelector('.overflow-link'), true); + } + } }, /** - * Update the text of the link that toggles the visibility of an additional - * row containing the complete policy value, depending on the toggle state. - * @private + * Sets the text for a toggle link with hide/show modes. + * @param {Object} link The DOM element to set the text for. + * @param {bool} show Indicates if the link is in show of hide mode. */ - updateToggleExpandedValueText_: function(event) { - this.querySelector('.toggle-expanded-value').textContent = - loadTimeData.getString( - this.classList.contains('show-overflowed-value') ? - 'hideExpandedValue' : - 'showExpandedValue'); + setExpandedText_: function(link, show) { + link.textContent = + loadTimeData.getString(show ? link.dataset.show : link.dataset.hide); }, /** - * Toggle the visibility of an additional row containing the complete policy - * value. + * Toggle the visibility of an additional row containing the complete text. * @private */ - toggleExpandedValue_: function() { - this.classList.toggle('show-overflowed-value'); - this.updateToggleExpandedValueText_(); + toggleExpanded_: function() { + const cell = this.parentElement; + // get the expandable row corresponding to this collapsed cell + row = cell.closest('tbody').querySelector(cell.dataset.expandableRow); + row.hidden = !row.hidden; + this.setExpandedText_(this, !row.hidden); }, };
diff --git a/chrome/browser/resources/policy_common.css b/chrome/browser/resources/policy_common.css index c894fd9..2a456ce 100644 --- a/chrome/browser/resources/policy_common.css +++ b/chrome/browser/resources/policy_common.css
@@ -112,30 +112,19 @@ } div.elide, -span.value { +span.value, +span.status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.toggle-expanded-value { +.overflow-link { padding: 0; } -tbody.has-overflowed-value span.value { - display: none; -} -tbody:not(.has-overflowed-value) .toggle-expanded-value { - display: none; -} - -tbody:not(.has-overflowed-value) > tr.expanded-value-container, -tbody:not(.show-overflowed-value) > tr.expanded-value-container { - display: none; -} - -td.expanded-value { +td.expanded-text { white-space: pre; word-wrap: break-word; }
diff --git a/chrome/browser/resources/policy_tool.html b/chrome/browser/resources/policy_tool.html index 75f7e68..1350aa08 100644 --- a/chrome/browser/resources/policy_tool.html +++ b/chrome/browser/resources/policy_tool.html
@@ -84,9 +84,15 @@ <div class="name elide"></div> </td> <td class="value-column"> - <div class="value-container"> - <span class="value"></span> - <a is="action-link" class="toggle-expanded-value"></a> + <div class="value-container collapsible-cell" + data-expandable-row=".expanded-value-container"> + <span class="value cell-text"></span> + <a is="action-link" + class="toggle-expanded-value overflow-link" + data-show="showExpandedValue" + data-hide="hideExpandedValue" + hidden> + </a> <button class="edit-button">$i18n{edit}</button> <form class="value-edit-form"> <input class="value-edit-field" type="text"> @@ -96,12 +102,23 @@ </div> </td> <td class="status-column"> - <div class="status elide"></div> + <div class="status-container collapsible-cell" + data-expandable-row=".expanded-status-container"> + <span class="status preformatted cell-text"></span> + <a is="action-link" + class="toggle-expanded-status overflow-link" + data-show="showExpandedStatus" + data-hide="hideExpandedStatus"> + </a> + </div> </td> </tr> - <tr class="expanded-value-container"> - <td class="expanded-value" colspan=3></td> - </tr> + <tr class="expanded-value-container" hidden> + <td class="expanded-text" colspan=3></td> + </tr> + <tr class="expanded-status-container" hidden> + <td class="expanded-text" colspan=3></td> + </tr> </tbody> </table> </div>
diff --git a/chrome/browser/resources/policy_tool.js b/chrome/browser/resources/policy_tool.js index e9d73b2..7f7ac5f 100644 --- a/chrome/browser/resources/policy_tool.js +++ b/chrome/browser/resources/policy_tool.js
@@ -213,13 +213,18 @@ /** @override */ policy.Policy.prototype.decorate = function() { - this.updateToggleExpandedValueText_(); this.querySelector('.edit-button') .addEventListener('click', this.onValueEditing_.bind(this)); this.querySelector('.value-edit-form').onsubmit = this.submitEditedValue_.bind(this); + const links = this.querySelectorAll('.overflow-link'); + for (let i = 0; i < links.length; i++) { + this.setExpandedText_(links[i], true); + } this.querySelector('.toggle-expanded-value') - .addEventListener('click', this.toggleExpandedValue_.bind(this)); + .addEventListener('click', this.toggleExpanded_); + this.querySelector('.toggle-expanded-status') + .addEventListener('click', this.toggleExpanded_); }; /** @override */ @@ -269,7 +274,8 @@ } this.unset = !value; this.querySelector('.value').textContent = value; - this.querySelector('.expanded-value').textContent = value; + this.querySelector('.expanded-value-container .expanded-text').textContent = + value; this.querySelector('.value-edit-field').value = value; }; @@ -279,13 +285,19 @@ valueContainer.querySelector('.edit-button').offsetWidth; }; +policy.Policy.prototype.hideExpandedValueRow_ = function() { + const cell = this.querySelector('.value-container'); + cell.querySelector('.overflow-link').hidden = true; + this.querySelector(cell.dataset.expandableRow).hidden = true; + this.setExpandedText_(cell.querySelector('.overflow-link'), true); +}; /** * Start editing value. * @private */ policy.Policy.prototype.onValueEditing_ = function() { + this.hideExpandedValueRow_(); this.classList.add('value-editing-on'); - this.classList.remove('has-overflowed-value'); this.querySelector('.value-edit-field').select(); };
diff --git a/chrome/browser/resources/settings/find_shortcut_behavior.js b/chrome/browser/resources/settings/find_shortcut_behavior.js index 0beae62..03a99ea0 100644 --- a/chrome/browser/resources/settings/find_shortcut_behavior.js +++ b/chrome/browser/resources/settings/find_shortcut_behavior.js
@@ -67,12 +67,16 @@ }, becomeActiveFindShortcutListener() { - assert(listeners.length == 0 || listeners[listeners.length - 1] != this); + assert( + listeners.indexOf(this) == -1, + 'Already listening for find shortcuts.'); listeners.push(this); }, removeSelfAsFindShortcutListener() { - assert(listeners.pop() == this); + const index = listeners.indexOf(this); + assert(index > -1, 'Find shortcut listener not found.'); + listeners.splice(index, 1); }, };
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.html b/chrome/browser/resources/settings/privacy_page/privacy_page.html index 0973d5d..24ed3b8 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.html +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.html
@@ -214,7 +214,9 @@ </settings-subpage> </template> <template is="dom-if" route-path="/content/automaticDownloads" no-search> - <settings-subpage page-title="$i18n{siteSettingsAutomaticDownloads}"> + <settings-subpage page-title="$i18n{siteSettingsAutomaticDownloads}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsAutoDownloadBlock}" toggle-on-label="$i18n{siteSettingsAutoDownloadAskRecommended}" @@ -222,12 +224,15 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.AUTOMATIC_DOWNLOADS}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" route-path="/content/backgroundSync" no-search> - <settings-subpage page-title="$i18n{siteSettingsBackgroundSync}"> + <settings-subpage page-title="$i18n{siteSettingsBackgroundSync}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsBackgroundSyncBlocked}" toggle-on-label= @@ -236,12 +241,15 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.BACKGROUND_SYNC}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" route-path="/content/camera" no-search> - <settings-subpage page-title="$i18n{siteSettingsCategoryCamera}"> + <settings-subpage page-title="$i18n{siteSettingsCategoryCamera}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <media-picker label="$i18n{siteSettingsCameraLabel}" type="camera"> </media-picker> <category-default-setting category="{{ContentSettingsTypes.CAMERA}}" @@ -251,12 +259,15 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.CAMERA}}" read-only-list - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" route-path="/content/cookies" no-search> - <settings-subpage page-title="$i18n{siteSettingsCategoryCookies}"> + <settings-subpage page-title="$i18n{siteSettingsCategoryCookies}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting category="{{ContentSettingsTypes.COOKIES}}" toggle-off-label="$i18n{siteSettingsBlocked}" toggle-on-label="$i18n{siteSettingsCookiesAllowedRecommended}" @@ -278,7 +289,8 @@ </div> <category-setting-exceptions category="{{ContentSettingsTypes.COOKIES}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> @@ -292,19 +304,24 @@ </settings-subpage> </template> <template is="dom-if" route-path="/content/images" no-search> - <settings-subpage page-title="$i18n{siteSettingsCategoryImages}"> + <settings-subpage page-title="$i18n{siteSettingsCategoryImages}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting category="{{ContentSettingsTypes.IMAGES}}" toggle-off-label="$i18n{siteSettingsDontShowImages}" toggle-on-label="$i18n{siteSettingsShowAllRecommended}"> </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.IMAGES}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" route-path="/content/location" no-search> - <settings-subpage page-title="$i18n{siteSettingsCategoryLocation}"> + <settings-subpage page-title="$i18n{siteSettingsCategoryLocation}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsBlocked}" toggle-on-label="$i18n{siteSettingsAskBeforeAccessingRecommended}" @@ -312,7 +329,8 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.GEOLOCATION}}" read-only-list - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> @@ -335,7 +353,9 @@ </settings-subpage> </template> <template is="dom-if" route-path="/content/javascript" no-search> - <settings-subpage page-title="$i18n{siteSettingsCategoryJavascript}"> + <settings-subpage page-title="$i18n{siteSettingsCategoryJavascript}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsBlocked}" toggle-on-label="$i18n{siteSettingsAllowedRecommended}" @@ -343,14 +363,17 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.JAVASCRIPT}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" if="[[enableSoundContentSetting_]]" no-search> <template is="dom-if" route-path="/content/sound" no-search> - <settings-subpage page-title="$i18n{siteSettingsSound}"> + <settings-subpage page-title="$i18n{siteSettingsSound}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsSoundBlock}" toggle-on-label="$i18n{siteSettingsSoundAllowRecommended}" @@ -367,13 +390,16 @@ </settings-toggle-button> <category-setting-exceptions category="{{ContentSettingsTypes.SOUND}}" - block-header="$i18n{siteSettingsBlockSound}"> + block-header="$i18n{siteSettingsBlockSound}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> </template> <template is="dom-if" route-path="/content/microphone" no-search> - <settings-subpage page-title="$i18n{siteSettingsCategoryMicrophone}"> + <settings-subpage page-title="$i18n{siteSettingsCategoryMicrophone}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <media-picker label="$i18n{siteSettingsMicrophoneLabel}" type="mic"> </media-picker> <category-default-setting category="{{ContentSettingsTypes.MIC}}" @@ -383,13 +409,16 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.MIC}}" read-only-list - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" if="[[enableSensorsContentSetting_]]" no-search> <template is="dom-if" route-path="/content/sensors" no-search> - <settings-subpage page-title="$i18n{siteSettingsSensors}"> + <settings-subpage page-title="$i18n{siteSettingsSensors}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsSensorsBlock}" toggle-on-label="$i18n{siteSettingsSensorsAllow}" @@ -397,13 +426,16 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.SENSORS}}" read-only-list - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> </template> <template is="dom-if" route-path="/content/notifications" no-search> - <settings-subpage page-title="$i18n{siteSettingsCategoryNotifications}"> + <settings-subpage page-title="$i18n{siteSettingsCategoryNotifications}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsBlocked}" toggle-on-label="$i18n{siteSettingsAskBeforeSendingRecommended}" @@ -411,12 +443,15 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.NOTIFICATIONS}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" route-path="/content/flash" no-search> - <settings-subpage page-title="$i18n{siteSettingsFlash}"> + <settings-subpage page-title="$i18n{siteSettingsFlash}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <a class="settings-box first" tabindex="-1" target="_blank"> $i18n{siteSettingsFlashPermissionsEphemeral} @@ -437,26 +472,32 @@ </if> <category-setting-exceptions category="{{ContentSettingsTypes.PLUGINS}}" - block-header="$i18n{siteSettingsBlock}" read-only-list> + block-header="$i18n{siteSettingsBlock}" read-only-list + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" route-path="/content/popups" no-search> - <settings-subpage page-title="$i18n{siteSettingsCategoryPopups}"> + <settings-subpage page-title="$i18n{siteSettingsCategoryPopups}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting category="{{ContentSettingsTypes.POPUPS}}" toggle-off-label="$i18n{siteSettingsBlockedRecommended}" toggle-on-label="$i18n{siteSettingsAllowed}"> </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.POPUPS}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" if="[[enableSafeBrowsingSubresourceFilter_]]" no-search> <template is="dom-if" route-path="/content/ads" no-search> - <settings-subpage page-title="$i18n{siteSettingsAds}"> + <settings-subpage page-title="$i18n{siteSettingsAds}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting category="{{ContentSettingsTypes.ADS}}" toggle-off-label="$i18n{siteSettingsAdsBlockRecommended}" @@ -465,13 +506,16 @@ <category-setting-exceptions category="{{ContentSettingsTypes.ADS}}" read-only-list - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> </template> <template is="dom-if" route-path="/content/unsandboxedPlugins" no-search> - <settings-subpage page-title="$i18n{siteSettingsUnsandboxedPlugins}"> + <settings-subpage page-title="$i18n{siteSettingsUnsandboxedPlugins}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsUnsandboxedPluginsBlock}" toggle-on-label= @@ -480,12 +524,15 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.UNSANDBOXED_PLUGINS}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> <template is="dom-if" route-path="/content/midiDevices" no-search> - <settings-subpage page-title="$i18n{siteSettingsMidiDevices}"> + <settings-subpage page-title="$i18n{siteSettingsMidiDevices}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsMidiDevicesBlock}" toggle-on-label= @@ -494,7 +541,8 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.MIDI_DEVICES}}" read-only-list - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> @@ -528,7 +576,14 @@ </settings-subpage> </template> <template is="dom-if" route-path="/content/protectedContent" no-search> +<if expr="not chromeos"> <settings-subpage page-title="$i18n{siteSettingsProtectedContent}"> +</if> +<if expr="chromeos"> + <settings-subpage page-title="$i18n{siteSettingsProtectedContent}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> +</if> <settings-toggle-button class="first" pref="{{prefs.webkit.webprefs.encrypted_media_enabled}}" label="[[getProtectedContentLabel_( @@ -551,7 +606,8 @@ if="[[prefs.settings.privacy.drm_enabled.value]]"> <category-setting-exceptions category="{{ContentSettingsTypes.PROTECTED_CONTENT}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </template> </if> @@ -559,7 +615,9 @@ </template> <template is="dom-if" if="[[enableClipboardContentSetting_]]"> <template is="dom-if" route-path="/content/clipboard" no-search> - <settings-subpage page-title="$i18n{siteSettingsClipboard}"> + <settings-subpage page-title="$i18n{siteSettingsClipboard}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsClipboardBlock}" toggle-on-label="$i18n{siteSettingsClipboardAskRecommended}" @@ -567,14 +625,17 @@ </category-default-setting> <category-setting-exceptions category="{{ContentSettingsTypes.CLIPBOARD}}" - block-header="$i18n{siteSettingsBlock}"> + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template> </template> <template is="dom-if" if="[[enablePaymentHandlerContentSetting_]]"> <template is="dom-if" route-path="/content/paymentHandler" no-search> - <settings-subpage page-title="$i18n{siteSettingsPaymentHandler}"> + <settings-subpage page-title="$i18n{siteSettingsPaymentHandler}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> <category-default-setting toggle-off-label="$i18n{siteSettingsPaymentHandlerBlock}" toggle-on-label="$i18n{siteSettingsPaymentHandlerAllowRecommended}" @@ -582,7 +643,8 @@ </category-default-setting> <category-setting-exceptions category="[[ContentSettingsTypes.PAYMENT_HANDLER]]" - block-header="$i18n{siteSettingsBlocked}"> + block-header="$i18n{siteSettingsBlocked}" + search-filter="[[searchFilter_]]"> </category-setting-exceptions> </settings-subpage> </template>
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.js b/chrome/browser/resources/settings/privacy_page/privacy_page.js index 75f9ce1..12c6175 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.js +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.js
@@ -169,6 +169,9 @@ /** @private */ showSignoutDialog_: Boolean, + + /** @private */ + searchFilter_: String, }, /** @override */
diff --git a/chrome/browser/resources/settings/settings_page/settings_section.html b/chrome/browser/resources/settings/settings_page/settings_section.html index 2c5a4f4a..e4036f1 100644 --- a/chrome/browser/resources/settings/settings_page/settings_section.html +++ b/chrome/browser/resources/settings/settings_page/settings_section.html
@@ -21,7 +21,7 @@ } #header .title { - color: var(--google-grey-900); + color: var(--cr-primary-text-color); font-size: 108%; font-weight: 400; letter-spacing: .25px; @@ -33,7 +33,7 @@ :host(:not(.expanded)) #card { @apply --cr-card-elevation; - background-color: white; + background-color: var(--cr-card-background-color); border-radius: var(--cr-card-border-radius); flex: 1; }
diff --git a/chrome/browser/resources/settings/settings_page/settings_subpage.js b/chrome/browser/resources/settings/settings_page/settings_subpage.js index 07b8a16a..9fa87be75 100644 --- a/chrome/browser/resources/settings/settings_page/settings_subpage.js +++ b/chrome/browser/resources/settings/settings_page/settings_subpage.js
@@ -100,6 +100,10 @@ if (!this.searchLabel) return; + const searchField = this.$$('cr-search-field'); + if (searchField) + searchField.setValue(''); + if (this.active_) this.becomeActiveFindShortcutListener(); else
diff --git a/chrome/browser/resources/settings/settings_ui/settings_ui.html b/chrome/browser/resources/settings/settings_ui/settings_ui.html index 04069b8..d90b7a7 100644 --- a/chrome/browser/resources/settings/settings_ui/settings_ui.html +++ b/chrome/browser/resources/settings/settings_ui/settings_ui.html
@@ -39,7 +39,7 @@ cr-toolbar { @apply --layout-center; --iron-icon-fill-color: white; - background-color: var(--google-blue-700); + background-color: var(--md-toolbar-color); color: white; min-height: 56px; z-index: 2;
diff --git a/chrome/browser/resources/settings/settings_ui/settings_ui.js b/chrome/browser/resources/settings/settings_ui/settings_ui.js index f74b2f77..e8685b84 100644 --- a/chrome/browser/resources/settings/settings_ui/settings_ui.js +++ b/chrome/browser/resources/settings/settings_ui/settings_ui.js
@@ -187,6 +187,7 @@ /** @override */ detached: function() { + this.removeSelfAsFindShortcutListener(); settings.resetRouteForTesting(); },
diff --git a/chrome/browser/resources/settings/site_settings/category_setting_exceptions.html b/chrome/browser/resources/settings/site_settings/category_setting_exceptions.html index 091cc75..c837275e 100644 --- a/chrome/browser/resources/settings/site_settings/category_setting_exceptions.html +++ b/chrome/browser/resources/settings/site_settings/category_setting_exceptions.html
@@ -19,19 +19,22 @@ category="[[category]]" category-subtype="[[ContentSetting.BLOCK]]" category-header="[[blockHeader]]" - read-only-list="[[readOnlyList]]"> + read-only-list="[[readOnlyList]]" + search-filter="[[searchFilter]]"> </site-list> <site-list category="[[category]]" category-subtype="[[ContentSetting.SESSION_ONLY]]" category-header="$i18n{siteSettingsSessionOnly}" - read-only-list="[[readOnlyList]]"> + read-only-list="[[readOnlyList]]" + search-filter="[[searchFilter]]"> </site-list> <site-list category="[[category]]" category-subtype="[[ContentSetting.ALLOW]]" category-header="$i18n{siteSettingsAllow}" - read-only-list="[[readOnlyList]]"> + read-only-list="[[readOnlyList]]" + search-filter="[[searchFilter]]"> </site-list> </template> <script src="category_setting_exceptions.js"></script>
diff --git a/chrome/browser/resources/settings/site_settings/category_setting_exceptions.js b/chrome/browser/resources/settings/site_settings/category_setting_exceptions.js index 3bfe4e9..bff5aae 100644 --- a/chrome/browser/resources/settings/site_settings/category_setting_exceptions.js +++ b/chrome/browser/resources/settings/site_settings/category_setting_exceptions.js
@@ -25,6 +25,8 @@ * The heading text for the blocked exception list. */ blockHeader: String, + + searchFilter: String, }, /** @override */
diff --git a/chrome/browser/resources/settings/site_settings/site_list.html b/chrome/browser/resources/settings/site_settings/site_list.html index 6376ae9..1d6af8c 100644 --- a/chrome/browser/resources/settings/site_settings/site_list.html +++ b/chrome/browser/resources/settings/site_settings/site_list.html
@@ -65,8 +65,13 @@ <div class="list-frame" hidden$="[[hasSites_(sites.*)]]"> <div class="list-item secondary">$i18n{noSitesAdded}</div> </div> + <div class="list-frame" + hidden$="[[!showNoSearchResults_(searchFilter, sites.*)]]"> + <div class="list-item secondary">$i18n{searchNoResults}</div> + </div> <div class="list-frame menu-content vertical-list" id="listContainer"> - <iron-list items="[[sites]]" preserve-focus risk-selection> + <iron-list items="[[getFilteredSites_(searchFilter, sites.*)]]" + preserve-focus risk-selection> <template> <site-list-entry model="[[item]]" read-only-list="[[readOnlyList]]" on-show-action-menu="onShowActionMenu_" tabindex$="[[tabIndex]]"
diff --git a/chrome/browser/resources/settings/site_settings/site_list.js b/chrome/browser/resources/settings/site_settings/site_list.js index 83002ed..ff91eb2 100644 --- a/chrome/browser/resources/settings/site_settings/site_list.js +++ b/chrome/browser/resources/settings/site_settings/site_list.js
@@ -110,6 +110,8 @@ /** @private */ tooltipText_: String, + + searchFilter: String, }, // <if expr="chromeos"> @@ -213,7 +215,15 @@ * @private */ hasSites_: function() { - return !!this.sites.length; + return this.sites.length > 0; + }, + + /** + * @return {boolean} + * @private + */ + showNoSearchResults_: function() { + return this.sites.length > 0 && this.getFilteredSites_().length == 0; }, /** @@ -444,4 +454,22 @@ if (actionMenu.open) actionMenu.close(); }, + + /** + * @return {!Array<!SiteException>} + * @private + */ + getFilteredSites_: function() { + if (!this.searchFilter) + return this.sites.slice(); + + const propNames = [ + 'displayName', + 'origin', + ]; + const searchFilter = this.searchFilter.toLowerCase(); + return this.sites.filter( + site => propNames.some( + propName => site[propName].toLowerCase().includes(searchFilter))); + }, });
diff --git a/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc b/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc index dd507d6..4b35479 100644 --- a/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc
@@ -564,8 +564,9 @@ EXPECT_EQ(kLocalBillingAddressId, credit_cards[0]->billing_address_id()); } +// Disabled due to flakiness: https://crbug.com/917498. IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, - ServerAddressConvertsToSameLocalAddress) { + DISABLED_ServerAddressConvertsToSameLocalAddress) { InitWithDefaultFeatures(); GetFakeServer()->SetWalletData(
diff --git a/chrome/browser/sync_file_system/local/local_file_change_tracker.cc b/chrome/browser/sync_file_system/local/local_file_change_tracker.cc index b7278d6..14926c8 100644 --- a/chrome/browser/sync_file_system/local/local_file_change_tracker.cc +++ b/chrome/browser/sync_file_system/local/local_file_change_tracker.cc
@@ -371,8 +371,8 @@ dirty_files.pop(); DCHECK_EQ(url.type(), storage::kFileSystemTypeSyncable); - switch (file_util->GetFileInfo(context.get(), url, - &file_info, &platform_path)) { + switch (file_util->GetFileInfo(context.get(), url, &file_info, + &platform_path)) { case base::File::FILE_OK: { if (!file_info.is_directory) { RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, @@ -386,7 +386,7 @@ // Push files and directories in this directory into |dirty_files|. std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator> enumerator( - file_util->CreateFileEnumerator(context.get(), url)); + file_util->CreateFileEnumerator(context.get(), url, false)); base::FilePath path_each; while (!(path_each = enumerator->Next()).empty()) { dirty_files.push(CreateSyncableFileSystemURL(
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc index 3ae60f3..c7a981c 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc
@@ -357,6 +357,15 @@ RemoveShelfItem(id); } +void ChromeLauncherController::SetItemStatusOrRemove( + const ash::ShelfID& id, + ash::ShelfItemStatus status) { + if (!IsPinned(id) && status == ash::STATUS_CLOSED) + RemoveShelfItem(id); + else + SetItemStatus(id, status); +} + bool ChromeLauncherController::IsPinned(const ash::ShelfID& id) { const ash::ShelfItem* item = GetItem(id); return item && ItemTypeIsPinned(*item); @@ -367,10 +376,7 @@ ash::ShelfID id(app_id); const ash::ShelfItem* item = GetItem(id); if (item) { - if (!IsPinned(id) && status == ash::STATUS_CLOSED) - RemoveShelfItem(id); - else - SetItemStatus(id, status); + SetItemStatusOrRemove(id, status); } else if (status != ash::STATUS_CLOSED && !app_id.empty()) { InsertAppLauncherItem( AppShortcutLauncherItemController::Create(ash::ShelfID(app_id)), status, @@ -465,7 +471,7 @@ // Since GetAppState() will use |web_contents_to_app_id_| we remove // the connection before calling it. web_contents_to_app_id_.erase(contents); - SetItemStatus(old_id, GetAppState(old_id.app_id)); + SetItemStatusOrRemove(old_id, GetAppState(old_id.app_id)); } } @@ -474,7 +480,7 @@ else web_contents_to_app_id_[contents] = shelf_id.app_id; - SetItemStatus(shelf_id, GetAppState(shelf_id.app_id)); + SetItemStatusOrRemove(shelf_id, GetAppState(shelf_id.app_id)); } ash::ShelfID ChromeLauncherController::GetShelfIDForWebContents(
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.h b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.h index d7a6a02..5200a45 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.h +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.h
@@ -364,6 +364,10 @@ // An internal helper to unpin a shelf item; this does not update prefs. void UnpinShelfItemInternal(const ash::ShelfID& id); + // Updates the running status of an item, or removes it if necessary. + void SetItemStatusOrRemove(const ash::ShelfID& id, + ash::ShelfItemStatus status); + // Resolves the app icon image loader for the app. AppIconLoader* GetAppIconLoaderForApp(const std::string& app_id);
diff --git a/chrome/browser/ui/webui/app_management/app_management_ui.cc b/chrome/browser/ui/webui/app_management/app_management_ui.cc index 8ee5416..d61bce4 100644 --- a/chrome/browser/ui/webui/app_management/app_management_ui.cc +++ b/chrome/browser/ui/webui/app_management/app_management_ui.cc
@@ -66,6 +66,10 @@ IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML); source->AddResourcePath("browser_proxy.js", IDR_APP_MANAGEMENT_BROWSER_PROXY_JS); + source->AddResourcePath("chrome_app_permission_view.html", + IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_HTML); + source->AddResourcePath("chrome_app_permission_view.js", + IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_JS); source->AddResourcePath("constants.html", IDR_APP_MANAGEMENT_CONSTANTS_HTML); source->AddResourcePath("constants.js", IDR_APP_MANAGEMENT_CONSTANTS_JS); source->AddResourcePath("fake_page_handler.js",
diff --git a/chrome/browser/ui/webui/policy_tool_ui.cc b/chrome/browser/ui/webui/policy_tool_ui.cc index dfbc301..892d434 100644 --- a/chrome/browser/ui/webui/policy_tool_ui.cc +++ b/chrome/browser/ui/webui/policy_tool_ui.cc
@@ -59,6 +59,10 @@ IDS_POLICY_TOOL_DELETE_FAILED); // Overwrite the title value added by PolicyUIHandler. source->AddLocalizedString("title", IDS_POLICY_TOOL_TITLE); + source->AddLocalizedString("showExpandedStatus", + IDS_POLICY_SHOW_EXPANDED_STATUS); + source->AddLocalizedString("hideExpandedStatus", + IDS_POLICY_HIDE_EXPANDED_STATUS); // Add required resources. source->AddResourcePath("policy_common.css", IDR_POLICY_COMMON_CSS);
diff --git a/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc b/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc index 24cbd0b..46184041 100644 --- a/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc +++ b/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc
@@ -225,7 +225,8 @@ if (need_status) { javascript += " var status = entries[i].getElementsByClassName('status-column')[0]" - " .getElementsByTagName('div')[0].textContent;" + " " + ".getElementsByClassName('status')[0].textContent;" " policies.chromePolicies[name] = {'value': value, 'status': status};"; } else { javascript += " policies.chromePolicies[name] = {'value': value};";
diff --git a/chrome/browser/ui/webui/policy_ui.cc b/chrome/browser/ui/webui/policy_ui.cc index a3bb09c8..92c4837 100644 --- a/chrome/browser/ui/webui/policy_ui.cc +++ b/chrome/browser/ui/webui/policy_ui.cc
@@ -58,6 +58,10 @@ IDS_POLICY_SHOW_EXPANDED_VALUE); source->AddLocalizedString("hideExpandedValue", IDS_POLICY_HIDE_EXPANDED_VALUE); + source->AddLocalizedString("showExpandedStatus", + IDS_POLICY_SHOW_EXPANDED_STATUS); + source->AddLocalizedString("hideExpandedStatus", + IDS_POLICY_HIDE_EXPANDED_STATUS); source->AddLocalizedString("policyLearnMore", IDS_POLICY_LEARN_MORE); // Add required resources. #if !defined(OS_ANDROID)
diff --git a/chrome/browser/ui/webui/policy_ui_browsertest.cc b/chrome/browser/ui/webui/policy_ui_browsertest.cc index 02fe9ff5..b8c3051 100644 --- a/chrome/browser/ui/webui/policy_ui_browsertest.cc +++ b/chrome/browser/ui/webui/policy_ui_browsertest.cc
@@ -275,7 +275,8 @@ " 'section.policy-table-section > * > tbody');" "var policies = [];" "for (var i = 0; i < entries.length; ++i) {" - " var items = entries[i].querySelectorAll('tr > td');" + " var items = " + "entries[i].querySelectorAll('tr:not(.expanded-status-container) > td');" " var values = [];" " for (var j = 0; j < items.length; ++j) {" " var item = items[j];"
diff --git a/chrome/common/channel_info.cc b/chrome/common/channel_info.cc index 3e08de4..7345984 100644 --- a/chrome/common/channel_info.cc +++ b/chrome/common/channel_info.cc
@@ -13,10 +13,4 @@ return version_info::GetVersionStringWithModifier(GetChannelName()); } -version_info::Channel GetChannel() { - if (!version_info::IsChannelSet()) - version_info::SetChannel(channel_info_internal::InitChannel()); - return version_info::GetChannel(); -} - } // namespace chrome
diff --git a/chrome/common/channel_info.h b/chrome/common/channel_info.h index 48e0f6af..881a255 100644 --- a/chrome/common/channel_info.h +++ b/chrome/common/channel_info.h
@@ -51,14 +51,6 @@ std::string GetChannelSuffixForDataDir(); #endif -namespace channel_info_internal { - -// Internal platform-specific implementation to initialize the GetChannel() -// return value. -version_info::Channel InitChannel(); - -} // namespace channel_info_internal - } // namespace chrome #endif // CHROME_COMMON_CHANNEL_INFO_H_
diff --git a/chrome/common/channel_info_android.cc b/chrome/common/channel_info_android.cc index 64e74334..d73a946 100644 --- a/chrome/common/channel_info_android.cc +++ b/chrome/common/channel_info_android.cc
@@ -24,12 +24,8 @@ return std::string(); } -namespace channel_info_internal { - -version_info::Channel InitChannel() { +version_info::Channel GetChannel() { return version_info::android::GetChannel(); } -} // namespace channel_info_internal - } // namespace chrome
diff --git a/chrome/common/channel_info_chromeos.cc b/chrome/common/channel_info_chromeos.cc index 4afe0ce7..29d1dca2c 100644 --- a/chrome/common/channel_info_chromeos.cc +++ b/chrome/common/channel_info_chromeos.cc
@@ -8,20 +8,23 @@ #include "components/version_info/version_info.h" namespace chrome { - namespace { +version_info::Channel g_chromeos_channel = version_info::Channel::UNKNOWN; + #if defined(GOOGLE_CHROME_BUILD) -version_info::Channel ChannelStringToChannel(const std::string& channel) { +// Sets the |g_chromeos_channel|. +void SetChannel(const std::string& channel) { if (channel == "stable-channel") - return version_info::Channel::STABLE; - if (channel == "beta-channel") - return version_info::Channel::BETA; - if (channel == "dev-channel") - return version_info::Channel::DEV; - if (channel == "canary-channel") - return version_info::Channel::CANARY; - return version_info::Channel::UNKNOWN; + g_chromeos_channel = version_info::Channel::STABLE; + else if (channel == "beta-channel") + g_chromeos_channel = version_info::Channel::BETA; + else if (channel == "dev-channel") + g_chromeos_channel = version_info::Channel::DEV; + else if (channel == "canary-channel") + g_chromeos_channel = version_info::Channel::CANARY; + else + g_chromeos_channel = version_info::Channel::UNKNOWN; } #endif @@ -29,7 +32,7 @@ std::string GetChannelName() { #if defined(GOOGLE_CHROME_BUILD) - switch (GetChannel()) { + switch (g_chromeos_channel) { case version_info::Channel::STABLE: return std::string(); case version_info::Channel::BETA: @@ -45,6 +48,22 @@ return std::string(); } +version_info::Channel GetChannel() { + static bool is_channel_set = false; + if (is_channel_set) + return g_chromeos_channel; + +#if defined(GOOGLE_CHROME_BUILD) + static const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK"; + std::string channel; + if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel)) { + SetChannel(channel); + is_channel_set = true; + } +#endif + return g_chromeos_channel; +} + #if defined(GOOGLE_CHROME_BUILD) std::string GetChannelSuffixForDataDir() { // ChromeOS doesn't support side-by-side installations. @@ -52,18 +71,4 @@ } #endif // defined(GOOGLE_CHROME_BUILD) -namespace channel_info_internal { - -version_info::Channel InitChannel() { -#if defined(GOOGLE_CHROME_BUILD) - static const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK"; - std::string channel; - if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel)) - return ChannelStringToChannel(channel); -#endif - return version_info::Channel::UNKNOWN; -} - -} // namespace channel_info_internal - } // namespace chrome
diff --git a/chrome/common/channel_info_mac.mm b/chrome/common/channel_info_mac.mm index f3fc0ad..08ffef5c 100644 --- a/chrome/common/channel_info_mac.mm +++ b/chrome/common/channel_info_mac.mm
@@ -55,12 +55,8 @@ return version_info::Channel::UNKNOWN; } -namespace channel_info_internal { - -version_info::Channel InitChannel() { +version_info::Channel GetChannel() { return GetChannelByName(GetChannelName()); } -} // namespace channel_info_internal - } // namespace chrome
diff --git a/chrome/common/channel_info_posix.cc b/chrome/common/channel_info_posix.cc index a538c6d3..7978d18 100644 --- a/chrome/common/channel_info_posix.cc +++ b/chrome/common/channel_info_posix.cc
@@ -67,12 +67,8 @@ } #endif // defined(GOOGLE_CHROME_BUILD) -namespace channel_info_internal { - -version_info::Channel InitChannel() { +version_info::Channel GetChannel() { return GetChannelImpl(nullptr, nullptr); } -} // namespace channel_info_internal - } // namespace chrome
diff --git a/chrome/common/channel_info_win.cc b/chrome/common/channel_info_win.cc index 323dc007..b40e2ef0 100644 --- a/chrome/common/channel_info_win.cc +++ b/chrome/common/channel_info_win.cc
@@ -25,12 +25,8 @@ #endif } -namespace channel_info_internal { - -version_info::Channel InitChannel() { +version_info::Channel GetChannel() { return install_static::GetChromeChannel(); } -} // namespace channel_info_internal - } // namespace chrome
diff --git a/chrome/test/chromedriver/logging.cc b/chrome/test/chromedriver/logging.cc index 6819978..96f5e703 100644 --- a/chrome/test/chromedriver/logging.cc +++ b/chrome/test/chromedriver/logging.cc
@@ -25,6 +25,7 @@ #include "chrome/test/chromedriver/devtools_events_logger.h" #include "chrome/test/chromedriver/performance_logger.h" #include "chrome/test/chromedriver/session.h" +#include "chrome/test/chromedriver/version.h" #if defined(OS_POSIX) #include <fcntl.h> @@ -253,6 +254,7 @@ printf("Failed to redirect stderr to log file.\n"); return false; } + VLOG(0) << "Starting ChromeDriver " << kChromeDriverVersion; } Log::truncate_logged_params = !cmd_line->HasSwitch("replayable");
diff --git a/chrome/test/chromedriver/server/http_handler.cc b/chrome/test/chromedriver/server/http_handler.cc index c5804732..b898e6a 100644 --- a/chrome/test/chromedriver/server/http_handler.cc +++ b/chrome/test/chromedriver/server/http_handler.cc
@@ -847,10 +847,17 @@ CommandMap::const_iterator iter = command_map_->begin(); while (true) { if (iter == command_map_->end()) { - std::unique_ptr<net::HttpServerResponseInfo> response( - new net::HttpServerResponseInfo(net::HTTP_NOT_FOUND)); - response->SetBody("unknown command: " + trimmed_path, "text/plain"); - send_response_func.Run(std::move(response)); + if (kW3CDefault) { + PrepareResponse( + trimmed_path, send_response_func, + Status(kUnknownCommand, "unknown command: " + trimmed_path), + nullptr, session_id, kW3CDefault); + } else { + std::unique_ptr<net::HttpServerResponseInfo> response( + new net::HttpServerResponseInfo(net::HTTP_NOT_FOUND)); + response->SetBody("unknown command: " + trimmed_path, "text/plain"); + send_response_func.Run(std::move(response)); + } return; } if (internal::MatchesCommand( @@ -865,13 +872,26 @@ std::unique_ptr<base::Value> parsed_body = base::JSONReader::Read(request.data); if (!parsed_body || !parsed_body->GetAsDictionary(&body_params)) { - std::unique_ptr<net::HttpServerResponseInfo> response( - new net::HttpServerResponseInfo(net::HTTP_BAD_REQUEST)); - response->SetBody("missing command parameters", "text/plain"); - send_response_func.Run(std::move(response)); + if (kW3CDefault) { + PrepareResponse(trimmed_path, send_response_func, + Status(kInvalidArgument, "missing command parameters"), + nullptr, session_id, kW3CDefault); + } else { + std::unique_ptr<net::HttpServerResponseInfo> response( + new net::HttpServerResponseInfo(net::HTTP_BAD_REQUEST)); + response->SetBody("missing command parameters", "text/plain"); + send_response_func.Run(std::move(response)); + } return; } params.MergeDictionary(body_params); + } else if (kW3CDefault && iter->method == kPost) { + // Data in JSON format is required for POST requests. See step 5 of + // https://www.w3.org/TR/2018/REC-webdriver1-20180605/#processing-model. + PrepareResponse(trimmed_path, send_response_func, + Status(kInvalidArgument, "missing command parameters"), + nullptr, session_id, kW3CDefault); + return; } iter->command.Run(params,
diff --git a/chrome/test/chromedriver/server/http_handler_unittest.cc b/chrome/test/chromedriver/server/http_handler_unittest.cc index b726b02..c20682a 100644 --- a/chrome/test/chromedriver/server/http_handler_unittest.cc +++ b/chrome/test/chromedriver/server/http_handler_unittest.cc
@@ -66,6 +66,7 @@ net::HttpServerRequestInfo request; request.method = "post"; request.path = "/base/session"; + request.data = "{}"; net::HttpServerResponseInfo response; handler.Handle(request, base::Bind(&OnResponse, &response)); ASSERT_EQ(net::HTTP_OK, response.status_code()); @@ -99,6 +100,7 @@ net::HttpServerRequestInfo request; request.method = "post"; request.path = "/path"; + request.data = "{}"; net::HttpServerResponseInfo response; handler.Handle(request, base::Bind(&OnResponse, &response)); ASSERT_EQ(net::HTTP_NOT_IMPLEMENTED, response.status_code()); @@ -111,6 +113,7 @@ net::HttpServerRequestInfo request; request.method = "post"; request.path = "/path"; + request.data = "{}"; net::HttpServerResponseInfo response; handler.Handle(request, base::Bind(&OnResponse, &response)); ASSERT_EQ(net::HTTP_OK, response.status_code());
diff --git a/chrome/test/data/webui/settings/find_shortcut_behavior_test.js b/chrome/test/data/webui/settings/find_shortcut_behavior_test.js index d88b868..7a3db418 100644 --- a/chrome/test/data/webui/settings/find_shortcut_behavior_test.js +++ b/chrome/test/data/webui/settings/find_shortcut_behavior_test.js
@@ -88,8 +88,11 @@ const resolver = new PromiseResolver(); const handler = e => { window.removeEventListener('keydown', handler); - if (e.defaultPrevented == defaultPrevented) + if (e.defaultPrevented == defaultPrevented) { resolver.resolve(); + } else { + resolver.reject(); + } }; window.addEventListener('keydown', handler); return resolver.promise; @@ -161,6 +164,20 @@ ]); }); + test('can remove listeners out of order', () => { + document.body.innerHTML = ` + <find-shortcut-element></find-shortcut-element> + <find-shortcut-element></find-shortcut-element>`; + const testElements = + document.body.querySelectorAll('find-shortcut-element'); + testElements[0].becomeActiveFindShortcutListener(); + testElements[1].becomeActiveFindShortcutListener(); + testElements[0].removeSelfAsFindShortcutListener(); + return check(testElements[1]).then(() => { + testElements[1].removeSelfAsFindShortcutListener(); + }); + }); + test('removing self when not active throws exception', () => { document.body.innerHTML = `<find-shortcut-element></find-shortcut-element>`; const testElement = document.body.querySelector('find-shortcut-element'); @@ -175,6 +192,19 @@ }); }); + test('becoming active when an inactive listener throws exception', () => { + document.body.innerHTML = ` + <find-shortcut-element></find-shortcut-element> + <find-shortcut-element></find-shortcut-element>`; + const testElements = + document.body.querySelectorAll('find-shortcut-element'); + return listenScope(testElements[0])( + () => listenScope(testElements[1])(() => { + assertThrows( + () => testElements[0].becomeActiveFindShortcutListener()); + })); + }); + test('cmd+ctrl+f bubbles up (defaultPrevented=false)', () => { const bubbledUp = listenOnceAndCheckDefaultPrevented(false); document.body.innerHTML = `<find-shortcut-element></find-shortcut-element>`;
diff --git a/chrome/test/data/webui/settings/site_list_tests.js b/chrome/test/data/webui/settings/site_list_tests.js index 3d89945..728e884 100644 --- a/chrome/test/data/webui/settings/site_list_tests.js +++ b/chrome/test/data/webui/settings/site_list_tests.js
@@ -294,6 +294,7 @@ settings.SiteSettingsPrefsBrowserProxyImpl.instance_ = browserProxy; PolymerTest.clearBody(); testElement = document.createElement('site-list'); + testElement.searchFilter = ''; document.body.appendChild(testElement); if (cr.isChromeOS) {
diff --git a/chromecast/media/cma/decoder/cast_audio_decoder.cc b/chromecast/media/cma/decoder/cast_audio_decoder.cc index 63a33da..dad1ac731 100644 --- a/chromecast/media/cma/decoder/cast_audio_decoder.cc +++ b/chromecast/media/cma/decoder/cast_audio_decoder.cc
@@ -28,6 +28,7 @@ #include "media/base/channel_layout.h" #include "media/base/channel_mixer.h" #include "media/base/decoder_buffer.h" +#include "media/base/media_util.h" #include "media/base/sample_format.h" #include "media/filters/ffmpeg_audio_decoder.h" @@ -292,7 +293,7 @@ result); } - ::media::MediaLog media_log_; + ::media::NullMediaLog media_log_; const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; InitializedCallback initialized_callback_; OutputFormat output_format_;
diff --git a/chromecast/media/cma/test/frame_segmenter_for_test.cc b/chromecast/media/cma/test/frame_segmenter_for_test.cc index 8f0c7ef6..f5d554e 100644 --- a/chromecast/media/cma/test/frame_segmenter_for_test.cc +++ b/chromecast/media/cma/test/frame_segmenter_for_test.cc
@@ -14,8 +14,8 @@ #include "chromecast/media/cma/base/decoder_buffer_adapter.h" #include "media/base/decoder_buffer.h" #include "media/base/demuxer.h" -#include "media/base/media_log.h" #include "media/base/media_tracks.h" +#include "media/base/media_util.h" #include "media/base/test_helpers.h" #include "media/filters/ffmpeg_demuxer.h" #include "media/filters/file_data_source.h" @@ -308,7 +308,7 @@ ::media::FileDataSource data_source; CHECK(data_source.Initialize(filepath)); - ::media::MediaLog media_log; + ::media::NullMediaLog media_log; ::media::FFmpegDemuxer demuxer( base::ThreadTaskRunnerHandle::Get(), &data_source, base::BindRepeating(&OnEncryptedMediaInitData),
diff --git a/chromeos/chromeos_switches.cc b/chromeos/chromeos_switches.cc index a5ca6165..340e9893 100644 --- a/chromeos/chromeos_switches.cc +++ b/chromeos/chromeos_switches.cc
@@ -52,7 +52,7 @@ base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kShowLanguageToggleInDemoMode{ - "ShowLanguageToggleInDemoMode", base::FEATURE_DISABLED_BY_DEFAULT}; + "ShowLanguageToggleInDemoMode", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kShowPlayInDemoMode{"ShowPlayInDemoMode", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/gwp_asan/README.md b/components/gwp_asan/README.md index 90fe485..25ba166 100644 --- a/components/gwp_asan/README.md +++ b/components/gwp_asan/README.md
@@ -1,5 +1,6 @@ GWP-ASan is a sampling debug allocator, similar to ElectricFence or Page Heap, -intended to detect heap memory errors in the wild. When crashes in a GWP-ASan -allocation are detected in the crash handler, additional debug information about -the allocation/deallocation context is added to the crash minidump. See -[GWP-ASan documentation](/docs/gwp_asan.md) for more information. +intended to detect heap memory errors in the wild. When memory errors with a +GWP-ASan allocation occur, the process crashes and the crash handler detects +that the exception happened in a GWP-ASan allocation and adds additional debug +information about the allocation/deallocation context to the crash minidump. See +the [GWP-ASan documentation](/docs/gwp_asan.md) for more information.
diff --git a/components/password_manager/content/browser/content_password_manager_driver.cc b/components/password_manager/content/browser/content_password_manager_driver.cc index 539fb562..9bc928f9 100644 --- a/components/password_manager/content/browser/content_password_manager_driver.cc +++ b/components/password_manager/content/browser/content_password_manager_driver.cc
@@ -174,6 +174,7 @@ !navigation_handle->IsSameDocument()) { NotifyDidNavigateMainFrame(navigation_handle->IsRendererInitiated(), navigation_handle->GetPageTransition(), + navigation_handle->HasUserGesture(), GetPasswordManager()); GetPasswordAutofillManager()->DidNavigateMainFrame(); }
diff --git a/components/password_manager/content/browser/form_submission_tracker_util.cc b/components/password_manager/content/browser/form_submission_tracker_util.cc index 4ef86c4c..0e4c3e5 100644 --- a/components/password_manager/content/browser/form_submission_tracker_util.cc +++ b/components/password_manager/content/browser/form_submission_tracker_util.cc
@@ -11,15 +11,23 @@ void NotifyDidNavigateMainFrame(bool is_renderer_initiated, ui::PageTransition transition, + bool has_user_gesture, FormSubmissionObserver* observer) { DCHECK(observer); - // Password manager isn't interested in - // - user initiated navigations (e.g. click on the bookmark), - // - hyperlink navigations. + // Password manager is interested in + // - form submission navigations, + // - any JavaScript initiated navigations (i.e. renderer initiated navigations + // without user gesture), because many form submissions are done with + // JavaScript. + // Password manager is not interested in + // - browser initiated navigations (e.g. reload, bookmark click), + // - hyperlink navigations (which are renderer navigations with user gesture). bool form_may_be_submitted = is_renderer_initiated && - !ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_LINK); + (ui::PageTransitionCoreTypeIs(transition, + ui::PAGE_TRANSITION_FORM_SUBMIT) || + !has_user_gesture); observer->DidNavigateMainFrame(form_may_be_submitted); }
diff --git a/components/password_manager/content/browser/form_submission_tracker_util.h b/components/password_manager/content/browser/form_submission_tracker_util.h index 8103c06..f91101a 100644 --- a/components/password_manager/content/browser/form_submission_tracker_util.h +++ b/components/password_manager/content/browser/form_submission_tracker_util.h
@@ -15,6 +15,7 @@ // form submision. void NotifyDidNavigateMainFrame(bool is_renderer_initiated, ui::PageTransition transition, + bool has_user_gesture, FormSubmissionObserver* observer); } // namespace password_manager
diff --git a/components/password_manager/content/browser/form_submission_tracker_util_unittest.cc b/components/password_manager/content/browser/form_submission_tracker_util_unittest.cc index 10ecc9b..76685fdf 100644 --- a/components/password_manager/content/browser/form_submission_tracker_util_unittest.cc +++ b/components/password_manager/content/browser/form_submission_tracker_util_unittest.cc
@@ -33,21 +33,35 @@ }; TEST_F(FormSubmissionTrackerUtilTest, NotRendererInitiated) { - EXPECT_CALL(observer(), DidNavigateMainFrame(false)); + EXPECT_CALL(observer(), + DidNavigateMainFrame(false /* form_may_be_submitted */)); NotifyDidNavigateMainFrame(false /* is_renderer_initiated */, - ui::PAGE_TRANSITION_FORM_SUBMIT, &observer()); + ui::PAGE_TRANSITION_RELOAD, + true /* has_user_gesture */, &observer()); } TEST_F(FormSubmissionTrackerUtilTest, LinkTransition) { - EXPECT_CALL(observer(), DidNavigateMainFrame(false)); + EXPECT_CALL(observer(), + DidNavigateMainFrame(false /* form_may_be_submitted */)); NotifyDidNavigateMainFrame(true /* is_renderer_initiated */, - ui::PAGE_TRANSITION_LINK, &observer()); + ui::PAGE_TRANSITION_LINK, + true /* has_user_gesture */, &observer()); } -TEST_F(FormSubmissionTrackerUtilTest, RendererInitiatedFormSubmit) { - EXPECT_CALL(observer(), DidNavigateMainFrame(true)); +TEST_F(FormSubmissionTrackerUtilTest, FormSubmission) { + EXPECT_CALL(observer(), + DidNavigateMainFrame(true /* form_may_be_submitted */)); NotifyDidNavigateMainFrame(true /* is_renderer_initiated */, - ui::PAGE_TRANSITION_FORM_SUBMIT, &observer()); + ui::PAGE_TRANSITION_FORM_SUBMIT, + true /* has_user_gesture */, &observer()); +} + +TEST_F(FormSubmissionTrackerUtilTest, PageRedirectAfterJavaScriptSubmission) { + EXPECT_CALL(observer(), + DidNavigateMainFrame(true /* form_may_be_submitted */)); + NotifyDidNavigateMainFrame(true /* is_renderer_initiated */, + ui::PAGE_TRANSITION_CLIENT_REDIRECT, + false /* has_user_gesture */, &observer()); } } // namespace
diff --git a/components/password_manager/core/browser/new_password_form_manager.cc b/components/password_manager/core/browser/new_password_form_manager.cc index 8448399..562dc4e0 100644 --- a/components/password_manager/core/browser/new_password_form_manager.cc +++ b/components/password_manager/core/browser/new_password_form_manager.cc
@@ -562,6 +562,9 @@ } void NewPasswordFormManager::Fill() { + if (!driver_) + return; + waiting_for_server_predictions_ = false; if (form_fetcher_->GetState() == FormFetcher::State::WAITING) @@ -583,11 +586,6 @@ RecordMetricOnCompareParsingResult(*observed_password_form); - // TODO(https://crbug.com/831123). Move this lines to the beginning of the - // function when the old parsing is removed. - if (!driver_) - return; - if (observed_password_form->is_new_password_reliable && !IsBlacklisted()) { driver_->FormEligibleForGenerationFound( {.new_password_renderer_id =
diff --git a/components/policy_strings.grdp b/components/policy_strings.grdp index 5c93369..492691fd 100644 --- a/components/policy_strings.grdp +++ b/components/policy_strings.grdp
@@ -476,4 +476,10 @@ <message name="IDS_POLICY_RISK_TAG_GOOGLE_SHARING" desc="Title of a group/tag whose policies enable functionality that might share user data with trusted Google services."> Sharing with Google </message> + <message name="IDS_POLICY_SHOW_EXPANDED_STATUS" desc="Text for the link that shows the policy status. Used when the policy status is too long to be always visible."> + Show status + </message> + <message name="IDS_POLICY_HIDE_EXPANDED_STATUS" desc="Text for the link that hides the policy status. Used when the policy status is too long to be always visible."> + Hide status + </message> </grit-part>
diff --git a/components/previews/content/previews_content_util.cc b/components/previews/content/previews_content_util.cc index 2f69d853..c851c0a1 100644 --- a/components/previews/content/previews_content_util.cc +++ b/components/previews/content/previews_content_util.cc
@@ -72,8 +72,7 @@ bool has_page_hints = false; if (should_load_page_hints) { // Initiate load of any applicable page hint details. - // TODO(dougarnett): Generalize method name to LoadPageHints(). - has_page_hints = previews_decider->LoadResourceHints(url); + has_page_hints = previews_decider->LoadPageHints(url); } // Note: this is for the beginning of navigation so we should not
diff --git a/components/previews/content/previews_content_util_unittest.cc b/components/previews/content/previews_content_util_unittest.cc index 707bd5c..2180f4e 100644 --- a/components/previews/content/previews_content_util_unittest.cc +++ b/components/previews/content/previews_content_util_unittest.cc
@@ -42,7 +42,7 @@ return IsEnabled(type); } - bool LoadResourceHints(const GURL& url) override { + bool LoadPageHints(const GURL& url) override { return url.host_piece().ends_with("hintcachedhost.com"); }
diff --git a/components/previews/content/previews_decider_impl.cc b/components/previews/content/previews_decider_impl.cc index 48e7483..72da57c7 100644 --- a/components/previews/content/previews_decider_impl.cc +++ b/components/previews/content/previews_decider_impl.cc
@@ -158,13 +158,6 @@ previews_ui_service_->OnBlacklistCleared(time); } -void PreviewsDeciderImpl::OnResourceLoadingHints( - const GURL& document_gurl, - const std::vector<std::string>& patterns_to_block) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - // TODO(dougarnett): Add metrics or deprecate. -} - void PreviewsDeciderImpl::SetPreviewsBlacklistForTesting( std::unique_ptr<PreviewsBlackList> previews_back_list) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -348,11 +341,9 @@ return PreviewsEligibilityReason::ALLOWED; } -bool PreviewsDeciderImpl::LoadResourceHints(const GURL& url) { +bool PreviewsDeciderImpl::LoadPageHints(const GURL& url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return previews_opt_guide_->MaybeLoadOptimizationHints( - url, base::BindOnce(&PreviewsDeciderImpl::OnResourceLoadingHints, - weak_factory_.GetWeakPtr())); + return previews_opt_guide_->MaybeLoadOptimizationHints(url); } bool PreviewsDeciderImpl::GetResourceLoadingHints(
diff --git a/components/previews/content/previews_decider_impl.h b/components/previews/content/previews_decider_impl.h index 9b3c6f1..aab49cc 100644 --- a/components/previews/content/previews_decider_impl.h +++ b/components/previews/content/previews_decider_impl.h
@@ -116,7 +116,7 @@ void SetIgnoreLongTermBlackListForServerPreviews( bool ignore_long_term_blacklist_for_server_previews); - bool LoadResourceHints(const GURL& url) override; + bool LoadPageHints(const GURL& url) override; bool GetResourceLoadingHints( const GURL& url, @@ -132,11 +132,6 @@ net::EffectiveConnectionType effective_connection_type); protected: - // Posts a task to deliver the resource patterns to the PreviewsUIService. - void OnResourceLoadingHints( - const GURL& document_gurl, - const std::vector<std::string>& patterns_to_block); - // Sets a blacklist for testing. void SetPreviewsBlacklistForTesting( std::unique_ptr<PreviewsBlackList> previews_back_list);
diff --git a/components/previews/content/previews_optimization_guide.cc b/components/previews/content/previews_optimization_guide.cc index 4e85f873..bd697e2 100644 --- a/components/previews/content/previews_optimization_guide.cc +++ b/components/previews/content/previews_optimization_guide.cc
@@ -64,47 +64,14 @@ } void PreviewsOptimizationGuide::OnLoadedHint( - ResourceLoadingHintsCallback callback, const GURL& document_url, const optimization_guide::proto::Hint& loaded_hint) const { DCHECK(ui_task_runner_->BelongsToCurrentThread()); - // TODO(dougarnett): Drop this load callback. - const optimization_guide::proto::PageHint* matched_page_hint = - PreviewsHints::FindPageHint(document_url, loaded_hint); - if (!matched_page_hint) - return; - - // Retrieve the resource patterns to be blocked from the page hint. - std::vector<std::string> resource_patterns_to_block; - for (const auto& optimization : - matched_page_hint->whitelisted_optimizations()) { - if (optimization.optimization_type() != - optimization_guide::proto::RESOURCE_LOADING) { - continue; - } - - // TODO(jegray): When persistence is added for hints, address handling of - // disabled experimental optimizations. - for (const auto& resource_loading_hint : - optimization.resource_loading_hints()) { - if (!resource_loading_hint.resource_pattern().empty() && - resource_loading_hint.loading_optimization_type() == - optimization_guide::proto::LOADING_BLOCK_RESOURCE) { - resource_patterns_to_block.push_back( - resource_loading_hint.resource_pattern()); - } - } - break; - } - if (!resource_patterns_to_block.empty()) { - std::move(callback).Run(document_url, resource_patterns_to_block); - } + // TODO(dougarnett): Consider UMA to capture here else drop this callback. } -bool PreviewsOptimizationGuide::MaybeLoadOptimizationHints( - const GURL& url, - ResourceLoadingHintsCallback callback) { +bool PreviewsOptimizationGuide::MaybeLoadOptimizationHints(const GURL& url) { DCHECK(ui_task_runner_->BelongsToCurrentThread()); if (!hints_) @@ -112,8 +79,7 @@ return hints_->MaybeLoadOptimizationHints( url, base::BindOnce(&PreviewsOptimizationGuide::OnLoadedHint, - ui_weak_ptr_factory_.GetWeakPtr(), - std::move(callback), url)); + ui_weak_ptr_factory_.GetWeakPtr(), url)); } bool PreviewsOptimizationGuide::GetResourceLoadingHints(
diff --git a/components/previews/content/previews_optimization_guide.h b/components/previews/content/previews_optimization_guide.h index b0dd804..6eec1202 100644 --- a/components/previews/content/previews_optimization_guide.h +++ b/components/previews/content/previews_optimization_guide.h
@@ -31,10 +31,6 @@ class PreviewsHints; class PreviewsUserData; -using ResourceLoadingHintsCallback = base::OnceCallback<void( - const GURL& document_gurl, - const std::vector<std::string>& resource_patterns_to_block)>; - // A Previews optimization guide that makes decisions guided by hints received // from the OptimizationGuideService. class PreviewsOptimizationGuide @@ -65,8 +61,7 @@ // (specifically, PageHints). If so, but the hints are not available // synchronously, this method will request that they be loaded (from disk or // network). - bool MaybeLoadOptimizationHints(const GURL& url, - ResourceLoadingHintsCallback callback); + bool MaybeLoadOptimizationHints(const GURL& url); // Whether |url| has loaded resource loading hints and, if it does, populates // |out_resource_patterns_to_block| with the resource patterns to block. @@ -89,12 +84,8 @@ // Updates the hints to the latest hints sent by the Component Updater. void UpdateHints(std::unique_ptr<PreviewsHints> hints); - // Handles a loaded hint. It checks if the |loaded_hint| has any page hint - // that apply to |doucment_url|. If so, it looks for any applicable resource - // loading hints and will call |callback| with the applicable resource loading - // details if found. - void OnLoadedHint(ResourceLoadingHintsCallback callback, - const GURL& document_url, + // Callback when a hint is loaded. + void OnLoadedHint(const GURL& document_url, const optimization_guide::proto::Hint& loaded_hint) const; // The OptimizationGuideService that this guide is listening to. Not owned.
diff --git a/components/previews/content/previews_optimization_guide_unittest.cc b/components/previews/content/previews_optimization_guide_unittest.cc index f7a0e47..0738a3c5 100644 --- a/components/previews/content/previews_optimization_guide_unittest.cc +++ b/components/previews/content/previews_optimization_guide_unittest.cc
@@ -88,13 +88,6 @@ guide_->OnHintsComponentAvailable(info); } - void MaybeLoadOptimizationHintsCallback( - const GURL& document_gurl, - const std::vector<std::string>& resource_patterns) { - loaded_hints_document_gurl_ = document_gurl; - loaded_hints_resource_patterns_ = resource_patterns; - } - void ResetGuide() { guide_.reset(); RunUntilIdle(); @@ -102,13 +95,6 @@ base::FilePath temp_dir() const { return temp_dir_.GetPath(); } - const GURL& loaded_hints_document_gurl() const { - return loaded_hints_document_gurl_; - } - const std::vector<std::string>& loaded_hints_resource_patterns() const { - return loaded_hints_resource_patterns_; - } - protected: void RunUntilIdle() { scoped_task_environment_.RunUntilIdle(); @@ -153,9 +139,6 @@ std::unique_ptr<PreviewsOptimizationGuide> guide_; std::unique_ptr<TestOptimizationGuideService> optimization_guide_service_; - GURL loaded_hints_document_gurl_; - std::vector<std::string> loaded_hints_resource_patterns_; - DISALLOW_COPY_AND_ASSIGN(PreviewsOptimizationGuideTest); }; @@ -879,15 +862,12 @@ InitializeFixedCountResourceLoadingHints(); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain.org/"))); EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain.org/"), base::DoNothing())); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.somedomain.org/news/football"), - base::BindOnce( - &PreviewsOptimizationGuideTest::MaybeLoadOptimizationHintsCallback, - base::Unretained(this)))); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.unknown.com"), base::DoNothing())); + GURL("https://www.somedomain.org/news/football"))); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://www.unknown.com"))); RunUntilIdle(); histogram_tester.ExpectUniqueSample( @@ -897,12 +877,6 @@ histogram_tester.ExpectUniqueSample( "ResourceLoadingHints.PageHints.TotalReceived", 2, 1); - // Verify loaded hint data for www.somedomain.org - EXPECT_EQ(GURL("https://www.somedomain.org/news/football"), - loaded_hints_document_gurl()); - EXPECT_EQ(1ul, loaded_hints_resource_patterns().size()); - EXPECT_EQ("news_cruft.js", loaded_hints_resource_patterns().front()); - PreviewsUserData user_data(kDefaultPageId); net::EffectiveConnectionType ect_threshold; // Verify whitelisting from loaded page hints. @@ -927,15 +901,12 @@ InitializeFixedCountResourceLoadingHintsWithTwoExperiments(); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain.org/"))); EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain.org/"), base::DoNothing())); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.somedomain.org/news/football"), - base::BindOnce( - &PreviewsOptimizationGuideTest::MaybeLoadOptimizationHintsCallback, - base::Unretained(this)))); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.unknown.com"), base::DoNothing())); + GURL("https://www.somedomain.org/news/football"))); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://www.unknown.com"))); RunUntilIdle(); histogram_tester.ExpectUniqueSample( @@ -945,10 +916,6 @@ histogram_tester.ExpectUniqueSample( "ResourceLoadingHints.PageHints.TotalReceived", 0, 1); - // Verify loaded hint data for www.somedomain.org - EXPECT_EQ(GURL(), loaded_hints_document_gurl()); - EXPECT_EQ(0ul, loaded_hints_resource_patterns().size()); - PreviewsUserData user_data(kDefaultPageId); net::EffectiveConnectionType ect_threshold; // Verify whitelisting from loaded page hints. @@ -978,15 +945,12 @@ InitializeFixedCountResourceLoadingHintsWithTwoExperiments(); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain.org/"))); EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain.org/"), base::DoNothing())); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.somedomain.org/news/football"), - base::BindOnce( - &PreviewsOptimizationGuideTest::MaybeLoadOptimizationHintsCallback, - base::Unretained(this)))); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.unknown.com"), base::DoNothing())); + GURL("https://www.somedomain.org/news/football"))); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://www.unknown.com"))); RunUntilIdle(); histogram_tester.ExpectUniqueSample( @@ -996,12 +960,6 @@ histogram_tester.ExpectUniqueSample( "ResourceLoadingHints.PageHints.TotalReceived", 1, 1); - // Verify loaded hint data for www.somedomain.org - EXPECT_EQ(GURL("https://www.somedomain.org/news/football"), - loaded_hints_document_gurl()); - EXPECT_EQ(1ul, loaded_hints_resource_patterns().size()); - EXPECT_EQ("news_cruft.js", loaded_hints_resource_patterns().front()); - PreviewsUserData user_data(kDefaultPageId); net::EffectiveConnectionType ect_threshold; // Verify whitelisting from loaded page hints. @@ -1031,15 +989,12 @@ InitializeFixedCountResourceLoadingHintsWithTwoExperiments(); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain.org/"))); EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain.org/"), base::DoNothing())); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.somedomain.org/news/football"), - base::BindOnce( - &PreviewsOptimizationGuideTest::MaybeLoadOptimizationHintsCallback, - base::Unretained(this)))); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.unknown.com"), base::DoNothing())); + GURL("https://www.somedomain.org/news/football"))); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://www.unknown.com"))); RunUntilIdle(); histogram_tester.ExpectUniqueSample( @@ -1049,12 +1004,6 @@ histogram_tester.ExpectUniqueSample( "ResourceLoadingHints.PageHints.TotalReceived", 1, 1); - // Verify loaded hint data for www.somedomain.org - EXPECT_EQ(GURL("https://www.somedomain.org/news/football"), - loaded_hints_document_gurl()); - EXPECT_EQ(1ul, loaded_hints_resource_patterns().size()); - EXPECT_EQ("football_cruft.js", loaded_hints_resource_patterns().front()); - PreviewsUserData user_data(kDefaultPageId); net::EffectiveConnectionType ect_threshold; // Verify whitelisting from loaded page hints. @@ -1085,15 +1034,12 @@ InitializeFixedCountResourceLoadingHintsWithTwoExperiments(); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain.org/"))); EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain.org/"), base::DoNothing())); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.somedomain.org/news/football"), - base::BindOnce( - &PreviewsOptimizationGuideTest::MaybeLoadOptimizationHintsCallback, - base::Unretained(this)))); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.unknown.com"), base::DoNothing())); + GURL("https://www.somedomain.org/news/football"))); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://www.unknown.com"))); RunUntilIdle(); histogram_tester.ExpectUniqueSample( @@ -1103,12 +1049,6 @@ histogram_tester.ExpectUniqueSample( "ResourceLoadingHints.PageHints.TotalReceived", 1, 1); - // Verify loaded hint data for www.somedomain.org - EXPECT_EQ(GURL("https://www.somedomain.org/news/football"), - loaded_hints_document_gurl()); - EXPECT_EQ(1ul, loaded_hints_resource_patterns().size()); - EXPECT_EQ("news_cruft.js", loaded_hints_resource_patterns().front()); - PreviewsUserData user_data(kDefaultPageId); net::EffectiveConnectionType ect_threshold; // Verify whitelisting from loaded page hints. @@ -1148,20 +1088,20 @@ InitializeMultipleResourceLoadingHints(key_count, page_patterns_per_key); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain0.org/"))); EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain0.org/"), base::DoNothing())); + GURL("https://somedomain0.org/news0/football"))); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain19.org/"))); EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain0.org/news0/football"), base::DoNothing())); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain19.org/"), base::DoNothing())); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain19.org/news0/football"), base::DoNothing())); + GURL("https://somedomain19.org/news0/football"))); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain20.org/"))); EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain20.org/"), base::DoNothing())); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain20.org/news0/football"), base::DoNothing())); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.unknown.com"), base::DoNothing())); + GURL("https://somedomain20.org/news0/football"))); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://www.unknown.com"))); EXPECT_TRUE(guide()->IsWhitelisted( &user_data, GURL("https://www.somedomain0.org/news0/football"), @@ -1228,8 +1168,8 @@ InitializeMultipleResourceLoadingHints(key_count, page_patterns_per_key); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain0.org/"), base::DoNothing())); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain0.org/"))); EXPECT_TRUE(guide()->IsWhitelisted( &user_data, GURL("https://www.somedomain0.org/news0/football"), PreviewsType::RESOURCE_LOADING_HINTS, &ect_threshold)); @@ -1240,8 +1180,8 @@ &user_data, GURL("https://www.somedomain0.org/news25/football"), PreviewsType::RESOURCE_LOADING_HINTS, &ect_threshold)); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain19.org/"), base::DoNothing())); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain19.org/"))); EXPECT_TRUE(guide()->IsWhitelisted( &user_data, GURL("https://www.somedomain19.org/news0/football"), PreviewsType::RESOURCE_LOADING_HINTS, &ect_threshold)); @@ -1254,8 +1194,8 @@ // The last page pattern should be dropped since it exceeds the threshold // count. - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain20.org/"), base::DoNothing())); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain20.org/"))); EXPECT_FALSE(guide()->IsWhitelisted( &user_data, GURL("https://www.somedomain20.org/news0/football"), PreviewsType::RESOURCE_LOADING_HINTS, &ect_threshold)); @@ -1298,8 +1238,8 @@ InitializeMultipleResourceLoadingHints(key_count, page_patterns_per_key); - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain0.org/"), base::DoNothing())); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain0.org/"))); EXPECT_TRUE(guide()->IsWhitelisted( &user_data, GURL("https://www.somedomain0.org/news0/football"), PreviewsType::RESOURCE_LOADING_HINTS, &ect_threshold)); @@ -1312,8 +1252,8 @@ // The third to last page pattern has all of its resource loading hints fall // within the threshold. - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain18.org/"), base::DoNothing())); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain18.org/"))); EXPECT_TRUE(guide()->IsWhitelisted( &user_data, GURL("https://www.somedomain18.org/news0/football"), PreviewsType::RESOURCE_LOADING_HINTS, &ect_threshold)); @@ -1326,8 +1266,8 @@ // The second to last page pattern had some of its resource loading hints // fall within the threshold. - EXPECT_TRUE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain19.org/"), base::DoNothing())); + EXPECT_TRUE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain19.org/"))); EXPECT_TRUE(guide()->IsWhitelisted( &user_data, GURL("https://www.somedomain19.org/news0/football"), PreviewsType::RESOURCE_LOADING_HINTS, &ect_threshold)); @@ -1340,8 +1280,8 @@ // The last page pattern should be dropped since all of its resource loading // hints exceeds the threshold count. - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://somedomain20.org/"), base::DoNothing())); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://somedomain20.org/"))); EXPECT_FALSE(guide()->IsWhitelisted( &user_data, GURL("https://www.somedomain20.org/news0/football"), PreviewsType::RESOURCE_LOADING_HINTS, &ect_threshold)); @@ -1373,8 +1313,8 @@ InitializeFixedCountResourceLoadingHints(); - EXPECT_FALSE(guide()->MaybeLoadOptimizationHints( - GURL("https://www.somedomain.org"), base::DoNothing())); + EXPECT_FALSE( + guide()->MaybeLoadOptimizationHints(GURL("https://www.somedomain.org"))); RunUntilIdle(); PreviewsUserData user_data(kDefaultPageId);
diff --git a/components/previews/core/previews_decider.h b/components/previews/core/previews_decider.h index c3693612..7d1b7c0 100644 --- a/components/previews/core/previews_decider.h +++ b/components/previews/core/previews_decider.h
@@ -41,7 +41,7 @@ // Requests that any applicable detailed page hints be loaded. Returns // whether client knows that it has hints for the host of |url| (that may // need to be loaded from persistent storage). - virtual bool LoadResourceHints(const GURL& url) = 0; + virtual bool LoadPageHints(const GURL& url) = 0; // Whether |url| has loaded resource loading hints and, if it does, populates // |out_resource_patterns_to_block| with the resource patterns to block.
diff --git a/components/previews/core/test_previews_decider.cc b/components/previews/core/test_previews_decider.cc index 02196a1..93fba96c 100644 --- a/components/previews/core/test_previews_decider.cc +++ b/components/previews/core/test_previews_decider.cc
@@ -25,7 +25,7 @@ return allow_previews_; } -bool TestPreviewsDecider::LoadResourceHints(const GURL& url) { +bool TestPreviewsDecider::LoadPageHints(const GURL& url) { return true; }
diff --git a/components/previews/core/test_previews_decider.h b/components/previews/core/test_previews_decider.h index 2999d3f..a9f8905 100644 --- a/components/previews/core/test_previews_decider.h +++ b/components/previews/core/test_previews_decider.h
@@ -23,7 +23,7 @@ bool ShouldCommitPreview(PreviewsUserData* previews_data, const GURL& url, PreviewsType type) const override; - bool LoadResourceHints(const GURL& url) override; + bool LoadPageHints(const GURL& url) override; bool GetResourceLoadingHints( const GURL& url, std::vector<std::string>* out_resource_patterns_to_block) const override;
diff --git a/components/version_info/version_info.cc b/components/version_info/version_info.cc index a2ba9e05..f378da9 100644 --- a/components/version_info/version_info.cc +++ b/components/version_info/version_info.cc
@@ -12,13 +12,6 @@ namespace version_info { -namespace { - -bool g_is_channel_set = false; -Channel g_channel = Channel::UNKNOWN; - -} // namespace - std::string GetProductNameAndVersionForUserAgent() { return "Chrome/" + GetVersionNumber(); } @@ -72,23 +65,6 @@ #endif } -bool IsChannelSet() { - return g_is_channel_set; -} - -void SetChannel(Channel channel) { - if (g_is_channel_set) - return; - - g_is_channel_set = true; - g_channel = channel; -} - -Channel GetChannel() { - DCHECK(g_is_channel_set); - return g_channel; -} - std::string GetChannelString(Channel channel) { switch (channel) { case Channel::STABLE:
diff --git a/components/version_info/version_info.h b/components/version_info/version_info.h index f41b85c..82b4739 100644 --- a/components/version_info/version_info.h +++ b/components/version_info/version_info.h
@@ -39,19 +39,6 @@ // Returns the OS type, e.g. "Windows", "Linux", "FreeBDS", ... std::string GetOSType(); -// Returns whether SetChannel() has been called or not. -bool IsChannelSet(); - -// Must be called before calling GetChannel(). Subsequent calls are no-ops. -// Ideally, there should be only one caller to SetChannel(). In situations where -// there are multiple callers, then the first caller "wins". To prevent -// inconsistencies with GetChannel(), all the callers should pass in the same -// |channel| value. -void SetChannel(Channel channel); - -// Gets the channel. DCHECKs if SetChannel() never got called. -Channel GetChannel(); - // Returns a string equivalent of |channel|, indenpendent of whether the build // is branded or not and without any additional modifiers. std::string GetChannelString(Channel channel);
diff --git a/content/browser/devtools/devtools_url_loader_interceptor.cc b/content/browser/devtools/devtools_url_loader_interceptor.cc index 442c24e3..c908d3c5 100644 --- a/content/browser/devtools/devtools_url_loader_interceptor.cc +++ b/content/browser/devtools/devtools_url_loader_interceptor.cc
@@ -171,6 +171,46 @@ network::URLLoaderCompletionStatus status; }; +class InterceptionJob; + +class InterceptionNetworkContext + : public base::RefCounted<InterceptionNetworkContext> { + public: + InterceptionNetworkContext( + network::mojom::URLLoaderFactoryPtrInfo target_factory, + network::mojom::CookieManagerPtrInfo cookie_manager) { + target_factory_.Bind(std::move(target_factory)); + target_factory_.set_connection_error_handler( + base::BindOnce(&InterceptionNetworkContext::OnConnectionError, + base::Unretained(this))); + cookie_manager_.Bind(std::move(cookie_manager)); + cookie_manager_.set_connection_error_handler( + base::BindOnce(&InterceptionNetworkContext::OnConnectionError, + base::Unretained(this))); + } + + network::mojom::URLLoaderFactory* target_factory() { + return target_factory_.get(); + } + network::mojom::CookieManager* cookie_manager() { + return cookie_manager_.get(); + } + void AddJob(InterceptionJob* job) { jobs_.insert(job); } + void RemoveJob(InterceptionJob* job) { + size_t count = jobs_.erase(job); + DCHECK_EQ(1ul, count); + } + + private: + friend class base::RefCounted<InterceptionNetworkContext>; + ~InterceptionNetworkContext() = default; + void OnConnectionError(); + + std::set<InterceptionJob*> jobs_; + network::mojom::URLLoaderFactoryPtr target_factory_; + network::mojom::CookieManagerPtr cookie_manager_; +}; + class InterceptionJob : public network::mojom::URLLoaderClient, public network::mojom::URLLoader { public: @@ -189,8 +229,7 @@ bool is_download, network::mojom::URLLoaderRequest loader_request, network::mojom::URLLoaderClientPtr client, - network::mojom::URLLoaderFactoryPtr target_factory, - network::mojom::CookieManagerPtr cookie_manager); + scoped_refptr<InterceptionNetworkContext> context); void GetResponseBody( std::unique_ptr<GetResponseBodyForInterceptionCallback> callback); @@ -199,6 +238,7 @@ std::unique_ptr<Modifications> modifications, std::unique_ptr<ContinueInterceptedRequestCallback> callback); void Detach(); + void Shutdown(); void OnAuthRequest( const scoped_refptr<net::AuthChallengeInfo>& auth_info, @@ -212,6 +252,7 @@ } ~InterceptionJob() override { + context_->RemoveJob(this); if (registered_in_global_request_map_) { size_t erased = GetInterceptionJobMap().erase(global_req_id_); DCHECK_EQ(1lu, erased); @@ -235,7 +276,6 @@ void StartRequest(); void CancelRequest(); - void Shutdown(); std::unique_ptr<InterceptedRequestInfo> BuildRequestInfo( const network::ResourceResponseHead* head); @@ -303,8 +343,7 @@ network::mojom::URLLoaderClientPtr client_; network::mojom::URLLoaderPtr loader_; - network::mojom::URLLoaderFactoryPtr target_factory_; - network::mojom::CookieManagerPtr cookie_manager_; + scoped_refptr<InterceptionNetworkContext> context_; enum State { kNotStarted, @@ -333,6 +372,12 @@ DISALLOW_COPY_AND_ASSIGN(InterceptionJob); }; +void InterceptionNetworkContext::OnConnectionError() { + std::set<InterceptionJob*> jobs = jobs_; + for (auto* job : jobs) + job->Shutdown(); +} + } // namespace class DevToolsURLLoaderInterceptor::Impl @@ -351,8 +396,7 @@ std::unique_ptr<CreateLoaderParameters> create_params, network::mojom::URLLoaderRequest loader_request, network::mojom::URLLoaderClientPtr client, - network::mojom::URLLoaderFactoryPtr target_factory, - network::mojom::CookieManagerPtr cookie_manager) { + scoped_refptr<InterceptionNetworkContext> context) { DCHECK(!frame_token.is_empty()); static int last_id = 0; @@ -362,7 +406,7 @@ new InterceptionJob(this, std::move(id), frame_token, process_id, std::move(create_params), is_download, std::move(loader_request), std::move(client), - std::move(target_factory), std::move(cookie_manager)); + std::move(context)); } void SetPatterns(std::vector<DevToolsNetworkInterceptor::Pattern> patterns, @@ -478,10 +522,9 @@ const int32_t process_id_; const bool is_download_; - network::mojom::URLLoaderFactoryPtr target_factory_; - network::mojom::CookieManagerPtr cookie_manager_; - base::WeakPtr<DevToolsURLLoaderInterceptor::Impl> interceptor_; + scoped_refptr<InterceptionNetworkContext> context_; mojo::BindingSet<network::mojom::URLLoaderFactory> bindings_; + base::WeakPtr<DevToolsURLLoaderInterceptor::Impl> interceptor_; SEQUENCE_CHECKER(sequence_checker_); }; @@ -521,41 +564,28 @@ DevToolsURLLoaderInterceptor::Impl* interceptor = interceptor_.get(); if (!interceptor_) { - target_factory_->CreateLoaderAndStart( + context_->target_factory()->CreateLoaderAndStart( std::move(loader), routing_id, request_id, options, request, std::move(client), traffic_annotation); return; } auto creation_params = std::make_unique<CreateLoaderParameters>( routing_id, request_id, options, request, traffic_annotation); - network::mojom::URLLoaderFactoryPtr factory_clone; - target_factory_->Clone(MakeRequest(&factory_clone)); - network::mojom::CookieManagerPtr cookie_manager_clone; - cookie_manager_->CloneInterface(mojo::MakeRequest(&cookie_manager_clone)); interceptor->CreateJob(frame_token_, process_id_, is_download_, std::move(creation_params), std::move(loader), - std::move(client), std::move(factory_clone), - std::move(cookie_manager_clone)); + std::move(client), context_); } void DevToolsURLLoaderFactoryProxy::StartOnIO( network::mojom::URLLoaderFactoryRequest loader_request, network::mojom::URLLoaderFactoryPtrInfo target_factory_info, network::mojom::CookieManagerPtrInfo cookie_manager) { - target_factory_.Bind(std::move(target_factory_info)); - target_factory_.set_connection_error_handler( - base::BindOnce(&DevToolsURLLoaderFactoryProxy::OnTargetFactoryError, - base::Unretained(this))); - + context_ = base::MakeRefCounted<InterceptionNetworkContext>( + std::move(target_factory_info), std::move(cookie_manager)); bindings_.AddBinding(this, std::move(loader_request)); bindings_.set_connection_error_handler( base::BindRepeating(&DevToolsURLLoaderFactoryProxy::OnProxyBindingError, base::Unretained(this))); - - cookie_manager_.Bind(std::move(cookie_manager)); - cookie_manager_.set_connection_error_handler( - base::BindOnce(&DevToolsURLLoaderFactoryProxy::OnTargetFactoryError, - base::Unretained(this))); } void DevToolsURLLoaderFactoryProxy::Clone( @@ -672,8 +702,7 @@ bool is_download, network::mojom::URLLoaderRequest loader_request, network::mojom::URLLoaderClientPtr client, - network::mojom::URLLoaderFactoryPtr target_factory, - network::mojom::CookieManagerPtr cookie_manager) + scoped_refptr<InterceptionNetworkContext> context) : id_prefix_(id), global_req_id_( std::make_tuple(process_id, @@ -689,11 +718,11 @@ client_binding_(this), loader_binding_(this), client_(std::move(client)), - target_factory_(std::move(target_factory)), - cookie_manager_(std::move(cookie_manager)), + context_(std::move(context)), state_(kNotStarted), waiting_for_resolution_(false), redirect_count_(0) { + context_->AddJob(this); UpdateIdAndRegister(); const network::ResourceRequest& request = create_loader_params_->request; stage_ = interceptor_->GetInterceptionStage( @@ -1052,7 +1081,8 @@ [](base::RepeatingClosure closure, bool) { closure.Run(); }, base::BarrierClosure(cookies.size(), std::move(callback))); for (auto& cookie : cookies) { - cookie_manager_->SetCanonicalCookie(*cookie, true, true, on_cookie_set); + context_->cookie_manager()->SetCanonicalCookie(*cookie, true, true, + on_cookie_set); } } @@ -1126,7 +1156,7 @@ client_binding_.set_connection_error_handler( base::BindOnce(&InterceptionJob::Shutdown, base::Unretained(this))); - target_factory_->CreateLoaderAndStart( + context_->target_factory()->CreateLoaderAndStart( MakeRequest(&loader_), create_loader_params_->routing_id, create_loader_params_->request_id, create_loader_params_->options, create_loader_params_->request, std::move(loader_client), @@ -1219,7 +1249,8 @@ net::CookieOptions::SameSiteCookieMode::INCLUDE_LAX); } } - cookie_manager_->GetCookieList(request.url, options, std::move(callback)); + context_->cookie_manager()->GetCookieList(request.url, options, + std::move(callback)); } void InterceptionJob::NotifyClient(
diff --git a/content/browser/devtools/devtools_url_request_interceptor.cc b/content/browser/devtools/devtools_url_request_interceptor.cc index 870cb80e..3566609 100644 --- a/content/browser/devtools/devtools_url_request_interceptor.cc +++ b/content/browser/devtools/devtools_url_request_interceptor.cc
@@ -14,10 +14,28 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_request_info.h" #include "net/url_request/url_request.h" +#include "services/network/public/cpp/features.h" namespace content { // static +std::unique_ptr<DevToolsURLRequestInterceptor> +DevToolsURLRequestInterceptor::MaybeCreate(BrowserContext* browser_context) { + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) + return nullptr; + + // TODO(caseq): Technically, this is wrong -- we currently maintain one + // interception controller per browser context, while in reality it is + // created per StoragePartition. + // So we only support interception for the first StoragePartition, which + // results in extensions not being supported. Luckily, this implementation + // of the interception is going away when network service is enabled. + if (DevToolsInterceptorController::FromBrowserContext(browser_context)) + return nullptr; + return std::make_unique<DevToolsURLRequestInterceptor>(browser_context); +} + +// static bool DevToolsURLRequestInterceptor::IsNavigationRequest( ResourceType resource_type) { return resource_type == RESOURCE_TYPE_MAIN_FRAME ||
diff --git a/content/browser/devtools/devtools_url_request_interceptor.h b/content/browser/devtools/devtools_url_request_interceptor.h index 397dd66..4ce985ee 100644 --- a/content/browser/devtools/devtools_url_request_interceptor.h +++ b/content/browser/devtools/devtools_url_request_interceptor.h
@@ -31,6 +31,9 @@ class DevToolsURLRequestInterceptor : public net::URLRequestInterceptor, public DevToolsNetworkInterceptor { public: + static std::unique_ptr<DevToolsURLRequestInterceptor> MaybeCreate( + BrowserContext* browser_context); + static bool IsNavigationRequest(ResourceType resource_type); explicit DevToolsURLRequestInterceptor(BrowserContext* browser_context);
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index a20be5d..1c3d4d5 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -2556,7 +2556,7 @@ } if (base::FeatureList::IsEnabled(features::kCrashReporting)) - MaybeGenerateCrashReport(termination_status); + MaybeGenerateCrashReport(termination_status, exit_code); // When a frame's process dies, its RenderFrame no longer exists, which means // that its child frames must be cleaned up as well. @@ -6182,7 +6182,8 @@ } void RenderFrameHostImpl::MaybeGenerateCrashReport( - base::TerminationStatus status) { + base::TerminationStatus status, + int exit_code) { if (!last_committed_url_.SchemeIsHTTPOrHTTPS()) return; @@ -6195,7 +6196,16 @@ std::string reason; switch (status) { case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: + break; case base::TERMINATION_STATUS_PROCESS_CRASHED: + if (exit_code == RESULT_CODE_HUNG) + reason = "unresponsive"; + break; + case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: + if (exit_code == RESULT_CODE_HUNG) + reason = "unresponsive"; + else + return; break; case base::TERMINATION_STATUS_OOM: #if defined(OS_CHROMEOS)
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index c8e2710..d7fb5b4b 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -1339,9 +1339,9 @@ CreateInitiatorSpecificURLLoaderFactories( const base::flat_set<url::Origin>& initiator_origins); - // Based on the termination |status|, may generate a crash report to be routed - // to the Reporting API. - void MaybeGenerateCrashReport(base::TerminationStatus status); + // Based on the termination |status| and |exit_code|, may generate a crash + // report to be routed to the Reporting API. + void MaybeGenerateCrashReport(base::TerminationStatus status, int exit_code); // Move every child frame into the pending deletion state. // For each process, send the command to delete the local subtree and execute
diff --git a/content/browser/isolated_origin_browsertest.cc b/content/browser/isolated_origin_browsertest.cc index 0c98461d..f5efcf97 100644 --- a/content/browser/isolated_origin_browsertest.cc +++ b/content/browser/isolated_origin_browsertest.cc
@@ -4,6 +4,7 @@ #include <sstream> +#include "base/bind.h" #include "base/command_line.h" #include "base/macros.h" #include "base/strings/string_util.h" @@ -11,8 +12,10 @@ #include "build/build_config.h" #include "content/browser/bad_message.h" #include "content/browser/child_process_security_policy_impl.h" +#include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/storage_partition_impl.h" #include "content/browser/web_contents/web_contents_impl.h" +#include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/site_isolation_policy.h" #include "content/public/common/content_features.h" @@ -1005,7 +1008,9 @@ public: StoragePartitonInterceptor( RenderProcessHostImpl* rph, - blink::mojom::StoragePartitionServiceRequest request) { + blink::mojom::StoragePartitionServiceRequest request, + const url::Origin& origin_to_inject) + : origin_to_inject_(origin_to_inject) { StoragePartitionImpl* storage_partition = static_cast<StoragePartitionImpl*>(rph->GetStoragePartition()); @@ -1043,9 +1048,7 @@ // security checks can be tested. void OpenLocalStorage(const url::Origin& origin, blink::mojom::StorageAreaRequest request) override { - url::Origin mismatched_origin = - url::Origin::Create(GURL("http://abc.foo.com")); - GetForwardingInterface()->OpenLocalStorage(mismatched_origin, + GetForwardingInterface()->OpenLocalStorage(origin_to_inject_, std::move(request)); } @@ -1054,27 +1057,63 @@ // calls can be forwarded to it. blink::mojom::StoragePartitionService* storage_partition_service_; + url::Origin origin_to_inject_; + DISALLOW_COPY_AND_ASSIGN(StoragePartitonInterceptor); }; void CreateTestStoragePartitionService( + const url::Origin& origin_to_inject, RenderProcessHostImpl* rph, blink::mojom::StoragePartitionServiceRequest request) { // This object will register as RenderProcessHostObserver, so it will // clean itself automatically on process exit. - new StoragePartitonInterceptor(rph, std::move(request)); + new StoragePartitonInterceptor(rph, std::move(request), origin_to_inject); } // Verify that an isolated renderer process cannot read localStorage of an // origin outside of its isolated site. // TODO(nasko): Write a test to verify the opposite - any non-isolated renderer // process cannot access data of an isolated site. -IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, LocalStorageOriginEnforcement) { - RenderProcessHostImpl::SetCreateStoragePartitionServiceFunction( - CreateTestStoragePartitionService); +IN_PROC_BROWSER_TEST_F( + IsolatedOriginTest, + LocalStorageOriginEnforcement_IsolatedAccessingNonIsolated) { + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + + auto mismatched_origin = url::Origin::Create(GURL("http://abc.foo.com")); + EXPECT_FALSE(policy->IsIsolatedOrigin(mismatched_origin)); + RenderProcessHostImpl::SetStoragePartitionServiceRequestHandlerForTesting( + base::BindRepeating(&CreateTestStoragePartitionService, + mismatched_origin)); GURL isolated_url( embedded_test_server()->GetURL("isolated.foo.com", "/title1.html")); + EXPECT_TRUE(policy->IsIsolatedOrigin(url::Origin::Create(isolated_url))); + EXPECT_TRUE(NavigateToURL(shell(), isolated_url)); + + content::RenderProcessHostKillWaiter kill_waiter( + shell()->web_contents()->GetMainFrame()->GetProcess()); + // Use ignore_result here, since on Android the renderer process is + // terminated, but ExecuteScript still returns true. It properly returns + // false on all other platforms. + ignore_result(ExecuteScript(shell()->web_contents()->GetMainFrame(), + "localStorage.length;")); + EXPECT_EQ(bad_message::RPH_MOJO_PROCESS_ERROR, kill_waiter.Wait()); +} + +// Verify that an IPC request for reading localStorage of an *opaque* origin +// will be rejected. +IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, + LocalStorageOriginEnforcement_OpaqueOrigin) { + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + + url::Origin opaque_origin; + RenderProcessHostImpl::SetStoragePartitionServiceRequestHandlerForTesting( + base::BindRepeating(&CreateTestStoragePartitionService, opaque_origin)); + + GURL isolated_url( + embedded_test_server()->GetURL("isolated.foo.com", "/title1.html")); + EXPECT_TRUE(policy->IsIsolatedOrigin(url::Origin::Create(isolated_url))); EXPECT_TRUE(NavigateToURL(shell(), isolated_url)); content::RenderProcessHostKillWaiter kill_waiter(
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index d0fe048..1897079 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -289,8 +289,6 @@ bool g_run_renderer_in_process = false; RendererMainThreadFactoryFunction g_renderer_main_thread_factory = nullptr; -RenderProcessHostImpl::CreateStoragePartitionServiceFunction - g_create_storage_partition = nullptr; base::Thread* g_in_process_thread; @@ -1237,6 +1235,14 @@ network_service->AddCorbExceptionForPlugin(process_id); } +RenderProcessHostImpl::StoragePartitionServiceRequestHandler& +GetStoragePartitionServiceRequestHandler() { + static base::NoDestructor< + RenderProcessHostImpl::StoragePartitionServiceRequestHandler> + instance; + return *instance; +} + void RemoveCorbExceptionForPluginOnIOThread(int process_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); @@ -1597,6 +1603,7 @@ instance_weak_factory_( new base::WeakPtrFactory<RenderProcessHostImpl>(this)), frame_sink_provider_(id_), + shutdown_exit_code_(-1), weak_factory_(this) { for (size_t i = 0; i < kNumKeepAliveClients; i++) keep_alive_client_count_[i] = 0; @@ -1672,9 +1679,9 @@ g_renderer_main_thread_factory = create; } -void RenderProcessHostImpl::SetCreateStoragePartitionServiceFunction( - CreateStoragePartitionServiceFunction function) { - g_create_storage_partition = function; +void RenderProcessHostImpl::SetStoragePartitionServiceRequestHandlerForTesting( + StoragePartitionServiceRequestHandler handler) { + GetStoragePartitionServiceRequestHandler() = handler; } RenderProcessHostImpl::~RenderProcessHostImpl() { @@ -2371,8 +2378,8 @@ void RenderProcessHostImpl::CreateStoragePartitionService( blink::mojom::StoragePartitionServiceRequest request) { - if (g_create_storage_partition) { - g_create_storage_partition(this, std::move(request)); + if (!GetStoragePartitionServiceRequestHandler().is_null()) { + GetStoragePartitionServiceRequestHandler().Run(this, std::move(request)); return; } @@ -3246,6 +3253,7 @@ if (!child_process_launcher_.get()) return false; + shutdown_exit_code_ = exit_code; return child_process_launcher_->Terminate(exit_code); } @@ -4177,6 +4185,10 @@ RemoveUserData(kSessionStorageHolderKey); + // RenderProcessGone relies on the exit code set during shutdown. + if (shutdown_exit_code_ != -1) + info.exit_code = shutdown_exit_code_; + base::IDMap<IPC::Listener*>::iterator iter(&listeners_); while (!iter.IsAtEnd()) { iter.GetCurrentValue()->OnMessageReceived(FrameHostMsg_RenderProcessGone(
diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index d23793bf..f17fb77 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h
@@ -16,6 +16,7 @@ #include <utility> #include <vector> +#include "base/callback_forward.h" #include "base/containers/flat_set.h" #include "base/gtest_prod_util.h" #include "base/macros.h" @@ -365,14 +366,14 @@ static void RegisterRendererMainThreadFactory( RendererMainThreadFactoryFunction create); - // Allows external code to supply a function which creates a - // StoragePartitionService. Used for supplying test versions of the + // Allows external code to supply a callback which handles a + // StoragePartitionServiceRequest. Used for supplying test versions of the // service. - using CreateStoragePartitionServiceFunction = - void (*)(RenderProcessHostImpl* rph, - blink::mojom::StoragePartitionServiceRequest request); - static void SetCreateStoragePartitionServiceFunction( - CreateStoragePartitionServiceFunction function); + using StoragePartitionServiceRequestHandler = base::RepeatingCallback<void( + RenderProcessHostImpl* rph, + blink::mojom::StoragePartitionServiceRequest request)>; + static void SetStoragePartitionServiceRequestHandlerForTesting( + StoragePartitionServiceRequestHandler handler); RenderFrameMessageFilter* render_frame_message_filter_for_testing() const { return render_frame_message_filter_.get(); @@ -876,6 +877,10 @@ // Fields for recording MediaStream UMA. bool has_recorded_media_stream_frame_depth_metric_ = false; + // If the RenderProcessHost is being shutdown via Shutdown(), this records the + // exit code. + int shutdown_exit_code_; + base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_; DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index 39afb7ea..cac5a38 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -1529,7 +1529,7 @@ ukm::SourceId RenderWidgetHostViewAura::GetClientSourceForMetrics() const { RenderFrameHostImpl* frame = GetFocusedFrame(); if (frame) { - frame->GetRenderWidgetHost() + return frame->GetRenderWidgetHost() ->delegate() ->GetUkmSourceIdForLastCommittedSource(); }
diff --git a/content/browser/security_exploit_browsertest.cc b/content/browser/security_exploit_browsertest.cc index 4c68676f..89b37840f 100644 --- a/content/browser/security_exploit_browsertest.cc +++ b/content/browser/security_exploit_browsertest.cc
@@ -399,13 +399,6 @@ // identical to the AttemptDuplicateRenderViewHost test case. IN_PROC_BROWSER_TEST_F(SecurityExploitBrowserTest, AttemptDuplicateRenderWidgetHost) { -#if defined(OS_WIN) - // PlzNavigate - // This test is failing in a flaky manner on Android as it appears to be - // leaking URLRequests. See crbug.com/702584. - if (IsBrowserSideNavigationEnabled()) - return; -#endif int duplicate_routing_id = MSG_ROUTING_NONE; RenderFrameHostImpl* pending_rfh = PrepareToDuplicateHosts(shell(), &duplicate_routing_id);
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index 46dece4..d09ed31 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -1560,7 +1560,8 @@ DCHECK_EQ(EmbeddedWorkerStatus::STOPPED, running_status()); DCHECK(inflight_requests_.IsEmpty()); DCHECK(request_timeouts_.empty()); - DCHECK(start_worker_first_purpose_); + // TODO(crbug.com/877359): Temporary CHECK for the linked bug. + CHECK(start_worker_first_purpose_); if (!ServiceWorkerMetrics::ShouldExcludeSiteFromHistogram(site_for_uma_) && start_worker_first_purpose_.value() ==
diff --git a/content/browser/storage_partition_impl_map.cc b/content/browser/storage_partition_impl_map.cc index e69aab0..5025231 100644 --- a/content/browser/storage_partition_impl_map.cc +++ b/content/browser/storage_partition_impl_map.cc
@@ -412,8 +412,11 @@ } URLRequestInterceptorScopedVector request_interceptors; - request_interceptors.push_back( - std::make_unique<DevToolsURLRequestInterceptor>(browser_context_)); + + auto devtools_interceptor = + DevToolsURLRequestInterceptor::MaybeCreate(browser_context_); + if (devtools_interceptor) + request_interceptors.push_back(std::move(devtools_interceptor)); request_interceptors.push_back(ServiceWorkerRequestHandler::CreateInterceptor( browser_context_->GetResourceContext())); request_interceptors.push_back(std::make_unique<AppCacheInterceptor>());
diff --git a/content/renderer/media/stream/webmediaplayer_ms_compositor.h b/content/renderer/media/stream/webmediaplayer_ms_compositor.h index 04ba671..85a5c92 100644 --- a/content/renderer/media/stream/webmediaplayer_ms_compositor.h +++ b/content/renderer/media/stream/webmediaplayer_ms_compositor.h
@@ -18,7 +18,7 @@ #include "cc/layers/surface_layer.h" #include "cc/layers/video_frame_provider.h" #include "content/common/content_export.h" -#include "media/base/media_log.h" +#include "media/base/media_util.h" #include "media/blink/webmediaplayer_params.h" #include "third_party/blink/public/platform/web_video_frame_submitter.h" @@ -180,7 +180,7 @@ // TODO(qiangchen, emircan): It might be nice to use a real MediaLog here from // the WebMediaPlayerMS instance, but it owns the MediaLog and this class has // non-deterministic destruction paths (either compositor or IO). - media::MediaLog media_log_; + media::NullMediaLog media_log_; size_t serial_;
diff --git a/content/renderer/media/stream/webmediaplayer_ms_unittest.cc b/content/renderer/media/stream/webmediaplayer_ms_unittest.cc index 89d89ec..a608d4a 100644 --- a/content/renderer/media/stream/webmediaplayer_ms_unittest.cc +++ b/content/renderer/media/stream/webmediaplayer_ms_unittest.cc
@@ -19,6 +19,7 @@ #include "content/renderer/media/stream/webmediaplayer_ms.h" #include "content/renderer/media/stream/webmediaplayer_ms_compositor.h" #include "content/renderer/render_frame_impl.h" +#include "media/base/media_util.h" #include "media/base/test_helpers.h" #include "media/base/video_frame.h" #include "media/video/mock_gpu_memory_buffer_video_frame_pool.h" @@ -691,7 +692,7 @@ ? blink::WebMediaPlayer::SurfaceLayerMode::kAlways : blink::WebMediaPlayer::SurfaceLayerMode::kNever; player_ = std::make_unique<WebMediaPlayerMS>( - nullptr, this, &delegate_, std::make_unique<media::MediaLog>(), + nullptr, this, &delegate_, std::make_unique<media::NullMediaLog>(), std::unique_ptr<MediaStreamRendererFactory>(render_factory_), blink::scheduler::GetSingleThreadTaskRunnerForTesting(), blink::scheduler::GetSingleThreadTaskRunnerForTesting(),
diff --git a/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc b/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc index d92d292c..f3f85e2 100644 --- a/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc +++ b/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc
@@ -310,7 +310,7 @@ // TODO(sandersd): Plumb a real log sink here so that we can contribute to the // media-internals UI. The current log just discards all messages. - media_log_ = std::make_unique<media::MediaLog>(); + media_log_ = std::make_unique<media::NullMediaLog>(); video_decoder_ = gpu_factories_->CreateVideoDecoder( media_log_.get(), base::BindRepeating(&OnRequestOverlayInfo),
diff --git a/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc b/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc index 95df6c2..b6303611 100644 --- a/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc +++ b/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc
@@ -12,7 +12,7 @@ #include "media/audio/null_audio_sink.h" #include "media/base/audio_parameters.h" #include "media/base/fake_audio_render_callback.h" -#include "media/base/media_log.h" +#include "media/base/media_util.h" #include "media/blink/webaudiosourceprovider_impl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -124,7 +124,7 @@ blink::WebMediaStreamSource blink_audio_source_; blink::WebMediaStreamTrack blink_audio_track_; - media::MediaLog media_log_; + media::NullMediaLog media_log_; media::FakeAudioRenderCallback fake_callback_; scoped_refptr<media::WebAudioSourceProviderImpl> audio_source_; };
diff --git a/content/renderer/pepper/video_decoder_shim.cc b/content/renderer/pepper/video_decoder_shim.cc index 75bc31a..9a75088 100644 --- a/content/renderer/pepper/video_decoder_shim.cc +++ b/content/renderer/pepper/video_decoder_shim.cc
@@ -27,7 +27,6 @@ #include "media/base/cdm_context.h" #include "media/base/decoder_buffer.h" #include "media/base/limits.h" -#include "media/base/media_log.h" #include "media/base/media_util.h" #include "media/base/video_decoder.h" #include "media/filters/ffmpeg_video_decoder.h" @@ -657,7 +656,7 @@ // WeakPtr is bound to main_message_loop_. Use only in shim callbacks. base::WeakPtr<VideoDecoderShim> shim_; - media::MediaLog media_log_; + media::NullMediaLog media_log_; std::unique_ptr<media::VideoDecoder> decoder_; bool initialized_ = false; scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index cd54805e..468a3d2 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -3588,7 +3588,8 @@ void RenderFrameImpl::UpdateSubresourceLoaderFactories( std::unique_ptr<blink::URLLoaderFactoryBundleInfo> subresource_loaders) { DCHECK(loader_factories_); - DCHECK(loader_factories_->IsHostChildURLLoaderFactoryBundle()); + // TODO(crbug/916625): CHECKing for crbug.com/916625. + CHECK(loader_factories_->IsHostChildURLLoaderFactoryBundle()); static_cast<HostChildURLLoaderFactoryBundle*>(loader_factories_.get()) ->UpdateThisAndAllClones(std::move(subresource_loaders)); }
diff --git a/docs/gwp_asan.md b/docs/gwp_asan.md index 678d499..702dbe5 100644 --- a/docs/gwp_asan.md +++ b/docs/gwp_asan.md
@@ -1,7 +1,7 @@ # GWP-ASan GWP-ASan is a debug tool intended to detect heap memory errors in the wild. It -samples alloctions to a debug allocator, similar to ElectricFence or Page Heap, +samples allocations to a debug allocator, similar to ElectricFence or Page Heap, in order to detect heap memory errors and report additional debugging context. ## Allocator @@ -49,7 +49,7 @@ ```shell chrome --enable-features="GwpAsanMalloc<Study" \ --force-fieldtrials=Study/Group1 \ - --force-fieldtrial-params=Study.Group1:TotalAllocations/64/AllocationSamplingFrequency/200/ProcessSamplingProbability/1.0 + --force-fieldtrial-params=Study.Group1:MaxAllocations/32/TotalPages/128/AllocationSamplingFrequency/1000/ProcessSamplingProbability/1.0 ``` ## Testing
diff --git a/gpu/angle_end2end_tests_main.cc b/gpu/angle_end2end_tests_main.cc index cf0206a..e6fde85 100644 --- a/gpu/angle_end2end_tests_main.cc +++ b/gpu/angle_end2end_tests_main.cc
@@ -18,6 +18,8 @@ } // namespace +// Located in third_party/angle/src/tests/test_utils/ANGLETest.cpp. +// Defined here so we can avoid depending on the ANGLE headers. void ANGLEProcessTestArgs(int *argc, char *argv[]); int main(int argc, char** argv) {
diff --git a/ios/chrome/browser/context_menu/BUILD.gn b/ios/chrome/browser/context_menu/BUILD.gn index a49caaa90..63b60e5 100644 --- a/ios/chrome/browser/context_menu/BUILD.gn +++ b/ios/chrome/browser/context_menu/BUILD.gn
@@ -11,6 +11,7 @@ deps = [ "//base", "//base/test:test_support", + "//components/strings", "//ios/chrome/app/strings", "//ios/chrome/browser/ui", "//ios/chrome/test/app:test_support",
diff --git a/ios/chrome/browser/context_menu/context_menu_egtest.mm b/ios/chrome/browser/context_menu/context_menu_egtest.mm index f75a001a0..d0b13d5 100644 --- a/ios/chrome/browser/context_menu/context_menu_egtest.mm +++ b/ios/chrome/browser/context_menu/context_menu_egtest.mm
@@ -7,6 +7,7 @@ #import <XCTest/XCTest.h> #import "base/test/ios/wait_util.h" +#include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/ui/util/ui_util.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/chrome/test/app/chrome_test_util.h" @@ -360,4 +361,71 @@ }); } +// Tests cancelling the context menu. +- (void)testDismissContextMenu { + const GURL initialURL = self.testServer->GetURL(kInitialPageUrl); + [ChromeEarlGrey loadURL:initialURL]; + [ChromeEarlGrey waitForWebViewContainingText:kInitialPageDestinationLinkText]; + + // Display the context menu twice. + for (NSInteger i = 0; i < 2; i++) { + LongPressElement(kInitialPageDestinationLinkId); + + // Make sure the context menu appeared. + [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] + assertWithMatcher:grey_notNil()]; + + if (IsIPadIdiom()) { + // Tap the tools menu to dismiss the popover. + [[EarlGrey selectElementWithMatcher:chrome_test_util::ToolsMenuButton()] + performAction:grey_tap()]; + } else { + TapOnContextMenuButton(chrome_test_util::CancelButton()); + } + + // Make sure the context menu disappeared. + [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] + assertWithMatcher:grey_nil()]; + } + + // Display the context menu one last time. + LongPressElement(kInitialPageDestinationLinkId); + + // Make sure the context menu appeared. + [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] + assertWithMatcher:grey_notNil()]; +} + +// Checks that all the options are displayed in the context menu. +- (void)testAppropriateContextMenu { + const GURL initialURL = self.testServer->GetURL(kInitialPageUrl); + [ChromeEarlGrey loadURL:initialURL]; + [ChromeEarlGrey waitForWebViewContainingText:kInitialPageDestinationLinkText]; + + LongPressElement(kInitialPageDestinationLinkId); + + // Check the different buttons. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_CONTENT_CONTEXT_OPENLINKNEWTAB)] + assertWithMatcher:grey_sufficientlyVisible()]; + [[EarlGrey selectElementWithMatcher: + chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_CONTENT_CONTEXT_OPENLINKNEWINCOGNITOTAB)] + assertWithMatcher:grey_sufficientlyVisible()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_CONTENT_CONTEXT_ADDTOREADINGLIST)] + assertWithMatcher:grey_sufficientlyVisible()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_CONTENT_CONTEXT_COPY)] + assertWithMatcher:grey_sufficientlyVisible()]; + if (!IsIPadIdiom()) { + [[EarlGrey selectElementWithMatcher: + chrome_test_util::ButtonWithAccessibilityLabelId(IDS_CANCEL)] + assertWithMatcher:grey_sufficientlyVisible()]; + } +} + @end
diff --git a/ios/chrome/browser/prerender/BUILD.gn b/ios/chrome/browser/prerender/BUILD.gn index a235a1320..f5260b2e 100644 --- a/ios/chrome/browser/prerender/BUILD.gn +++ b/ios/chrome/browser/prerender/BUILD.gn
@@ -29,8 +29,12 @@ "//ios/chrome/browser/itunes_urls:itunes_urls", "//ios/chrome/browser/net", "//ios/chrome/browser/signin", + "//ios/chrome/browser/snapshots", "//ios/chrome/browser/tabs", "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/ntp:util", + "//ios/chrome/browser/web", + "//ios/chrome/browser/web_state_list", "//ios/web", "//ui/base", "//url",
diff --git a/ios/chrome/browser/prerender/prerender_service.h b/ios/chrome/browser/prerender/prerender_service.h index 06a6df1..9501f12 100644 --- a/ios/chrome/browser/prerender/prerender_service.h +++ b/ios/chrome/browser/prerender/prerender_service.h
@@ -13,6 +13,7 @@ @class PreloadController; @protocol PreloadControllerDelegate; +@class TabModel; namespace ios { class ChromeBrowserState; @@ -50,6 +51,15 @@ ui::PageTransition transition, bool immediately); + // If |url| is prerendered, loads the prerendered web state into |tab_model| + // at the active index, replacing the existing active web state. If not, or if + // it isn't possible to replace the active web state, cancels the active + // preload. Metrics and snapshots are appropriately updated. Returns true if + // the active webstate was replaced, false otherwise. + bool MaybeLoadPrerenderedURL(const GURL& url, + ui::PageTransition transition, + TabModel* tab_model); + // Cancels any outstanding prerender requests and destroys any prerendered // pages. void CancelPrerender(); @@ -60,9 +70,6 @@ // Returns true if the given |web_state| is being prerendered. bool IsWebStatePrerendered(web::WebState* web_state); - // Returns the WebState containing the prerendered contents. - std::unique_ptr<web::WebState> ReleasePrerenderContents(); - // KeyedService implementation. void Shutdown() override;
diff --git a/ios/chrome/browser/prerender/prerender_service.mm b/ios/chrome/browser/prerender/prerender_service.mm index 478c5d7..d2669614 100644 --- a/ios/chrome/browser/prerender/prerender_service.mm +++ b/ios/chrome/browser/prerender/prerender_service.mm
@@ -4,11 +4,19 @@ #import "ios/chrome/browser/prerender/prerender_service.h" +#include "base/metrics/histogram_macros.h" #import "ios/chrome/browser/prerender/preload_controller.h" +#import "ios/chrome/browser/snapshots/snapshot_tab_helper.h" #import "ios/chrome/browser/tabs/legacy_tab_helper.h" #import "ios/chrome/browser/tabs/tab.h" +#import "ios/chrome/browser/tabs/tab_model.h" +#import "ios/chrome/browser/ui/ntp/ntp_util.h" +#import "ios/chrome/browser/web/load_timing_tab_helper.h" +#import "ios/chrome/browser/web_state_list/web_state_list.h" +#import "ios/web/public/navigation_manager.h" #include "ios/web/public/web_client.h" #include "ios/web/public/web_state/web_state.h" +#include "ui/base/page_transition_types.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -46,6 +54,64 @@ immediately:immediately]; } +bool PrerenderService::MaybeLoadPrerenderedURL(const GURL& url, + ui::PageTransition transition, + TabModel* tab_model) { + if (!HasPrerenderForUrl(url)) { + CancelPrerender(); + return false; + } + + std::unique_ptr<web::WebState> new_web_state = + [controller_ releasePrerenderContents]; + DCHECK(new_web_state); + WebStateList* web_state_list = tab_model.webStateList; + DCHECK_NE(WebStateList::kInvalidIndex, web_state_list->active_index()); + + web::NavigationManager* active_navigation_manager = + web_state_list->GetActiveWebState()->GetNavigationManager(); + int lastIndex = active_navigation_manager->GetLastCommittedItemIndex(); + UMA_HISTOGRAM_COUNTS_100("Prerender.PrerenderLoadedOnIndex", lastIndex); + + BOOL onFirstNTP = + IsVisibleURLNewTabPage(web_state_list->GetActiveWebState()) && + lastIndex == 0; + UMA_HISTOGRAM_BOOLEAN("Prerender.PrerenderLoadedOnFirstNTP", onFirstNTP); + + web::NavigationManager* new_navigation_manager = + new_web_state->GetNavigationManager(); + + if (new_navigation_manager->CanPruneAllButLastCommittedItem()) { + new_navigation_manager->CopyStateFromAndPrune(active_navigation_manager); + web_state_list->ReplaceWebStateAt(web_state_list->active_index(), + std::move(new_web_state)); + + // new_web_state is now null after the std::move, so grab a new pointer to + // it for further updates. + web::WebState* active_web_state = web_state_list->GetActiveWebState(); + if (!active_web_state->IsLoading()) { + // If the page has finished loading, take a snapshot. If the page is + // still loading, do nothing, as the tab helper will automatically take + // a snapshot once the load completes. + SnapshotTabHelper::FromWebState(active_web_state)->UpdateSnapshot(); + } + + bool typed_or_generated_transition = + PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_TYPED) || + PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED); + if (typed_or_generated_transition) { + LoadTimingTabHelper::FromWebState(active_web_state) + ->DidPromotePrerenderTab(); + } + + [tab_model saveSessionImmediately:NO]; + return true; + } + + CancelPrerender(); + return false; +} + void PrerenderService::CancelPrerender() { [controller_ cancelPrerender]; } @@ -57,7 +123,3 @@ bool PrerenderService::IsWebStatePrerendered(web::WebState* web_state) { return [controller_ isWebStatePrerendered:web_state]; } - -std::unique_ptr<web::WebState> PrerenderService::ReleasePrerenderContents() { - return [controller_ releasePrerenderContents]; -}
diff --git a/ios/chrome/browser/tabs/tab_title_util.mm b/ios/chrome/browser/tabs/tab_title_util.mm index a87e47d..deaea0f 100644 --- a/ios/chrome/browser/tabs/tab_title_util.mm +++ b/ios/chrome/browser/tabs/tab_title_util.mm
@@ -22,8 +22,12 @@ NSString* GetTabTitle(web::WebState* web_state) { base::string16 title; - if (!web_state->GetNavigationManager()->GetVisibleItem() && - DownloadManagerTabHelper::FromWebState(web_state)->has_download_task()) { + web::NavigationManager* navigationManager = web_state->GetNavigationManager(); + DownloadManagerTabHelper* downloadTabHelper = + DownloadManagerTabHelper::FromWebState(web_state); + if (navigationManager && downloadTabHelper && + !navigationManager->GetVisibleItem() && + downloadTabHelper->has_download_task()) { title = l10n_util::GetStringUTF16(IDS_DOWNLOAD_TAB_TITLE); } else { title = web_state->GetTitle();
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index f441562..8c55032 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -4002,67 +4002,20 @@ return; } - bool typed_or_generated_transition = - PageTransitionCoreTypeIs(params.transition_type, - ui::PAGE_TRANSITION_TYPED) || - PageTransitionCoreTypeIs(params.transition_type, - ui::PAGE_TRANSITION_GENERATED); - + // Set _insertedTabWasPrerenderedTab to YES, so that if a prerendered tab is + // inserted, the correct toolbar height is used and animations are played. + _insertedTabWasPrerenderedTab = YES; + // Ask the prerender service to load this URL if it can, and return if it does + // so. PrerenderService* prerenderService = PrerenderServiceFactory::GetForBrowserState(self.browserState); - if (prerenderService && prerenderService->HasPrerenderForUrl(params.url)) { - std::unique_ptr<web::WebState> newWebState = - prerenderService->ReleasePrerenderContents(); - DCHECK(newWebState); - - int lastIndex = self.currentWebState->GetNavigationManager() - ->GetLastCommittedItemIndex(); - UMA_HISTOGRAM_COUNTS_100("Prerender.PrerenderLoadedOnIndex", lastIndex); - - BOOL onFirstNTP = - IsVisibleURLNewTabPage(self.currentWebState) && lastIndex == 0; - UMA_HISTOGRAM_BOOLEAN("Prerender.PrerenderLoadedOnFirstNTP", onFirstNTP); - - Tab* oldTab = self.tabModel.currentTab; - Tab* newTab = LegacyTabHelper::GetTabForWebState(newWebState.get()); - DCHECK(oldTab); - DCHECK(newTab); - - bool canPruneItems = - [newTab navigationManager]->CanPruneAllButLastCommittedItem(); - - if (canPruneItems) { - [newTab navigationManager]->CopyStateFromAndPrune( - [oldTab navigationManager]); - - // Set _insertedTabWasPrerenderedTab to YES while the Tab is inserted - // so that the correct toolbar height is used and animation are played. - _insertedTabWasPrerenderedTab = YES; - self.tabModel.webStateList->ReplaceWebStateAt( - [self.tabModel indexOfTab:oldTab], std::move(newWebState)); - _insertedTabWasPrerenderedTab = NO; - - if (!newTab.webState->IsLoading()) { - // If the page has finished loading, take a snapshot. If the page is - // still loading, do nothing, as the tab helper will automatically take - // a snapshot once the load completes. - SnapshotTabHelper::FromWebState(newTab.webState) - ->UpdateSnapshotWithCallback(nil); - } - - if (typed_or_generated_transition) { - LoadTimingTabHelper::FromWebState(newTab.webState) - ->DidPromotePrerenderTab(); - } - - [self.tabModel saveSessionImmediately:NO]; - return; - } + if (prerenderService && + prerenderService->MaybeLoadPrerenderedURL( + params.url, params.transition_type, self.tabModel)) { + _insertedTabWasPrerenderedTab = NO; + return; } - - if (prerenderService) { - prerenderService->CancelPrerender(); - } + _insertedTabWasPrerenderedTab = NO; // Some URLs are not allowed while in incognito. If we are in incognito and // load a disallowed URL, instead create a new tab not in the incognito state. @@ -4076,8 +4029,12 @@ [self webPageOrderedOpen:command]; return; } - - if (typed_or_generated_transition) { + BOOL typedOrGeneratedTransition = + PageTransitionCoreTypeIs(params.transition_type, + ui::PAGE_TRANSITION_TYPED) || + PageTransitionCoreTypeIs(params.transition_type, + ui::PAGE_TRANSITION_GENERATED); + if (typedOrGeneratedTransition) { LoadTimingTabHelper::FromWebState(self.currentWebState) ->DidInitiatePageLoad(); }
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_egtest.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_egtest.mm index 9e7dda4..8dba6a7 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_egtest.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_egtest.mm
@@ -300,22 +300,6 @@ [[EarlGrey selectElementWithMatcher:chrome_test_util::BackButton()] performAction:grey_tap()]; - // Test that the omnibox is visible and taking full width, before any scroll - // happen on iPhone. - if (!IsRegularXRegularSizeClass()) { - // Test that the omnibox is still pinned to the top of the screen and - // under the safe area. - CGFloat safeAreaTop = ntp_home::CollectionView().safeAreaInsets.top; - - CGFloat contentOffset = ntp_home::CollectionView().contentOffset.y; - CGFloat fakeOmniboxOrigin = ntp_home::FakeOmnibox().frame.origin.y; - CGFloat pinnedOffset = contentOffset - (fakeOmniboxOrigin - safeAreaTop); - [[EarlGrey selectElementWithMatcher:grey_accessibilityID( - [ContentSuggestionsHeaderItem - accessibilityIdentifier])] - assertWithMatcher:ntp_home::HeaderPinnedOffset(pinnedOffset)]; - } - // Check that the first items are visible as the collection should be // scrolled. [[EarlGrey @@ -439,6 +423,23 @@ performAction:grey_tap()]; // Check the tile is back. + ConditionBlock condition = ^{ + NSError* error = nil; + [[EarlGrey + selectElementWithMatcher: + grey_allOf( + chrome_test_util::StaticTextWithAccessibilityLabel(pageTitle), + grey_sufficientlyVisible(), nil)] + assertWithMatcher:grey_notNil() + error:&error]; + return error == nil; + }; + NSString* errorMessage = + @"The tile wasn't added back after hitting 'Undo' on the snackbar"; + GREYAssert(base::test::ios::WaitUntilConditionOrTimeout( + base::test::ios::kWaitForUIElementTimeout, condition), + errorMessage); + [[EarlGrey selectElementWithMatcher: grey_allOf(chrome_test_util::StaticTextWithAccessibilityLabel( pageTitle),
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm index e29df69..c1a76f4 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm
@@ -11,6 +11,7 @@ #include "base/strings/sys_string_conversions.h" #include "base/test/scoped_command_line.h" #include "components/reading_list/core/reading_list_model.h" +#include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/chrome_switches.h" @@ -41,6 +42,7 @@ #import "ios/chrome/test/earl_grey/chrome_test_case.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" +#include "ui/base/l10n/l10n_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -165,6 +167,61 @@ chrome_test_util::VerifyAccessibilityForCurrentScreen(); } +// Tests that the collections shortcut are displayed and working. +- (void)testCollectionShortcuts { + // Check the Bookmarks. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_CONTENT_SUGGESTIONS_BOOKMARKS)] + performAction:grey_tap()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::HeaderWithAccessibilityLabelId( + IDS_IOS_CONTENT_SUGGESTIONS_BOOKMARKS)] + assertWithMatcher:grey_sufficientlyVisible()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::NavigationBarDoneButton()] + performAction:grey_tap()]; + + // Check the ReadingList. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_CONTENT_SUGGESTIONS_READING_LIST)] + performAction:grey_tap()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::HeaderWithAccessibilityLabelId( + IDS_IOS_TOOLS_MENU_READING_LIST)] + assertWithMatcher:grey_sufficientlyVisible()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::NavigationBarDoneButton()] + performAction:grey_tap()]; + + // Check the RecentTabs. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_CONTENT_SUGGESTIONS_RECENT_TABS)] + performAction:grey_tap()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::HeaderWithAccessibilityLabelId( + IDS_IOS_CONTENT_SUGGESTIONS_RECENT_TABS)] + assertWithMatcher:grey_sufficientlyVisible()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::NavigationBarDoneButton()] + performAction:grey_tap()]; + + // Check the History. + [[EarlGrey + selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_CONTENT_SUGGESTIONS_HISTORY)] + performAction:grey_tap()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::HeaderWithAccessibilityLabelId( + IDS_HISTORY_TITLE)] + assertWithMatcher:grey_sufficientlyVisible()]; + [[EarlGrey + selectElementWithMatcher:chrome_test_util::NavigationBarDoneButton()] + performAction:grey_tap()]; +} + // Tests that the fake omnibox width is correctly updated after a rotation. - (void)testOmniboxWidthRotation { // TODO(crbug.com/652465): Enable the test for iPad when rotation bug is @@ -275,6 +332,24 @@ assertWithMatcher:grey_not(grey_sufficientlyVisible())]; } +// Tests that the app doesn't crash when opening multiple tabs. +- (void)testOpenMultipleTabs { + NSInteger numberOfTabs = 10; + for (NSInteger i = 0; i < numberOfTabs; i++) { + [ChromeEarlGreyUI openNewTab]; + } + id<GREYMatcher> matcher; + if (IsIPadIdiom()) { + matcher = grey_accessibilityID(@"Enter Tab Switcher"); + } else { + matcher = grey_allOf(grey_accessibilityID(kToolbarStackButtonIdentifier), + grey_sufficientlyVisible(), nil); + } + [[EarlGrey selectElementWithMatcher:matcher] + assertWithMatcher:grey_accessibilityValue([NSString + stringWithFormat:@"%@", @(numberOfTabs + 1)])]; +} + // Tests that the promo is correctly displayed and removed once tapped. - (void)testPromoTap { // Setup the promo.
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.h b/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.h index eeeb702f..9b0889b 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.h +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.h
@@ -27,10 +27,6 @@ // plus or minus |margin|. id<GREYMatcher> OmniboxWidthBetween(CGFloat width, CGFloat margin); -// Returns a matcher, which is true if the view's frame.origin.y is equal to -// |offset|. -id<GREYMatcher> HeaderPinnedOffset(CGFloat offset); - // Returns a vector of 10 suggestions. std::vector<ntp_snippets::ContentSuggestion> Suggestions(); } // namespace ntp_home
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.mm index 4caf9a4..74151e9 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.mm
@@ -85,21 +85,6 @@ descriptionBlock:describe]; } -id<GREYMatcher> HeaderPinnedOffset(CGFloat offset) { - MatchesBlock matches = ^BOOL(UIView* view) { - return view.frame.origin.y == offset; - }; - DescribeToBlock describe = ^void(id<GREYDescription> description) { - [description - appendText:[NSString - stringWithFormat:@"CSHeader has correct offset: %g", - offset]]; - }; - - return [[GREYElementMatcherBlock alloc] initWithMatchesBlock:matches - descriptionBlock:describe]; -} - UICollectionView* CollectionView() { return base::mac::ObjCCast<UICollectionView>( SubviewWithAccessibilityIdentifier(
diff --git a/ios/chrome/browser/ui/dialogs/javascript_dialog_egtest.mm b/ios/chrome/browser/ui/dialogs/javascript_dialog_egtest.mm index 8987b1bd..551cd4b 100644 --- a/ios/chrome/browser/ui/dialogs/javascript_dialog_egtest.mm +++ b/ios/chrome/browser/ui/dialogs/javascript_dialog_egtest.mm
@@ -518,9 +518,13 @@ // Show settings. [ChromeEarlGreyUI openSettingsMenu]; - [[EarlGrey selectElementWithMatcher:chrome_test_util:: - StaticTextWithAccessibilityLabelId( - IDS_IOS_SETTINGS_TITLE)] + [[EarlGrey + selectElementWithMatcher:grey_allOf(grey_accessibilityLabel( + l10n_util::GetNSString( + IDS_IOS_SETTINGS_TITLE)), + grey_accessibilityTrait( + UIAccessibilityTraitHeader), + nil)] assertWithMatcher:grey_sufficientlyVisible()]; // Show an alert.
diff --git a/ios/chrome/browser/ui/first_run/first_run_egtest.mm b/ios/chrome/browser/ui/first_run/first_run_egtest.mm index 23dfea50f..eb1b833 100644 --- a/ios/chrome/browser/ui/first_run/first_run_egtest.mm +++ b/ios/chrome/browser/ui/first_run/first_run_egtest.mm
@@ -129,8 +129,12 @@ IDS_IOS_FIRSTRUN_PRIVACY_TITLE))] assertWithMatcher:grey_sufficientlyVisible()]; - [[EarlGrey selectElementWithMatcher:SettingsMenuBackButton()] - performAction:grey_tap()]; + [[EarlGrey + selectElementWithMatcher:grey_allOf( + grey_accessibilityID(@"ic_arrow_back"), + grey_accessibilityTrait( + UIAccessibilityTraitButton), + nil)] performAction:grey_tap()]; // Ensure we went back to the First Run screen. [[EarlGrey selectElementWithMatcher:privacyLink] @@ -150,8 +154,12 @@ IDS_IOS_FIRSTRUN_TERMS_TITLE))] assertWithMatcher:grey_sufficientlyVisible()]; - [[EarlGrey selectElementWithMatcher:SettingsMenuBackButton()] - performAction:grey_tap()]; + [[EarlGrey + selectElementWithMatcher:grey_allOf( + grey_accessibilityID(@"ic_arrow_back"), + grey_accessibilityTrait( + UIAccessibilityTraitButton), + nil)] performAction:grey_tap()]; // Ensure we went back to the First Run screen. [[EarlGrey selectElementWithMatcher:termsOfServiceLink]
diff --git a/ios/chrome/browser/ui/settings/BUILD.gn b/ios/chrome/browser/ui/settings/BUILD.gn index 46d33a3..c01ddf6 100644 --- a/ios/chrome/browser/ui/settings/BUILD.gn +++ b/ios/chrome/browser/ui/settings/BUILD.gn
@@ -44,10 +44,10 @@ "dataplan_usage_table_view_controller.mm", "google_services_navigation_coordinator.h", "google_services_navigation_coordinator.mm", + "google_services_settings_command_handler.h", "google_services_settings_consumer.h", "google_services_settings_coordinator.h", "google_services_settings_coordinator.mm", - "google_services_settings_local_commands.h", "google_services_settings_mediator.h", "google_services_settings_mediator.mm", "google_services_settings_service_delegate.h",
diff --git a/ios/chrome/browser/ui/settings/about_chrome_table_view_controller.mm b/ios/chrome/browser/ui/settings/about_chrome_table_view_controller.mm index 367a3a2c..de3bfce 100644 --- a/ios/chrome/browser/ui/settings/about_chrome_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/about_chrome_table_view_controller.mm
@@ -53,9 +53,8 @@ #pragma mark - Public - (instancetype)init { - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = l10n_util::GetNSString(IDS_IOS_ABOUT_PRODUCT_NAME); }
diff --git a/ios/chrome/browser/ui/settings/accounts_table_view_controller.mm b/ios/chrome/browser/ui/settings/accounts_table_view_controller.mm index 83ad1cb..caf178c 100644 --- a/ios/chrome/browser/ui/settings/accounts_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/accounts_table_view_controller.mm
@@ -126,9 +126,8 @@ closeSettingsOnAddAccount:(BOOL)closeSettingsOnAddAccount { DCHECK(browserState); DCHECK(!browserState->IsOffTheRecord()); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { _browserState = browserState; _closeSettingsOnAddAccount = closeSettingsOnAddAccount;
diff --git a/ios/chrome/browser/ui/settings/autofill_credit_card_edit_table_view_controller.mm b/ios/chrome/browser/ui/settings/autofill_credit_card_edit_table_view_controller.mm index 5268cbe..f19bc5a 100644 --- a/ios/chrome/browser/ui/settings/autofill_credit_card_edit_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/autofill_credit_card_edit_table_view_controller.mm
@@ -64,9 +64,8 @@ - (instancetype)initWithCreditCard:(const autofill::CreditCard&)creditCard personalDataManager:(autofill::PersonalDataManager*)dataManager { - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { DCHECK(dataManager);
diff --git a/ios/chrome/browser/ui/settings/autofill_credit_card_settings_egtest.mm b/ios/chrome/browser/ui/settings/autofill_credit_card_settings_egtest.mm index 02ab75b..e78c20d 100644 --- a/ios/chrome/browser/ui/settings/autofill_credit_card_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/autofill_credit_card_settings_egtest.mm
@@ -50,6 +50,13 @@ NSString* const kCreditCardLabelTemplate = @"Test User, %@"; +// Return the edit button from the navigation bar. +id<GREYMatcher> NavigationBarEditButton() { + return grey_allOf( + ButtonWithAccessibilityLabelId(IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON), + grey_not(grey_accessibilityTrait(UIAccessibilityTraitNotEnabled)), nil); +} + } // namespace // Various tests for the Autofill credit cards section of the settings. @@ -171,8 +178,7 @@ [self openEditCreditCard:[self creditCardLabel:creditCard]]; // Switch on edit mode. - [[EarlGrey selectElementWithMatcher:ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] performAction:grey_tap()]; chrome_test_util::VerifyAccessibilityForCurrentScreen(); @@ -190,8 +196,7 @@ [self openCreditCardsSettings]; // Switch on edit mode. - [[EarlGrey selectElementWithMatcher:ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] performAction:grey_tap()]; // Check the Autofill credit card switch is disabled.
diff --git a/ios/chrome/browser/ui/settings/autofill_credit_card_table_view_controller.mm b/ios/chrome/browser/ui/settings/autofill_credit_card_table_view_controller.mm index b12e6f3c..b22425d 100644 --- a/ios/chrome/browser/ui/settings/autofill_credit_card_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/autofill_credit_card_table_view_controller.mm
@@ -77,9 +77,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = l10n_util::GetNSString(IDS_AUTOFILL_PAYMENT_METHODS); self.shouldHideDoneButton = YES;
diff --git a/ios/chrome/browser/ui/settings/autofill_profile_edit_table_view_controller.mm b/ios/chrome/browser/ui/settings/autofill_profile_edit_table_view_controller.mm index b829140..01a13953 100644 --- a/ios/chrome/browser/ui/settings/autofill_profile_edit_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/autofill_profile_edit_table_view_controller.mm
@@ -95,9 +95,8 @@ personalDataManager:(autofill::PersonalDataManager*)dataManager { DCHECK(dataManager); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { _personalDataManager = dataManager; _autofillProfile = profile;
diff --git a/ios/chrome/browser/ui/settings/autofill_profile_settings_egtest.mm b/ios/chrome/browser/ui/settings/autofill_profile_settings_egtest.mm index 8e50de2..7e1ae8b3 100644 --- a/ios/chrome/browser/ui/settings/autofill_profile_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/autofill_profile_settings_egtest.mm
@@ -85,6 +85,13 @@ stringWithFormat:@"%@_textField", l10n_util::GetNSString(categoryId)]; } +// Return the edit button from the navigation bar. +id<GREYMatcher> NavigationBarEditButton() { + return grey_allOf( + ButtonWithAccessibilityLabelId(IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON), + grey_not(grey_accessibilityTrait(UIAccessibilityTraitNotEnabled)), nil); +} + } // namespace // Various tests for the Autofill profiles section of the settings. @@ -191,8 +198,7 @@ // Keep editing the Country field and verify that validation works. for (const UserTypedCountryExpectedResultPair& expectation : kCountryTests) { // Switch on edit mode. - [[EarlGrey selectElementWithMatcher:ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] performAction:grey_tap()]; // Replace the text field with the user-version of the country. @@ -241,8 +247,7 @@ [self openEditProfile:kProfileLabel]; // Switch on edit mode. - [[EarlGrey selectElementWithMatcher:ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] performAction:grey_tap()]; chrome_test_util::VerifyAccessibilityForCurrentScreen(); @@ -260,8 +265,7 @@ [self openAutofillProfilesSettings]; // Switch on edit mode. - [[EarlGrey selectElementWithMatcher:ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] performAction:grey_tap()]; // Check the Autofill profile switch is disabled.
diff --git a/ios/chrome/browser/ui/settings/autofill_profile_table_view_controller.mm b/ios/chrome/browser/ui/settings/autofill_profile_table_view_controller.mm index e222bd28..ea4a65a04 100644 --- a/ios/chrome/browser/ui/settings/autofill_profile_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/autofill_profile_table_view_controller.mm
@@ -76,9 +76,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = l10n_util::GetNSString(IDS_AUTOFILL_ADDRESSES_SETTINGS_TITLE); self.shouldHideDoneButton = YES;
diff --git a/ios/chrome/browser/ui/settings/bandwidth_management_table_view_controller.mm b/ios/chrome/browser/ui/settings/bandwidth_management_table_view_controller.mm index 53dbb00..6935c9a 100644 --- a/ios/chrome/browser/ui/settings/bandwidth_management_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/bandwidth_management_table_view_controller.mm
@@ -58,9 +58,8 @@ @implementation BandwidthManagementTableViewController - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = l10n_util::GetNSString(IDS_IOS_BANDWIDTH_MANAGEMENT_SETTINGS); _browserState = browserState;
diff --git a/ios/chrome/browser/ui/settings/block_popups_egtest.mm b/ios/chrome/browser/ui/settings/block_popups_egtest.mm index 2b0486d..20b23dd 100644 --- a/ios/chrome/browser/ui/settings/block_popups_egtest.mm +++ b/ios/chrome/browser/ui/settings/block_popups_egtest.mm
@@ -215,10 +215,12 @@ [[EarlGrey selectElementWithMatcher:grey_text(base::SysUTF8ToNSString( allowedPattern))] assertWithMatcher:grey_notVisible()]; - [[EarlGrey - selectElementWithMatcher:grey_accessibilityLabel(l10n_util::GetNSString( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON))] - assertWithMatcher:grey_notVisible()]; + [[EarlGrey selectElementWithMatcher: + grey_allOf(chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON), + grey_not(grey_accessibilityTrait( + UIAccessibilityTraitNotEnabled)), + nil)] assertWithMatcher:grey_notVisible()]; [[EarlGrey selectElementWithMatcher:SettingsDoneButton()] assertWithMatcher:grey_sufficientlyVisible()]; @@ -230,10 +232,12 @@ [[EarlGrey selectElementWithMatcher:grey_text(base::SysUTF8ToNSString( allowedPattern))] assertWithMatcher:grey_sufficientlyVisible()]; - [[EarlGrey - selectElementWithMatcher:grey_accessibilityLabel(l10n_util::GetNSString( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON))] - assertWithMatcher:grey_sufficientlyVisible()]; + [[EarlGrey selectElementWithMatcher: + grey_allOf(chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON), + grey_not(grey_accessibilityTrait( + UIAccessibilityTraitNotEnabled)), + nil)] assertWithMatcher:grey_sufficientlyVisible()]; // Close the settings menu. [[EarlGrey selectElementWithMatcher:SettingsMenuBackButton()]
diff --git a/ios/chrome/browser/ui/settings/block_popups_table_view_controller.mm b/ios/chrome/browser/ui/settings/block_popups_table_view_controller.mm index 0e496a60..dfd59209 100644 --- a/ios/chrome/browser/ui/settings/block_popups_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/block_popups_table_view_controller.mm
@@ -63,9 +63,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { _browserState = browserState; HostContentSettingsMap* settingsMap =
diff --git a/ios/chrome/browser/ui/settings/cells/BUILD.gn b/ios/chrome/browser/ui/settings/cells/BUILD.gn index 98b0d91..c30184c 100644 --- a/ios/chrome/browser/ui/settings/cells/BUILD.gn +++ b/ios/chrome/browser/ui/settings/cells/BUILD.gn
@@ -28,6 +28,8 @@ "settings_cells_constants.mm", "settings_detail_item.h", "settings_detail_item.mm", + "settings_image_detail_text_item.h", + "settings_image_detail_text_item.mm", "settings_multiline_detail_item.h", "settings_multiline_detail_item.mm", "settings_search_item.h",
diff --git a/ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.h b/ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.h new file mode 100644 index 0000000..79f1783 --- /dev/null +++ b/ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.h
@@ -0,0 +1,47 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_SETTINGS_CELLS_SETTINGS_IMAGE_DETAIL_TEXT_ITEM_H_ +#define IOS_CHROME_BROWSER_UI_SETTINGS_CELLS_SETTINGS_IMAGE_DETAIL_TEXT_ITEM_H_ + +#import <Foundation/Foundation.h> + +#import "ios/chrome/browser/ui/table_view/cells/table_view_item.h" + +// SettingsImageDetailTextItem is an item that displays an image, a title and +// a detail text (optional). This item uses multi-lines text field. +@interface SettingsImageDetailTextItem : TableViewItem + +// The image to display (required). +@property(nonatomic, strong) UIImage* image; + +// The title text to display. +@property(nonatomic, copy) NSString* text; + +// The detail text to display. +@property(nonatomic, copy) NSString* detailText; + +@end + +// Cell representation for SettingsImageDetailTextItem. +// +--------------------------------------------------+ +// | +-------+ | +// | | image | Multiline title | +// | | | Optional multiline detail text | +// | +-------+ | +// +--------------------------------------------------+ +@interface SettingsImageDetailTextCell : UITableViewCell + +// Cell image. +@property(nonatomic, readonly, strong) UIImageView* imageView; + +// Cell title. +@property(nonatomic, readonly, strong) UILabel* textLabel; + +// Cell subtitle. +@property(nonatomic, readonly, strong) UILabel* detailTextLabel; + +@end + +#endif // IOS_CHROME_BROWSER_UI_SETTINGS_CELLS_SETTINGS_IMAGE_DETAIL_TEXT_ITEM_H_
diff --git a/ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.mm b/ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.mm new file mode 100644 index 0000000..bf073c1 --- /dev/null +++ b/ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.mm
@@ -0,0 +1,146 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.h" + +#include "base/logging.h" +#include "ios/chrome/browser/ui/table_view/cells/table_view_cells_constants.h" +#import "ios/chrome/browser/ui/util/uikit_ui_util.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface SettingsImageDetailTextCell () + +@property(nonatomic, weak, readonly) NSLayoutConstraint* imageWidthConstraint; +@property(nonatomic, weak, readonly) NSLayoutConstraint* imageHeightConstraint; + +@end + +#pragma mark - SettingsImageDetailTextItem + +@implementation SettingsImageDetailTextItem + +- (instancetype)initWithType:(NSInteger)type { + self = [super initWithType:type]; + if (self) { + self.cellClass = [SettingsImageDetailTextCell class]; + } + return self; +} + +- (void)configureCell:(SettingsImageDetailTextCell*)cell + withStyler:(ChromeTableViewStyler*)styler { + [super configureCell:cell withStyler:styler]; + cell.textLabel.text = self.text; + cell.detailTextLabel.text = self.detailText; + DCHECK(self.image); + cell.imageView.image = self.image; + cell.imageWidthConstraint.constant = self.image.size.width; + cell.imageHeightConstraint.constant = self.image.size.height; +} + +@end + +#pragma mark - SettingsImageDetailTextCell + +@implementation SettingsImageDetailTextCell + +@synthesize imageView = _imageView; +@synthesize textLabel = _textLabel; +@synthesize detailTextLabel = _detailTextLabel; + +- (instancetype)initWithStyle:(UITableViewCellStyle)style + reuseIdentifier:(NSString*)reuseIdentifier { + self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; + if (self) { + self.isAccessibilityElement = YES; + [self addSubviews]; + [self setViewConstraints]; + } + return self; +} + +// Creates and adds subviews. +- (void)addSubviews { + UIView* contentView = self.contentView; + + _imageView = [[UIImageView alloc] init]; + _imageView.translatesAutoresizingMaskIntoConstraints = NO; + [contentView addSubview:_imageView]; + + _textLabel = [[UILabel alloc] init]; + _textLabel.numberOfLines = 0; + _textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; + _textLabel.adjustsFontForContentSizeCategory = YES; + _textLabel.textColor = UIColor.blackColor; + + _detailTextLabel = [[UILabel alloc] init]; + _detailTextLabel.numberOfLines = 0; + _detailTextLabel.font = + [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]; + _detailTextLabel.adjustsFontForContentSizeCategory = YES; + _detailTextLabel.textColor = + UIColorFromRGB(kTableViewSecondaryLabelLightGrayTextColor); +} + +// Sets constraints on subviews. +- (void)setViewConstraints { + UIView* contentView = self.contentView; + + UIStackView* textStackView = [[UIStackView alloc] + initWithArrangedSubviews:@[ _textLabel, _detailTextLabel ]]; + textStackView.axis = UILayoutConstraintAxisVertical; + textStackView.translatesAutoresizingMaskIntoConstraints = NO; + [contentView addSubview:textStackView]; + + _imageWidthConstraint = [_imageView.widthAnchor constraintEqualToConstant:0]; + _imageHeightConstraint = + [_imageView.heightAnchor constraintEqualToConstant:0]; + + [NSLayoutConstraint activateConstraints:@[ + // Horizontal contraints for |_imageView| and |textStackView|. + _imageWidthConstraint, + [_imageView.leadingAnchor + constraintEqualToAnchor:contentView.leadingAnchor + constant:kTableViewHorizontalSpacing], + [textStackView.leadingAnchor + constraintEqualToAnchor:_imageView.trailingAnchor + constant:kTableViewHorizontalSpacing], + [contentView.trailingAnchor + constraintEqualToAnchor:textStackView.trailingAnchor + constant:kTableViewHorizontalSpacing], + // Vertical contraints for |_imageView| and |textStackView|. + _imageHeightConstraint, + [_imageView.centerYAnchor + constraintEqualToAnchor:contentView.centerYAnchor], + [_imageView.topAnchor + constraintGreaterThanOrEqualToAnchor:contentView.topAnchor + constant:kTableViewLargeVerticalSpacing], + [contentView.bottomAnchor + constraintGreaterThanOrEqualToAnchor:_imageView.bottomAnchor + constant:kTableViewLargeVerticalSpacing], + [textStackView.centerYAnchor + constraintEqualToAnchor:contentView.centerYAnchor], + [textStackView.topAnchor + constraintGreaterThanOrEqualToAnchor:contentView.topAnchor + constant:kTableViewLargeVerticalSpacing], + [contentView.bottomAnchor + constraintGreaterThanOrEqualToAnchor:textStackView.bottomAnchor + constant:kTableViewLargeVerticalSpacing], + ]]; +} + +#pragma mark - UIAccessibility + +- (NSString*)accessibilityLabel { + if (self.detailTextLabel.text) { + return [NSString stringWithFormat:@"%@, %@", self.textLabel.text, + self.detailTextLabel.text]; + } + return self.textLabel.text; +} + +@end
diff --git a/ios/chrome/browser/ui/settings/clear_browsing_data_collection_view_controller.mm b/ios/chrome/browser/ui/settings/clear_browsing_data_collection_view_controller.mm index 0cab8c41..35f648d 100644 --- a/ios/chrome/browser/ui/settings/clear_browsing_data_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/clear_browsing_data_collection_view_controller.mm
@@ -124,8 +124,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); UICollectionViewLayout* layout = [[MDCCollectionViewFlowLayout alloc] init]; - self = - [super initWithLayout:layout style:CollectionViewControllerStyleAppBar]; + self = [super initWithLayout:layout + style:CollectionViewControllerStyleDefault]; if (self) { self.accessibilityTraits |= UIAccessibilityTraitButton;
diff --git a/ios/chrome/browser/ui/settings/content_settings_table_view_controller.mm b/ios/chrome/browser/ui/settings/content_settings_table_view_controller.mm index a2a6c9b..4029f8a 100644 --- a/ios/chrome/browser/ui/settings/content_settings_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/content_settings_table_view_controller.mm
@@ -77,9 +77,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { browserState_ = browserState; self.title = l10n_util::GetNSString(IDS_IOS_CONTENT_SETTINGS_TITLE);
diff --git a/ios/chrome/browser/ui/settings/dataplan_usage_table_view_controller.mm b/ios/chrome/browser/ui/settings/dataplan_usage_table_view_controller.mm index 2ef7fc28..cb936ab 100644 --- a/ios/chrome/browser/ui/settings/dataplan_usage_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/dataplan_usage_table_view_controller.mm
@@ -53,9 +53,8 @@ basePref:(const char*)basePreference wifiPref:(const char*)wifiPreference title:(NSString*)title { - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = title; basePreference_.Init(basePreference, prefs);
diff --git a/ios/chrome/browser/ui/settings/google_services_settings_local_commands.h b/ios/chrome/browser/ui/settings/google_services_settings_command_handler.h similarity index 74% rename from ios/chrome/browser/ui/settings/google_services_settings_local_commands.h rename to ios/chrome/browser/ui/settings/google_services_settings_command_handler.h index fd30a07..75a998e2 100644 --- a/ios/chrome/browser/ui/settings/google_services_settings_local_commands.h +++ b/ios/chrome/browser/ui/settings/google_services_settings_command_handler.h
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_SETTINGS_LOCAL_COMMANDS_H_ -#define IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_SETTINGS_LOCAL_COMMANDS_H_ +#ifndef IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_SETTINGS_COMMAND_HANDLER_H_ +#define IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_SETTINGS_COMMAND_HANDLER_H_ -// Protocol to communicate GoogleServicesSettingsVC actions to its coordinator. -@protocol GoogleServicesSettingsLocalCommands<NSObject> +// Protocol to communicate user actions from the mediator to its coordinator. +@protocol GoogleServicesSettingsCommandHandler <NSObject> // Restarts the authentication flow. - (void)restartAuthenticationFlow; @@ -19,4 +19,4 @@ @end -#endif // IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_SETTINGS_LOCAL_COMMANDS_H_ +#endif // IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_SETTINGS_COMMAND_HANDLER_H_
diff --git a/ios/chrome/browser/ui/settings/google_services_settings_coordinator.mm b/ios/chrome/browser/ui/settings/google_services_settings_coordinator.mm index 9c0bc49e..309feec 100644 --- a/ios/chrome/browser/ui/settings/google_services_settings_coordinator.mm +++ b/ios/chrome/browser/ui/settings/google_services_settings_coordinator.mm
@@ -14,7 +14,7 @@ #include "ios/chrome/browser/sync/sync_setup_service_factory.h" #import "ios/chrome/browser/ui/authentication/authentication_flow.h" #import "ios/chrome/browser/ui/commands/application_commands.h" -#import "ios/chrome/browser/ui/settings/google_services_settings_local_commands.h" +#import "ios/chrome/browser/ui/settings/google_services_settings_command_handler.h" #import "ios/chrome/browser/ui/settings/google_services_settings_mediator.h" #import "ios/chrome/browser/ui/settings/google_services_settings_view_controller.h" #include "ios/chrome/browser/unified_consent/unified_consent_service_factory.h" @@ -24,8 +24,8 @@ #error "This file requires ARC support." #endif -@interface GoogleServicesSettingsCoordinator ()< - GoogleServicesSettingsLocalCommands, +@interface GoogleServicesSettingsCoordinator () < + GoogleServicesSettingsCommandHandler, GoogleServicesSettingsViewControllerPresentationDelegate> // Google services settings mediator. @@ -47,9 +47,8 @@ GoogleServicesSettingsViewController* viewController = [[GoogleServicesSettingsViewController alloc] initWithLayout:layout - style:CollectionViewControllerStyleAppBar]; + style:CollectionViewControllerStyleDefault]; viewController.presentationDelegate = self; - viewController.localDispatcher = self; self.viewController = viewController; SyncSetupService* syncSetupService = SyncSetupServiceFactory::GetForBrowserState(self.browserState); @@ -62,6 +61,7 @@ unifiedConsentService:unifiedConsentService]; self.mediator.consumer = viewController; self.mediator.authService = self.authService; + self.mediator.commandHandler = self; viewController.modelDelegate = self.mediator; viewController.serviceDelegate = self.mediator; DCHECK(self.navigationController); @@ -86,7 +86,7 @@ self.viewController); } -#pragma mark - GoogleServicesSettingsLocalCommands +#pragma mark - GoogleServicesSettingsCommandHandler - (void)restartAuthenticationFlow { ChromeIdentity* authenticatedIdentity =
diff --git a/ios/chrome/browser/ui/settings/google_services_settings_egtest.mm b/ios/chrome/browser/ui/settings/google_services_settings_egtest.mm index a7ff41253..6abf779e7 100644 --- a/ios/chrome/browser/ui/settings/google_services_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/google_services_settings_egtest.mm
@@ -49,8 +49,6 @@ chrome_test_util::VerifyAccessibilityForCurrentScreen(); // Close settings. - [[EarlGrey selectElementWithMatcher:SettingsMenuBackButton()] - performAction:grey_tap()]; [[EarlGrey selectElementWithMatcher:SettingsDoneButton()] performAction:grey_tap()]; }
diff --git a/ios/chrome/browser/ui/settings/google_services_settings_mediator.h b/ios/chrome/browser/ui/settings/google_services_settings_mediator.h index f931223f..576df88 100644 --- a/ios/chrome/browser/ui/settings/google_services_settings_mediator.h +++ b/ios/chrome/browser/ui/settings/google_services_settings_mediator.h
@@ -13,6 +13,7 @@ #import "ios/chrome/browser/ui/settings/google_services_settings_view_controller_model_delegate.h" class AuthenticationService; +@protocol GoogleServicesSettingsCommandHandler; @class GoogleServicesSettingsViewController; class PrefService; class SyncSetupService; @@ -23,13 +24,16 @@ // Mediator for the Google services settings. @interface GoogleServicesSettingsMediator - : NSObject<GoogleServicesSettingsServiceDelegate, - GoogleServicesSettingsViewControllerModelDelegate> + : NSObject <GoogleServicesSettingsServiceDelegate, + GoogleServicesSettingsViewControllerModelDelegate> // View controller. @property(nonatomic, weak) id<GoogleServicesSettingsConsumer> consumer; // Authentication service. @property(nonatomic, assign) AuthenticationService* authService; +// Command handler. +@property(nonatomic, weak) id<GoogleServicesSettingsCommandHandler> + commandHandler; // Designated initializer. All the paramters should not be null. // |userPrefService|: preference service from the browser state.
diff --git a/ios/chrome/browser/ui/settings/google_services_settings_mediator.mm b/ios/chrome/browser/ui/settings/google_services_settings_mediator.mm index 216ddde6..11bf8e37 100644 --- a/ios/chrome/browser/ui/settings/google_services_settings_mediator.mm +++ b/ios/chrome/browser/ui/settings/google_services_settings_mediator.mm
@@ -15,6 +15,7 @@ #import "ios/chrome/browser/signin/authentication_service_factory.h" #import "ios/chrome/browser/ui/settings/cells/legacy/legacy_settings_image_detail_text_item.h" #import "ios/chrome/browser/ui/settings/cells/legacy/legacy_sync_switch_item.h" +#import "ios/chrome/browser/ui/settings/google_services_settings_command_handler.h" #import "ios/chrome/browser/ui/settings/sync_utils/sync_util.h" #import "ios/chrome/browser/ui/settings/utils/observable_boolean.h" #import "ios/chrome/browser/ui/settings/utils/pref_backed_boolean.h" @@ -42,7 +43,9 @@ // List of items. typedef NS_ENUM(NSInteger, ItemType) { // SyncErrorSectionIdentifier, - SyncErrorItemType = kItemTypeEnumZero, + RestartAuthenticationFlowErrorItemType = kItemTypeEnumZero, + ReauthDialogAsSyncIsInAuthErrorItemType, + ShowPassphraseDialogErrorItemType, // NonPersonalizedSectionIdentifier section. AutocompleteSearchesAndURLsItemType, PreloadPagesItemType, @@ -90,8 +93,6 @@ // YES if at least one switch in the personalized section is currently animating // from one state to another. @property(nonatomic, assign) BOOL personalizedSectionBeingAnimated; -// Item to display the sync error. -@property(nonatomic, strong) LegacySettingsImageDetailTextItem* syncErrorItem; // All the items for the personalized section. @property(nonatomic, strong, readonly) ItemArray personalizedItems; // Item for the autocomplete wallet feature. @@ -170,23 +171,6 @@ return self.authService->IsAuthenticated(); } -- (LegacySettingsImageDetailTextItem*)syncErrorItem { - if (!_syncErrorItem) { - _syncErrorItem = [[LegacySettingsImageDetailTextItem alloc] - initWithType:SyncErrorItemType]; - { - // TODO(crbug.com/889470): Needs asset for the sync error. - CGSize size = CGSizeMake(40, 40); - UIGraphicsBeginImageContextWithOptions(size, YES, 0); - [[UIColor grayColor] setFill]; - UIRectFill(CGRectMake(0, 0, size.width, size.height)); - _syncErrorItem.image = UIGraphicsGetImageFromCurrentImageContext(); - UIGraphicsEndImageContext(); - } - } - return _syncErrorItem; -} - - (ItemArray)nonPersonalizedItems { if (!_nonPersonalizedItems) { LegacySyncSwitchItem* autocompleteSearchesAndURLsItem = [self @@ -195,8 +179,6 @@ IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_TEXT detailStringID: IDS_IOS_GOOGLE_SERVICES_SETTINGS_AUTOCOMPLETE_SEARCHES_AND_URLS_DETAIL - commandID: - GoogleServicesSettingsCommandIDToggleAutocompleteSearchesService dataType:0]; LegacySyncSwitchItem* preloadPagesItem = [self switchItemWithItemType:PreloadPagesItemType @@ -204,8 +186,6 @@ IDS_IOS_GOOGLE_SERVICES_SETTINGS_PRELOAD_PAGES_TEXT detailStringID: IDS_IOS_GOOGLE_SERVICES_SETTINGS_PRELOAD_PAGES_DETAIL - commandID: - GoogleServicesSettingsCommandIDTogglePreloadPagesService dataType:0]; LegacySyncSwitchItem* improveChromeItem = [self switchItemWithItemType:ImproveChromeItemType @@ -213,8 +193,6 @@ IDS_IOS_GOOGLE_SERVICES_SETTINGS_IMPROVE_CHROME_TEXT detailStringID: IDS_IOS_GOOGLE_SERVICES_SETTINGS_IMPROVE_CHROME_DETAIL - commandID: - GoogleServicesSettingsCommandIDToggleImproveChromeService dataType:0]; LegacySyncSwitchItem* betterSearchAndBrowsingItemType = [self switchItemWithItemType:BetterSearchAndBrowsingItemType @@ -222,8 +200,6 @@ IDS_IOS_GOOGLE_SERVICES_SETTINGS_BETTER_SEARCH_AND_BROWSING_TEXT detailStringID: IDS_IOS_GOOGLE_SERVICES_SETTINGS_BETTER_SEARCH_AND_BROWSING_DETAIL - commandID: - GoogleServicesSettingsCommandIDToggleBetterSearchAndBrowsingService dataType:0]; _nonPersonalizedItems = @[ autocompleteSearchesAndURLsItem, preloadPagesItem, improveChromeItem, @@ -239,34 +215,55 @@ - (LegacySyncSwitchItem*)switchItemWithItemType:(NSInteger)itemType textStringID:(int)textStringID detailStringID:(int)detailStringID - commandID:(NSInteger)commandID dataType:(NSInteger)dataType { LegacySyncSwitchItem* switchItem = [[LegacySyncSwitchItem alloc] initWithType:itemType]; switchItem.text = GetNSString(textStringID); if (detailStringID) switchItem.detailText = GetNSString(detailStringID); - switchItem.commandID = commandID; switchItem.dataType = dataType; return switchItem; } +// Creates a item to display the sync error. +- (LegacySettingsImageDetailTextItem*)createSyncErrorItemWithItemType: + (NSInteger)itemType { + LegacySettingsImageDetailTextItem* syncErrorItem = + [[LegacySettingsImageDetailTextItem alloc] initWithType:itemType]; + syncErrorItem.text = l10n_util::GetNSString(IDS_IOS_SYNC_ERROR_TITLE); + syncErrorItem.detailText = + GetSyncErrorDescriptionForSyncSetupService(self.syncSetupService); + { + // TODO(crbug.com/889470): Needs asset for the sync error. + CGSize size = CGSizeMake(40, 40); + UIGraphicsBeginImageContextWithOptions(size, YES, 0); + [[UIColor grayColor] setFill]; + UIRectFill(CGRectMake(0, 0, size.width, size.height)); + syncErrorItem.image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + } + return syncErrorItem; +} + // Reloads the sync feedback section. If |notifyConsummer| is YES, the consomer // is notified to add or remove the sync error section. - (void)updateSyncErrorSectionAndNotifyConsumer:(BOOL)notifyConsummer { CollectionViewModel* model = self.consumer.collectionViewModel; - GoogleServicesSettingsCommandID commandID = - GoogleServicesSettingsCommandIDNoOp; + BOOL hasError = NO; + ItemType type; if (self.isAuthenticated) { switch (self.syncSetupService->GetSyncServiceState()) { case SyncSetupService::kSyncServiceUnrecoverableError: - commandID = GoogleServicesSettingsCommandIDRestartAuthenticationFlow; + type = RestartAuthenticationFlowErrorItemType; + hasError = YES; break; case SyncSetupService::kSyncServiceSignInNeedsUpdate: - commandID = GoogleServicesSettingsReauthDialogAsSyncIsInAuthError; + type = ReauthDialogAsSyncIsInAuthErrorItemType; + hasError = YES; break; case SyncSetupService::kSyncServiceNeedsPassphrase: - commandID = GoogleServicesSettingsCommandIDShowPassphraseDialog; + type = ShowPassphraseDialogErrorItemType; + hasError = YES; break; case SyncSetupService::kNoSyncServiceError: case SyncSetupService::kSyncServiceCouldNotConnect: @@ -274,7 +271,7 @@ break; } } - if (commandID == GoogleServicesSettingsCommandIDNoOp) { + if (!hasError) { // No action to do, therefore the sync error section should not be visibled. if ([model hasSectionForSectionIdentifier:SyncFeedbackSectionIdentifier]) { // Remove the sync error item if it exists. @@ -291,25 +288,28 @@ // Add the sync error item and its section (if it doesn't already exist) and // reload them. BOOL sectionAdded = NO; + LegacySettingsImageDetailTextItem* syncErrorItem = + [self createSyncErrorItemWithItemType:type]; if (![model hasSectionForSectionIdentifier:SyncFeedbackSectionIdentifier]) { // Adding the sync error item and its section. [model insertSectionWithIdentifier:SyncFeedbackSectionIdentifier atIndex:0]; - [model addItem:self.syncErrorItem + [model addItem:syncErrorItem toSectionWithIdentifier:SyncFeedbackSectionIdentifier]; sectionAdded = YES; + } else { + [model + deleteAllItemsFromSectionWithIdentifier:SyncFeedbackSectionIdentifier]; + [model addItem:syncErrorItem + toSectionWithIdentifier:SyncFeedbackSectionIdentifier]; } - NSUInteger sectionIndex = - [model sectionForSectionIdentifier:SyncFeedbackSectionIdentifier]; - self.syncErrorItem.text = l10n_util::GetNSString(IDS_IOS_SYNC_ERROR_TITLE); - self.syncErrorItem.detailText = - GetSyncErrorDescriptionForSyncSetupService(self.syncSetupService); - self.syncErrorItem.commandID = commandID; if (notifyConsummer) { + NSUInteger sectionIndex = + [model sectionForSectionIdentifier:SyncFeedbackSectionIdentifier]; + NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:sectionIndex]; if (sectionAdded) { - NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:sectionIndex]; [self.consumer insertSections:indexSet]; } else { - [self.consumer reloadItem:self.syncErrorItem]; + [self.consumer reloadSections:indexSet]; } } } @@ -317,25 +317,27 @@ // Updates the non-personalized section according to the user consent. - (void)updateNonPersonalizedSection { for (CollectionViewItem* item in self.nonPersonalizedItems) { - if ([item isKindOfClass:[LegacySyncSwitchItem class]]) { - LegacySyncSwitchItem* switchItem = - base::mac::ObjCCast<LegacySyncSwitchItem>(item); - switch (switchItem.commandID) { - case GoogleServicesSettingsCommandIDToggleAutocompleteSearchesService: - switchItem.on = self.autocompleteSearchPreference.value; - break; - case GoogleServicesSettingsCommandIDTogglePreloadPagesService: - switchItem.on = self.preloadPagesPreference.value; - break; - case GoogleServicesSettingsCommandIDToggleImproveChromeService: - switchItem.on = self.sendDataUsagePreference.value; - break; - case GoogleServicesSettingsCommandIDToggleBetterSearchAndBrowsingService: - switchItem.on = self.anonymizedDataCollectionPreference.value; - break; - } - } else { - NOTREACHED(); + ItemType type = static_cast<ItemType>(item.type); + LegacySyncSwitchItem* switchItem = + base::mac::ObjCCastStrict<LegacySyncSwitchItem>(item); + switch (type) { + case AutocompleteSearchesAndURLsItemType: + switchItem.on = self.autocompleteSearchPreference.value; + break; + case PreloadPagesItemType: + switchItem.on = self.preloadPagesPreference.value; + break; + case ImproveChromeItemType: + switchItem.on = self.sendDataUsagePreference.value; + break; + case BetterSearchAndBrowsingItemType: + switchItem.on = self.anonymizedDataCollectionPreference.value; + break; + case RestartAuthenticationFlowErrorItemType: + case ReauthDialogAsSyncIsInAuthErrorItemType: + case ShowPassphraseDialogErrorItemType: + NOTREACHED(); + break; } } } @@ -351,32 +353,74 @@ #pragma mark - GoogleServicesSettingsServiceDelegate -- (void)toggleAutocompleteWalletServiceWithValue:(BOOL)value { - self.autocompleteWalletPreference.value = value; -} - -- (void)toggleAutocompleteSearchesServiceWithValue:(BOOL)value { - self.autocompleteSearchPreference.value = value; -} - -- (void)togglePreloadPagesServiceWithValue:(BOOL)value { - self.preloadPagesPreference.value = value; - if (value) { - // Should be wifi only, until https://crbug.com/872101 is fixed. - self.preloadPagesWifiOnlyPreference.value = YES; +- (void)toggleSwitchItem:(LegacySyncSwitchItem*)switchItem + withValue:(BOOL)value { + ItemType type = static_cast<ItemType>(switchItem.type); + switch (type) { + case AutocompleteSearchesAndURLsItemType: + self.autocompleteSearchPreference.value = value; + break; + case PreloadPagesItemType: + self.preloadPagesPreference.value = value; + if (value) { + // Should be wifi only, until https://crbug.com/872101 is fixed. + self.preloadPagesWifiOnlyPreference.value = YES; + } + break; + case ImproveChromeItemType: + self.sendDataUsagePreference.value = value; + if (value) { + // Should be wifi only, until https://crbug.com/872101 is fixed. + self.sendDataUsageWifiOnlyPreference.value = YES; + } + break; + case BetterSearchAndBrowsingItemType: + self.anonymizedDataCollectionPreference.value = value; + break; + case RestartAuthenticationFlowErrorItemType: + case ReauthDialogAsSyncIsInAuthErrorItemType: + case ShowPassphraseDialogErrorItemType: + NOTREACHED(); + break; } } -- (void)toggleImproveChromeServiceWithValue:(BOOL)value { - self.sendDataUsagePreference.value = value; - if (value) { - // Should be wifi only, until https://crbug.com/872101 is fixed. - self.sendDataUsageWifiOnlyPreference.value = YES; +- (BOOL)shouldHighlightItem:(CollectionViewItem*)item { + ItemType type = static_cast<ItemType>(item.type); + switch (type) { + case RestartAuthenticationFlowErrorItemType: + case ReauthDialogAsSyncIsInAuthErrorItemType: + case ShowPassphraseDialogErrorItemType: + return YES; + break; + case AutocompleteSearchesAndURLsItemType: + case PreloadPagesItemType: + case ImproveChromeItemType: + case BetterSearchAndBrowsingItemType: + return NO; + break; } } -- (void)toggleBetterSearchAndBrowsingServiceWithValue:(BOOL)value { - self.anonymizedDataCollectionPreference.value = value; +- (void)didSelectItem:(CollectionViewItem*)item { + ItemType type = static_cast<ItemType>(item.type); + switch (type) { + case RestartAuthenticationFlowErrorItemType: + [self.commandHandler restartAuthenticationFlow]; + break; + case ReauthDialogAsSyncIsInAuthErrorItemType: + [self.commandHandler openReauthDialogAsSyncIsInAuthError]; + break; + case ShowPassphraseDialogErrorItemType: + [self.commandHandler openPassphraseDialog]; + break; + case AutocompleteSearchesAndURLsItemType: + case PreloadPagesItemType: + case ImproveChromeItemType: + case BetterSearchAndBrowsingItemType: + NOTREACHED(); + break; + } } #pragma mark - BooleanObserver
diff --git a/ios/chrome/browser/ui/settings/google_services_settings_service_delegate.h b/ios/chrome/browser/ui/settings/google_services_settings_service_delegate.h index ae7b3f7..60fd6c1 100644 --- a/ios/chrome/browser/ui/settings/google_services_settings_service_delegate.h +++ b/ios/chrome/browser/ui/settings/google_services_settings_service_delegate.h
@@ -5,49 +5,21 @@ #ifndef IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_SETTINGS_SERVICE_DELEGATE_H_ #define IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_SETTINGS_SERVICE_DELEGATE_H_ -// List of Google Services Settings commands. -typedef NS_ENUM(NSInteger, GoogleServicesSettingsCommandID) { - // Does nothing. - GoogleServicesSettingsCommandIDNoOp, +@class CollectionViewItem; +@class LegacySyncSwitchItem; - // Restarts the sign-in authentication flow. Related to error: - // SyncSetupService::kSyncServiceUnrecoverableError. - GoogleServicesSettingsCommandIDRestartAuthenticationFlow, - // Opens the reauth sync dialog. Related to error: - // SyncSetupService::kSyncServiceNeedsPassphrase. - GoogleServicesSettingsReauthDialogAsSyncIsInAuthError, - // Opens the passphrase dialog. Related to error: - // SyncSetupService::kSyncServiceNeedsPassphrase. - GoogleServicesSettingsCommandIDShowPassphraseDialog, - - // Non-personalized section. - // Enable/disabble autocomplete searches service. - GoogleServicesSettingsCommandIDToggleAutocompleteSearchesService, - // Enable/disabble preload pages service. - GoogleServicesSettingsCommandIDTogglePreloadPagesService, - // Enable/disabble improve chrome service. - GoogleServicesSettingsCommandIDToggleImproveChromeService, - // Enable/disabble better search and browsing service. - GoogleServicesSettingsCommandIDToggleBetterSearchAndBrowsingService, -}; - -// Protocol to handle Google services settings commands. +// Protocol to handle user actions from the Google services settings view. @protocol GoogleServicesSettingsServiceDelegate<NSObject> -// Non-personalized section. -// Called when GoogleServicesSettingsCommandIDToggleAutocompleteSearchesService -// is triggered. -- (void)toggleAutocompleteSearchesServiceWithValue:(BOOL)value; -// Called when GoogleServicesSettingsCommandIDTogglePreloadPagesService is -// triggered. -- (void)togglePreloadPagesServiceWithValue:(BOOL)value; -// Called when GoogleServicesSettingsCommandIDToggleImproveChromeService is -// triggered. -- (void)toggleImproveChromeServiceWithValue:(BOOL)value; -// Called when -// GoogleServicesSettingsCommandIDToggleBetterSearchAndBrowsingService is -// triggered. -- (void)toggleBetterSearchAndBrowsingServiceWithValue:(BOOL)value; +// Called when the UISwitch from the LegacySyncSwitchItem is toggled. +- (void)toggleSwitchItem:(LegacySyncSwitchItem*)switchItem + withValue:(BOOL)value; + +// Returns YES if the item can be highlighted; +- (BOOL)shouldHighlightItem:(CollectionViewItem*)item; + +// Called when cell is tapped. +- (void)didSelectItem:(CollectionViewItem*)item; @end
diff --git a/ios/chrome/browser/ui/settings/google_services_settings_view_controller.h b/ios/chrome/browser/ui/settings/google_services_settings_view_controller.h index 27b0026..b503e5e 100644 --- a/ios/chrome/browser/ui/settings/google_services_settings_view_controller.h +++ b/ios/chrome/browser/ui/settings/google_services_settings_view_controller.h
@@ -11,7 +11,6 @@ @class GoogleServicesSettingsViewController; @protocol GoogleServicesSettingsServiceDelegate; -@protocol GoogleServicesSettingsLocalCommands; @protocol GoogleServicesSettingsViewControllerModelDelegate; // Delegate for presentation events related to @@ -38,9 +37,6 @@ // Handler for GoogleServicesSettingsCommand. @property(nonatomic, weak) id<GoogleServicesSettingsServiceDelegate> serviceDelegate; -// Local command dispatcher. -@property(nonatomic, weak) id<GoogleServicesSettingsLocalCommands> - localDispatcher; @end
diff --git a/ios/chrome/browser/ui/settings/google_services_settings_view_controller.mm b/ios/chrome/browser/ui/settings/google_services_settings_view_controller.mm index e6907053..1c4245b 100644 --- a/ios/chrome/browser/ui/settings/google_services_settings_view_controller.mm +++ b/ios/chrome/browser/ui/settings/google_services_settings_view_controller.mm
@@ -6,9 +6,7 @@ #include "base/mac/foundation_util.h" #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" -#import "ios/chrome/browser/ui/settings/cells/legacy/legacy_settings_image_detail_text_item.h" #import "ios/chrome/browser/ui/settings/cells/legacy/legacy_sync_switch_item.h" -#import "ios/chrome/browser/ui/settings/google_services_settings_local_commands.h" #import "ios/chrome/browser/ui/settings/google_services_settings_service_delegate.h" #import "ios/chrome/browser/ui/settings/google_services_settings_view_controller_model_delegate.h" #include "ios/chrome/grit/ios_strings.h" @@ -56,30 +54,7 @@ LegacySyncSwitchItem* syncSwitchItem = base::mac::ObjCCastStrict<LegacySyncSwitchItem>( [self.collectionViewModel itemAtIndexPath:indexPath]); - BOOL isOn = sender.isOn; - GoogleServicesSettingsCommandID commandID = - static_cast<GoogleServicesSettingsCommandID>(syncSwitchItem.commandID); - switch (commandID) { - case GoogleServicesSettingsCommandIDToggleAutocompleteSearchesService: - [self.serviceDelegate toggleAutocompleteSearchesServiceWithValue:isOn]; - break; - case GoogleServicesSettingsCommandIDTogglePreloadPagesService: - [self.serviceDelegate togglePreloadPagesServiceWithValue:isOn]; - break; - case GoogleServicesSettingsCommandIDToggleImproveChromeService: - [self.serviceDelegate toggleImproveChromeServiceWithValue:isOn]; - break; - case GoogleServicesSettingsCommandIDToggleBetterSearchAndBrowsingService: - [self.serviceDelegate toggleBetterSearchAndBrowsingServiceWithValue:isOn]; - break; - case GoogleServicesSettingsCommandIDRestartAuthenticationFlow: - case GoogleServicesSettingsReauthDialogAsSyncIsInAuthError: - case GoogleServicesSettingsCommandIDShowPassphraseDialog: - case GoogleServicesSettingsCommandIDNoOp: - // Command ID not related with switch action. - NOTREACHED(); - break; - } + [self.serviceDelegate toggleSwitchItem:syncSwitchItem withValue:sender.isOn]; } #pragma mark - UICollectionViewDataSource @@ -178,17 +153,7 @@ shouldHighlightItemAtIndexPath:indexPath]; CollectionViewItem* item = [self.collectionViewModel itemAtIndexPath:indexPath]; - if ([item isKindOfClass:[LegacySyncSwitchItem class]]) { - return NO; - } else if ([item isKindOfClass:[LegacySettingsImageDetailTextItem class]]) { - return YES; - } - // The highlight of an item should be explicitly defined. If the item can be - // highlighted, then a command ID should be defined in - // -[GoogleServicesSettingsViewController collectionView: - // didSelectItemAtIndexPath:]. - NOTREACHED(); - return NO; + return [self.serviceDelegate shouldHighlightItem:item]; } - (void)collectionView:(UICollectionView*)collectionView @@ -196,36 +161,7 @@ [super collectionView:collectionView didSelectItemAtIndexPath:indexPath]; CollectionViewItem* item = [self.collectionViewModel itemAtIndexPath:indexPath]; - GoogleServicesSettingsCommandID commandID = - GoogleServicesSettingsCommandIDNoOp; - if ([item isKindOfClass:[LegacySettingsImageDetailTextItem class]]) { - LegacySettingsImageDetailTextItem* imageDetailTextItem = - base::mac::ObjCCast<LegacySettingsImageDetailTextItem>(item); - commandID = static_cast<GoogleServicesSettingsCommandID>( - imageDetailTextItem.commandID); - } else { - // A command ID should be defined when the cell is selected. - NOTREACHED(); - } - switch (commandID) { - case GoogleServicesSettingsCommandIDRestartAuthenticationFlow: - [self.localDispatcher restartAuthenticationFlow]; - break; - case GoogleServicesSettingsReauthDialogAsSyncIsInAuthError: - [self.localDispatcher openReauthDialogAsSyncIsInAuthError]; - break; - case GoogleServicesSettingsCommandIDShowPassphraseDialog: - [self.localDispatcher openPassphraseDialog]; - break; - case GoogleServicesSettingsCommandIDNoOp: - case GoogleServicesSettingsCommandIDToggleAutocompleteSearchesService: - case GoogleServicesSettingsCommandIDTogglePreloadPagesService: - case GoogleServicesSettingsCommandIDToggleImproveChromeService: - case GoogleServicesSettingsCommandIDToggleBetterSearchAndBrowsingService: - // Command ID not related with cell selection. - NOTREACHED(); - break; - } + [self.serviceDelegate didSelectItem:item]; } @end
diff --git a/ios/chrome/browser/ui/settings/handoff_table_view_controller.mm b/ios/chrome/browser/ui/settings/handoff_table_view_controller.mm index c9abff1..4de7925 100644 --- a/ios/chrome/browser/ui/settings/handoff_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/handoff_table_view_controller.mm
@@ -46,9 +46,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = l10n_util::GetNSString(IDS_IOS_OPTIONS_CONTINUITY_LABEL); _handoffEnabled.Init(prefs::kIosHandoffToOtherDevices,
diff --git a/ios/chrome/browser/ui/settings/import_data_table_view_controller.mm b/ios/chrome/browser/ui/settings/import_data_table_view_controller.mm index 44be3f3..eb78d4bcf 100644 --- a/ios/chrome/browser/ui/settings/import_data_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/import_data_table_view_controller.mm
@@ -57,9 +57,8 @@ isSignedIn:(BOOL)isSignedIn { DCHECK(fromEmail); DCHECK(toEmail); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { _delegate = delegate; _fromEmail = [fromEmail copy];
diff --git a/ios/chrome/browser/ui/settings/material_cell_catalog_view_controller.mm b/ios/chrome/browser/ui/settings/material_cell_catalog_view_controller.mm index c1fdcf8..fbea349a 100644 --- a/ios/chrome/browser/ui/settings/material_cell_catalog_view_controller.mm +++ b/ios/chrome/browser/ui/settings/material_cell_catalog_view_controller.mm
@@ -128,8 +128,8 @@ - (instancetype)init { UICollectionViewLayout* layout = [[MDCCollectionViewFlowLayout alloc] init]; - self = - [super initWithLayout:layout style:CollectionViewControllerStyleAppBar]; + self = [super initWithLayout:layout + style:CollectionViewControllerStyleDefault]; if (self) { // TODO(crbug.com/764578): -loadModel should not be called from // initializer. A possible fix is to move this call to -viewDidLoad.
diff --git a/ios/chrome/browser/ui/settings/password_details_table_view_controller.mm b/ios/chrome/browser/ui/settings/password_details_table_view_controller.mm index 98242fd..ded81ae 100644 --- a/ios/chrome/browser/ui/settings/password_details_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/password_details_table_view_controller.mm
@@ -103,9 +103,8 @@ (id<ReauthenticationProtocol>)reauthenticationModule { DCHECK(delegate); DCHECK(reauthenticationModule); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { _delegate = delegate; _weakReauthenticationModule = reauthenticationModule;
diff --git a/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm b/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm index a3d896e..8ef90d9 100644 --- a/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm
@@ -219,6 +219,13 @@ return grey_accessibilityID(kSettingsToolbarDeleteButtonId); } +// Return the edit button from the navigation bar. +id<GREYMatcher> NavigationBarEditButton() { + return grey_allOf(chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON), + grey_userInteractionEnabled(), nil); +} + // This is similar to grey_ancestor, but only limited to the immediate parent. id<GREYMatcher> MatchParentWith(id<GREYMatcher> parentMatcher) { MatchesBlock matches = ^BOOL(id element) { @@ -401,9 +408,7 @@ // Tap Edit in any settings view. void TapEdit() { - [[EarlGrey - selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] performAction:grey_tap()]; } @@ -412,10 +417,10 @@ PasswordForm CreateSampleFormWithIndex(int index) { PasswordForm form; form.username_value = - base::ASCIIToUTF16(base::StringPrintf("concrete username %03d", index)); + base::ASCIIToUTF16(base::StringPrintf("concrete username %02d", index)); form.password_value = - base::ASCIIToUTF16(base::StringPrintf("concrete password %03d", index)); - form.origin = GURL(base::StringPrintf("https://www%03d.example.com", index)); + base::ASCIIToUTF16(base::StringPrintf("concrete password %02d", index)); + form.origin = GURL(base::StringPrintf("https://www%02d.example.com", index)); form.signon_realm = form.origin.spec(); return form; } @@ -670,9 +675,7 @@ // Finally, verify that the Edit button is visible and disabled, because there // are no other password entries left for deletion via the "Edit" mode. - [[EarlGrey - selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] assertWithMatcher:grey_allOf(grey_sufficientlyVisible(), grey_not(grey_enabled()), nil)]; @@ -732,9 +735,7 @@ // Finally, verify that the Edit button is visible and disabled, because there // are no other password entries left for deletion via the "Edit" mode. - [[EarlGrey - selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] assertWithMatcher:grey_allOf(grey_sufficientlyVisible(), grey_not(grey_enabled()), nil)]; @@ -787,9 +788,7 @@ // Finally, verify that the Edit button is visible and disabled, because there // are no other password entries left for deletion via the "Edit" mode. - [[EarlGrey - selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] assertWithMatcher:grey_allOf(grey_sufficientlyVisible(), grey_not(grey_enabled()), nil)]; @@ -1438,12 +1437,12 @@ selectElementWithMatcher:grey_accessibilityID(kPasswordsTableViewId)] performAction:grey_scrollInDirection(kGREYDirectionDown, kJump)]; [GetInteractionForPasswordEntry([NSString - stringWithFormat:@"www%03d.example.com, concrete username %03d", + stringWithFormat:@"www%02d.example.com, concrete username %02d", kRemoteIndex, kRemoteIndex]) performAction:grey_tap()]; // Check that the detail view loaded correctly by verifying the site content. id<GREYMatcher> siteCell = grey_accessibilityLabel([NSString - stringWithFormat:@"https://www%03d.example.com/", kRemoteIndex]); + stringWithFormat:@"https://www%02d.example.com/", kRemoteIndex]); [GetInteractionForPasswordDetailItem(siteCell) assertWithMatcher:grey_notNil()]; @@ -1473,9 +1472,7 @@ performAction:grey_tap()]; // Verify that the Edit button is visible and disabled. - [[EarlGrey - selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( - IDS_IOS_NAVIGATION_BAR_EDIT_BUTTON)] + [[EarlGrey selectElementWithMatcher:NavigationBarEditButton()] assertWithMatcher:grey_allOf(grey_sufficientlyVisible(), grey_not(grey_enabled()), nil)];
diff --git a/ios/chrome/browser/ui/settings/passwords_table_view_controller.mm b/ios/chrome/browser/ui/settings/passwords_table_view_controller.mm index 8e8974df..086dd631 100644 --- a/ios/chrome/browser/ui/settings/passwords_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/passwords_table_view_controller.mm
@@ -213,9 +213,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { browserState_ = browserState; reauthenticationModule_ = [[ReauthenticationModule alloc]
diff --git a/ios/chrome/browser/ui/settings/privacy_table_view_controller.mm b/ios/chrome/browser/ui/settings/privacy_table_view_controller.mm index 93fa46f..687eefa0 100644 --- a/ios/chrome/browser/ui/settings/privacy_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/privacy_table_view_controller.mm
@@ -97,9 +97,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { _browserState = browserState; self.title =
diff --git a/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm b/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm index 42eaebb..a9aaf04 100644 --- a/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/search_engine_table_view_controller.mm
@@ -64,9 +64,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { _templateURLService = ios::TemplateURLServiceFactory::GetForBrowserState(browserState);
diff --git a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm index c56794b..51bc8494 100644 --- a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm
@@ -274,8 +274,8 @@ dispatcher:(id<ApplicationCommands>)dispatcher { DCHECK(!browserState->IsOffTheRecord()); UICollectionViewLayout* layout = [[MDCCollectionViewFlowLayout alloc] init]; - self = - [super initWithLayout:layout style:CollectionViewControllerStyleAppBar]; + self = [super initWithLayout:layout + style:CollectionViewControllerStyleDefault]; if (self) { _browserState = browserState; self.title = l10n_util::GetNSStringWithFixup(IDS_IOS_SETTINGS_TITLE); @@ -352,6 +352,9 @@ const CGFloat kSettingsSeparatorLeadingInset = 56; self.styler.separatorInset = UIEdgeInsetsMake(0, kSettingsSeparatorLeadingInset, 0, 0); + + self.navigationItem.largeTitleDisplayMode = + UINavigationItemLargeTitleDisplayModeAlways; } // TODO(crbug.com/661915): Refactor TemplateURLObserver and re-implement this so
diff --git a/ios/chrome/browser/ui/settings/settings_navigation_controller.mm b/ios/chrome/browser/ui/settings/settings_navigation_controller.mm index a0effec..d26c27d 100644 --- a/ios/chrome/browser/ui/settings/settings_navigation_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_navigation_controller.mm
@@ -11,7 +11,6 @@ #include "ios/chrome/browser/sync/sync_setup_service_factory.h" #import "ios/chrome/browser/ui/icons/chrome_icon.h" #import "ios/chrome/browser/ui/keyboard/UIKeyCommand+Chrome.h" -#import "ios/chrome/browser/ui/material_components/app_bar_view_controller_presenting.h" #import "ios/chrome/browser/ui/material_components/utils.h" #import "ios/chrome/browser/ui/settings/accounts_table_view_controller.h" #import "ios/chrome/browser/ui/settings/autofill_credit_card_table_view_controller.h" @@ -31,77 +30,24 @@ #include "ios/chrome/grit/ios_strings.h" #import "ios/public/provider/chrome/browser/chrome_browser_provider.h" #import "ios/public/provider/chrome/browser/user_feedback/user_feedback_provider.h" -#import "ios/third_party/material_components_ios/src/components/AppBar/src/MDCAppBarContainerViewController.h" -#import "ios/third_party/material_components_ios/src/components/AppBar/src/MDCAppBarViewController.h" #include "ui/base/l10n/l10n_util_mac.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif -// TODO(crbug.com/785484): Implements workaround for iPhone X safe area bug in -// MDC. -@interface SettingsAppBarContainerViewController - : MDCAppBarContainerViewController -@end - -@implementation SettingsAppBarContainerViewController - -// TODO(crbug.com/785484): Remove once fixed in MDC: -// https://github.com/material-components/material-components-ios/pull/2890 -- (void)viewDidLayoutSubviews { - [super viewDidLayoutSubviews]; - - id<LayoutGuideProvider> safeAreaLayoutGuide = self.view.safeAreaLayoutGuide; - UIView* contentView = self.contentViewController.view; - UIView* headerView = self.appBarViewController.headerView; - contentView.translatesAutoresizingMaskIntoConstraints = NO; - [NSLayoutConstraint activateConstraints:@[ - [contentView.topAnchor constraintEqualToAnchor:headerView.bottomAnchor], - [contentView.leadingAnchor - constraintEqualToAnchor:safeAreaLayoutGuide.leadingAnchor], - [contentView.trailingAnchor - constraintEqualToAnchor:safeAreaLayoutGuide.trailingAnchor], - [contentView.bottomAnchor - constraintEqualToAnchor:safeAreaLayoutGuide.bottomAnchor], - ]]; -} - -@end - -@interface SettingsNavigationController ()< - GoogleServicesSettingsCoordinatorDelegate, - UIGestureRecognizerDelegate> +@interface SettingsNavigationController () < + GoogleServicesSettingsCoordinatorDelegate> // Google services settings coordinator. @property(nonatomic, strong) GoogleServicesSettingsCoordinator* googleServicesSettingsCoordinator; -// Sets up the UI. Used by both initializers. -- (void)configureUI; - -// Closes the settings by calling |closeSettings| on |delegate|. -- (void)closeSettings; - -// Creates an autoreleased Back button for a UINavigationItem which will pop the -// top view controller when it is pressed. Should only be called by view -// controllers owned by SettingsNavigationController. -- (UIBarButtonItem*)backButton; - -// Creates an autoreleased "X" button that closes the settings when tapped. -- (UIBarButtonItem*)closeButton; - -// Creates an autoreleased "CANCEL" button that closes the settings when tapped. -- (UIBarButtonItem*)cancelButton; - @end @implementation SettingsNavigationController { ios::ChromeBrowserState* mainBrowserState_; // weak __weak id<SettingsNavigationControllerDelegate> delegate_; - // Keeps a mapping between the view controllers that are wrapped to display an - // app bar and the containers that wrap them. - NSMutableDictionary* appBarContainedViewControllers_; } @synthesize googleServicesSettingsCoordinator = @@ -292,11 +238,29 @@ mainBrowserState_ = browserState; delegate_ = delegate; shouldCommitSyncChangesOnDismissal_ = YES; - [self configureUI]; + [self setModalPresentationStyle:UIModalPresentationFormSheet]; + [self setModalTransitionStyle:UIModalTransitionStyleCoverVertical]; } return self; } +- (void)viewDidLoad { + [super viewDidLoad]; + self.navigationBar.prefersLargeTitles = YES; + self.navigationBar.accessibilityIdentifier = @"SettingNavigationBar"; +} + +#pragma mark - Public + +- (UIBarButtonItem*)doneButton { + UIBarButtonItem* item = [[UIBarButtonItem alloc] + initWithBarButtonSystemItem:UIBarButtonSystemItemDone + target:self + action:@selector(closeSettings)]; + item.accessibilityIdentifier = kSettingsDoneButtonId; + return item; +} + - (void)settingsWillBeDismissed { // Notify all controllers that settings are about to be dismissed. for (UIViewController* controller in [self viewControllers]) { @@ -321,10 +285,6 @@ [delegate_ closeSettings]; } -- (void)back { - [self popViewControllerAnimated:YES]; -} - - (void)popViewControllerOrCloseSettingsAnimated:(BOOL)animated { if (self.viewControllers.count > 1) { // Pop the top view controller to reveal the view controller underneath. @@ -336,47 +296,9 @@ } } -- (void)configureUI { - [self setModalPresentationStyle:UIModalPresentationFormSheet]; - [self setModalTransitionStyle:UIModalTransitionStyleCoverVertical]; - // Since the navigation bar is hidden, the gesture to swipe to go back can - // become inactive. Setting the delegate to self is an MDC workaround to have - // it consistently work with AppBar. - // https://github.com/material-components/material-components-ios/issues/720 - [self setNavigationBarHidden:YES]; - [self.interactivePopGestureRecognizer setDelegate:self]; -} +#pragma mark - Private -- (BOOL)hasRightDoneButton { - UIBarButtonItem* rightButton = - self.topViewController.navigationItem.rightBarButtonItem; - if (!rightButton) - return NO; - UIBarButtonItem* doneButton = [self doneButton]; - return [rightButton style] == [doneButton style] && - [[rightButton title] compare:[doneButton title]] == NSOrderedSame; -} - -- (UIBarButtonItem*)backButton { - // Create a custom Back bar button item, as Material Navigation Bar deprecated - // the back arrow with a shaft. - return [ChromeIcon templateBarButtonItemWithImage:[ChromeIcon backIcon] - target:self - action:@selector(back)]; -} - -- (UIBarButtonItem*)doneButton { - // Create a custom Done bar button item, as Material Navigation Bar does not - // handle a system UIBarButtonSystemItemDone item. - UIBarButtonItem* item = [[UIBarButtonItem alloc] - initWithTitle:l10n_util::GetNSString(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON) - style:UIBarButtonItemStyleDone - target:self - action:@selector(closeSettings)]; - item.accessibilityIdentifier = kSettingsDoneButtonId; - return item; -} - +// Creates an autoreleased "X" button that closes the settings when tapped. - (UIBarButtonItem*)closeButton { UIBarButtonItem* closeButton = [ChromeIcon templateBarButtonItemWithImage:[ChromeIcon closeIcon] @@ -386,24 +308,6 @@ return closeButton; } -- (UIBarButtonItem*)cancelButton { - // Create a custom Cancel bar button item, as Material Navigation Bar does not - // handle a system UIBarButtonSystemItemCancel item. - return [[UIBarButtonItem alloc] - initWithTitle:l10n_util::GetNSString(IDS_IOS_NAVIGATION_BAR_CANCEL_BUTTON) - style:UIBarButtonItemStyleDone - target:self - action:@selector(closeSettings)]; -} - -- (UIInterfaceOrientationMask)supportedInterfaceOrientations { - return [self.topViewController supportedInterfaceOrientations]; -} - -- (BOOL)shouldAutorotate { - return [self.topViewController shouldAutorotate]; -} - #pragma mark - GoogleServicesSettingsCoordinatorDelegate - (void)googleServicesSettingsCoordinatorDidRemove: @@ -412,13 +316,6 @@ self.googleServicesSettingsCoordinator = nil; } -#pragma mark - UIGestureRecognizerDelegate - -- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer { - DCHECK_EQ(gestureRecognizer, self.interactivePopGestureRecognizer); - return self.viewControllers.count > 1; -} - #pragma mark - Accessibility - (BOOL)accessibilityPerformEscape { @@ -430,47 +327,6 @@ #pragma mark - UINavigationController -- (void)pushViewController:(UIViewController*)viewController - animated:(BOOL)animated { - // Add a back button if the view controller is not the root view controller - // and doesn’t already have a left bar button item. - if (self.viewControllers.count > 0 && - viewController.navigationItem.leftBarButtonItems.count == 0) { - viewController.navigationItem.leftBarButtonItem = [self backButton]; - } - // Wrap the view controller in an MDCAppBarContainerViewController if - // needed. - [super pushViewController:[self wrappedControllerIfNeeded:viewController] - animated:animated]; -} - -- (UIViewController*)popViewControllerAnimated:(BOOL)animated { - UIViewController* viewController = [super popViewControllerAnimated:animated]; - // Unwrap the view controller from its MDCAppBarContainerViewController if - // needed. - return [self unwrappedControllerIfNeeded:viewController]; -} - -- (NSArray*)popToViewController:(UIViewController*)viewController - animated:(BOOL)animated { - // First, check if the view controller was wrapped in an app bar container. - MDCAppBarContainerViewController* appBarContainer = - [self appBarContainerForController:viewController]; - // Pop the view controllers. - NSArray* poppedViewControllers = - [super popToViewController:appBarContainer ?: viewController - animated:animated]; - // Unwrap the popped view controllers from their - // MDCAppBarContainerViewController if needed. - NSMutableArray* viewControllers = [NSMutableArray array]; - [poppedViewControllers - enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL* stop) { - [viewControllers - addObject:[self unwrappedControllerIfNeeded:viewController]]; - }]; - return viewControllers; -} - // Ensures that the keyboard is always dismissed during a navigation transition. - (BOOL)disablesAutomaticKeyboardDismissal { return NO; @@ -582,80 +438,6 @@ return mainBrowserState_; } -#pragma mark - AppBar Containment - -// If viewController doesn't implement the AppBarPresenting protocol, it is -// wrapped in an MDCAppBarContainerViewController, which is returned. Otherwise, -// viewController is returned. -- (UIViewController*)wrappedControllerIfNeeded:(UIViewController*)controller { - // If the controller can't be presented with an app bar, it needs to be - // wrapped in an MDCAppBarContainerViewController. - if (![controller - conformsToProtocol:@protocol(AppBarViewControllerPresenting)]) { - MDCAppBarContainerViewController* appBarContainer = - [[SettingsAppBarContainerViewController alloc] - initWithContentViewController:controller]; - - // Configure the style. - appBarContainer.view.backgroundColor = [UIColor whiteColor]; - ConfigureAppBarViewControllerWithCardStyle( - appBarContainer.appBarViewController); - - // Override the header view's background color. - appBarContainer.appBarViewController.headerView.backgroundColor = - [UIColor groupTableViewBackgroundColor]; - - // Register the app bar container and return it. - [self registerAppBarContainer:appBarContainer]; - return appBarContainer; - } else { - return controller; - } -} - -// If controller is an MDCAppBarContainerViewController, it returns its content -// view controller. Otherwise, it returns viewController. -- (UIViewController*)unwrappedControllerIfNeeded:(UIViewController*)controller { - MDCAppBarContainerViewController* potentialAppBarController = - base::mac::ObjCCast<MDCAppBarContainerViewController>(controller); - if (potentialAppBarController) { - // Unregister the app bar container and return it. - [self unregisterAppBarContainer:potentialAppBarController]; - return [potentialAppBarController contentViewController]; - } else { - return controller; - } -} - -// Adds an app bar container in a dictionary mapping its content view -// controller's pointer to itself. -- (void)registerAppBarContainer:(MDCAppBarContainerViewController*)container { - if (!appBarContainedViewControllers_) { - appBarContainedViewControllers_ = [[NSMutableDictionary alloc] init]; - } - NSValue* key = [self keyForController:[container contentViewController]]; - [appBarContainedViewControllers_ setObject:container forKey:key]; -} - -// Removes the app bar container entry from the aforementioned dictionary. -- (void)unregisterAppBarContainer:(MDCAppBarContainerViewController*)container { - NSValue* key = [self keyForController:[container contentViewController]]; - [appBarContainedViewControllers_ removeObjectForKey:key]; -} - -// Returns the app bar container containing |controller| if it is contained. -// Otherwise, returns nil. -- (MDCAppBarContainerViewController*)appBarContainerForController: - (UIViewController*)controller { - NSValue* key = [self keyForController:controller]; - return [appBarContainedViewControllers_ objectForKey:key]; -} - -// Returns the dictionary key to use when dealing with |controller|. -- (NSValue*)keyForController:(UIViewController*)controller { - return [NSValue valueWithNonretainedObject:controller]; -} - #pragma mark - UIResponder - (BOOL)canBecomeFirstResponder {
diff --git a/ios/chrome/browser/ui/settings/settings_root_collection_view_controller.mm b/ios/chrome/browser/ui/settings/settings_root_collection_view_controller.mm index fe1c263..902e9675 100644 --- a/ios/chrome/browser/ui/settings/settings_root_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_root_collection_view_controller.mm
@@ -61,6 +61,9 @@ self.appBarViewController.headerView.backgroundColor = [UIColor groupTableViewBackgroundColor]; self.styler.separatorInset = UIEdgeInsetsMake(0, 16, 0, 16); + + self.navigationItem.largeTitleDisplayMode = + UINavigationItemLargeTitleDisplayModeNever; } - (void)viewWillAppear:(BOOL)animated {
diff --git a/ios/chrome/browser/ui/settings/settings_root_table_view_controller.h b/ios/chrome/browser/ui/settings/settings_root_table_view_controller.h index 506e074..b6bed32 100644 --- a/ios/chrome/browser/ui/settings/settings_root_table_view_controller.h +++ b/ios/chrome/browser/ui/settings/settings_root_table_view_controller.h
@@ -18,9 +18,8 @@ // into the Settings UI. It handles the configuration and display of the MDC // AppBar. @interface SettingsRootTableViewController - : ChromeTableViewController<AppBarViewControllerPresenting, - SettingsRootViewControlling, - TableViewLinkHeaderFooterItemDelegate> + : ChromeTableViewController <SettingsRootViewControlling, + TableViewLinkHeaderFooterItemDelegate> // Whether this table view controller should hide the "Done" button (the right // navigation bar button). Default is NO.
diff --git a/ios/chrome/browser/ui/settings/settings_root_table_view_controller.mm b/ios/chrome/browser/ui/settings/settings_root_table_view_controller.mm index baa7b4a7..88e4bd5 100644 --- a/ios/chrome/browser/ui/settings/settings_root_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_root_table_view_controller.mm
@@ -121,8 +121,9 @@ self.tableView.estimatedSectionFooterHeight = kEstimatedHeaderFooterHeight; self.tableView.separatorInset = UIEdgeInsetsMake(0, kTableViewSeparatorInset, 0, 0); - // Do not set the estimated height of the footer/header as if there is no - // header/footer, there is an empty space. + + self.navigationItem.largeTitleDisplayMode = + UINavigationItemLargeTitleDisplayModeNever; } - (void)viewWillAppear:(BOOL)animated {
diff --git a/ios/chrome/browser/ui/settings/settings_root_table_view_controller_unittest.mm b/ios/chrome/browser/ui/settings/settings_root_table_view_controller_unittest.mm index ac8f7b3..c5505d7d 100644 --- a/ios/chrome/browser/ui/settings/settings_root_table_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/settings/settings_root_table_view_controller_unittest.mm
@@ -24,7 +24,7 @@ SettingsRootTableViewController* Controller() { return [[SettingsRootTableViewController alloc] initWithTableViewStyle:UITableViewStylePlain - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; } SettingsNavigationController* NavigationController() { @@ -56,8 +56,11 @@ // |shouldShowEditButton|. controller.tableView.editing = NO; [controller updateEditButton]; - EXPECT_NSEQ(l10n_util::GetNSString(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON), - controller.navigationItem.rightBarButtonItem.title); + UIBarButtonItem* item = [[UIBarButtonItem alloc] + initWithBarButtonSystemItem:UIBarButtonSystemItemDone + target:nil + action:nil]; + EXPECT_NSEQ(item.title, controller.navigationItem.rightBarButtonItem.title); // Check that there the OK button if the table view is being edited and the // controller has the default behavior for |shouldShowEditButton|.
diff --git a/ios/chrome/browser/ui/settings/sync_encryption_passphrase_table_view_controller.mm b/ios/chrome/browser/ui/settings/sync_encryption_passphrase_table_view_controller.mm index 5b3d4343..948ba75 100644 --- a/ios/chrome/browser/ui/settings/sync_encryption_passphrase_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/sync_encryption_passphrase_table_view_controller.mm
@@ -67,9 +67,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = l10n_util::GetNSString(IDS_IOS_SYNC_ENTER_PASSPHRASE_TITLE); self.shouldHideDoneButton = YES;
diff --git a/ios/chrome/browser/ui/settings/sync_encryption_table_view_controller.mm b/ios/chrome/browser/ui/settings/sync_encryption_table_view_controller.mm index c6170c6b..76db309 100644 --- a/ios/chrome/browser/ui/settings/sync_encryption_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/sync_encryption_table_view_controller.mm
@@ -58,9 +58,8 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = l10n_util::GetNSString(IDS_IOS_SYNC_ENCRYPTION_TITLE); _browserState = browserState;
diff --git a/ios/chrome/browser/ui/settings/sync_settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/sync_settings_collection_view_controller.mm index fd340c2..3e31f767 100644 --- a/ios/chrome/browser/ui/settings/sync_settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/sync_settings_collection_view_controller.mm
@@ -211,8 +211,8 @@ allowSwitchSyncAccount:(BOOL)allowSwitchSyncAccount { DCHECK(browserState); UICollectionViewLayout* layout = [[MDCCollectionViewFlowLayout alloc] init]; - self = - [super initWithLayout:layout style:CollectionViewControllerStyleAppBar]; + self = [super initWithLayout:layout + style:CollectionViewControllerStyleDefault]; if (self) { _allowSwitchSyncAccount = allowSwitchSyncAccount; _browserState = browserState;
diff --git a/ios/chrome/browser/ui/settings/table_cell_catalog_view_controller.mm b/ios/chrome/browser/ui/settings/table_cell_catalog_view_controller.mm index 87a2490a..bc146363 100644 --- a/ios/chrome/browser/ui/settings/table_cell_catalog_view_controller.mm +++ b/ios/chrome/browser/ui/settings/table_cell_catalog_view_controller.mm
@@ -11,6 +11,7 @@ #import "ios/chrome/browser/ui/settings/cells/autofill_data_item.h" #import "ios/chrome/browser/ui/settings/cells/encryption_item.h" #import "ios/chrome/browser/ui/settings/cells/settings_detail_item.h" +#import "ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.h" #import "ios/chrome/browser/ui/settings/cells/settings_switch_item.h" #import "ios/chrome/browser/ui/settings/cells/sync_switch_item.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_detail_text_item.h" @@ -57,6 +58,7 @@ ItemTypeSettingsSwitch1, ItemTypeSettingsSwitch2, ItemTypeSyncSwitch, + ItemTypeSettingsSyncError, ItemTypeAutofillEditItem, ItemTypeAutofillData, ItemTypeAccount, @@ -68,7 +70,7 @@ - (instancetype)init { if ((self = [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar])) { + appBarStyle:ChromeTableViewControllerStyleNoAppBar])) { } return self; } @@ -200,6 +202,16 @@ [model addItem:syncSwitchItem toSectionWithIdentifier:SectionIdentifierSettings]; + SettingsImageDetailTextItem* imageDetailTextItem = + [[SettingsImageDetailTextItem alloc] + initWithType:ItemTypeSettingsSyncError]; + imageDetailTextItem.text = @"This is an error description about sync"; + imageDetailTextItem.detailText = + @"This is more detail about the sync error description"; + imageDetailTextItem.image = [ChromeIcon infoIcon]; + [model addItem:imageDetailTextItem + toSectionWithIdentifier:SectionIdentifierSettings]; + EncryptionItem* encryptionChecked = [[EncryptionItem alloc] initWithType:ItemTypeEncryption]; encryptionChecked.text =
diff --git a/ios/chrome/browser/ui/settings/time_range_selector_collection_view_controller.mm b/ios/chrome/browser/ui/settings/time_range_selector_collection_view_controller.mm index 697fec41..934e702 100644 --- a/ios/chrome/browser/ui/settings/time_range_selector_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/time_range_selector_collection_view_controller.mm
@@ -70,8 +70,8 @@ initWithPrefs:(PrefService*)prefs delegate:(id<TimeRangeSelectorCollectionViewControllerDelegate>)delegate { UICollectionViewLayout* layout = [[MDCCollectionViewFlowLayout alloc] init]; - self = - [super initWithLayout:layout style:CollectionViewControllerStyleAppBar]; + self = [super initWithLayout:layout + style:CollectionViewControllerStyleDefault]; if (self) { _weakDelegate = delegate; self.title = l10n_util::GetNSString(
diff --git a/ios/chrome/browser/ui/settings/translate_table_view_controller.mm b/ios/chrome/browser/ui/settings/translate_table_view_controller.mm index af04f82..e83afc4 100644 --- a/ios/chrome/browser/ui/settings/translate_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/translate_table_view_controller.mm
@@ -68,9 +68,8 @@ - (instancetype)initWithPrefs:(PrefService*)prefs { DCHECK(prefs); - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { _prefs = prefs; _translationEnabled = [[PrefBackedBoolean alloc]
diff --git a/ios/chrome/browser/ui/settings/voice_search_table_view_controller.mm b/ios/chrome/browser/ui/settings/voice_search_table_view_controller.mm index cad4a73..e4f09b2 100644 --- a/ios/chrome/browser/ui/settings/voice_search_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/voice_search_table_view_controller.mm
@@ -51,9 +51,8 @@ @implementation VoiceSearchTableViewController - (instancetype)initWithPrefs:(PrefService*)prefs { - self = - [super initWithTableViewStyle:UITableViewStyleGrouped - appBarStyle:ChromeTableViewControllerStyleWithAppBar]; + self = [super initWithTableViewStyle:UITableViewStyleGrouped + appBarStyle:ChromeTableViewControllerStyleNoAppBar]; if (self) { self.title = l10n_util::GetNSString(IDS_IOS_VOICE_SEARCH_SETTING_TITLE); _prefs = prefs;
diff --git a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_egtest.mm b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_egtest.mm index 61391d2..48debfb 100644 --- a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_egtest.mm +++ b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_egtest.mm
@@ -115,7 +115,11 @@ [[EarlGrey selectElementWithMatcher: chrome_test_util::SettingsImportDataKeepSeparateButton()] performAction:grey_tap()]; - TapButtonWithLabelId(IDS_IOS_OPTIONS_IMPORT_DATA_CONTINUE_BUTTON); + id<GREYMatcher> matcher = grey_allOf( + chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_OPTIONS_IMPORT_DATA_CONTINUE_BUTTON), + grey_not(grey_accessibilityTrait(UIAccessibilityTraitNotEnabled)), nil); + [[EarlGrey selectElementWithMatcher:matcher] performAction:grey_tap()]; // Check the signed-in user did change. [SigninEarlGreyUtils assertSignedInWithIdentity:identity2]; @@ -150,7 +154,11 @@ [[EarlGrey selectElementWithMatcher:chrome_test_util:: SettingsImportDataImportButton()] performAction:grey_tap()]; - TapButtonWithLabelId(IDS_IOS_OPTIONS_IMPORT_DATA_CONTINUE_BUTTON); + [[EarlGrey selectElementWithMatcher: + grey_allOf(chrome_test_util::ButtonWithAccessibilityLabelId( + IDS_IOS_OPTIONS_IMPORT_DATA_CONTINUE_BUTTON), + grey_userInteractionEnabled(), nil)] + performAction:grey_tap()]; // Check the signed-in user did change. [SigninEarlGreyUtils assertSignedInWithIdentity:identity2]; @@ -290,9 +298,12 @@ [ChromeEarlGreyUI tapSettingsMenuButton:SecondarySignInButton()]; [SigninEarlGreyUI selectIdentityWithEmail:identity.userEmail]; - // Tap Settings link. + // Wait until the next screen appears. id<GREYMatcher> settings_link_matcher = grey_allOf( grey_accessibilityLabel(@"Settings"), grey_sufficientlyVisible(), nil); + + WaitForMatcher(settings_link_matcher); + // Tap Settings link. [[EarlGrey selectElementWithMatcher:settings_link_matcher] performAction:grey_tap()];
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_mediator.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_mediator.mm index b88c1b17e..9b3f207 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_mediator.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_mediator.mm
@@ -8,7 +8,6 @@ #include "base/metrics/histogram_macros.h" #include "base/scoped_observer.h" -#include "base/strings/sys_string_conversions.h" #include "components/favicon/ios/web_favicon_driver.h" #include "components/sessions/core/tab_restore_service.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" @@ -20,6 +19,7 @@ #import "ios/chrome/browser/snapshots/snapshot_cache_observer.h" #import "ios/chrome/browser/snapshots/snapshot_tab_helper.h" #import "ios/chrome/browser/tabs/tab_model.h" +#import "ios/chrome/browser/tabs/tab_title_util.h" #import "ios/chrome/browser/ui/tab_grid/grid/grid_consumer.h" #import "ios/chrome/browser/ui/tab_grid/grid/grid_item.h" #include "ios/chrome/browser/ui/util/ui_util.h" @@ -48,7 +48,7 @@ if (IsURLNtp(web_state->GetVisibleURL())) { item.hidesTitle = YES; } - item.title = base::SysUTF16ToNSString(web_state->GetTitle()); + item.title = tab_util::GetTabTitle(web_state); return item; }
diff --git a/ios/chrome/test/earl_grey/chrome_matchers.h b/ios/chrome/test/earl_grey/chrome_matchers.h index f7282c9..ec77b25 100644 --- a/ios/chrome/test/earl_grey/chrome_matchers.h +++ b/ios/chrome/test/earl_grey/chrome_matchers.h
@@ -37,6 +37,14 @@ // accessibility trait UIAccessibilityTraitStaticText. id<GREYMatcher> StaticTextWithAccessibilityLabel(NSString* label); +// Matcher for element with accessibility label corresponding to |message_id| +// and accessibility trait UIAccessibilityTraitHeader. +id<GREYMatcher> HeaderWithAccessibilityLabelId(int message_id); + +// Matcher for element with accessibility label corresponding to |label| and +// accessibility trait UIAccessibilityTraitHeader. +id<GREYMatcher> HeaderWithAccessibilityLabel(NSString* label); + // Returns matcher for a cancel button. id<GREYMatcher> CancelButton();
diff --git a/ios/chrome/test/earl_grey/chrome_matchers.mm b/ios/chrome/test/earl_grey/chrome_matchers.mm index 2193082..015e533 100644 --- a/ios/chrome/test/earl_grey/chrome_matchers.mm +++ b/ios/chrome/test/earl_grey/chrome_matchers.mm
@@ -102,6 +102,22 @@ descriptionBlock:describe]; } +// Returns the subview of |parentView| corresponding to the +// ContentSuggestionsViewController. Returns nil if it is not in its subviews. +UIView* SubviewWithAccessibilityIdentifier(NSString* accessibilityID, + UIView* parentView) { + if (parentView.accessibilityIdentifier == accessibilityID) { + return parentView; + } + for (UIView* view in parentView.subviews) { + UIView* resultView = + SubviewWithAccessibilityIdentifier(accessibilityID, view); + if (resultView) + return resultView; + } + return nil; +} + } // namespace namespace chrome_test_util { @@ -168,17 +184,27 @@ image_matcher, nil); } +id<GREYMatcher> StaticTextWithAccessibilityLabelId(int message_id) { + return StaticTextWithAccessibilityLabel( + l10n_util::GetNSStringWithFixup(message_id)); +} + id<GREYMatcher> StaticTextWithAccessibilityLabel(NSString* label) { return grey_allOf(grey_accessibilityLabel(label), grey_accessibilityTrait(UIAccessibilityTraitStaticText), nil); } -id<GREYMatcher> StaticTextWithAccessibilityLabelId(int message_id) { - return StaticTextWithAccessibilityLabel( +id<GREYMatcher> HeaderWithAccessibilityLabelId(int message_id) { + return HeaderWithAccessibilityLabel( l10n_util::GetNSStringWithFixup(message_id)); } +id<GREYMatcher> HeaderWithAccessibilityLabel(NSString* label) { + return grey_allOf(grey_accessibilityLabel(label), + grey_accessibilityTrait(UIAccessibilityTraitHeader), nil); +} + id<GREYMatcher> CancelButton() { return ButtonWithAccessibilityLabelId(IDS_CANCEL); } @@ -316,7 +342,9 @@ } id<GREYMatcher> NavigationBarDoneButton() { - return ButtonWithAccessibilityLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON); + return grey_allOf( + ButtonWithAccessibilityLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON), + grey_userInteractionEnabled(), nil); } id<GREYMatcher> BookmarksNavigationBarDoneButton() { @@ -421,8 +449,15 @@ } id<GREYMatcher> SettingsMenuBackButton() { - return grey_allOf(grey_accessibilityID(@"ic_arrow_back"), - grey_accessibilityTrait(UIAccessibilityTraitButton), nil); + UINavigationBar* navBar = base::mac::ObjCCastStrict<UINavigationBar>( + SubviewWithAccessibilityIdentifier( + @"SettingNavigationBar", + [[UIApplication sharedApplication] keyWindow])); + return grey_allOf(grey_anyOf(grey_accessibilityLabel(navBar.backItem.title), + grey_accessibilityLabel(@"Back"), nil), + grey_kindOfClass([UIButton class]), + grey_ancestor(grey_kindOfClass([UINavigationBar class])), + nil); } id<GREYMatcher> SettingsMenuPrivacyButton() {
diff --git a/media/base/media_log.h b/media/base/media_log.h index 3c529ed3..164b6e94 100644 --- a/media/base/media_log.h +++ b/media/base/media_log.h
@@ -74,7 +74,8 @@ // with whitespace in the latter kind of events. static std::string MediaEventToMessageString(const MediaLogEvent& event); - MediaLog(); + // Constructor is protected, see below. + virtual ~MediaLog(); // Add an event to this log. Inheritors should override AddEventLocked to @@ -139,6 +140,9 @@ virtual std::unique_ptr<MediaLog> Clone(); protected: + // Ensures only subclasses and factories (e.g. Clone()) can create MediaLog. + MediaLog(); + // Methods that may be overridden by inheritors. All calls may arrive on any // thread, but will be synchronized with respect to any other *Locked calls on // any other thread, and with any parent log invalidation. @@ -175,9 +179,7 @@ MediaLog(scoped_refptr<ParentLogRecord> parent_log_record); private: - // The underlying media log. - scoped_refptr<ParentLogRecord> parent_log_record_; - + // Allows MediaLogTest to construct MediaLog directly for testing. friend class MediaLogTest; FRIEND_TEST_ALL_PREFIXES(MediaLogTest, EventsAreForwarded); FRIEND_TEST_ALL_PREFIXES(MediaLogTest, EventsAreNotForwardedAfterInvalidate); @@ -192,6 +194,9 @@ // the event, and sets the last 3 characters to an ellipsis. static std::string TruncateUrlString(std::string log_string); + // The underlying media log. + scoped_refptr<ParentLogRecord> parent_log_record_; + // A unique (to this process) id for this MediaLog. int32_t id_; DISALLOW_COPY_AND_ASSIGN(MediaLog);
diff --git a/media/base/media_log_unittest.cc b/media/base/media_log_unittest.cc index a6a1806..741806b8 100644 --- a/media/base/media_log_unittest.cc +++ b/media/base/media_log_unittest.cc
@@ -18,6 +18,9 @@ class MediaLogTest : public testing::Test { public: static constexpr size_t kMaxUrlLength = MediaLog::kMaxUrlLength; + + protected: + MediaLog media_log; }; constexpr size_t MediaLogTest::kMaxUrlLength; @@ -28,14 +31,14 @@ // Verify that CreatedEvent does not truncate the short URL. std::unique_ptr<MediaLogEvent> created_event = - MediaLog().CreateCreatedEvent(short_url); + media_log.CreateCreatedEvent(short_url); std::string stored_url; created_event->params.GetString("origin_url", &stored_url); EXPECT_EQ(stored_url, short_url); // Verify that LoadEvent does not truncate the short URL. std::unique_ptr<MediaLogEvent> load_event = - MediaLog().CreateLoadEvent(short_url); + media_log.CreateLoadEvent(short_url); load_event->params.GetString("url", &stored_url); EXPECT_EQ(stored_url, short_url); } @@ -52,7 +55,7 @@ // Verify that long CreatedEvent URL... std::unique_ptr<MediaLogEvent> created_event = - MediaLog().CreateCreatedEvent(long_url); + media_log.CreateCreatedEvent(long_url); std::string stored_url; created_event->params.GetString("origin_url", &stored_url); @@ -67,7 +70,7 @@ // Verify that long LoadEvent URL... std::unique_ptr<MediaLogEvent> load_event = - MediaLog().CreateCreatedEvent(long_url); + media_log.CreateCreatedEvent(long_url); load_event->params.GetString("url", &stored_url); // ... is truncated EXPECT_EQ(stored_url.length(), MediaLogTest::kMaxUrlLength);
diff --git a/media/base/pipeline_impl_unittest.cc b/media/base/pipeline_impl_unittest.cc index aa793d0..10a9974d 100644 --- a/media/base/pipeline_impl_unittest.cc +++ b/media/base/pipeline_impl_unittest.cc
@@ -22,7 +22,7 @@ #include "base/time/clock.h" #include "media/base/fake_text_track_stream.h" #include "media/base/gmock_callback_support.h" -#include "media/base/media_log.h" +#include "media/base/media_util.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/base/text_renderer.h" @@ -322,7 +322,7 @@ StrictMock<CallbackHelper> callbacks_; base::SimpleTestTickClock test_tick_clock_; base::MessageLoop message_loop_; - MediaLog media_log_; + NullMediaLog media_log_; std::unique_ptr<PipelineImpl> pipeline_; std::unique_ptr<StrictMock<MockDemuxer>> demuxer_;
diff --git a/media/blink/multibuffer_data_source_unittest.cc b/media/blink/multibuffer_data_source_unittest.cc index ea067d7..421ecba8 100644 --- a/media/blink/multibuffer_data_source_unittest.cc +++ b/media/blink/multibuffer_data_source_unittest.cc
@@ -10,8 +10,8 @@ #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/test/scoped_feature_list.h" -#include "media/base/media_log.h" #include "media/base/media_switches.h" +#include "media/base/media_util.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/blink/buffered_data_source_host_impl.h" @@ -196,7 +196,7 @@ private: // Whether the resource is downloading or deferred. bool downloading_; - MediaLog media_log_; + NullMediaLog media_log_; DISALLOW_COPY_AND_ASSIGN(MockMultibufferDataSource); };
diff --git a/media/blink/webaudiosourceprovider_impl_unittest.cc b/media/blink/webaudiosourceprovider_impl_unittest.cc index 18628a5..21955a3 100644 --- a/media/blink/webaudiosourceprovider_impl_unittest.cc +++ b/media/blink/webaudiosourceprovider_impl_unittest.cc
@@ -9,7 +9,7 @@ #include "base/run_loop.h" #include "media/base/audio_parameters.h" #include "media/base/fake_audio_render_callback.h" -#include "media/base/media_log.h" +#include "media/base/media_util.h" #include "media/base/mock_audio_renderer_sink.h" #include "media/blink/webaudiosourceprovider_impl.h" #include "testing/gmock/include/gmock/gmock.h" @@ -106,7 +106,7 @@ protected: AudioParameters params_; FakeAudioRenderCallback fake_callback_; - MediaLog media_log_; + NullMediaLog media_log_; scoped_refptr<MockAudioRendererSink> mock_sink_; scoped_refptr<WebAudioSourceProviderImpl> wasp_impl_;
diff --git a/media/cast/sender/h264_vt_encoder_unittest.cc b/media/cast/sender/h264_vt_encoder_unittest.cc index f5681b0..d8f13c6 100644 --- a/media/cast/sender/h264_vt_encoder_unittest.cc +++ b/media/cast/sender/h264_vt_encoder_unittest.cc
@@ -19,7 +19,6 @@ #include "media/base/cdm_context.h" #include "media/base/decoder_buffer.h" #include "media/base/media.h" -#include "media/base/media_log.h" #include "media/base/media_switches.h" #include "media/base/media_util.h" #include "media/cast/common/rtp_time.h" @@ -166,7 +165,7 @@ friend class base::RefCountedThreadSafe<EndToEndFrameChecker>; virtual ~EndToEndFrameChecker() {} - MediaLog media_log_; + NullMediaLog media_log_; FFmpegVideoDecoder decoder_; base::queue<scoped_refptr<VideoFrame>> expectations_; int count_frames_checked_;
diff --git a/media/cdm/cenc_utils.cc b/media/cdm/cenc_utils.cc index edc481b0..19583549 100644 --- a/media/cdm/cenc_utils.cc +++ b/media/cdm/cenc_utils.cc
@@ -7,6 +7,7 @@ #include <memory> #include "base/stl_util.h" +#include "media/base/media_util.h" #include "media/formats/mp4/box_definitions.h" #include "media/formats/mp4/box_reader.h" @@ -33,7 +34,7 @@ DCHECK(!input.empty()); // TODO(wolenetz): Questionable MediaLog usage, http://crbug.com/712310 - MediaLog media_log; + NullMediaLog media_log; // Verify that |input| contains only 'pssh' boxes. // ReadAllChildrenAndCheckFourCC() is templated, so it checks that each
diff --git a/media/filters/audio_decoder_stream_unittest.cc b/media/filters/audio_decoder_stream_unittest.cc index c89abf5..f71d5832 100644 --- a/media/filters/audio_decoder_stream_unittest.cc +++ b/media/filters/audio_decoder_stream_unittest.cc
@@ -11,7 +11,7 @@ #include "base/test/scoped_task_environment.h" #include "base/threading/sequenced_task_runner_handle.h" #include "media/base/gmock_callback_support.h" -#include "media/base/media_log.h" +#include "media/base/media_util.h" #include "media/base/mock_filters.h" #include "media/filters/decoder_stream.h" #include "testing/gmock/include/gmock/gmock.h" @@ -111,7 +111,7 @@ } base::test::ScopedTaskEnvironment task_environment_; - MediaLog media_log_; + NullMediaLog media_log_; testing::NiceMock<MockDemuxerStream> demuxer_stream_{DemuxerStream::AUDIO}; AudioDecoderStream audio_decoder_stream_;
diff --git a/media/filters/audio_decoder_unittest.cc b/media/filters/audio_decoder_unittest.cc index c43b115..514efa2 100644 --- a/media/filters/audio_decoder_unittest.cc +++ b/media/filters/audio_decoder_unittest.cc
@@ -394,7 +394,7 @@ base::MessageLoop message_loop_; - MediaLog media_log_; + NullMediaLog media_log_; scoped_refptr<DecoderBuffer> data_; std::unique_ptr<InMemoryUrlProtocol> protocol_; std::unique_ptr<AudioFileReader> reader_;
diff --git a/media/filters/decoder_selector_unittest.cc b/media/filters/decoder_selector_unittest.cc index 8e3c2bc..cb16c8ff 100644 --- a/media/filters/decoder_selector_unittest.cc +++ b/media/filters/decoder_selector_unittest.cc
@@ -13,6 +13,7 @@ #include "build/build_config.h" #include "media/base/demuxer_stream.h" #include "media/base/gmock_callback_support.h" +#include "media/base/media_util.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/filters/decoder_selector.h" @@ -288,7 +289,7 @@ void RunUntilIdle() { scoped_task_environment_.RunUntilIdle(); } base::test::ScopedTaskEnvironment scoped_task_environment_; - MediaLog media_log_; + NullMediaLog media_log_; std::unique_ptr<StreamTraits> traits_; StrictMock<MockDemuxerStream> demuxer_stream_;
diff --git a/media/filters/decrypting_audio_decoder_unittest.cc b/media/filters/decrypting_audio_decoder_unittest.cc index def5e26..069f110c 100644 --- a/media/filters/decrypting_audio_decoder_unittest.cc +++ b/media/filters/decrypting_audio_decoder_unittest.cc
@@ -243,7 +243,7 @@ MOCK_METHOD1(OnWaiting, void(WaitingReason)); base::MessageLoop message_loop_; - MediaLog media_log_; + NullMediaLog media_log_; std::unique_ptr<DecryptingAudioDecoder> decoder_; std::unique_ptr<StrictMock<MockCdmContext>> cdm_context_; std::unique_ptr<StrictMock<MockDecryptor>> decryptor_;
diff --git a/media/filters/decrypting_video_decoder_unittest.cc b/media/filters/decrypting_video_decoder_unittest.cc index d372090f..4515c82d 100644 --- a/media/filters/decrypting_video_decoder_unittest.cc +++ b/media/filters/decrypting_video_decoder_unittest.cc
@@ -15,6 +15,7 @@ #include "media/base/decoder_buffer.h" #include "media/base/decrypt_config.h" #include "media/base/gmock_callback_support.h" +#include "media/base/media_util.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/base/video_frame.h" @@ -219,7 +220,7 @@ MOCK_METHOD1(OnWaiting, void(WaitingReason)); base::MessageLoop message_loop_; - MediaLog media_log_; + NullMediaLog media_log_; std::unique_ptr<DecryptingVideoDecoder> decoder_; std::unique_ptr<StrictMock<MockCdmContext>> cdm_context_; std::unique_ptr<StrictMock<MockDecryptor>> decryptor_;
diff --git a/media/filters/demuxer_perftest.cc b/media/filters/demuxer_perftest.cc index a89b8d95..aa10862 100644 --- a/media/filters/demuxer_perftest.cc +++ b/media/filters/demuxer_perftest.cc
@@ -16,8 +16,8 @@ #include "base/time/time.h" #include "build/build_config.h" #include "media/base/media.h" -#include "media/base/media_log.h" #include "media/base/media_tracks.h" +#include "media/base/media_util.h" #include "media/base/test_data_util.h" #include "media/base/timestamp_constants.h" #include "media/filters/ffmpeg_demuxer.h" @@ -173,7 +173,7 @@ static void RunDemuxerBenchmark(const std::string& filename) { base::FilePath file_path(GetTestDataFilePath(filename)); base::TimeDelta total_time; - MediaLog media_log_; + NullMediaLog media_log_; for (int i = 0; i < kBenchmarkIterations; ++i) { // Setup. base::test::ScopedTaskEnvironment scoped_task_environment_;
diff --git a/media/filters/ffmpeg_demuxer_unittest.cc b/media/filters/ffmpeg_demuxer_unittest.cc index 3843f19..c60ac81a 100644 --- a/media/filters/ffmpeg_demuxer_unittest.cc +++ b/media/filters/ffmpeg_demuxer_unittest.cc
@@ -22,8 +22,8 @@ #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "media/base/decrypt_config.h" -#include "media/base/media_log.h" #include "media/base/media_tracks.h" +#include "media/base/media_util.h" #include "media/base/mock_demuxer_host.h" #include "media/base/mock_media_log.h" #include "media/base/test_helpers.h" @@ -269,7 +269,7 @@ // using StrictMock<MockMediaLog> for all FFmpegDemuxerTests. See // https://crbug.com/749178. StrictMock<MockMediaLog> media_log_; - MediaLog dummy_media_log_; + NullMediaLog dummy_media_log_; std::unique_ptr<FileDataSource> data_source_; std::unique_ptr<FFmpegDemuxer> demuxer_;
diff --git a/media/filters/stream_parser_factory.cc b/media/filters/stream_parser_factory.cc index 8e24981..a00e3562 100644 --- a/media/filters/stream_parser_factory.cc +++ b/media/filters/stream_parser_factory.cc
@@ -16,6 +16,7 @@ #include "build/build_config.h" #include "media/base/media.h" #include "media/base/media_switches.h" +#include "media/base/media_util.h" #include "media/base/video_codecs.h" #include "media/formats/mp4/mp4_stream_parser.h" #include "media/formats/mpeg/adts_stream_parser.h" @@ -503,7 +504,7 @@ const std::string& type, const std::vector<std::string>& codecs) { // TODO(wolenetz): Questionable MediaLog usage, http://crbug.com/712310 - MediaLog media_log; + NullMediaLog media_log; return CheckTypeAndCodecs(type, codecs, &media_log, nullptr, nullptr, nullptr); }
diff --git a/media/filters/video_renderer_algorithm_unittest.cc b/media/filters/video_renderer_algorithm_unittest.cc index e659a573..6ae205cf 100644 --- a/media/filters/video_renderer_algorithm_unittest.cc +++ b/media/filters/video_renderer_algorithm_unittest.cc
@@ -15,7 +15,7 @@ #include "base/strings/stringprintf.h" #include "base/test/simple_test_tick_clock.h" #include "build/build_config.h" -#include "media/base/media_log.h" +#include "media/base/media_util.h" #include "media/base/timestamp_constants.h" #include "media/base/video_frame_pool.h" #include "media/base/wall_clock_time_source.h" @@ -333,7 +333,7 @@ } protected: - MediaLog media_log_; + NullMediaLog media_log_; VideoFramePool frame_pool_; std::unique_ptr<base::SimpleTestTickClock> tick_clock_; WallClockTimeSource time_source_;
diff --git a/media/filters/vp9_uncompressed_header_parser.cc b/media/filters/vp9_uncompressed_header_parser.cc index 0118e81..d69fa929 100644 --- a/media/filters/vp9_uncompressed_header_parser.cc +++ b/media/filters/vp9_uncompressed_header_parser.cc
@@ -4,6 +4,8 @@ #include "media/filters/vp9_uncompressed_header_parser.h" +#include <type_traits> + #include "base/logging.h" namespace media { @@ -990,7 +992,7 @@ } else { fhdr->refresh_frame_flags = reader_.ReadLiteral(8); - static_assert(arraysize(fhdr->ref_frame_sign_bias) >= + static_assert(std::extent<decltype(fhdr->ref_frame_sign_bias)>() >= Vp9RefType::VP9_FRAME_LAST + kVp9NumRefsPerFrame, "ref_frame_sign_bias is not big enough"); for (size_t i = 0; i < kVp9NumRefsPerFrame; i++) {
diff --git a/media/formats/common/stream_parser_test_base.h b/media/formats/common/stream_parser_test_base.h index 2cc97c6..fc47ccc 100644 --- a/media/formats/common/stream_parser_test_base.h +++ b/media/formats/common/stream_parser_test_base.h
@@ -12,7 +12,7 @@ #include "base/macros.h" #include "media/base/audio_decoder_config.h" -#include "media/base/media_log.h" +#include "media/base/media_util.h" #include "media/base/stream_parser.h" #include "media/base/stream_parser_buffer.h" #include "media/base/text_track_config.h" @@ -66,7 +66,7 @@ void OnNewSegment(); void OnEndOfSegment(); - MediaLog media_log_; + NullMediaLog media_log_; std::unique_ptr<StreamParser> parser_; std::stringstream results_stream_; AudioDecoderConfig last_audio_config_;
diff --git a/media/formats/mp2t/es_parser_mpeg1audio_unittest.cc b/media/formats/mp2t/es_parser_mpeg1audio_unittest.cc index a7edeaf5..d3e4dd8a 100644 --- a/media/formats/mp2t/es_parser_mpeg1audio_unittest.cc +++ b/media/formats/mp2t/es_parser_mpeg1audio_unittest.cc
@@ -8,7 +8,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/time/time.h" -#include "media/base/media_log.h" +#include "media/base/media_util.h" #include "media/base/stream_parser_buffer.h" #include "media/formats/mp2t/es_parser_mpeg1audio.h" #include "media/formats/mp2t/es_parser_test_base.h" @@ -28,7 +28,7 @@ bool Process(const std::vector<Packet>& pes_packets, bool force_timing); private: - MediaLog media_log_; + NullMediaLog media_log_; DISALLOW_COPY_AND_ASSIGN(EsParserMpeg1AudioTest); };
diff --git a/media/formats/mp2t/mp2t_stream_parser_unittest.cc b/media/formats/mp2t/mp2t_stream_parser_unittest.cc index f3189e9..bd1590a 100644 --- a/media/formats/mp2t/mp2t_stream_parser_unittest.cc +++ b/media/formats/mp2t/mp2t_stream_parser_unittest.cc
@@ -20,9 +20,9 @@ #include "media/base/audio_decoder_config.h" #include "media/base/decoder_buffer.h" #include "media/base/encryption_pattern.h" -#include "media/base/media_log.h" #include "media/base/media_track.h" #include "media/base/media_tracks.h" +#include "media/base/media_util.h" #include "media/base/stream_parser_buffer.h" #include "media/base/test_data_util.h" #include "media/base/text_track_config.h" @@ -179,7 +179,7 @@ } protected: - MediaLog media_log_; + NullMediaLog media_log_; std::unique_ptr<Mp2tStreamParser> parser_; int segment_count_; int config_count_;
diff --git a/media/formats/mp4/box_definitions.cc b/media/formats/mp4/box_definitions.cc index 9c4a2202..ebe972f 100644 --- a/media/formats/mp4/box_definitions.cc +++ b/media/formats/mp4/box_definitions.cc
@@ -14,6 +14,7 @@ #include "base/strings/string_number_conversions.h" #include "build/build_config.h" #include "media/base/media_switches.h" +#include "media/base/media_util.h" #include "media/base/video_types.h" #include "media/base/video_util.h" #include "media/formats/common/opus_constants.h" @@ -610,7 +611,7 @@ bool AVCDecoderConfigurationRecord::Parse(const uint8_t* data, int data_size) { BufferReader reader(data, data_size); // TODO(wolenetz): Questionable MediaLog usage, http://crbug.com/712310 - MediaLog media_log; + NullMediaLog media_log; return ParseInternal(&reader, &media_log); }
diff --git a/media/formats/mp4/dolby_vision.cc b/media/formats/mp4/dolby_vision.cc index fd32c85f..eac7831 100644 --- a/media/formats/mp4/dolby_vision.cc +++ b/media/formats/mp4/dolby_vision.cc
@@ -5,6 +5,7 @@ #include "media/formats/mp4/dolby_vision.h" #include "base/logging.h" +#include "media/base/media_util.h" #include "media/base/video_codecs.h" #include "media/formats/mp4/box_definitions.h" #include "media/formats/mp4/box_reader.h" @@ -35,7 +36,7 @@ bool DolbyVisionConfiguration::ParseForTesting(const uint8_t* data, int data_size) { BufferReader reader(data, data_size); - MediaLog media_log; + NullMediaLog media_log; return ParseInternal(&reader, &media_log); }
diff --git a/media/formats/mp4/hevc.cc b/media/formats/mp4/hevc.cc index b2f606db..c45f556c 100644 --- a/media/formats/mp4/hevc.cc +++ b/media/formats/mp4/hevc.cc
@@ -11,6 +11,7 @@ #include "base/logging.h" #include "media/base/decrypt_config.h" +#include "media/base/media_util.h" #include "media/formats/mp4/avc.h" #include "media/formats/mp4/box_definitions.h" #include "media/formats/mp4/box_reader.h" @@ -49,7 +50,7 @@ bool HEVCDecoderConfigurationRecord::Parse(const uint8_t* data, int data_size) { BufferReader reader(data, data_size); // TODO(wolenetz): Questionable MediaLog usage, http://crbug.com/712310 - MediaLog media_log; + NullMediaLog media_log; return ParseInternal(&reader, &media_log); }
diff --git a/media/gpu/test/video_frame_validator.cc b/media/gpu/test/video_frame_validator.cc index 0f5bf6b..2be9a3f 100644 --- a/media/gpu/test/video_frame_validator.cc +++ b/media/gpu/test/video_frame_validator.cc
@@ -201,7 +201,7 @@ base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_APPEND); const size_t num_planes = VideoFrame::NumPlanes(video_frame->format()); for (size_t i = 0; i < num_planes; i++) { - size_t plane_w = VideoFrame::Rows(i, video_frame->format(), width); + size_t plane_w = VideoFrame::Columns(i, video_frame->format(), width); size_t plane_h = VideoFrame::Rows(i, video_frame->format(), height); int data_size = base::checked_cast<int>(plane_w * plane_h); const uint8_t* data = video_frame->data(i);
diff --git a/media/gpu/v4l2/v4l2_h264_accelerator.cc b/media/gpu/v4l2/v4l2_h264_accelerator.cc index d66dfa05..faa2629 100644 --- a/media/gpu/v4l2/v4l2_h264_accelerator.cc +++ b/media/gpu/v4l2/v4l2_h264_accelerator.cc
@@ -4,7 +4,10 @@ #include "media/gpu/v4l2/v4l2_h264_accelerator.h" +#include <type_traits> + #include "base/logging.h" +#include "base/stl_util.h" #include "media/gpu/macros.h" #include "media/gpu/v4l2/v4l2_decode_surface.h" #include "media/gpu/v4l2/v4l2_decode_surface_handler.h" @@ -65,7 +68,7 @@ memset(v4l2_decode_param_.dpb, 0, sizeof(v4l2_decode_param_.dpb)); size_t i = 0; for (const auto& pic : dpb) { - if (i >= arraysize(v4l2_decode_param_.dpb)) { + if (i >= base::size(v4l2_decode_param_.dpb)) { VLOGF(1) << "Invalid DPB size"; break; } @@ -123,10 +126,10 @@ SPS_TO_V4L2SPS(offset_for_top_to_bottom_field); SPS_TO_V4L2SPS(num_ref_frames_in_pic_order_cnt_cycle); - static_assert(arraysize(v4l2_sps.offset_for_ref_frame) == - arraysize(sps->offset_for_ref_frame), + static_assert(std::extent<decltype(v4l2_sps.offset_for_ref_frame)>() == + std::extent<decltype(sps->offset_for_ref_frame)>(), "offset_for_ref_frame arrays must be same size"); - for (size_t i = 0; i < arraysize(v4l2_sps.offset_for_ref_frame); ++i) + for (size_t i = 0; i < base::size(v4l2_sps.offset_for_ref_frame); ++i) v4l2_sps.offset_for_ref_frame[i] = sps->offset_for_ref_frame[i]; SPS_TO_V4L2SPS(max_num_ref_frames); SPS_TO_V4L2SPS(pic_width_in_mbs_minus1); @@ -198,24 +201,26 @@ struct v4l2_ctrl_h264_scaling_matrix v4l2_scaling_matrix; memset(&v4l2_scaling_matrix, 0, sizeof(v4l2_scaling_matrix)); - static_assert(arraysize(v4l2_scaling_matrix.scaling_list_4x4) <= - arraysize(pps->scaling_list4x4) && - arraysize(v4l2_scaling_matrix.scaling_list_4x4[0]) <= - arraysize(pps->scaling_list4x4[0]) && - arraysize(v4l2_scaling_matrix.scaling_list_8x8) <= - arraysize(pps->scaling_list8x8) && - arraysize(v4l2_scaling_matrix.scaling_list_8x8[0]) <= - arraysize(pps->scaling_list8x8[0]), - "scaling_lists must be of correct size"); - static_assert(arraysize(v4l2_scaling_matrix.scaling_list_4x4) <= - arraysize(sps->scaling_list4x4) && - arraysize(v4l2_scaling_matrix.scaling_list_4x4[0]) <= - arraysize(sps->scaling_list4x4[0]) && - arraysize(v4l2_scaling_matrix.scaling_list_8x8) <= - arraysize(sps->scaling_list8x8) && - arraysize(v4l2_scaling_matrix.scaling_list_8x8[0]) <= - arraysize(sps->scaling_list8x8[0]), - "scaling_lists must be of correct size"); + static_assert( + std::extent<decltype(v4l2_scaling_matrix.scaling_list_4x4)>() <= + std::extent<decltype(pps->scaling_list4x4)>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_4x4[0])>() <= + std::extent<decltype(pps->scaling_list4x4[0])>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_8x8)>() <= + std::extent<decltype(pps->scaling_list8x8)>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_8x8[0])>() <= + std::extent<decltype(pps->scaling_list8x8[0])>(), + "scaling_lists must be of correct size"); + static_assert( + std::extent<decltype(v4l2_scaling_matrix.scaling_list_4x4)>() <= + std::extent<decltype(sps->scaling_list4x4)>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_4x4[0])>() <= + std::extent<decltype(sps->scaling_list4x4[0])>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_8x8)>() <= + std::extent<decltype(sps->scaling_list8x8)>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_8x8[0])>() <= + std::extent<decltype(sps->scaling_list8x8[0])>(), + "scaling_lists must be of correct size"); const auto* scaling_list4x4 = &sps->scaling_list4x4[0]; const auto* scaling_list8x8 = &sps->scaling_list8x8[0]; @@ -224,14 +229,16 @@ scaling_list8x8 = &pps->scaling_list8x8[0]; } - for (size_t i = 0; i < arraysize(v4l2_scaling_matrix.scaling_list_4x4); ++i) { - for (size_t j = 0; j < arraysize(v4l2_scaling_matrix.scaling_list_4x4[i]); + for (size_t i = 0; i < base::size(v4l2_scaling_matrix.scaling_list_4x4); + ++i) { + for (size_t j = 0; j < base::size(v4l2_scaling_matrix.scaling_list_4x4[i]); ++j) { v4l2_scaling_matrix.scaling_list_4x4[i][j] = scaling_list4x4[i][j]; } } - for (size_t i = 0; i < arraysize(v4l2_scaling_matrix.scaling_list_8x8); ++i) { - for (size_t j = 0; j < arraysize(v4l2_scaling_matrix.scaling_list_8x8[i]); + for (size_t i = 0; i < base::size(v4l2_scaling_matrix.scaling_list_8x8); + ++i) { + for (size_t j = 0; j < base::size(v4l2_scaling_matrix.scaling_list_8x8[i]); ++j) { v4l2_scaling_matrix.scaling_list_8x8[i][j] = scaling_list8x8[i][j]; }
diff --git a/media/gpu/v4l2/v4l2_vp8_accelerator.cc b/media/gpu/v4l2/v4l2_vp8_accelerator.cc index c973b63f..95a4602 100644 --- a/media/gpu/v4l2/v4l2_vp8_accelerator.cc +++ b/media/gpu/v4l2/v4l2_vp8_accelerator.cc
@@ -4,10 +4,13 @@ #include "media/gpu/v4l2/v4l2_vp8_accelerator.h" +#include <type_traits> + #include <linux/videodev2.h> #include "base/logging.h" #include "base/numerics/safe_conversions.h" +#include "base/stl_util.h" #include "media/filters/vp8_parser.h" #include "media/gpu/macros.h" #include "media/gpu/v4l2/v4l2_decode_surface.h" @@ -166,11 +169,11 @@ base::checked_cast<__u32>(frame_hdr->macroblock_bit_offset); v4l2_frame_hdr.num_dct_parts = frame_hdr->num_of_dct_partitions; - static_assert(arraysize(v4l2_frame_hdr.dct_part_sizes) == - arraysize(frame_hdr->dct_partition_sizes), + static_assert(std::extent<decltype(v4l2_frame_hdr.dct_part_sizes)>() == + std::extent<decltype(frame_hdr->dct_partition_sizes)>(), "DCT partition size arrays must have equal number of elements"); for (size_t i = 0; i < frame_hdr->num_of_dct_partitions && - i < arraysize(v4l2_frame_hdr.dct_part_sizes); + i < base::size(v4l2_frame_hdr.dct_part_sizes); ++i) v4l2_frame_hdr.dct_part_sizes[i] = frame_hdr->dct_partition_sizes[i];
diff --git a/media/gpu/v4l2/v4l2_vp9_accelerator.cc b/media/gpu/v4l2/v4l2_vp9_accelerator.cc index ef1b2f0..a5ca3705 100644 --- a/media/gpu/v4l2/v4l2_vp9_accelerator.cc +++ b/media/gpu/v4l2/v4l2_vp9_accelerator.cc
@@ -4,10 +4,13 @@ #include "media/gpu/v4l2/v4l2_vp9_accelerator.h" +#include <type_traits> + #include <linux/videodev2.h> #include <string.h> #include "base/logging.h" +#include "base/stl_util.h" #include "media/gpu/macros.h" #include "media/gpu/v4l2/v4l2_decode_surface.h" #include "media/gpu/v4l2/v4l2_decode_surface_handler.h" @@ -68,13 +71,14 @@ SafeArrayMemcpy(v4l2_segm_params->pred_probs, vp9_segm_params.pred_probs); SafeArrayMemcpy(v4l2_segm_params->feature_data, vp9_segm_params.feature_data); - static_assert(arraysize(v4l2_segm_params->feature_enabled) == - arraysize(vp9_segm_params.feature_enabled) && - arraysize(v4l2_segm_params->feature_enabled[0]) == - arraysize(vp9_segm_params.feature_enabled[0]), - "feature_enabled arrays must be of same size"); - for (size_t i = 0; i < arraysize(v4l2_segm_params->feature_enabled); ++i) { - for (size_t j = 0; j < arraysize(v4l2_segm_params->feature_enabled[i]); + static_assert( + std::extent<decltype(v4l2_segm_params->feature_enabled)>() == + std::extent<decltype(vp9_segm_params.feature_enabled)>() && + std::extent<decltype(v4l2_segm_params->feature_enabled[0])>() == + std::extent<decltype(vp9_segm_params.feature_enabled[0])>(), + "feature_enabled arrays must be of same size"); + for (size_t i = 0; i < base::size(v4l2_segm_params->feature_enabled); ++i) { + for (size_t j = 0; j < base::size(v4l2_segm_params->feature_enabled[i]); ++j) { v4l2_segm_params->feature_enabled[i][j] = vp9_segm_params.feature_enabled[i][j]; @@ -270,7 +274,7 @@ struct v4l2_ctrl_vp9_decode_param v4l2_decode_param; memset(&v4l2_decode_param, 0, sizeof(v4l2_decode_param)); - DCHECK_EQ(ref_pictures.size(), arraysize(v4l2_decode_param.ref_frames)); + DCHECK_EQ(ref_pictures.size(), base::size(v4l2_decode_param.ref_frames)); std::vector<scoped_refptr<V4L2DecodeSurface>> ref_surfaces; for (size_t i = 0; i < ref_pictures.size(); ++i) { @@ -285,11 +289,11 @@ } } - static_assert(arraysize(v4l2_decode_param.active_ref_frames) == - arraysize(frame_hdr->ref_frame_idx), + static_assert(std::extent<decltype(v4l2_decode_param.active_ref_frames)>() == + std::extent<decltype(frame_hdr->ref_frame_idx)>(), "active reference frame array sizes mismatch"); - for (size_t i = 0; i < arraysize(frame_hdr->ref_frame_idx); ++i) { + for (size_t i = 0; i < base::size(frame_hdr->ref_frame_idx); ++i) { uint8_t idx = frame_hdr->ref_frame_idx[i]; if (idx >= ref_pictures.size()) return false;
diff --git a/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.cc b/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.cc index e12f045c..51df8cd 100644 --- a/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.cc +++ b/media/gpu/vaapi/vaapi_jpeg_decode_accelerator.cc
@@ -180,7 +180,7 @@ VAIQMatrixBufferJPEGBaseline* iq_matrix) { memset(iq_matrix, 0, sizeof(*iq_matrix)); static_assert(kJpegMaxQuantizationTableNum == - base::size(decltype(iq_matrix->load_quantiser_table){}), + std::extent<decltype(iq_matrix->load_quantiser_table)>(), "max number of quantization table mismatched"); static_assert( sizeof(iq_matrix->quantiser_table[0]) == sizeof(q_table[0].value), @@ -212,7 +212,7 @@ } static_assert(kJpegMaxHuffmanTableNumBaseline == - base::size(decltype(huffman_table->load_huffman_table){}), + std::extent<decltype(huffman_table->load_huffman_table)>(), "max number of huffman table mismatched"); static_assert(sizeof(huffman_table->huffman_table[0].num_dc_codes) == sizeof(dc_table[0].code_length),
diff --git a/media/gpu/vaapi/vaapi_jpeg_encoder.cc b/media/gpu/vaapi/vaapi_jpeg_encoder.cc index 18e49db..e4bd4f1 100644 --- a/media/gpu/vaapi/vaapi_jpeg_encoder.cc +++ b/media/gpu/vaapi/vaapi_jpeg_encoder.cc
@@ -4,12 +4,13 @@ #include "media/gpu/vaapi/vaapi_jpeg_encoder.h" +#include <array> +#include <type_traits> + #include <stddef.h> #include <string.h> -#include <array> #include "base/logging.h" -#include "base/macros.h" #include "base/numerics/safe_conversions.h" #include "base/stl_util.h" #include "media/filters/jpeg_parser.h" @@ -51,9 +52,9 @@ // responsible for scaling the quantization tables based on picture // parameter quality. const JpegQuantizationTable& luminance = kDefaultQuantTable[0]; - static_assert( - arraysize(luminance.value) == arraysize(q_matrix->lum_quantiser_matrix), - "Luminance quantization table size mismatch."); + static_assert(std::extent<decltype(luminance.value)>() == + std::extent<decltype(q_matrix->lum_quantiser_matrix)>(), + "Luminance quantization table size mismatch."); static_assert(base::size(kZigZag8x8) == base::size(luminance.value), "Luminance quantization table size mismatch."); q_matrix->load_lum_quantiser_matrix = 1; @@ -62,8 +63,8 @@ } const JpegQuantizationTable& chrominance = kDefaultQuantTable[1]; - static_assert(arraysize(chrominance.value) == - arraysize(q_matrix->chroma_quantiser_matrix), + static_assert(std::extent<decltype(chrominance.value)>() == + std::extent<decltype(q_matrix->chroma_quantiser_matrix)>(), "Chrominance quantization table size mismatch."); static_assert(base::size(kZigZag8x8) == base::size(chrominance.value), "Chrominance quantization table size mismatch."); @@ -77,9 +78,9 @@ VAHuffmanTableBufferJPEGBaseline* huff_table_param) { static_assert(base::size(kDefaultDcTable) == base::size(kDefaultAcTable), "DC table and AC table size mismatch."); - static_assert( - arraysize(kDefaultDcTable) == arraysize(huff_table_param->huffman_table), - "DC table and destination table size mismatch."); + static_assert(base::size(kDefaultDcTable) == + std::extent<decltype(huff_table_param->huffman_table)>(), + "DC table and destination table size mismatch."); for (size_t i = 0; i < base::size(kDefaultDcTable); ++i) { const JpegHuffmanTable& dcTable = kDefaultDcTable[i]; @@ -93,9 +94,10 @@ // so it has different size than // |huff_table_param->huffman_table[i].dc_values|. Therefore we can't use // SafeArrayMemcpy() here. - static_assert(arraysize(huff_table_param->huffman_table[i].dc_values) <= - arraysize(dcTable.code_value), - "DC table code value array too small."); + static_assert( + std::extent<decltype(huff_table_param->huffman_table[i].dc_values)>() <= + std::extent<decltype(dcTable.code_value)>(), + "DC table code value array too small."); memcpy(huff_table_param->huffman_table[i].dc_values, &dcTable.code_value[0], sizeof(huff_table_param->huffman_table[i].dc_values));
diff --git a/media/gpu/vaapi/vaapi_utils.cc b/media/gpu/vaapi/vaapi_utils.cc index ff4a7861..1bd831b8 100644 --- a/media/gpu/vaapi/vaapi_utils.cc +++ b/media/gpu/vaapi/vaapi_utils.cc
@@ -4,6 +4,8 @@ #include "media/gpu/vaapi/vaapi_utils.h" +#include <type_traits> + #include <va/va.h> #include "base/logging.h" @@ -200,8 +202,8 @@ CheckedMemcpy(pic_param.mb_segment_tree_probs, sgmnt_hdr.segment_prob); - static_assert(base::size(decltype(sgmnt_hdr.lf_update_value){}) == - base::size(decltype(pic_param.loop_filter_level){}), + static_assert(std::extent<decltype(sgmnt_hdr.lf_update_value)>() == + std::extent<decltype(pic_param.loop_filter_level)>(), "loop filter level arrays mismatch"); for (size_t i = 0; i < base::size(sgmnt_hdr.lf_update_value); ++i) { int lf_level = lf_hdr.level; @@ -220,14 +222,14 @@ } static_assert( - base::size(decltype(lf_hdr.ref_frame_delta){}) == - base::size(decltype(pic_param.loop_filter_deltas_ref_frame){}), + std::extent<decltype(lf_hdr.ref_frame_delta)>() == + std::extent<decltype(pic_param.loop_filter_deltas_ref_frame)>(), "loop filter deltas arrays size mismatch"); - static_assert(base::size(decltype(lf_hdr.mb_mode_delta){}) == - base::size(decltype(pic_param.loop_filter_deltas_mode){}), + static_assert(std::extent<decltype(lf_hdr.mb_mode_delta)>() == + std::extent<decltype(pic_param.loop_filter_deltas_mode)>(), "loop filter deltas arrays size mismatch"); - static_assert(base::size(decltype(lf_hdr.ref_frame_delta){}) == - base::size(decltype(lf_hdr.mb_mode_delta){}), + static_assert(std::extent<decltype(lf_hdr.ref_frame_delta)>() == + std::extent<decltype(lf_hdr.mb_mode_delta)>(), "loop filter deltas arrays size mismatch"); for (size_t i = 0; i < base::size(lf_hdr.ref_frame_delta); ++i) { pic_param.loop_filter_deltas_ref_frame[i] = lf_hdr.ref_frame_delta[i];
diff --git a/media/gpu/vaapi/vaapi_video_encode_accelerator.cc b/media/gpu/vaapi/vaapi_video_encode_accelerator.cc index def3b06..3c9e636 100644 --- a/media/gpu/vaapi/vaapi_video_encode_accelerator.cc +++ b/media/gpu/vaapi/vaapi_video_encode_accelerator.cc
@@ -8,6 +8,7 @@ #include <algorithm> #include <memory> +#include <type_traits> #include <utility> #include <va/va.h> @@ -1090,16 +1091,17 @@ if (frame_header->IsKeyframe()) pic_param.pic_flags.bits.forced_lf_adjustment = true; - static_assert( - arraysize(pic_param.loop_filter_level) == - arraysize(pic_param.ref_lf_delta) && - arraysize(pic_param.ref_lf_delta) == - arraysize(pic_param.mode_lf_delta) && - arraysize(pic_param.ref_lf_delta) == - arraysize(frame_header->loopfilter_hdr.ref_frame_delta) && - arraysize(pic_param.mode_lf_delta) == - arraysize(frame_header->loopfilter_hdr.mb_mode_delta), - "Invalid loop filter array sizes"); + static_assert(std::extent<decltype(pic_param.loop_filter_level)>() == + std::extent<decltype(pic_param.ref_lf_delta)>() && + std::extent<decltype(pic_param.ref_lf_delta)>() == + std::extent<decltype(pic_param.mode_lf_delta)>() && + std::extent<decltype(pic_param.ref_lf_delta)>() == + std::extent<decltype( + frame_header->loopfilter_hdr.ref_frame_delta)>() && + std::extent<decltype(pic_param.mode_lf_delta)>() == + std::extent<decltype( + frame_header->loopfilter_hdr.mb_mode_delta)>(), + "Invalid loop filter array sizes"); for (size_t i = 0; i < base::size(pic_param.loop_filter_level); ++i) { pic_param.loop_filter_level[i] = frame_header->loopfilter_hdr.level;
diff --git a/media/gpu/vaapi/vaapi_vp9_accelerator.cc b/media/gpu/vaapi/vaapi_vp9_accelerator.cc index 11c0b583..d46aab8b 100644 --- a/media/gpu/vaapi/vaapi_vp9_accelerator.cc +++ b/media/gpu/vaapi/vaapi_vp9_accelerator.cc
@@ -4,6 +4,8 @@ #include "media/gpu/vaapi/vaapi_vp9_accelerator.h" +#include <type_traits> + #include "base/stl_util.h" #include "media/gpu/decode_surface_handler.h" #include "media/gpu/macros.h" @@ -120,9 +122,10 @@ slice_param.slice_data_offset = 0; slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; - static_assert(arraysize(Vp9SegmentationParams::feature_enabled) == - arraysize(slice_param.seg_param), - "seg_param array of incorrect size"); + static_assert( + std::extent<decltype(Vp9SegmentationParams::feature_enabled)>() == + std::extent<decltype(slice_param.seg_param)>(), + "seg_param array of incorrect size"); for (size_t i = 0; i < base::size(slice_param.seg_param); ++i) { VASegmentParameterVP9& seg_param = slice_param.seg_param[i]; #define SEG_TO_SP_SF(a, b) seg_param.segment_flags.fields.a = b
diff --git a/media/gpu/vaapi/vaapi_wrapper.cc b/media/gpu/vaapi/vaapi_wrapper.cc index aa747385..4921aab 100644 --- a/media/gpu/vaapi/vaapi_wrapper.cc +++ b/media/gpu/vaapi/vaapi_wrapper.cc
@@ -4,6 +4,8 @@ #include "media/gpu/vaapi/vaapi_wrapper.h" +#include <type_traits> + #include <dlfcn.h> #include <string.h> @@ -503,7 +505,8 @@ report_error_to_uma_cb_(base::DoNothing()) { VADisplayState* display_state = VADisplayState::Get(); - static_assert(arraysize(supported_profiles_) == VaapiWrapper::kCodecModeMax, + static_assert(std::extent<decltype(supported_profiles_)>() == + VaapiWrapper::kCodecModeMax, "The array size of supported profile is incorrect."); if (!display_state->Initialize())
diff --git a/media/gpu/video_encode_accelerator_unittest.cc b/media/gpu/video_encode_accelerator_unittest.cc index 722bc3e..22b12ee7 100644 --- a/media/gpu/video_encode_accelerator_unittest.cc +++ b/media/gpu/video_encode_accelerator_unittest.cc
@@ -42,7 +42,6 @@ #include "media/base/bitstream_buffer.h" #include "media/base/cdm_context.h" #include "media/base/decoder_buffer.h" -#include "media/base/media_log.h" #include "media/base/media_util.h" #include "media/base/test_data_util.h" #include "media/base/video_decoder.h" @@ -848,7 +847,7 @@ FrameStats CompareFrames(const VideoFrame& original_frame, const VideoFrame& output_frame); - MediaLog media_log_; + NullMediaLog media_log_; const VideoCodecProfile profile_; const VideoPixelFormat pixel_format_; const bool verify_quality_;
diff --git a/media/mojo/services/interface_factory_impl.cc b/media/mojo/services/interface_factory_impl.cc index a2a103e..311ca5a 100644 --- a/media/mojo/services/interface_factory_impl.cc +++ b/media/mojo/services/interface_factory_impl.cc
@@ -10,7 +10,6 @@ #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" -#include "media/base/media_log.h" #include "media/mojo/services/mojo_decryptor_service.h" #include "media/mojo/services/mojo_media_client.h" #include "mojo/public/cpp/bindings/strong_binding.h" @@ -43,13 +42,9 @@ InterfaceFactoryImpl::InterfaceFactoryImpl( service_manager::mojom::InterfaceProviderPtr interfaces, - MediaLog* media_log, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref, MojoMediaClient* mojo_media_client) : -#if BUILDFLAG(ENABLE_MOJO_RENDERER) - media_log_(media_log), -#endif #if BUILDFLAG(ENABLE_MOJO_CDM) interfaces_(std::move(interfaces)), #endif @@ -116,7 +111,7 @@ // audio device ID. See interface_factory.mojom. const std::string& audio_device_id = type_specific_id; auto renderer = mojo_media_client_->CreateRenderer( - interfaces_.get(), base::ThreadTaskRunnerHandle::Get(), media_log_, + interfaces_.get(), base::ThreadTaskRunnerHandle::Get(), &media_log_, audio_device_id); if (!renderer) { DLOG(ERROR) << "Renderer creation failed.";
diff --git a/media/mojo/services/interface_factory_impl.h b/media/mojo/services/interface_factory_impl.h index 1de15a9..9e3d0533 100644 --- a/media/mojo/services/interface_factory_impl.h +++ b/media/mojo/services/interface_factory_impl.h
@@ -8,6 +8,7 @@ #include <memory> #include "base/macros.h" +#include "media/base/media_util.h" #include "media/mojo/buildflags.h" #include "media/mojo/interfaces/interface_factory.mojom.h" #include "media/mojo/services/deferred_destroy_strong_binding_set.h" @@ -19,14 +20,12 @@ namespace media { class CdmFactory; -class MediaLog; class MojoMediaClient; class InterfaceFactoryImpl : public DeferredDestroy<mojom::InterfaceFactory> { public: InterfaceFactoryImpl( service_manager::mojom::InterfaceProviderPtr interfaces, - MediaLog* media_log, std::unique_ptr<service_manager::ServiceKeepaliveRef> keepalive_ref, MojoMediaClient* mojo_media_client); ~InterfaceFactoryImpl() final; @@ -72,7 +71,8 @@ #endif // BUILDFLAG(ENABLE_MOJO_VIDEO_DECODER) #if BUILDFLAG(ENABLE_MOJO_RENDERER) - MediaLog* media_log_; + // TODO(xhwang): Use MojoMediaLog for Renderer. + NullMediaLog media_log_; mojo::StrongBindingSet<mojom::Renderer> renderer_bindings_; #endif // BUILDFLAG(ENABLE_MOJO_RENDERER)
diff --git a/media/mojo/services/media_service.cc b/media/mojo/services/media_service.cc index 59799f9..b272103 100644 --- a/media/mojo/services/media_service.cc +++ b/media/mojo/services/media_service.cc
@@ -57,9 +57,9 @@ return; interface_factory_bindings_.AddBinding( - std::make_unique<InterfaceFactoryImpl>( - std::move(host_interfaces), &media_log_, keepalive_.CreateRef(), - mojo_media_client_.get()), + std::make_unique<InterfaceFactoryImpl>(std::move(host_interfaces), + keepalive_.CreateRef(), + mojo_media_client_.get()), std::move(request)); }
diff --git a/media/mojo/services/media_service.h b/media/mojo/services/media_service.h index 6a0b93f..98972d5 100644 --- a/media/mojo/services/media_service.h +++ b/media/mojo/services/media_service.h
@@ -9,7 +9,6 @@ #include "base/macros.h" #include "build/build_config.h" -#include "media/base/media_log.h" #include "media/mojo/interfaces/interface_factory.mojom.h" #include "media/mojo/interfaces/media_service.mojom.h" #include "media/mojo/services/deferred_destroy_strong_binding_set.h" @@ -46,7 +45,6 @@ mojom::InterfaceFactoryRequest request, service_manager::mojom::InterfaceProviderPtr host_interfaces) final; - MediaLog media_log_; service_manager::ServiceBinding service_binding_; service_manager::ServiceKeepalive keepalive_; @@ -58,8 +56,6 @@ // |mojo_media_client_| must be destructed before |ref_factory_|. std::unique_ptr<MojoMediaClient> mojo_media_client_; - // Note: Since |&media_log_| is passed to bindings, the bindings must be - // destructed first. DeferredDestroyStrongBindingSet<mojom::InterfaceFactory> interface_factory_bindings_;
diff --git a/media/renderers/audio_renderer_impl_unittest.cc b/media/renderers/audio_renderer_impl_unittest.cc index 24aad49..58407ce 100644 --- a/media/renderers/audio_renderer_impl_unittest.cc +++ b/media/renderers/audio_renderer_impl_unittest.cc
@@ -507,7 +507,7 @@ AudioParameters hardware_params_; base::test::ScopedTaskEnvironment task_environment_; const scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; - MediaLog media_log_; + NullMediaLog media_log_; std::unique_ptr<AudioRendererImpl> renderer_; scoped_refptr<FakeAudioRendererSink> sink_; base::SimpleTestTickClock tick_clock_;
diff --git a/media/renderers/video_renderer_impl_unittest.cc b/media/renderers/video_renderer_impl_unittest.cc index ad55f50e..d13692ed 100644 --- a/media/renderers/video_renderer_impl_unittest.cc +++ b/media/renderers/video_renderer_impl_unittest.cc
@@ -28,6 +28,7 @@ #include "media/base/gmock_callback_support.h" #include "media/base/limits.h" #include "media/base/media_switches.h" +#include "media/base/media_util.h" #include "media/base/mock_filters.h" #include "media/base/null_video_sink.h" #include "media/base/test_helpers.h" @@ -445,7 +446,7 @@ protected: base::test::ScopedTaskEnvironment task_environment_; - MediaLog media_log_; + NullMediaLog media_log_; // Fixture members. std::unique_ptr<VideoRendererImpl> renderer_;
diff --git a/media/test/mock_media_source.h b/media/test/mock_media_source.h index 7155144..7b1fad8 100644 --- a/media/test/mock_media_source.h +++ b/media/test/mock_media_source.h
@@ -9,6 +9,7 @@ #include "base/time/time.h" #include "media/base/demuxer.h" +#include "media/base/media_util.h" #include "media/base/pipeline_status.h" #include "media/filters/chunk_demuxer.h" #include "testing/gmock/include/gmock/gmock.h" @@ -105,7 +106,7 @@ private: void VerifyExpectedAppendResult(bool append_result); - MediaLog media_log_; + NullMediaLog media_log_; scoped_refptr<DecoderBuffer> file_data_; size_t current_position_; size_t initial_append_size_;
diff --git a/net/BUILD.gn b/net/BUILD.gn index d229882..0dbd8f4b 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -2220,8 +2220,8 @@ if (is_fuchsia) { public_deps += [ + "//third_party/fuchsia-sdk/sdk:hardware_ethernet", "//third_party/fuchsia-sdk/sdk:netstack", - "//third_party/fuchsia-sdk/sdk:zircon_ethernet", ] }
diff --git a/net/base/network_change_notifier_fuchsia_unittest.cc b/net/base/network_change_notifier_fuchsia_unittest.cc index e2f4c72..685e777d 100644 --- a/net/base/network_change_notifier_fuchsia_unittest.cc +++ b/net/base/network_change_notifier_fuchsia_unittest.cc
@@ -414,10 +414,11 @@ OnNetworkChanged(NetworkChangeNotifier::CONNECTION_NONE)); EXPECT_CALL(observer_, OnNetworkChanged(NetworkChangeNotifier::CONNECTION_WIFI)); - netstack_.PushInterface(CreateNetInterface( - kDefaultNic, fuchsia::netstack::NetInterfaceFlagUp, - zircon::ethernet::INFO_FEATURE_WLAN, CreateIPv4Address(169, 254, 0, 1), - CreateIPv4Address(255, 255, 255, 0), {})); + netstack_.PushInterface( + CreateNetInterface(kDefaultNic, fuchsia::netstack::NetInterfaceFlagUp, + fuchsia::hardware::ethernet::INFO_FEATURE_WLAN, + CreateIPv4Address(169, 254, 0, 1), + CreateIPv4Address(255, 255, 255, 0), {})); netstack_.NotifyInterfaces(); base::RunLoop().RunUntilIdle(); } @@ -463,10 +464,11 @@ } TEST_F(NetworkChangeNotifierFuchsiaTest, FoundWiFi) { - netstack_.PushInterface(CreateNetInterface( - kDefaultNic, fuchsia::netstack::NetInterfaceFlagUp, - zircon::ethernet::INFO_FEATURE_WLAN, CreateIPv4Address(169, 254, 0, 1), - CreateIPv4Address(255, 255, 255, 0), {})); + netstack_.PushInterface( + CreateNetInterface(kDefaultNic, fuchsia::netstack::NetInterfaceFlagUp, + fuchsia::hardware::ethernet::INFO_FEATURE_WLAN, + CreateIPv4Address(169, 254, 0, 1), + CreateIPv4Address(255, 255, 255, 0), {})); CreateNotifier(); EXPECT_EQ(NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI, notifier_->GetCurrentConnectionType());
diff --git a/net/base/network_interfaces_fuchsia.cc b/net/base/network_interfaces_fuchsia.cc index 52d4c4e..d4e23a7 100644 --- a/net/base/network_interfaces_fuchsia.cc +++ b/net/base/network_interfaces_fuchsia.cc
@@ -27,7 +27,7 @@ ConnectionType ConvertConnectionType( const fuchsia::netstack::NetInterface& iface) { - return iface.features & zircon::ethernet::INFO_FEATURE_WLAN + return iface.features & fuchsia::hardware::ethernet::INFO_FEATURE_WLAN ? NetworkChangeNotifier::CONNECTION_WIFI : NetworkChangeNotifier::CONNECTION_UNKNOWN; } @@ -84,7 +84,7 @@ return output; // Skip loopback. - if (iface_in.features & zircon::ethernet::INFO_FEATURE_LOOPBACK) + if (iface_in.features & fuchsia::hardware::ethernet::INFO_FEATURE_LOOPBACK) return output; output.push_back(NetworkInterfaceFromAddress(iface_in, 0));
diff --git a/net/disk_cache/backend_unittest.cc b/net/disk_cache/backend_unittest.cc index cbc1d32a..625874c 100644 --- a/net/disk_cache/backend_unittest.cc +++ b/net/disk_cache/backend_unittest.cc
@@ -11,6 +11,7 @@ #include "base/metrics/field_trial.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" @@ -441,17 +442,17 @@ entry2->Close(); char buffer[30]; - base::strlcpy(buffer, kName1, arraysize(buffer)); + base::strlcpy(buffer, kName1, base::size(buffer)); ASSERT_THAT(OpenEntry(buffer, &entry2), IsOk()); EXPECT_TRUE(entry1 == entry2); entry2->Close(); - base::strlcpy(buffer + 1, kName1, arraysize(buffer) - 1); + base::strlcpy(buffer + 1, kName1, base::size(buffer) - 1); ASSERT_THAT(OpenEntry(buffer + 1, &entry2), IsOk()); EXPECT_TRUE(entry1 == entry2); entry2->Close(); - base::strlcpy(buffer + 3, kName1, arraysize(buffer) - 3); + base::strlcpy(buffer + 3, kName1, base::size(buffer) - 3); ASSERT_THAT(OpenEntry(buffer + 3, &entry2), IsOk()); EXPECT_TRUE(entry1 == entry2); entry2->Close();
diff --git a/net/disk_cache/blockfile/backend_impl.cc b/net/disk_cache/blockfile/backend_impl.cc index 9123d5f4c..ebb1bb2f 100644 --- a/net/disk_cache/blockfile/backend_impl.cc +++ b/net/disk_cache/blockfile/backend_impl.cc
@@ -20,6 +20,7 @@ #include "base/metrics/histogram.h" #include "base/rand_util.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -2126,7 +2127,7 @@ bool ok = block_files_.IsValid(cache_entry->entry()->address()); ok = ok && block_files_.IsValid(cache_entry->rankings()->address()); EntryStore* data = cache_entry->entry()->Data(); - for (size_t i = 0; i < arraysize(data->data_addr); i++) { + for (size_t i = 0; i < base::size(data->data_addr); i++) { if (data->data_addr[i]) { Addr address(data->data_addr[i]); if (address.is_block_file())
diff --git a/net/disk_cache/blockfile/mapped_file_unittest.cc b/net/disk_cache/blockfile/mapped_file_unittest.cc index f5fd0f5..72bbfe6e 100644 --- a/net/disk_cache/blockfile/mapped_file_unittest.cc +++ b/net/disk_cache/blockfile/mapped_file_unittest.cc
@@ -2,9 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/files/file_path.h" -#include "base/strings/string_util.h" #include "net/disk_cache/blockfile/mapped_file.h" +#include "base/files/file_path.h" +#include "base/stl_util.h" +#include "base/strings/string_util.h" #include "net/disk_cache/disk_cache_test_base.h" #include "net/disk_cache/disk_cache_test_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -49,7 +50,7 @@ char buffer1[20]; char buffer2[20]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); - base::strlcpy(buffer1, "the data", arraysize(buffer1)); + base::strlcpy(buffer1, "the data", base::size(buffer1)); EXPECT_TRUE(file->Write(buffer1, sizeof(buffer1), 8192)); EXPECT_TRUE(file->Read(buffer2, sizeof(buffer2), 8192)); EXPECT_STREQ(buffer1, buffer2); @@ -68,7 +69,7 @@ char buffer1[20]; char buffer2[20]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); - base::strlcpy(buffer1, "the data", arraysize(buffer1)); + base::strlcpy(buffer1, "the data", base::size(buffer1)); bool completed; EXPECT_TRUE(file->Write(buffer1, sizeof(buffer1), 1024 * 1024, &callback, &completed));
diff --git a/net/disk_cache/blockfile/stats.cc b/net/disk_cache/blockfile/stats.cc index 72e15e7..161e013 100644 --- a/net/disk_cache/blockfile/stats.cc +++ b/net/disk_cache/blockfile/stats.cc
@@ -11,6 +11,7 @@ #include "base/metrics/histogram_samples.h" #include "base/metrics/sample_vector.h" #include "base/metrics/statistics_recorder.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -67,7 +68,7 @@ "Doom recent entries", "unused" }; -static_assert(arraysize(kCounterNames) == disk_cache::Stats::MAX_COUNTER, +static_assert(base::size(kCounterNames) == disk_cache::Stats::MAX_COUNTER, "update the names"); } // namespace
diff --git a/net/disk_cache/simple/simple_index_file_unittest.cc b/net/disk_cache/simple/simple_index_file_unittest.cc index 1780e277..5ce8e41c 100644 --- a/net/disk_cache/simple/simple_index_file_unittest.cc +++ b/net/disk_cache/simple/simple_index_file_unittest.cc
@@ -15,6 +15,7 @@ #include "base/pickle.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" @@ -178,7 +179,7 @@ TEST_F(SimpleIndexFileTest, Serialize) { SimpleIndex::EntrySet entries; static const uint64_t kHashes[] = {11, 22, 33}; - static const size_t kNumHashes = arraysize(kHashes); + static const size_t kNumHashes = base::size(kHashes); EntryMetadata metadata_entries[kNumHashes]; SimpleIndexFile::IndexMetadata index_metadata( @@ -219,9 +220,9 @@ TEST_F(SimpleIndexFileTest, ReadV7Format) { static const uint64_t kHashes[] = {11, 22, 33}; static const uint32_t kSizes[] = {394, 594, 495940}; - static_assert(arraysize(kHashes) == arraysize(kSizes), + static_assert(base::size(kHashes) == base::size(kSizes), "Need same number of hashes and sizes"); - static const size_t kNumHashes = arraysize(kHashes); + static const size_t kNumHashes = base::size(kHashes); V7IndexMetadataForTest v7_metadata(kNumHashes, 100 * 1024 * 1024); @@ -298,7 +299,7 @@ SimpleIndex::EntrySet entries; static const uint64_t kHashes[] = {11, 22, 33}; - static const size_t kNumHashes = arraysize(kHashes); + static const size_t kNumHashes = base::size(kHashes); EntryMetadata metadata_entries[kNumHashes]; for (size_t i = 0; i < kNumHashes; ++i) { uint64_t hash = kHashes[i];
diff --git a/net/dns/address_sorter_posix.cc b/net/dns/address_sorter_posix.cc index 4379643c..ff9059f 100644 --- a/net/dns/address_sorter_posix.cc +++ b/net/dns/address_sorter_posix.cc
@@ -22,6 +22,7 @@ #include <vector> #include "base/logging.h" +#include "base/stl_util.h" #include "net/base/net_errors.h" #include "net/log/net_log_source.h" #include "net/socket/client_socket_factory.h" @@ -251,11 +252,11 @@ AddressSorterPosix::AddressSorterPosix(ClientSocketFactory* socket_factory) : socket_factory_(socket_factory), precedence_table_(LoadPolicy(kDefaultPrecedenceTable, - arraysize(kDefaultPrecedenceTable))), - label_table_(LoadPolicy(kDefaultLabelTable, - arraysize(kDefaultLabelTable))), + base::size(kDefaultPrecedenceTable))), + label_table_( + LoadPolicy(kDefaultLabelTable, base::size(kDefaultLabelTable))), ipv4_scope_table_(LoadPolicy(kDefaultIPv4ScopeTable, - arraysize(kDefaultIPv4ScopeTable))) { + base::size(kDefaultIPv4ScopeTable))) { NetworkChangeNotifier::AddIPAddressObserver(this); OnIPAddressChanged(); }
diff --git a/net/dns/dns_config_service_posix_unittest.cc b/net/dns/dns_config_service_posix_unittest.cc index b94a8dce..ab9c3763 100644 --- a/net/dns/dns_config_service_posix_unittest.cc +++ b/net/dns/dns_config_service_posix_unittest.cc
@@ -9,6 +9,7 @@ #include "base/cancelable_callback.h" #include "base/files/file_util.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/sys_byteorder.h" #include "base/test/scoped_task_environment.h" #include "base/test/test_timeouts.h" @@ -72,7 +73,7 @@ res->dnsrch[0] = res->defdname; res->dnsrch[1] = res->defdname + sizeof("chromium.org"); - for (unsigned i = 0; i < arraysize(kNameserversIPv4) && i < MAXNS; ++i) { + for (unsigned i = 0; i < base::size(kNameserversIPv4) && i < MAXNS; ++i) { struct sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_port = base::HostToNet16(NS_DEFAULTPORT + i); @@ -84,7 +85,7 @@ #if defined(OS_LINUX) // Install IPv6 addresses, replacing the corresponding IPv4 addresses. unsigned nscount6 = 0; - for (unsigned i = 0; i < arraysize(kNameserversIPv6) && i < MAXNS; ++i) { + for (unsigned i = 0; i < base::size(kNameserversIPv6) && i < MAXNS; ++i) { if (!kNameserversIPv6[i]) continue; // Must use malloc to mimick res_ninit. @@ -121,14 +122,14 @@ config->search.push_back("example.com"); config->nameservers.clear(); - for (unsigned i = 0; i < arraysize(kNameserversIPv4) && i < MAXNS; ++i) { + for (unsigned i = 0; i < base::size(kNameserversIPv4) && i < MAXNS; ++i) { IPAddress ip; EXPECT_TRUE(ip.AssignFromIPLiteral(kNameserversIPv4[i])); config->nameservers.push_back(IPEndPoint(ip, NS_DEFAULTPORT + i)); } #if defined(OS_LINUX) - for (unsigned i = 0; i < arraysize(kNameserversIPv6) && i < MAXNS; ++i) { + for (unsigned i = 0; i < base::size(kNameserversIPv6) && i < MAXNS; ++i) { if (!kNameserversIPv6[i]) continue; IPAddress ip;
diff --git a/net/dns/dns_hosts_unittest.cc b/net/dns/dns_hosts_unittest.cc index 48616d4..0b5476d 100644 --- a/net/dns/dns_hosts_unittest.cc +++ b/net/dns/dns_hosts_unittest.cc
@@ -4,6 +4,7 @@ #include "net/dns/dns_hosts.h" +#include "base/stl_util.h" #include "net/base/ip_address.h" #include "testing/gtest/include/gtest/gtest.h" @@ -71,7 +72,7 @@ }; DnsHosts expected_hosts, actual_hosts; - PopulateExpectedHosts(kEntries, arraysize(kEntries), &expected_hosts); + PopulateExpectedHosts(kEntries, base::size(kEntries), &expected_hosts); ParseHosts(kContents, &actual_hosts); ASSERT_EQ(expected_hosts, actual_hosts); } @@ -84,7 +85,7 @@ }; DnsHosts expected_hosts, actual_hosts; - PopulateExpectedHosts(kEntries, arraysize(kEntries), &expected_hosts); + PopulateExpectedHosts(kEntries, base::size(kEntries), &expected_hosts); ParseHostsWithCommaModeForTesting( kContents, &actual_hosts, PARSE_HOSTS_COMMA_IS_TOKEN); ASSERT_EQ(0UL, actual_hosts.size()); @@ -99,7 +100,7 @@ }; DnsHosts expected_hosts, actual_hosts; - PopulateExpectedHosts(kEntries, arraysize(kEntries), &expected_hosts); + PopulateExpectedHosts(kEntries, base::size(kEntries), &expected_hosts); ParseHostsWithCommaModeForTesting( kContents, &actual_hosts, PARSE_HOSTS_COMMA_IS_WHITESPACE); ASSERT_EQ(expected_hosts, actual_hosts); @@ -117,7 +118,7 @@ { "comma2", ADDRESS_FAMILY_IPV4, "127.0.0.1" }, }; DnsHosts expected_hosts; - PopulateExpectedHosts(kEntries, arraysize(kEntries), &expected_hosts); + PopulateExpectedHosts(kEntries, base::size(kEntries), &expected_hosts); ASSERT_EQ(expected_hosts, actual_hosts); #else ASSERT_EQ(0UL, actual_hosts.size());
diff --git a/net/dns/dns_response_unittest.cc b/net/dns/dns_response_unittest.cc index 130b4c0..a71732f 100644 --- a/net/dns/dns_response_unittest.cc +++ b/net/dns/dns_response_unittest.cc
@@ -8,6 +8,7 @@ #include "base/big_endian.h" #include "base/optional.h" +#include "base/stl_util.h" #include "base/time/time.h" #include "net/base/address_list.h" #include "net/base/io_buffer.h" @@ -573,36 +574,44 @@ int expected_ttl_sec; } cases[] = { { - kT0QuerySize, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram), - kT0IpAddresses, arraysize(kT0IpAddresses), - kT0CanonName, - kT0TTL, + kT0QuerySize, + kT0ResponseDatagram, + base::size(kT0ResponseDatagram), + kT0IpAddresses, + base::size(kT0IpAddresses), + kT0CanonName, + kT0TTL, }, { - kT1QuerySize, - kT1ResponseDatagram, arraysize(kT1ResponseDatagram), - kT1IpAddresses, arraysize(kT1IpAddresses), - kT1CanonName, - kT1TTL, + kT1QuerySize, + kT1ResponseDatagram, + base::size(kT1ResponseDatagram), + kT1IpAddresses, + base::size(kT1IpAddresses), + kT1CanonName, + kT1TTL, }, { - kT2QuerySize, - kT2ResponseDatagram, arraysize(kT2ResponseDatagram), - kT2IpAddresses, arraysize(kT2IpAddresses), - kT2CanonName, - kT2TTL, + kT2QuerySize, + kT2ResponseDatagram, + base::size(kT2ResponseDatagram), + kT2IpAddresses, + base::size(kT2IpAddresses), + kT2CanonName, + kT2TTL, }, { - kT3QuerySize, - kT3ResponseDatagram, arraysize(kT3ResponseDatagram), - kT3IpAddresses, arraysize(kT3IpAddresses), - kT3CanonName, - kT3TTL, + kT3QuerySize, + kT3ResponseDatagram, + base::size(kT3ResponseDatagram), + kT3IpAddresses, + base::size(kT3IpAddresses), + kT3CanonName, + kT3TTL, }, }; - for (size_t i = 0; i < arraysize(cases); ++i) { + for (size_t i = 0; i < base::size(cases); ++i) { const TestCase& t = cases[i]; DnsResponse response(t.response_data, t.response_size, t.query_size); AddressList addr_list; @@ -707,26 +716,26 @@ size_t size; DnsResponse::Result expected_result; } cases[] = { - { kResponseTruncatedRecord, arraysize(kResponseTruncatedRecord), - DnsResponse::DNS_MALFORMED_RESPONSE }, - { kResponseTruncatedCNAME, arraysize(kResponseTruncatedCNAME), - DnsResponse::DNS_MALFORMED_CNAME }, - { kResponseNameMismatch, arraysize(kResponseNameMismatch), - DnsResponse::DNS_NAME_MISMATCH }, - { kResponseNameMismatchInChain, arraysize(kResponseNameMismatchInChain), - DnsResponse::DNS_NAME_MISMATCH }, - { kResponseSizeMismatch, arraysize(kResponseSizeMismatch), - DnsResponse::DNS_SIZE_MISMATCH }, - { kResponseCNAMEAfterAddress, arraysize(kResponseCNAMEAfterAddress), - DnsResponse::DNS_CNAME_AFTER_ADDRESS }, - // Not actually a failure, just an empty result. - { kResponseNoAddresses, arraysize(kResponseNoAddresses), - DnsResponse::DNS_PARSE_OK }, + {kResponseTruncatedRecord, base::size(kResponseTruncatedRecord), + DnsResponse::DNS_MALFORMED_RESPONSE}, + {kResponseTruncatedCNAME, base::size(kResponseTruncatedCNAME), + DnsResponse::DNS_MALFORMED_CNAME}, + {kResponseNameMismatch, base::size(kResponseNameMismatch), + DnsResponse::DNS_NAME_MISMATCH}, + {kResponseNameMismatchInChain, base::size(kResponseNameMismatchInChain), + DnsResponse::DNS_NAME_MISMATCH}, + {kResponseSizeMismatch, base::size(kResponseSizeMismatch), + DnsResponse::DNS_SIZE_MISMATCH}, + {kResponseCNAMEAfterAddress, base::size(kResponseCNAMEAfterAddress), + DnsResponse::DNS_CNAME_AFTER_ADDRESS}, + // Not actually a failure, just an empty result. + {kResponseNoAddresses, base::size(kResponseNoAddresses), + DnsResponse::DNS_PARSE_OK}, }; const size_t kQuerySize = 12 + 7; - for (size_t i = 0; i < arraysize(cases); ++i) { + for (size_t i = 0; i < base::size(cases); ++i) { const TestCase& t = cases[i]; DnsResponse response(t.data, t.size, kQuerySize);
diff --git a/net/dns/dns_test_util.h b/net/dns/dns_test_util.h index 4d958486..6a4f72c4 100644 --- a/net/dns/dns_test_util.h +++ b/net/dns/dns_test_util.h
@@ -13,6 +13,7 @@ #include <utility> #include <vector> +#include "base/stl_util.h" #include "net/dns/dns_client.h" #include "net/dns/dns_config.h" #include "net/dns/dns_response.h" @@ -52,7 +53,7 @@ static const char kT0CanonName[] = "www.l.google.com"; static const int kT0TTL = 0x000000e4; // +1 for the CNAME record. -static const unsigned kT0RecordCount = arraysize(kT0IpAddresses) + 1; +static const unsigned kT0RecordCount = base::size(kT0IpAddresses) + 1; //----------------------------------------------------------------------------- // Query/response set for codereview.chromium.org, ID is fixed to 1. @@ -82,7 +83,7 @@ static const char kT1CanonName[] = "ghs.l.google.com"; static const int kT1TTL = 0x0000010b; // +1 for the CNAME record. -static const unsigned kT1RecordCount = arraysize(kT1IpAddresses) + 1; +static const unsigned kT1RecordCount = base::size(kT1IpAddresses) + 1; //----------------------------------------------------------------------------- // Query/response set for www.ccs.neu.edu, ID is fixed to 2. @@ -111,7 +112,7 @@ static const char kT2CanonName[] = "vulcan.ccs.neu.edu"; static const int kT2TTL = 0x0000012c; // +1 for the CNAME record. -static const unsigned kT2RecordCount = arraysize(kT2IpAddresses) + 1; +static const unsigned kT2RecordCount = base::size(kT2IpAddresses) + 1; //----------------------------------------------------------------------------- // Query/response set for www.google.az, ID is fixed to 3. @@ -153,7 +154,7 @@ static const char kT3CanonName[] = "www.l.google.com"; static const int kT3TTL = 0x00000015; // +2 for the CNAME records, +1 for TXT record. -static const unsigned kT3RecordCount = arraysize(kT3IpAddresses) + 3; +static const unsigned kT3RecordCount = base::size(kT3IpAddresses) + 3; class AddressSorter; class DnsClient;
diff --git a/net/dns/dns_transaction_unittest.cc b/net/dns/dns_transaction_unittest.cc index 1c481a7a..9a2d5e26 100644 --- a/net/dns/dns_transaction_unittest.cc +++ b/net/dns/dns_transaction_unittest.cc
@@ -13,10 +13,10 @@ #include "base/base64url.h" #include "base/bind.h" #include "base/containers/circular_deque.h" -#include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/rand_util.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/sys_byteorder.h" @@ -841,7 +841,8 @@ TEST_F(DnsTransactionTest, Lookup) { AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, + base::size(kT0ResponseDatagram)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.Run(transaction_factory_.get())); @@ -855,7 +856,7 @@ expected_opt_rdata.AddOpt(ednsOpt); AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram), + kT0ResponseDatagram, base::size(kT0ResponseDatagram), &expected_opt_rdata); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); @@ -877,7 +878,7 @@ } AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram), + kT0ResponseDatagram, base::size(kT0ResponseDatagram), &expected_opt_rdata); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); @@ -888,9 +889,11 @@ // consumes a socket from ClientSocketFactory. TEST_F(DnsTransactionTest, ConcurrentLookup) { AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, + base::size(kT0ResponseDatagram)); AddAsyncQueryAndResponse(1 /* id */, kT1HostName, kT1Qtype, - kT1ResponseDatagram, arraysize(kT1ResponseDatagram)); + kT1ResponseDatagram, + base::size(kT1ResponseDatagram)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); helper0.StartTransaction(transaction_factory_.get()); @@ -905,9 +908,11 @@ TEST_F(DnsTransactionTest, CancelLookup) { AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, + base::size(kT0ResponseDatagram)); AddAsyncQueryAndResponse(1 /* id */, kT1HostName, kT1Qtype, - kT1ResponseDatagram, arraysize(kT1ResponseDatagram)); + kT1ResponseDatagram, + base::size(kT1ResponseDatagram)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); helper0.StartTransaction(transaction_factory_.get()); @@ -924,7 +929,8 @@ TEST_F(DnsTransactionTest, DestroyFactory) { AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, + base::size(kT0ResponseDatagram)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); helper0.StartTransaction(transaction_factory_.get()); @@ -939,7 +945,8 @@ TEST_F(DnsTransactionTest, CancelFromCallback) { AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, + base::size(kT0ResponseDatagram)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); helper0.set_cancel_in_callback(); @@ -953,14 +960,14 @@ // First attempt receives mismatched response synchronously. std::unique_ptr<DnsSocketData> data(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::UDP)); - data->AddResponseData(kT1ResponseDatagram, arraysize(kT1ResponseDatagram), + data->AddResponseData(kT1ResponseDatagram, base::size(kT1ResponseDatagram), SYNCHRONOUS); AddSocketData(std::move(data)); // Second attempt receives valid response synchronously. std::unique_ptr<DnsSocketData> data1(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::UDP)); - data1->AddResponseData(kT0ResponseDatagram, arraysize(kT0ResponseDatagram), + data1->AddResponseData(kT0ResponseDatagram, base::size(kT0ResponseDatagram), SYNCHRONOUS); AddSocketData(std::move(data1)); @@ -975,14 +982,14 @@ // First attempt receives mismatched response asynchronously. std::unique_ptr<DnsSocketData> data0(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, ASYNC, Transport::UDP)); - data0->AddResponseData(kT1ResponseDatagram, arraysize(kT1ResponseDatagram), + data0->AddResponseData(kT1ResponseDatagram, base::size(kT1ResponseDatagram), ASYNC); AddSocketData(std::move(data0)); // Second attempt receives valid response asynchronously. std::unique_ptr<DnsSocketData> data1(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, ASYNC, Transport::UDP)); - data1->AddResponseData(kT0ResponseDatagram, arraysize(kT0ResponseDatagram), + data1->AddResponseData(kT0ResponseDatagram, base::size(kT0ResponseDatagram), ASYNC); AddSocketData(std::move(data1)); @@ -996,7 +1003,8 @@ // Attempt receives mismatched response and fails because only one attempt is // allowed. AddAsyncQueryAndResponse(1 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, + base::size(kT0ResponseDatagram)); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_DNS_MALFORMED_RESPONSE); EXPECT_TRUE(helper0.Run(transaction_factory_.get())); @@ -1011,7 +1019,7 @@ // Second attempt receives valid NXDOMAIN response. std::unique_ptr<DnsSocketData> data(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::UDP)); - data->AddResponseData(kT1ResponseDatagram, arraysize(kT1ResponseDatagram), + data->AddResponseData(kT1ResponseDatagram, base::size(kT1ResponseDatagram), SYNCHRONOUS); data->AddRcode(dns_protocol::kRcodeNXDOMAIN, ASYNC); AddSocketData(std::move(data)); @@ -1088,7 +1096,7 @@ 0, 1, 2, 0, 1, // The first transaction. 1, 2, 0, // The second transaction starts from the next server. }; - CheckServerOrder(kOrder, arraysize(kOrder)); + CheckServerOrder(kOrder, base::size(kOrder)); } TEST_F(DnsTransactionTest, SuffixSearchAboveNdots) { @@ -1116,7 +1124,7 @@ // Also check if suffix search causes server rotation. unsigned kOrder0[] = {0, 1, 0, 1}; - CheckServerOrder(kOrder0, arraysize(kOrder0)); + CheckServerOrder(kOrder0, base::size(kOrder0)); } TEST_F(DnsTransactionTest, SuffixSearchBelowNdots) { @@ -1235,7 +1243,7 @@ AddAsyncQueryAndRcode("x.y.z.a", dns_protocol::kTypeA, dns_protocol::kRcodeNXDOMAIN); AddAsyncQueryAndResponse(0 /* id */, "x.y.z.b", dns_protocol::kTypeA, - kResponseNoData, arraysize(kResponseNoData)); + kResponseNoData, base::size(kResponseNoData)); TransactionHelper helper0("x.y.z", dns_protocol::kTypeA, 0 /* answers */); @@ -1248,7 +1256,7 @@ ConfigureFactory(); AddSyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, base::size(kT0ResponseDatagram)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.Run(transaction_factory_.get())); @@ -1263,7 +1271,8 @@ dns_protocol::kRcodeNXDOMAIN); // "www.ccs.neu.edu" AddAsyncQueryAndResponse(2 /* id */, kT2HostName, kT2Qtype, - kT2ResponseDatagram, arraysize(kT2ResponseDatagram)); + kT2ResponseDatagram, + base::size(kT2ResponseDatagram)); TransactionHelper helper0("www", kT2Qtype, kT2RecordCount); EXPECT_TRUE(helper0.Run(transaction_factory_.get())); @@ -1277,7 +1286,7 @@ AddAsyncQueryAndRcode("www.lab.ccs.neu.edu", dns_protocol::kTypeA, dns_protocol::kRcodeNXDOMAIN); AddSyncQueryAndResponse(2 /* id */, kT2HostName, kT2Qtype, - kT2ResponseDatagram, arraysize(kT2ResponseDatagram)); + kT2ResponseDatagram, base::size(kT2ResponseDatagram)); TransactionHelper helper0("www", kT2Qtype, kT2RecordCount); EXPECT_TRUE(helper0.Run(transaction_factory_.get())); @@ -1300,7 +1309,8 @@ socket_factory_->fail_next_socket_ = true; // Second DNS query succeeds. AddAsyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, + base::size(kT0ResponseDatagram)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.Run(transaction_factory_.get())); } @@ -1308,7 +1318,7 @@ TEST_F(DnsTransactionTest, HttpsGetLookup) { ConfigDohServers(true /* clear_udp */, false /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1328,7 +1338,7 @@ TEST_F(DnsTransactionTest, HttpsGetMalformed) { ConfigDohServers(true /* clear_udp */, false /* use_post */); AddQueryAndResponse(1 /* id */, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_DNS_MALFORMED_RESPONSE); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1337,7 +1347,7 @@ TEST_F(DnsTransactionTest, HttpsPostLookup) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1357,7 +1367,7 @@ TEST_F(DnsTransactionTest, HttpsPostMalformed) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(1 /* id */, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_DNS_MALFORMED_RESPONSE); @@ -1367,7 +1377,7 @@ TEST_F(DnsTransactionTest, HttpsPostLookupAsync) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), ASYNC, Transport::HTTPS); + base::size(kT0ResponseDatagram), ASYNC, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); } @@ -1383,7 +1393,7 @@ TEST_F(DnsTransactionTest, HttpsPostLookupFailStart) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_FAILED); SetDohJobMakerCallback(base::BindRepeating(DohJobMakerCallbackFailStart)); @@ -1420,7 +1430,7 @@ TEST_F(DnsTransactionTest, HttpsPostLookupFailAsync) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_DNS_MALFORMED_RESPONSE); SetDohJobMakerCallback(base::BindRepeating(DohJobMakerCallbackFailAsync)); @@ -1433,7 +1443,7 @@ 0, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::HTTPS)); data->AddResponseData(kT0ResponseDatagram, 20, SYNCHRONOUS); data->AddResponseData(kT0ResponseDatagram + 20, - arraysize(kT0ResponseDatagram) - 20, SYNCHRONOUS); + base::size(kT0ResponseDatagram) - 20, SYNCHRONOUS); AddSocketData(std::move(data)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1445,7 +1455,7 @@ 0, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::HTTPS)); data->AddResponseData(kT0ResponseDatagram, 20, ASYNC); data->AddResponseData(kT0ResponseDatagram + 20, - arraysize(kT0ResponseDatagram) - 20, ASYNC); + base::size(kT0ResponseDatagram) - 20, ASYNC); AddSocketData(std::move(data)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1455,7 +1465,7 @@ ConfigDohServers(true /* clear_udp */, true /* use_post */); std::unique_ptr<DnsSocketData> data(new DnsSocketData( 0, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::HTTPS)); - data->AddResponseData(kT0ResponseDatagram, arraysize(kT0ResponseDatagram), + data->AddResponseData(kT0ResponseDatagram, base::size(kT0ResponseDatagram), ASYNC); data->AddResponseData(kT0ResponseDatagram, 0, ASYNC); AddSocketData(std::move(data)); @@ -1467,7 +1477,7 @@ ConfigDohServers(true /* clear_udp */, true /* use_post */); std::unique_ptr<DnsSocketData> data(new DnsSocketData( 0, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::HTTPS)); - data->AddResponseData(kT0ResponseDatagram, arraysize(kT0ResponseDatagram), + data->AddResponseData(kT0ResponseDatagram, base::size(kT0ResponseDatagram), SYNCHRONOUS); data->AddResponseData(kT0ResponseDatagram, 0, ASYNC); AddSocketData(std::move(data)); @@ -1481,7 +1491,7 @@ 0, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::HTTPS)); data->AddResponseData(kT0ResponseDatagram, 20, ASYNC); data->AddResponseData(kT0ResponseDatagram + 20, - arraysize(kT0ResponseDatagram) - 20, SYNCHRONOUS); + base::size(kT0ResponseDatagram) - 20, SYNCHRONOUS); AddSocketData(std::move(data)); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1535,10 +1545,10 @@ config_.attempts = 2; ConfigDohServers(false /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), ASYNC, Transport::UDP); + base::size(kT0ResponseDatagram), ASYNC, Transport::UDP); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); SetDohJobMakerCallback(base::BindRepeating(DohJobMakerCallbackFailStart)); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1550,11 +1560,11 @@ SetDohJobMakerCallback(base::BindRepeating(DohJobMakerCallbackFailStart)); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); AddQueryAndTimeout(kT0HostName, kT0Qtype); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), ASYNC, Transport::UDP); + base::size(kT0ResponseDatagram), ASYNC, Transport::UDP); transaction_ids_.push_back(0); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); @@ -1576,7 +1586,7 @@ AddQueryAndErrorResponse(0, kT0HostName, kT0Qtype, ERR_CONNECTION_REFUSED, SYNCHRONOUS, Transport::UDP); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), ASYNC, Transport::UDP); + base::size(kT0ResponseDatagram), ASYNC, Transport::UDP); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1592,7 +1602,7 @@ SYNCHRONOUS, Transport::UDP); AddQueryAndResponse(1, kT1HostName, kT1Qtype, kT1ResponseDatagram, - arraysize(kT1ResponseDatagram), ASYNC, Transport::UDP); + base::size(kT1ResponseDatagram), ASYNC, Transport::UDP); TransactionHelper helper1(kT1HostName, kT1Qtype, kT1RecordCount); EXPECT_TRUE(helper1.RunUntilDone(transaction_factory_.get())); @@ -1612,14 +1622,14 @@ AddQueryAndErrorResponse(0, kT0HostName, kT0Qtype, ERR_CONNECTION_REFUSED, SYNCHRONOUS, Transport::HTTPS); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), ASYNC, Transport::HTTPS); + base::size(kT0ResponseDatagram), ASYNC, Transport::HTTPS); AddQueryAndErrorResponse(1, kT1HostName, kT1Qtype, ERR_CONNECTION_REFUSED, SYNCHRONOUS, Transport::HTTPS); AddQueryAndErrorResponse(1, kT1HostName, kT1Qtype, ERR_CONNECTION_REFUSED, SYNCHRONOUS, Transport::HTTPS); AddQueryAndResponse(1, kT1HostName, kT1Qtype, kT1ResponseDatagram, - arraysize(kT1ResponseDatagram), ASYNC, Transport::HTTPS); + base::size(kT1ResponseDatagram), ASYNC, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); TransactionHelper helper1(kT1HostName, kT1Qtype, kT1RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1648,7 +1658,7 @@ AddQueryAndRcode(kT0HostName, kT0Qtype, dns_protocol::kRcodeSERVFAIL, ASYNC, Transport::HTTPS); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1658,13 +1668,13 @@ config_.attempts = 3; ConfigDohServers(false /* clear_udp */, true /* use_post */, 2); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), ASYNC, Transport::UDP); + base::size(kT0ResponseDatagram), ASYNC, Transport::UDP); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); SetDohJobMakerCallback(base::BindRepeating(DohJobMakerCallbackFailStart)); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); @@ -1674,10 +1684,10 @@ config_.attempts = 2; ConfigDohServers(true /* clear_udp */, true /* use_post */, 2); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_FAILED); SetDohJobMakerCallback(base::BindRepeating(DohJobMakerCallbackFailStart)); @@ -1719,10 +1729,10 @@ TEST_F(DnsTransactionTest, HttpsPostTestNoCookies) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); AddQueryAndResponse(1, kT1HostName, kT1Qtype, kT1ResponseDatagram, - arraysize(kT1ResponseDatagram), SYNCHRONOUS, + base::size(kT1ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); TransactionHelper helper1(kT1HostName, kT1Qtype, kT1RecordCount); @@ -1755,7 +1765,7 @@ TEST_F(DnsTransactionTest, HttpsPostNoContentLength) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); SetResponseModifierCallback(base::BindRepeating(MakeResponseWithoutLength)); @@ -1770,7 +1780,7 @@ TEST_F(DnsTransactionTest, HttpsPostWithBadRequestResponse) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_DNS_MALFORMED_RESPONSE); SetResponseModifierCallback( @@ -1786,7 +1796,7 @@ TEST_F(DnsTransactionTest, HttpsPostWithWrongType) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_DNS_MALFORMED_RESPONSE); SetResponseModifierCallback(base::BindRepeating(MakeResponseWrongType)); @@ -1804,10 +1814,10 @@ TEST_F(DnsTransactionTest, HttpsGetRedirect) { ConfigDohServers(true /* clear_udp */, false /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); SetResponseModifierCallback(base::BindRepeating(MakeResponseRedirect)); @@ -1821,7 +1831,7 @@ TEST_F(DnsTransactionTest, HttpsPostWithNoType) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, ERR_DNS_MALFORMED_RESPONSE); SetResponseModifierCallback(base::BindRepeating(MakeResponseNoType)); @@ -1864,7 +1874,7 @@ TEST_F(DnsTransactionTest, HttpsPostLookupWithLog) { ConfigDohServers(true /* clear_udp */, true /* use_post */); AddQueryAndResponse(0, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), SYNCHRONOUS, + base::size(kT0ResponseDatagram), SYNCHRONOUS, Transport::HTTPS); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); CountingObserver observer; @@ -1880,7 +1890,7 @@ AddAsyncQueryAndRcode(kT0HostName, kT0Qtype, dns_protocol::kRcodeNOERROR | dns_protocol::kFlagTC); AddQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, kT0ResponseDatagram, - arraysize(kT0ResponseDatagram), ASYNC, Transport::TCP); + base::size(kT0ResponseDatagram), ASYNC, Transport::TCP); TransactionHelper helper0(kT0HostName, kT0Qtype, kT0RecordCount); EXPECT_TRUE(helper0.Run(transaction_factory_.get())); @@ -1910,7 +1920,7 @@ data->AddResponseWithLength( std::make_unique<DnsResponse>( reinterpret_cast<const char*>(kT0ResponseDatagram), - arraysize(kT0ResponseDatagram), 0), + base::size(kT0ResponseDatagram), 0), ASYNC, static_cast<uint16_t>(kT0QuerySize - 1)); AddSocketData(std::move(data)); @@ -1940,8 +1950,8 @@ data->AddResponseWithLength( std::make_unique<DnsResponse>( reinterpret_cast<const char*>(kT0ResponseDatagram), - arraysize(kT0ResponseDatagram) - 1, 0), - ASYNC, static_cast<uint16_t>(arraysize(kT0ResponseDatagram))); + base::size(kT0ResponseDatagram) - 1, 0), + ASYNC, static_cast<uint16_t>(base::size(kT0ResponseDatagram))); // Then return a 0-length read. data->AddReadError(0, ASYNC); AddSocketData(std::move(data)); @@ -1959,8 +1969,8 @@ data->AddResponseWithLength( std::make_unique<DnsResponse>( reinterpret_cast<const char*>(kT0ResponseDatagram), - arraysize(kT0ResponseDatagram) - 1, 0), - SYNCHRONOUS, static_cast<uint16_t>(arraysize(kT0ResponseDatagram))); + base::size(kT0ResponseDatagram) - 1, 0), + SYNCHRONOUS, static_cast<uint16_t>(base::size(kT0ResponseDatagram))); // Then return a 0-length read. data->AddReadError(0, SYNCHRONOUS); AddSocketData(std::move(data)); @@ -1999,7 +2009,7 @@ std::unique_ptr<DnsSocketData> data(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::UDP)); // First attempt gets a mismatched response. - data->AddResponseData(kT1ResponseDatagram, arraysize(kT1ResponseDatagram), + data->AddResponseData(kT1ResponseDatagram, base::size(kT1ResponseDatagram), SYNCHRONOUS); // Second read from first attempt gets TCP required. data->AddRcode(dns_protocol::kFlagTC, ASYNC); @@ -2021,7 +2031,7 @@ std::unique_ptr<DnsSocketData> data(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::UDP)); // First attempt gets a mismatched response. - data->AddResponseData(kT1ResponseDatagram, arraysize(kT1ResponseDatagram), + data->AddResponseData(kT1ResponseDatagram, base::size(kT1ResponseDatagram), SYNCHRONOUS); // Second read from first attempt gets TCP required. data->AddRcode(dns_protocol::kFlagTC, ASYNC); @@ -2029,7 +2039,7 @@ // Second attempt gets a valid response, which happens before the TCP // required. AddSyncQueryAndResponse(0 /* id */, kT0HostName, kT0Qtype, - kT0ResponseDatagram, arraysize(kT0ResponseDatagram)); + kT0ResponseDatagram, base::size(kT0ResponseDatagram)); std::unique_ptr<DnsSocketData> tcp_data(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, ASYNC, Transport::TCP)); tcp_data->AddReadError(ERR_CONNECTION_CLOSED, SYNCHRONOUS); @@ -2067,7 +2077,7 @@ // Attempt 1. std::unique_ptr<DnsSocketData> data(new DnsSocketData( 0 /* id */, kT0HostName, kT0Qtype, SYNCHRONOUS, Transport::UDP)); - data->AddResponseData(kT1ResponseDatagram, arraysize(kT1ResponseDatagram), + data->AddResponseData(kT1ResponseDatagram, base::size(kT1ResponseDatagram), SYNCHRONOUS); data->AddRcode(dns_protocol::kFlagTC, ASYNC); AddSocketData(std::move(data));
diff --git a/net/dns/dns_util_unittest.cc b/net/dns/dns_util_unittest.cc index 384f217..5b2c9cc2 100644 --- a/net/dns/dns_util_unittest.cc +++ b/net/dns/dns_util_unittest.cc
@@ -4,6 +4,7 @@ #include "net/dns/dns_util.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -103,7 +104,7 @@ // change the calls to from |IsValidDNSDomainName| to |IsValidDNSDomain|, and // remove |IsValidDNSDomainName| (defined above). - for (size_t i = 0; i < arraysize(bad_hostnames); ++i) { + for (size_t i = 0; i < base::size(bad_hostnames); ++i) { EXPECT_FALSE(IsValidDNSDomainName(bad_hostnames[i])); } @@ -113,7 +114,7 @@ "www_.noodles.blorg", "www.noodles.blorg.", "_privet._tcp.local", }; - for (size_t i = 0; i < arraysize(good_hostnames); ++i) { + for (size_t i = 0; i < base::size(good_hostnames); ++i) { EXPECT_TRUE(IsValidDNSDomainName(good_hostnames[i])); } }
diff --git a/net/dns/host_cache_unittest.cc b/net/dns/host_cache_unittest.cc index 58d86df..f60f269 100644 --- a/net/dns/host_cache_unittest.cc +++ b/net/dns/host_cache_unittest.cc
@@ -584,7 +584,7 @@ -1}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i)); const HostCache::Key& key1 = tests[i].key1;
diff --git a/net/ftp/ftp_directory_listing_parser.cc b/net/ftp/ftp_directory_listing_parser.cc index 1096ae0..5532318 100644 --- a/net/ftp/ftp_directory_listing_parser.cc +++ b/net/ftp/ftp_directory_listing_parser.cc
@@ -66,7 +66,7 @@ }, }; - for (size_t i = 0; i < arraysize(parsers); i++) { + for (size_t i = 0; i < base::size(parsers); i++) { entries->clear(); if (parsers[i].callback.Run()) { *server_type = parsers[i].server_type; @@ -95,7 +95,7 @@ &converted_text)) { const char* const kNewlineSeparators[] = {"\n", "\r\n"}; - for (size_t j = 0; j < arraysize(kNewlineSeparators); j++) { + for (size_t j = 0; j < base::size(kNewlineSeparators); j++) { int rv = ParseListing(converted_text, base::ASCIIToUTF16(kNewlineSeparators[j]), encoding_name, current_time, entries, server_type);
diff --git a/net/ftp/ftp_directory_listing_parser_ls_unittest.cc b/net/ftp/ftp_directory_listing_parser_ls_unittest.cc index d0f684c..07689d5 100644 --- a/net/ftp/ftp_directory_listing_parser_ls_unittest.cc +++ b/net/ftp/ftp_directory_listing_parser_ls_unittest.cc
@@ -5,6 +5,7 @@ #include "net/ftp/ftp_directory_listing_parser_unittest.h" #include "base/format_macros.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "net/ftp/ftp_directory_listing_parser_ls.h" @@ -153,7 +154,7 @@ FtpDirectoryListingEntry::FILE, "README", 528, 2007, 11, 1, 0, 0 }, }; - for (size_t i = 0; i < arraysize(good_cases); i++) { + for (size_t i = 0; i < base::size(good_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, good_cases[i].input)); @@ -180,7 +181,7 @@ "drwxr-xr-x 3 ftp 4096 May 15 18:11", "drwxr-xr-x folder 0 May 15 18:11", }; - for (size_t i = 0; i < arraysize(ignored_cases); i++) { + for (size_t i = 0; i < base::size(ignored_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, ignored_cases[i])); @@ -205,7 +206,7 @@ // Invalid month value (30). "drwxrwxrwx 2 root root 4096 2012-30-07 00:31 notas_servico", }; - for (size_t i = 0; i < arraysize(bad_cases); i++) { + for (size_t i = 0; i < base::size(bad_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, bad_cases[i]));
diff --git a/net/ftp/ftp_directory_listing_parser_vms.cc b/net/ftp/ftp_directory_listing_parser_vms.cc index 8f1bfe1..c1cb7b0 100644 --- a/net/ftp/ftp_directory_listing_parser_vms.cc +++ b/net/ftp/ftp_directory_listing_parser_vms.cc
@@ -7,6 +7,7 @@ #include <vector> #include "base/numerics/safe_math.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" @@ -154,7 +155,7 @@ "privilege", }; - for (size_t i = 0; i < arraysize(kPermissionDeniedMessages); i++) { + for (size_t i = 0; i < base::size(kPermissionDeniedMessages); i++) { if (text.find(base::ASCIIToUTF16(kPermissionDeniedMessages[i])) != base::string16::npos) return true;
diff --git a/net/ftp/ftp_directory_listing_parser_vms_unittest.cc b/net/ftp/ftp_directory_listing_parser_vms_unittest.cc index 24d1588..7fa7505 100644 --- a/net/ftp/ftp_directory_listing_parser_vms_unittest.cc +++ b/net/ftp/ftp_directory_listing_parser_vms_unittest.cc
@@ -5,9 +5,10 @@ #include "net/ftp/ftp_directory_listing_parser_unittest.h" #include "base/format_macros.h" +#include "base/stl_util.h" +#include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "net/ftp/ftp_directory_listing_parser_vms.h" @@ -49,7 +50,7 @@ "(RWED,RWED,RE,RE)", FtpDirectoryListingEntry::FILE, "announce.txt", 512, 2005, 3, 12, 8, 44}, }; - for (size_t i = 0; i < arraysize(good_cases); i++) { + for (size_t i = 0; i < base::size(good_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, good_cases[i].input)); @@ -115,7 +116,7 @@ "README.TXT;1 19223372036854775807/19223372036854775807 18-APR-2000 " "10:40:39.90", }; - for (size_t i = 0; i < arraysize(bad_cases); i++) { + for (size_t i = 0; i < base::size(bad_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, bad_cases[i])); std::vector<base::string16> lines(GetSingleLineTestCase(bad_cases[i])); @@ -140,7 +141,7 @@ "Total of 1 file, 2 blocks.", "Directory ANYNYMOUS_ROOT:[000000]", }; - for (size_t i = 0; i < arraysize(bad_cases); i++) { + for (size_t i = 0; i < base::size(bad_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, bad_cases[i])); std::vector<base::string16> lines(
diff --git a/net/ftp/ftp_directory_listing_parser_windows_unittest.cc b/net/ftp/ftp_directory_listing_parser_windows_unittest.cc index d574fc9..2a35742a 100644 --- a/net/ftp/ftp_directory_listing_parser_windows_unittest.cc +++ b/net/ftp/ftp_directory_listing_parser_windows_unittest.cc
@@ -5,6 +5,7 @@ #include "net/ftp/ftp_directory_listing_parser_unittest.h" #include "base/format_macros.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "net/ftp/ftp_directory_listing_parser_windows.h" @@ -58,7 +59,7 @@ FtpDirectoryListingEntry::DIRECTORY, "Christmas Midday", -1, 2010, 12, 25, 12, 0 }, }; - for (size_t i = 0; i < arraysize(good_cases); i++) { + for (size_t i = 0; i < base::size(good_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, good_cases[i].input)); @@ -77,7 +78,7 @@ "11-02-09 05:32 <DIR>", "11-02-09 05:32PM <DIR>", }; - for (size_t i = 0; i < arraysize(ignored_cases); i++) { + for (size_t i = 0; i < base::size(ignored_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, ignored_cases[i])); @@ -111,7 +112,7 @@ "12-25-10 12:99AM 0 minutes out of range", "12-25-10 12:00ZM 0 what does ZM mean", }; - for (size_t i = 0; i < arraysize(bad_cases); i++) { + for (size_t i = 0; i < base::size(bad_cases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, bad_cases[i]));
diff --git a/net/ftp/ftp_util_unittest.cc b/net/ftp/ftp_util_unittest.cc index 8342fb4..8a26907 100644 --- a/net/ftp/ftp_util_unittest.cc +++ b/net/ftp/ftp_util_unittest.cc
@@ -5,6 +5,7 @@ #include "net/ftp/ftp_util.h" #include "base/format_macros.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -40,7 +41,7 @@ { "//a//b///c", "a:[b]c" }, { "a//b///c", "[.a.b]c" }, }; - for (size_t i = 0; i < arraysize(kTestCases); i++) { + for (size_t i = 0; i < base::size(kTestCases); i++) { EXPECT_EQ(kTestCases[i].expected_output, FtpUtil::UnixFilePathToVMS(kTestCases[i].input)) << kTestCases[i].input; @@ -77,7 +78,7 @@ { "//a//b///c//", "a:[b.c]" }, { "a//b///c//", "[.a.b.c]" }, }; - for (size_t i = 0; i < arraysize(kTestCases); i++) { + for (size_t i = 0; i < base::size(kTestCases); i++) { EXPECT_EQ(kTestCases[i].expected_output, FtpUtil::UnixDirectoryPathToVMS(kTestCases[i].input)) << kTestCases[i].input; @@ -117,7 +118,7 @@ { "/a/b/c", "/a/b/c" }, { "/a/b/c/d", "/a/b/c/d" }, }; - for (size_t i = 0; i < arraysize(kTestCases); i++) { + for (size_t i = 0; i < base::size(kTestCases); i++) { EXPECT_EQ(kTestCases[i].expected_output, FtpUtil::VMSPathToUnix(kTestCases[i].input)) << kTestCases[i].input; @@ -173,7 +174,7 @@ { "Sep", "02", "09:00", 1994, 9, 2, 9, 0 }, { "Dec", "06", "21:00", 1993, 12, 6, 21, 0 }, }; - for (size_t i = 0; i < arraysize(kTestCases); i++) { + for (size_t i = 0; i < base::size(kTestCases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s %s %s", i, kTestCases[i].month, kTestCases[i].day, kTestCases[i].rest)); @@ -214,7 +215,7 @@ { "11-01-2007", "12:42", 2007, 11, 1, 12, 42 }, }; - for (size_t i = 0; i < arraysize(kTestCases); i++) { + for (size_t i = 0; i < base::size(kTestCases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s %s", i, kTestCases[i].date, kTestCases[i].time)); @@ -252,7 +253,7 @@ { " foo abc ", 1, "abc" }, { " foo abc ", 2, "" }, }; - for (size_t i = 0; i < arraysize(kTestCases); i++) { + for (size_t i = 0; i < base::size(kTestCases); i++) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s %d", i, kTestCases[i].text, kTestCases[i].column));
diff --git a/net/http/bidirectional_stream_unittest.cc b/net/http/bidirectional_stream_unittest.cc index 28f52e6..1c023ec 100644 --- a/net/http/bidirectional_stream_unittest.cc +++ b/net/http/bidirectional_stream_unittest.cc
@@ -52,7 +52,7 @@ namespace { const char kBodyData[] = "Body data"; -const size_t kBodyDataSize = arraysize(kBodyData); +const size_t kBodyDataSize = base::size(kBodyData); const std::string kBodyDataString(kBodyData, kBodyDataSize); // Size of the buffer to be allocated for each read. const size_t kReadBufferSize = 4096;
diff --git a/net/http/http_auth.cc b/net/http/http_auth.cc index bd8f9228..54bc7812 100644 --- a/net/http/http_auth.cc +++ b/net/http/http_auth.cc
@@ -6,6 +6,7 @@ #include <algorithm> +#include "base/stl_util.h" #include "base/strings/string_tokenizer.h" #include "base/strings/string_util.h" #include "net/base/net_errors.h" @@ -133,7 +134,7 @@ static const char* const kSchemeNames[] = { kBasicAuthScheme, kDigestAuthScheme, kNtlmAuthScheme, kNegotiateAuthScheme, kSpdyProxyAuthScheme, kMockAuthScheme}; - static_assert(arraysize(kSchemeNames) == AUTH_SCHEME_MAX, + static_assert(base::size(kSchemeNames) == AUTH_SCHEME_MAX, "http auth scheme names incorrect size"); if (scheme < AUTH_SCHEME_BASIC || scheme >= AUTH_SCHEME_MAX) { NOTREACHED();
diff --git a/net/http/http_auth_filter_unittest.cc b/net/http/http_auth_filter_unittest.cc index 40d67ce..bf72616 100644 --- a/net/http/http_auth_filter_unittest.cc +++ b/net/http/http_auth_filter_unittest.cc
@@ -7,6 +7,7 @@ #include <memory> #include <ostream> +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -23,9 +24,7 @@ "gog" }; -enum { - ALL_SERVERS_MATCH = (1 << arraysize(server_whitelist_array)) - 1 -}; +enum { ALL_SERVERS_MATCH = (1 << base::size(server_whitelist_array)) - 1 }; struct UrlData { GURL url; @@ -73,7 +72,7 @@ TEST(HttpAuthFilterTest, EmptyFilter) { // Create an empty filter HttpAuthFilterWhitelist filter((std::string())); - for (size_t i = 0; i < arraysize(urls); i++) { + for (size_t i = 0; i < base::size(urls); i++) { EXPECT_EQ(urls[i].target == HttpAuth::AUTH_PROXY, filter.IsValid(urls[i].url, urls[i].target)) << " " << i << ": " << urls[i].url; @@ -83,14 +82,14 @@ TEST(HttpAuthFilterTest, NonEmptyFilter) { // Create an non-empty filter std::string server_whitelist_filter_string; - for (size_t i = 0; i < arraysize(server_whitelist_array); ++i) { + for (size_t i = 0; i < base::size(server_whitelist_array); ++i) { if (!server_whitelist_filter_string.empty()) server_whitelist_filter_string += ","; server_whitelist_filter_string += "*"; server_whitelist_filter_string += server_whitelist_array[i]; } HttpAuthFilterWhitelist filter(server_whitelist_filter_string); - for (size_t i = 0; i < arraysize(urls); i++) { + for (size_t i = 0; i < base::size(urls); i++) { EXPECT_EQ(urls[i].matches, filter.IsValid(urls[i].url, urls[i].target)) << " " << i << ": " << urls[i].url; }
diff --git a/net/http/http_auth_gssapi_posix.cc b/net/http/http_auth_gssapi_posix.cc index c83d278..d85cba8 100644 --- a/net/http/http_auth_gssapi_posix.cc +++ b/net/http/http_auth_gssapi_posix.cc
@@ -11,7 +11,7 @@ #include "base/files/file_path.h" #include "base/format_macros.h" #include "base/logging.h" -#include "base/macros.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_restrictions.h" @@ -441,7 +441,7 @@ #endif }; library_names = kDefaultLibraryNames; - num_lib_names = arraysize(kDefaultLibraryNames); + num_lib_names = base::size(kDefaultLibraryNames); } for (size_t i = 0; i < num_lib_names; ++i) {
diff --git a/net/http/http_auth_gssapi_posix_unittest.cc b/net/http/http_auth_gssapi_posix_unittest.cc index 4dcc6c5e..416a873 100644 --- a/net/http/http_auth_gssapi_posix_unittest.cc +++ b/net/http/http_auth_gssapi_posix_unittest.cc
@@ -8,6 +8,7 @@ #include "base/logging.h" #include "base/native_library.h" +#include "base/stl_util.h" #include "net/base/net_errors.h" #include "net/http/http_auth_challenge_tokenizer.h" #include "net/http/mock_gssapi_library_posix.h" @@ -60,7 +61,7 @@ 1, // Locally initiated 0); // Open gss_buffer_desc in_buffer = {0, NULL}; - gss_buffer_desc out_buffer = {arraysize(kInitialAuthResponse), + gss_buffer_desc out_buffer = {base::size(kInitialAuthResponse), const_cast<char*>(kInitialAuthResponse)}; library->ExpectSecurityContext( "Negotiate", @@ -135,7 +136,7 @@ kAuthResponse) // Output token }; - for (size_t i = 0; i < arraysize(queries); ++i) { + for (size_t i = 0; i < base::size(queries); ++i) { mock_library->ExpectSecurityContext(queries[i].expected_package, queries[i].response_code, queries[i].minor_response_code, @@ -158,7 +159,7 @@ gss_buffer_desc output_token = { 0, NULL }; OM_uint32 ret_flags = 0; OM_uint32 time_rec = 0; - for (size_t i = 0; i < arraysize(queries); ++i) { + for (size_t i = 0; i < base::size(queries); ++i) { major_status = mock_library->init_sec_context(&minor_status, initiator_cred_handle, &context_handle,
diff --git a/net/http/http_auth_handler_basic_unittest.cc b/net/http/http_auth_handler_basic_unittest.cc index be5c2e8..1f6ea6f 100644 --- a/net/http/http_auth_handler_basic_unittest.cc +++ b/net/http/http_auth_handler_basic_unittest.cc
@@ -7,6 +7,7 @@ #include <memory> #include <string> +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "net/base/net_errors.h" @@ -39,7 +40,7 @@ }; GURL origin("http://www.example.com"); HttpAuthHandlerBasic::Factory factory; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { std::string challenge = "Basic realm=\"Atlantis\""; SSLInfo null_ssl_info; std::unique_ptr<HttpAuthHandler> basic; @@ -101,7 +102,7 @@ tests[0].challenge, HttpAuth::AUTH_SERVER, null_ssl_info, origin, NetLogWithSource(), &basic)); - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { std::string challenge(tests[i].challenge); HttpAuthChallengeTokenizer tok(challenge.begin(), challenge.end()); @@ -194,7 +195,7 @@ }; HttpAuthHandlerBasic::Factory factory; GURL origin("http://www.example.com"); - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { std::string challenge = tests[i].challenge; SSLInfo null_ssl_info; std::unique_ptr<HttpAuthHandler> basic;
diff --git a/net/http/http_auth_handler_digest_unittest.cc b/net/http/http_auth_handler_digest_unittest.cc index 10b9690..86097ff 100644 --- a/net/http/http_auth_handler_digest_unittest.cc +++ b/net/http/http_auth_handler_digest_unittest.cc
@@ -4,6 +4,7 @@ #include <string> +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "net/base/net_errors.h" @@ -358,7 +359,7 @@ GURL origin("http://www.example.com"); std::unique_ptr<HttpAuthHandlerDigest::Factory> factory( new HttpAuthHandlerDigest::Factory()); - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { SSLInfo null_ssl_info; std::unique_ptr<HttpAuthHandler> handler; int rv = factory->CreateAuthHandlerFromString( @@ -522,7 +523,7 @@ GURL origin("http://www.example.com"); std::unique_ptr<HttpAuthHandlerDigest::Factory> factory( new HttpAuthHandlerDigest::Factory()); - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { SSLInfo null_ssl_info; std::unique_ptr<HttpAuthHandler> handler; int rv = factory->CreateAuthHandlerFromString(
diff --git a/net/http/http_auth_handler_negotiate_unittest.cc b/net/http/http_auth_handler_negotiate_unittest.cc index fc5a7af..ad4f9b0 100644 --- a/net/http/http_auth_handler_negotiate_unittest.cc +++ b/net/http/http_auth_handler_negotiate_unittest.cc
@@ -7,6 +7,7 @@ #include <string> #include "base/memory/ptr_util.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" @@ -159,7 +160,7 @@ kAuthResponse) // Output token }; - for (size_t i = 0; i < arraysize(queries); ++i) { + for (size_t i = 0; i < base::size(queries); ++i) { mock_library->ExpectSecurityContext(queries[i].expected_package, queries[i].response_code, queries[i].minor_response_code,
diff --git a/net/http/http_auth_handler_ntlm_portable_unittest.cc b/net/http/http_auth_handler_ntlm_portable_unittest.cc index d9f861f6..5614330b 100644 --- a/net/http/http_auth_handler_ntlm_portable_unittest.cc +++ b/net/http/http_auth_handler_ntlm_portable_unittest.cc
@@ -6,6 +6,7 @@ #include "base/base64.h" #include "base/containers/span.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" @@ -230,7 +231,7 @@ // Validate the authenticate message std::string decoded; ASSERT_TRUE(DecodeChallenge(token, &decoded)); - ASSERT_EQ(arraysize(ntlm::test::kExpectedAuthenticateMsgSpecResponseV1), + ASSERT_EQ(base::size(ntlm::test::kExpectedAuthenticateMsgSpecResponseV1), decoded.size()); ASSERT_EQ(0, memcmp(decoded.data(), ntlm::test::kExpectedAuthenticateMsgSpecResponseV1,
diff --git a/net/http/http_auth_unittest.cc b/net/http/http_auth_unittest.cc index 58f9f04..43a7514 100644 --- a/net/http/http_auth_unittest.cc +++ b/net/http/http_auth_unittest.cc
@@ -9,6 +9,7 @@ #include <string> #include "base/memory/ref_counted.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "net/base/net_errors.h" @@ -130,7 +131,7 @@ http_auth_handler_factory->SetHttpAuthPreferences(kNegotiateAuthScheme, &http_auth_preferences); - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { // Make a HttpResponseHeaders object. std::string headers_with_status_line("HTTP/1.1 401 Unauthorized\n"); headers_with_status_line += tests[i].headers;
diff --git a/net/http/http_basic_state.cc b/net/http/http_basic_state.cc index efe92f8b..6a9d4b9 100644 --- a/net/http/http_basic_state.cc +++ b/net/http/http_basic_state.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/logging.h" +#include "base/stl_util.h" #include "net/base/io_buffer.h" #include "net/http/http_request_info.h" #include "net/http/http_response_body_drainer.h" @@ -59,7 +60,7 @@ std::string HttpBasicState::GenerateRequestLine() const { static const char kSuffix[] = " HTTP/1.1\r\n"; - const size_t kSuffixLen = arraysize(kSuffix) - 1; + const size_t kSuffixLen = base::size(kSuffix) - 1; const std::string path = using_proxy_ ? HttpUtil::SpecForRequest(url_) : url_.PathForRequest(); // Don't use StringPrintf for concatenation because it is very inefficient.
diff --git a/net/http/http_byte_range_unittest.cc b/net/http/http_byte_range_unittest.cc index 412c7f80..4188bee5 100644 --- a/net/http/http_byte_range_unittest.cc +++ b/net/http/http_byte_range_unittest.cc
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/macros.h" #include "net/http/http_byte_range.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { @@ -28,7 +28,7 @@ { -1, -1, 100000, true }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { HttpByteRange range; range.set_first_byte_position(tests[i].first_byte_position); range.set_last_byte_position(tests[i].last_byte_position); @@ -60,7 +60,7 @@ { 10, 10000, -1, 1000000, true, 10, 10000 }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { HttpByteRange range; range.set_first_byte_position(tests[i].first_byte_position); range.set_last_byte_position(tests[i].last_byte_position); @@ -93,7 +93,7 @@ {HttpByteRange::RightUnbounded(100), "bytes=100-"}, {HttpByteRange::Suffix(100), "bytes=-100"}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { EXPECT_EQ(tests[i].expected, tests[i].range.GetHeaderValue()); } }
diff --git a/net/http/http_cache_transaction.cc b/net/http/http_cache_transaction.cc index e35eff3f..16ece82 100644 --- a/net/http/http_cache_transaction.cc +++ b/net/http/http_cache_transaction.cc
@@ -21,10 +21,10 @@ #include "base/compiler_specific.h" #include "base/format_macros.h" #include "base/location.h" -#include "base/macros.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" // For HexEncode. #include "base/strings/string_piece.h" #include "base/strings/string_util.h" // For LowerCaseEqualsASCII. @@ -202,7 +202,7 @@ weak_factory_(this) { TRACE_EVENT0("io", "HttpCacheTransaction::Transaction"); static_assert(HttpCache::Transaction::kNumValidationHeaders == - arraysize(kValidationHeaders), + base::size(kValidationHeaders), "invalid number of validation headers"); io_callback_ = base::BindRepeating(&Transaction::OnIOComplete, @@ -2354,7 +2354,7 @@ if (request_->extra_headers.HasHeader(HttpRequestHeaders::kRange)) range_found = true; - for (size_t i = 0; i < arraysize(kSpecialHeaders); ++i) { + for (size_t i = 0; i < base::size(kSpecialHeaders); ++i) { if (HeaderMatches(request_->extra_headers, kSpecialHeaders[i].search)) { effective_load_flags_ |= kSpecialHeaders[i].load_flag; special_headers = true; @@ -2364,7 +2364,7 @@ // Check for conditionalization headers which may correspond with a // cache validation request. - for (size_t i = 0; i < arraysize(kValidationHeaders); ++i) { + for (size_t i = 0; i < base::size(kValidationHeaders); ++i) { const ValidationHeaderInfo& info = kValidationHeaders[i]; std::string validation_value; if (request_->extra_headers.GetHeader( @@ -2620,7 +2620,7 @@ DCHECK_EQ(UPDATE, mode_); DCHECK(external_validation_.initialized); - for (size_t i = 0; i < arraysize(kValidationHeaders); i++) { + for (size_t i = 0; i < base::size(kValidationHeaders); i++) { if (external_validation_.values[i].empty()) continue; // Retrieve either the cached response's "etag" or "last-modified" header.
diff --git a/net/http/http_chunked_decoder_unittest.cc b/net/http/http_chunked_decoder_unittest.cc index 2d2898c..246512d 100644 --- a/net/http/http_chunked_decoder_unittest.cc +++ b/net/http/http_chunked_decoder_unittest.cc
@@ -9,6 +9,7 @@ #include <vector> #include "base/format_macros.h" +#include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "net/base/net_errors.h" #include "net/test/gtest_util.h" @@ -70,14 +71,14 @@ const char* const inputs[] = { "B\r\nhello hello\r\n0\r\n\r\n" }; - RunTest(inputs, arraysize(inputs), "hello hello", true, 0); + RunTest(inputs, base::size(inputs), "hello hello", true, 0); } TEST(HttpChunkedDecoderTest, OneChunk) { const char* const inputs[] = { "5\r\nhello\r\n" }; - RunTest(inputs, arraysize(inputs), "hello", false, 0); + RunTest(inputs, base::size(inputs), "hello", false, 0); } TEST(HttpChunkedDecoderTest, Typical) { @@ -87,7 +88,7 @@ "5\r\nworld\r\n", "0\r\n\r\n" }; - RunTest(inputs, arraysize(inputs), "hello world", true, 0); + RunTest(inputs, base::size(inputs), "hello world", true, 0); } TEST(HttpChunkedDecoderTest, Incremental) { @@ -104,7 +105,7 @@ "\r", "\n" }; - RunTest(inputs, arraysize(inputs), "hello", true, 0); + RunTest(inputs, base::size(inputs), "hello", true, 0); } // Same as above, but group carriage returns with previous input. @@ -118,7 +119,7 @@ "\n\r", "\n" }; - RunTest(inputs, arraysize(inputs), "hello", true, 0); + RunTest(inputs, base::size(inputs), "hello", true, 0); } TEST(HttpChunkedDecoderTest, LF_InsteadOf_CRLF) { @@ -131,7 +132,7 @@ "5\nworld\n", "0\n\n" }; - RunTest(inputs, arraysize(inputs), "hello world", true, 0); + RunTest(inputs, base::size(inputs), "hello world", true, 0); } TEST(HttpChunkedDecoderTest, Extensions) { @@ -139,7 +140,7 @@ "5;x=0\r\nhello\r\n", "0;y=\"2 \"\r\n\r\n" }; - RunTest(inputs, arraysize(inputs), "hello", true, 0); + RunTest(inputs, base::size(inputs), "hello", true, 0); } TEST(HttpChunkedDecoderTest, Trailers) { @@ -150,7 +151,7 @@ "Bar: 2\r\n", "\r\n" }; - RunTest(inputs, arraysize(inputs), "hello", true, 0); + RunTest(inputs, base::size(inputs), "hello", true, 0); } TEST(HttpChunkedDecoderTest, TrailersUnfinished) { @@ -159,7 +160,7 @@ "0\r\n", "Foo: 1\r\n" }; - RunTest(inputs, arraysize(inputs), "hello", false, 0); + RunTest(inputs, base::size(inputs), "hello", false, 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_TooBig) { @@ -170,7 +171,7 @@ "48469410265455838241\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_0X) { @@ -181,7 +182,7 @@ "0x5\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, ChunkSize_TrailingSpace) { @@ -193,7 +194,7 @@ "5 \r\nhello\r\n", "0\r\n\r\n" }; - RunTest(inputs, arraysize(inputs), "hello", true, 0); + RunTest(inputs, base::size(inputs), "hello", true, 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_TrailingTab) { @@ -203,7 +204,7 @@ "5\t\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_TrailingFormFeed) { @@ -214,7 +215,7 @@ "5\f\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_TrailingVerticalTab) { @@ -225,7 +226,7 @@ "5\v\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_TrailingNonHexDigit) { @@ -236,7 +237,7 @@ "5H\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_LeadingSpace) { @@ -247,7 +248,7 @@ " 5\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidLeadingSeparator) { @@ -255,7 +256,7 @@ "\r\n5\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_NoSeparator) { @@ -264,7 +265,7 @@ "1\r\n \r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 1); + RunTestUntilFailure(inputs, base::size(inputs), 1); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_Negative) { @@ -272,7 +273,7 @@ "8\r\n12345678\r\n-5\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidChunkSize_Plus) { @@ -283,7 +284,7 @@ "+5\r\nhello\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, InvalidConsecutiveCRLFs) { @@ -292,7 +293,7 @@ "\r\n\r\n\r\n\r\n", "0\r\n\r\n" }; - RunTestUntilFailure(inputs, arraysize(inputs), 1); + RunTestUntilFailure(inputs, base::size(inputs), 1); } TEST(HttpChunkedDecoderTest, ReallyBigChunks) { @@ -339,7 +340,7 @@ // Chunk terminator and the final chunk. char final_chunk[] = "\r\n0\r\n\r\n"; - EXPECT_EQ(OK, decoder.FilterBuf(final_chunk, arraysize(final_chunk))); + EXPECT_EQ(OK, decoder.FilterBuf(final_chunk, base::size(final_chunk))); EXPECT_TRUE(decoder.reached_eof()); // Since |data| never included any chunk headers, it should not have been @@ -353,20 +354,20 @@ TEST(HttpChunkedDecoderTest, ExcessiveChunkLen) { // Smallest number that can't be represented as a signed int64. const char* const inputs[] = {"8000000000000000\r\nhello\r\n"}; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, ExcessiveChunkLen2) { // Smallest number that can't be represented as an unsigned int64. const char* const inputs[] = {"10000000000000000\r\nhello\r\n"}; - RunTestUntilFailure(inputs, arraysize(inputs), 0); + RunTestUntilFailure(inputs, base::size(inputs), 0); } TEST(HttpChunkedDecoderTest, BasicExtraData) { const char* const inputs[] = { "5\r\nhello\r\n0\r\n\r\nextra bytes" }; - RunTest(inputs, arraysize(inputs), "hello", true, 11); + RunTest(inputs, base::size(inputs), "hello", true, 11); } TEST(HttpChunkedDecoderTest, IncrementalExtraData) { @@ -383,7 +384,7 @@ "\r", "\nextra bytes" }; - RunTest(inputs, arraysize(inputs), "hello", true, 11); + RunTest(inputs, base::size(inputs), "hello", true, 11); } TEST(HttpChunkedDecoderTest, MultipleExtraDataBlocks) { @@ -391,7 +392,7 @@ "5\r\nhello\r\n0\r\n\r\nextra", " bytes" }; - RunTest(inputs, arraysize(inputs), "hello", true, 11); + RunTest(inputs, base::size(inputs), "hello", true, 11); } // Test when the line with the chunk length is too long. @@ -404,7 +405,7 @@ big_chunk.get(), "5" }; - RunTestUntilFailure(inputs, arraysize(inputs), 1); + RunTestUntilFailure(inputs, base::size(inputs), 1); } // Test when the extension portion of the line with the chunk length is too @@ -418,7 +419,7 @@ "5;", big_chunk.get() }; - RunTestUntilFailure(inputs, arraysize(inputs), 1); + RunTestUntilFailure(inputs, base::size(inputs), 1); } } // namespace
diff --git a/net/http/http_content_disposition_unittest.cc b/net/http/http_content_disposition_unittest.cc index f283ce9..36e3994 100644 --- a/net/http/http_content_disposition_unittest.cc +++ b/net/http/http_content_disposition_unittest.cc
@@ -4,6 +4,7 @@ #include "net/http/http_content_disposition.h" +#include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" @@ -201,7 +202,7 @@ {"attachment; foobar=x; filename=\"foo.html\"", "", L"foo.html"}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { HttpContentDisposition header(tests[i].header, tests[i].referrer_charset); EXPECT_EQ(tests[i].expected, base::UTF8ToWide(header.filename())) @@ -414,7 +415,7 @@ // TODO(abarth): http://greenbytes.de/tech/tc2231/#attrfc2047token // TODO(abarth): http://greenbytes.de/tech/tc2231/#attrfc2047quoted }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { HttpContentDisposition header(tests[i].header, std::string()); EXPECT_EQ(tests[i].expected_type, header.type()) << "Failed on input: " << tests[i].header; @@ -487,7 +488,7 @@ HttpContentDisposition::INVALID}, }; - for (size_t i = 0; i < arraysize(kTestCases); ++i) { + for (size_t i = 0; i < base::size(kTestCases); ++i) { const ParseResultTestCase& test_case = kTestCases[i]; HttpContentDisposition content_disposition(test_case.header, "utf-8"); int result = content_disposition.parse_result_flags();
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index f636610..d36d1de2 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -19,10 +19,10 @@ #include "base/files/file_util.h" #include "base/json/json_writer.h" #include "base/logging.h" -#include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -2236,7 +2236,7 @@ data.set_busy_before_sync_reads(true); session_deps_.socket_factory->AddSocketDataProvider(&data); - const int kNumUnreadBodies = arraysize(data_writes) - 1; + const int kNumUnreadBodies = base::size(data_writes) - 1; std::string response_lines[kNumUnreadBodies]; uint32_t first_socket_log_id = NetLogSource::kInvalidId; @@ -2283,7 +2283,7 @@ "HTTP/1.1 200 Hunky-Dory", }; - static_assert(kNumUnreadBodies == arraysize(kStatusLines), + static_assert(kNumUnreadBodies == base::size(kStatusLines), "forgot to update kStatusLines"); for (int i = 0; i < kNumUnreadBodies; ++i) @@ -4988,7 +4988,7 @@ }; MockWrite socks5_writes[] = { MockWrite(ASYNC, kSOCKS5GreetRequest, kSOCKS5GreetRequestLength), - MockWrite(ASYNC, kSOCKS5Request, arraysize(kSOCKS5Request)), + MockWrite(ASYNC, kSOCKS5Request, base::size(kSOCKS5Request)), MockWrite(SYNCHRONOUS, "GET /socks5 HTTP/1.1\r\n" "Host: test\r\n" @@ -5525,7 +5525,7 @@ "proxy-authorization", "Basic Zm9vOmJhcg==" }; spdy::SpdySerializedFrame req_get_authorization(spdy_util_.ConstructSpdyGet( - kExtraAuthorizationHeaders, arraysize(kExtraAuthorizationHeaders) / 2, 3, + kExtraAuthorizationHeaders, base::size(kExtraAuthorizationHeaders) / 2, 3, LOWEST)); MockWrite spdy_writes[] = { CreateMockWrite(req_get, 0), CreateMockWrite(req_get_authorization, 3), @@ -5540,7 +5540,7 @@ spdy::SpdySerializedFrame resp_authentication( spdy_util_.ConstructSpdyReplyError( "407", kExtraAuthenticationHeaders, - arraysize(kExtraAuthenticationHeaders) / 2, 1)); + base::size(kExtraAuthenticationHeaders) / 2, 1)); spdy::SpdySerializedFrame body_authentication( spdy_util_.ConstructSpdyDataFrame(1, true)); spdy::SpdySerializedFrame resp_data( @@ -7073,18 +7073,18 @@ base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>(ntlm::test::kExpectedNegotiateMsg), - arraysize(ntlm::test::kExpectedNegotiateMsg)), + base::size(ntlm::test::kExpectedNegotiateMsg)), &negotiate_msg); base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>(ntlm::test::kChallengeMsgFromSpecV2), - arraysize(ntlm::test::kChallengeMsgFromSpecV2)), + base::size(ntlm::test::kChallengeMsgFromSpecV2)), &challenge_msg); base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>( ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2), - arraysize( + base::size( ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2)), &authenticate_msg); @@ -7225,18 +7225,18 @@ base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>(ntlm::test::kExpectedNegotiateMsg), - arraysize(ntlm::test::kExpectedNegotiateMsg)), + base::size(ntlm::test::kExpectedNegotiateMsg)), &negotiate_msg); base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>(ntlm::test::kChallengeMsgFromSpecV2), - arraysize(ntlm::test::kChallengeMsgFromSpecV2)), + base::size(ntlm::test::kChallengeMsgFromSpecV2)), &challenge_msg); base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>( ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2), - arraysize( + base::size( ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2)), &authenticate_msg); @@ -7471,18 +7471,18 @@ base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>(ntlm::test::kExpectedNegotiateMsg), - arraysize(ntlm::test::kExpectedNegotiateMsg)), + base::size(ntlm::test::kExpectedNegotiateMsg)), &negotiate_msg); base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>(ntlm::test::kChallengeMsgFromSpecV2), - arraysize(ntlm::test::kChallengeMsgFromSpecV2)), + base::size(ntlm::test::kChallengeMsgFromSpecV2)), &challenge_msg); base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>( ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2), - arraysize( + base::size( ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2)), &authenticate_msg); @@ -7635,18 +7635,18 @@ base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>(ntlm::test::kExpectedNegotiateMsg), - arraysize(ntlm::test::kExpectedNegotiateMsg)), + base::size(ntlm::test::kExpectedNegotiateMsg)), &negotiate_msg); base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>(ntlm::test::kChallengeMsgFromSpecV2), - arraysize(ntlm::test::kChallengeMsgFromSpecV2)), + base::size(ntlm::test::kChallengeMsgFromSpecV2)), &challenge_msg); base::Base64Encode( base::StringPiece( reinterpret_cast<const char*>( ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2), - arraysize( + base::size( ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2)), &authenticate_msg); @@ -9551,7 +9551,7 @@ "http://login.example.com/", }; spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyReplyError( - "302", kExtraHeaders, arraysize(kExtraHeaders) / 2, 1)); + "302", kExtraHeaders, base::size(kExtraHeaders) / 2, 1)); MockRead data_reads[] = { CreateMockRead(resp, 1), MockRead(ASYNC, 0, 3), // EOF }; @@ -9651,7 +9651,7 @@ "http://login.example.com/", }; spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyReplyError( - "404", kExtraHeaders, arraysize(kExtraHeaders) / 2, 1)); + "404", kExtraHeaders, base::size(kExtraHeaders) / 2, 1)); spdy::SpdySerializedFrame body( spdy_util_.ConstructSpdyDataFrame(1, "The host does not exist", true)); MockRead data_reads[] = { @@ -9712,7 +9712,7 @@ "proxy-authorization", "Basic Zm9vOmJhcg==", }; spdy::SpdySerializedFrame connect2(spdy_util_.ConstructSpdyConnect( - kAuthCredentials, arraysize(kAuthCredentials) / 2, 3, LOWEST, + kAuthCredentials, base::size(kAuthCredentials) / 2, 3, LOWEST, HostPortPair("www.example.org", 443))); // fetch https://www.example.org/ via HTTP const char get[] = @@ -9734,7 +9734,7 @@ "proxy-authenticate", "Basic realm=\"MyRealm1\"", }; spdy::SpdySerializedFrame conn_auth_resp(spdy_util_.ConstructSpdyReplyError( - kAuthStatus, kAuthChallenge, arraysize(kAuthChallenge) / 2, 1)); + kAuthStatus, kAuthChallenge, base::size(kAuthChallenge) / 2, 1)); spdy::SpdySerializedFrame conn_resp( spdy_util_.ConstructSpdyGetReply(NULL, 0, 3)); @@ -10611,19 +10611,16 @@ char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 }; MockWrite data_writes[] = { - MockWrite(ASYNC, write_buffer, arraysize(write_buffer)), - MockWrite( - "GET / HTTP/1.1\r\n" - "Host: www.example.org\r\n" - "Connection: keep-alive\r\n\r\n")}; + MockWrite(ASYNC, write_buffer, base::size(write_buffer)), + MockWrite("GET / HTTP/1.1\r\n" + "Host: www.example.org\r\n" + "Connection: keep-alive\r\n\r\n")}; MockRead data_reads[] = { - MockRead(ASYNC, read_buffer, arraysize(read_buffer)), - MockRead("HTTP/1.0 200 OK\r\n"), - MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), - MockRead("Payload"), - MockRead(SYNCHRONOUS, OK) - }; + MockRead(ASYNC, read_buffer, base::size(read_buffer)), + MockRead("HTTP/1.0 200 OK\r\n"), + MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), + MockRead("Payload"), MockRead(SYNCHRONOUS, OK)}; StaticSocketDataProvider data(data_reads, data_writes); session_deps_.socket_factory->AddSocketDataProvider(&data); @@ -10672,20 +10669,17 @@ MockWrite data_writes[] = { MockWrite(ASYNC, reinterpret_cast<char*>(write_buffer), - arraysize(write_buffer)), - MockWrite( - "GET / HTTP/1.1\r\n" - "Host: www.example.org\r\n" - "Connection: keep-alive\r\n\r\n")}; + base::size(write_buffer)), + MockWrite("GET / HTTP/1.1\r\n" + "Host: www.example.org\r\n" + "Connection: keep-alive\r\n\r\n")}; MockRead data_reads[] = { - MockRead(ASYNC, reinterpret_cast<char*>(read_buffer), - arraysize(read_buffer)), - MockRead("HTTP/1.0 200 OK\r\n"), - MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), - MockRead("Payload"), - MockRead(SYNCHRONOUS, OK) - }; + MockRead(ASYNC, reinterpret_cast<char*>(read_buffer), + base::size(read_buffer)), + MockRead("HTTP/1.0 200 OK\r\n"), + MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), + MockRead("Payload"), MockRead(SYNCHRONOUS, OK)}; StaticSocketDataProvider data(data_reads, data_writes); session_deps_.socket_factory->AddSocketDataProvider(&data); @@ -10735,19 +10729,16 @@ char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 }; MockWrite data_writes[] = { - MockWrite(ASYNC, write_buffer, arraysize(write_buffer)), - MockWrite( - "GET / HTTP/1.1\r\n" - "Host: www.example.org\r\n" - "Connection: keep-alive\r\n\r\n")}; + MockWrite(ASYNC, write_buffer, base::size(write_buffer)), + MockWrite("GET / HTTP/1.1\r\n" + "Host: www.example.org\r\n" + "Connection: keep-alive\r\n\r\n")}; MockRead data_reads[] = { - MockRead(ASYNC, read_buffer, arraysize(read_buffer)), - MockRead("HTTP/1.0 200 OK\r\n"), - MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), - MockRead("Payload"), - MockRead(SYNCHRONOUS, OK) - }; + MockRead(ASYNC, read_buffer, base::size(read_buffer)), + MockRead("HTTP/1.0 200 OK\r\n"), + MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), + MockRead("Payload"), MockRead(SYNCHRONOUS, OK)}; StaticSocketDataProvider data(data_reads, data_writes); session_deps_.socket_factory->AddSocketDataProvider(&data); @@ -10805,21 +10796,19 @@ { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 }; MockWrite data_writes[] = { - MockWrite(ASYNC, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)), - MockWrite(ASYNC, kSOCKS5OkRequest, arraysize(kSOCKS5OkRequest)), - MockWrite( - "GET / HTTP/1.1\r\n" - "Host: www.example.org\r\n" - "Connection: keep-alive\r\n\r\n")}; + MockWrite(ASYNC, kSOCKS5GreetRequest, base::size(kSOCKS5GreetRequest)), + MockWrite(ASYNC, kSOCKS5OkRequest, base::size(kSOCKS5OkRequest)), + MockWrite("GET / HTTP/1.1\r\n" + "Host: www.example.org\r\n" + "Connection: keep-alive\r\n\r\n")}; MockRead data_reads[] = { - MockRead(ASYNC, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)), - MockRead(ASYNC, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)), - MockRead("HTTP/1.0 200 OK\r\n"), - MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), - MockRead("Payload"), - MockRead(SYNCHRONOUS, OK) - }; + MockRead(ASYNC, kSOCKS5GreetResponse, base::size(kSOCKS5GreetResponse)), + MockRead(ASYNC, kSOCKS5OkResponse, base::size(kSOCKS5OkResponse)), + MockRead("HTTP/1.0 200 OK\r\n"), + MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), + MockRead("Payload"), + MockRead(SYNCHRONOUS, OK)}; StaticSocketDataProvider data(data_reads, data_writes); session_deps_.socket_factory->AddSocketDataProvider(&data); @@ -10879,22 +10868,20 @@ { 0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0x00, 0x00 }; MockWrite data_writes[] = { - MockWrite(ASYNC, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)), + MockWrite(ASYNC, kSOCKS5GreetRequest, base::size(kSOCKS5GreetRequest)), MockWrite(ASYNC, reinterpret_cast<const char*>(kSOCKS5OkRequest), - arraysize(kSOCKS5OkRequest)), - MockWrite( - "GET / HTTP/1.1\r\n" - "Host: www.example.org\r\n" - "Connection: keep-alive\r\n\r\n")}; + base::size(kSOCKS5OkRequest)), + MockWrite("GET / HTTP/1.1\r\n" + "Host: www.example.org\r\n" + "Connection: keep-alive\r\n\r\n")}; MockRead data_reads[] = { - MockRead(ASYNC, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)), - MockRead(ASYNC, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)), - MockRead("HTTP/1.0 200 OK\r\n"), - MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), - MockRead("Payload"), - MockRead(SYNCHRONOUS, OK) - }; + MockRead(ASYNC, kSOCKS5GreetResponse, base::size(kSOCKS5GreetResponse)), + MockRead(ASYNC, kSOCKS5OkResponse, base::size(kSOCKS5OkResponse)), + MockRead("HTTP/1.0 200 OK\r\n"), + MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"), + MockRead("Payload"), + MockRead(SYNCHRONOUS, OK)}; StaticSocketDataProvider data(data_reads, data_writes); session_deps_.socket_factory->AddSocketDataProvider(&data); @@ -11005,7 +10992,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(tests[i].proxy_server, TRAFFIC_ANNOTATION_FOR_TESTS); @@ -11063,7 +11050,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(tests[i].proxy_server, TRAFFIC_ANNOTATION_FOR_TESTS); @@ -11132,7 +11119,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(tests[i].proxy_server, TRAFFIC_ANNOTATION_FOR_TESTS); @@ -14908,7 +14895,7 @@ ERR_CERT_AUTHORITY_INVALID, ERR_CERT_DATE_INVALID, }; - for (size_t i = 0; i < arraysize(kErrors); i++) { + for (size_t i = 0; i < base::size(kErrors); i++) { CheckErrorIsPassedBack(kErrors[i], ASYNC); CheckErrorIsPassedBack(kErrors[i], SYNCHRONOUS); } @@ -15192,7 +15179,7 @@ requests[1].traffic_annotation = net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS); - for (size_t i = 0; i < arraysize(requests); ++i) { + for (size_t i = 0; i < base::size(requests); ++i) { session_deps_.socket_factory->ResetNextMockIndexes(); std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_)); HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
diff --git a/net/http/http_proxy_client_socket_pool_unittest.cc b/net/http/http_proxy_client_socket_pool_unittest.cc index 5964ca1..ba34c73 100644 --- a/net/http/http_proxy_client_socket_pool_unittest.cc +++ b/net/http/http_proxy_client_socket_pool_unittest.cc
@@ -13,6 +13,7 @@ #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_param_associator.h" #include "base/metrics/field_trial_params.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -49,7 +50,7 @@ const char * const kAuthHeaders[] = { "proxy-authorization", "Basic Zm9vOmJhcg==" }; -const int kAuthHeadersSize = arraysize(kAuthHeaders) / 2; +const int kAuthHeadersSize = base::size(kAuthHeaders) / 2; enum HttpProxyType { HTTP, @@ -709,7 +710,7 @@ "location", redirectTarget.c_str(), "set-cookie", "foo=bar", }; - const int responseHeadersSize = arraysize(responseHeaders) / 2; + const int responseHeadersSize = base::size(responseHeaders) / 2; spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyReplyError( "302", responseHeaders, responseHeadersSize, 1)); MockRead spdy_reads[] = {
diff --git a/net/http/http_response_headers.cc b/net/http/http_response_headers.cc index 2c034e1..63f47c78 100644 --- a/net/http/http_response_headers.cc +++ b/net/http/http_response_headers.cc
@@ -19,6 +19,7 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/pickle.h" +#include "base/stl_util.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" @@ -114,11 +115,11 @@ }; bool ShouldUpdateHeader(base::StringPiece name) { - for (size_t i = 0; i < arraysize(kNonUpdatedHeaders); ++i) { + for (size_t i = 0; i < base::size(kNonUpdatedHeaders); ++i) { if (base::LowerCaseEqualsASCII(name, kNonUpdatedHeaders[i])) return false; } - for (size_t i = 0; i < arraysize(kNonUpdatedHeaderPrefixes); ++i) { + for (size_t i = 0; i < base::size(kNonUpdatedHeaderPrefixes); ++i) { if (base::StartsWith(name, kNonUpdatedHeaderPrefixes[i], base::CompareCase::INSENSITIVE_ASCII)) return false; @@ -853,17 +854,17 @@ } void HttpResponseHeaders::AddHopByHopHeaders(HeaderSet* result) { - for (size_t i = 0; i < arraysize(kHopByHopResponseHeaders); ++i) + for (size_t i = 0; i < base::size(kHopByHopResponseHeaders); ++i) result->insert(std::string(kHopByHopResponseHeaders[i])); } void HttpResponseHeaders::AddCookieHeaders(HeaderSet* result) { - for (size_t i = 0; i < arraysize(kCookieResponseHeaders); ++i) + for (size_t i = 0; i < base::size(kCookieResponseHeaders); ++i) result->insert(std::string(kCookieResponseHeaders[i])); } void HttpResponseHeaders::AddChallengeHeaders(HeaderSet* result) { - for (size_t i = 0; i < arraysize(kChallengeResponseHeaders); ++i) + for (size_t i = 0; i < base::size(kChallengeResponseHeaders); ++i) result->insert(std::string(kChallengeResponseHeaders[i])); } @@ -872,7 +873,7 @@ } void HttpResponseHeaders::AddSecurityStateHeaders(HeaderSet* result) { - for (size_t i = 0; i < arraysize(kSecurityStateHeaders); ++i) + for (size_t i = 0; i < base::size(kSecurityStateHeaders); ++i) result->insert(std::string(kSecurityStateHeaders[i])); }
diff --git a/net/http/http_stream_factory_unittest.cc b/net/http/http_stream_factory_unittest.cc index d39ebb9e..020313f 100644 --- a/net/http/http_stream_factory_unittest.cc +++ b/net/http/http_stream_factory_unittest.cc
@@ -13,9 +13,9 @@ #include <vector> #include "base/compiler_specific.h" -#include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" #include "net/base/completion_once_callback.h" @@ -493,7 +493,7 @@ using HttpStreamFactoryTest = TestWithScopedTaskEnvironment; TEST_F(HttpStreamFactoryTest, PreconnectDirect) { - for (size_t i = 0; i < arraysize(kTests); ++i) { + for (size_t i = 0; i < base::size(kTests); ++i) { SpdySessionDependencies session_deps( ProxyResolutionService::CreateDirect()); std::unique_ptr<HttpNetworkSession> session( @@ -524,7 +524,7 @@ } TEST_F(HttpStreamFactoryTest, PreconnectHttpProxy) { - for (size_t i = 0; i < arraysize(kTests); ++i) { + for (size_t i = 0; i < base::size(kTests); ++i) { SpdySessionDependencies session_deps(ProxyResolutionService::CreateFixed( "http_proxy", TRAFFIC_ANNOTATION_FOR_TESTS)); std::unique_ptr<HttpNetworkSession> session( @@ -558,7 +558,7 @@ } TEST_F(HttpStreamFactoryTest, PreconnectSocksProxy) { - for (size_t i = 0; i < arraysize(kTests); ++i) { + for (size_t i = 0; i < base::size(kTests); ++i) { SpdySessionDependencies session_deps(ProxyResolutionService::CreateFixed( "socks4://socks_proxy:1080", TRAFFIC_ANNOTATION_FOR_TESTS)); std::unique_ptr<HttpNetworkSession> session( @@ -592,7 +592,7 @@ } TEST_F(HttpStreamFactoryTest, PreconnectDirectWithExistingSpdySession) { - for (size_t i = 0; i < arraysize(kTests); ++i) { + for (size_t i = 0; i < base::size(kTests); ++i) { SpdySessionDependencies session_deps( ProxyResolutionService::CreateDirect()); std::unique_ptr<HttpNetworkSession> session( @@ -776,7 +776,7 @@ // Tests that a bad QUIC proxy is added to the list of bad proxies. TEST_F(HttpStreamFactoryTest, QuicProxyMarkedAsBad) { - for (size_t i = 0; i < arraysize(quic_proxy_test_mock_errors); ++i) { + for (size_t i = 0; i < base::size(quic_proxy_test_mock_errors); ++i) { std::unique_ptr<ProxyResolutionService> proxy_resolution_service; proxy_resolution_service = ProxyResolutionService::CreateFixedFromPacResult( "QUIC bad:99; DIRECT", TRAFFIC_ANNOTATION_FOR_TESTS);
diff --git a/net/http/http_stream_parser_unittest.cc b/net/http/http_stream_parser_unittest.cc index 193e9ad1..658cda0 100644 --- a/net/http/http_stream_parser_unittest.cc +++ b/net/http/http_stream_parser_unittest.cc
@@ -16,6 +16,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" @@ -271,7 +272,7 @@ callback1.callback()); EXPECT_EQ(ERR_IO_PENDING, result1); base::RunLoop().RunUntilIdle(); - upload_data_stream.AppendData(kChunk, arraysize(kChunk) - 1, true); + upload_data_stream.AppendData(kChunk, base::size(kChunk) - 1, true); // Check progress after read completes. progress = upload_data_stream.GetUploadProgress(); @@ -648,11 +649,11 @@ &response, callback.callback())); base::RunLoop().RunUntilIdle(); - upload_data_stream.AppendData(kChunk, arraysize(kChunk) - 1, false); + upload_data_stream.AppendData(kChunk, base::size(kChunk) - 1, false); base::RunLoop().RunUntilIdle(); // This write should fail. - upload_data_stream.AppendData(kChunk, arraysize(kChunk) - 1, false); + upload_data_stream.AppendData(kChunk, base::size(kChunk) - 1, false); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_FAILED)); EXPECT_EQ(CountWriteBytes(writes), parser.sent_bytes()); @@ -725,7 +726,7 @@ ASSERT_FALSE(callback.have_result()); // Now append the only chunk and wait for the callback. - upload_stream.AppendData(kChunk, arraysize(kChunk) - 1, true); + upload_stream.AppendData(kChunk, base::size(kChunk) - 1, true); ASSERT_THAT(callback.WaitForResult(), IsOk()); // Attempt to read the response status and the response headers. @@ -777,7 +778,7 @@ NetLogWithSource()), IsOk()); // Append the only chunk. - upload_stream.AppendData(kChunk, arraysize(kChunk) - 1, true); + upload_stream.AppendData(kChunk, base::size(kChunk) - 1, true); SequencedSocketData data(reads, writes); std::unique_ptr<ClientSocketHandle> socket_handle = @@ -859,7 +860,7 @@ }; ChunkedUploadDataStream upload_stream(0); - upload_stream.AppendData(kChunk1, arraysize(kChunk1) - 1, false); + upload_stream.AppendData(kChunk1, base::size(kChunk1) - 1, false); ASSERT_THAT(upload_stream.Init(TestCompletionCallback().callback(), NetLogWithSource()), IsOk()); @@ -896,12 +897,12 @@ ASSERT_FALSE(callback.have_result()); // Now append another chunk. - upload_stream.AppendData(kChunk2, arraysize(kChunk2) - 1, false); + upload_stream.AppendData(kChunk2, base::size(kChunk2) - 1, false); ASSERT_FALSE(callback.have_result()); // Add the final chunk, while the write for the second is still pending, // which should not confuse the state machine. - upload_stream.AppendData(kChunk3, arraysize(kChunk3) - 1, true); + upload_stream.AppendData(kChunk3, base::size(kChunk3) - 1, true); ASSERT_FALSE(callback.have_result()); // Wait for writes to complete. @@ -1132,7 +1133,7 @@ for (size_t protocol = 0; protocol < NUM_PROTOCOLS; protocol++) { SCOPED_TRACE(protocol); - for (size_t i = 0; i < arraysize(reads); i++) { + for (size_t i = 0; i < base::size(reads); i++) { SCOPED_TRACE(i); SequencedSocketData data(reads[i], writes); std::unique_ptr<ClientSocketHandle> socket_handle( @@ -1161,7 +1162,7 @@ int rv = parser.ReadResponseHeaders(callback.callback()); EXPECT_EQ(CountWriteBytes(writes), parser.sent_bytes()); - if (i == arraysize(reads) - 1) { + if (i == base::size(reads) - 1) { EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(response_info.headers.get()); EXPECT_EQ(CountReadBytes(reads[i]), parser.received_bytes());
diff --git a/net/http/http_transaction_test_util.cc b/net/http/http_transaction_test_util.cc index c74e4af..bb000a7 100644 --- a/net/http/http_transaction_test_util.cc +++ b/net/http/http_transaction_test_util.cc
@@ -12,6 +12,7 @@ #include "base/location.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/clock.h" @@ -153,7 +154,7 @@ return it->second; // look for builtins: - for (size_t i = 0; i < arraysize(kBuiltinMockTransactions); ++i) { + for (size_t i = 0; i < base::size(kBuiltinMockTransactions); ++i) { if (url == GURL(kBuiltinMockTransactions[i]->url)) return kBuiltinMockTransactions[i]; }
diff --git a/net/http/http_util_unittest.cc b/net/http/http_util_unittest.cc index bf8818b..7883b3e4 100644 --- a/net/http/http_util_unittest.cc +++ b/net/http/http_util_unittest.cc
@@ -5,6 +5,7 @@ #include <algorithm> #include <limits> +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "net/http/http_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -47,7 +48,7 @@ "user-agent", "via", }; - for (size_t i = 0; i < arraysize(unsafe_headers); ++i) { + for (size_t i = 0; i < base::size(unsafe_headers); ++i) { EXPECT_FALSE(HttpUtil::IsSafeHeader(unsafe_headers[i])) << unsafe_headers[i]; EXPECT_FALSE(HttpUtil::IsSafeHeader(base::ToUpperASCII(unsafe_headers[i]))) @@ -93,7 +94,7 @@ "user_agent", "viaa", }; - for (size_t i = 0; i < arraysize(safe_headers); ++i) { + for (size_t i = 0; i < base::size(safe_headers); ++i) { EXPECT_TRUE(HttpUtil::IsSafeHeader(safe_headers[i])) << safe_headers[i]; EXPECT_TRUE(HttpUtil::IsSafeHeader(base::ToUpperASCII(safe_headers[i]))) << safe_headers[i]; @@ -340,7 +341,7 @@ {"foo\nbar\n\r\njunk", 10}, {"foo\nbar\r\n\njunk", 10}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { int input_len = static_cast<int>(strlen(tests[i].input)); int eoh = HttpUtil::LocateEndOfHeaders(tests[i].input, input_len); EXPECT_EQ(tests[i].expected_result, eoh); @@ -364,7 +365,7 @@ {"foo\nbar\n\r\njunk", 10}, {"foo\nbar\r\n\njunk", 10}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { int input_len = static_cast<int>(strlen(tests[i].input)); int eoh = HttpUtil::LocateEndOfAdditionalHeaders(tests[i].input, input_len); EXPECT_EQ(tests[i].expected_result, eoh); @@ -686,7 +687,7 @@ }, }; // clang-format on - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { std::string input = tests[i].input; std::replace(input.begin(), input.end(), '|', '\0'); std::string raw = HttpUtil::AssembleRawHeaders(input.data(), input.size()); @@ -726,7 +727,7 @@ "wss://www.google.com:78/foobar?query=1", } }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { SCOPED_TRACE(i); GURL url(GURL(tests[i].url)); @@ -986,7 +987,7 @@ // TODO(abarth): Add more interesting test cases. }; // clang-format on - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { std::string mime_type; std::string charset; bool had_charset = false; @@ -1094,7 +1095,7 @@ { "Mon, 1 Jan 1900 12:34:56 GMT", false, base::TimeDelta() } }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { base::TimeDelta retry_after; bool return_value = HttpUtil::ParseRetryAfterHeader( tests[i].retry_after_string, now, &retry_after); @@ -1572,7 +1573,7 @@ {"foo,\"bar\"", "INVALID"}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { std::string value(tests[i].value); std::string reformatted; std::set<std::string> allowed_encodings; @@ -1602,7 +1603,7 @@ {"foo,\"bar\"", "INVALID"}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { std::string value(tests[i].value); std::string reformatted; std::set<std::string> used_encodings;
diff --git a/net/http/http_vary_data_unittest.cc b/net/http/http_vary_data_unittest.cc index bf1c873..7442d01 100644 --- a/net/http/http_vary_data_unittest.cc +++ b/net/http/http_vary_data_unittest.cc
@@ -4,6 +4,7 @@ #include <algorithm> +#include "base/stl_util.h" #include "net/http/http_request_info.h" #include "net/http/http_response_headers.h" #include "net/http/http_vary_data.h" @@ -43,7 +44,7 @@ const bool kExpectedValid[] = {false, true, true, true}; - for (size_t i = 0; i < arraysize(kTestResponses); ++i) { + for (size_t i = 0; i < base::size(kTestResponses); ++i) { TestTransaction t; t.Init(std::string(), kTestResponses[i]);
diff --git a/net/http/transport_security_state_static.template b/net/http/transport_security_state_static.template index fc5d6673..ceb400a 100644 --- a/net/http/transport_security_state_static.template +++ b/net/http/transport_security_state_static.template
@@ -9,6 +9,7 @@ #include <stdint.h> +#include "base/stl_util.h" #include "net/http/transport_security_state_source.h" // These are SubjectPublicKeyInfo hashes for public key pinning. The @@ -46,7 +47,7 @@ kHSTSRootPosition, kExpectCTReportURIs, kPinsets, - arraysize(kPinsets) + base::size(kPinsets) }; #endif // NET_HTTP_TRANSPORT_SECURITY_STATE_STATIC_H_
diff --git a/net/http/transport_security_state_static_unittest.template b/net/http/transport_security_state_static_unittest.template index 6978227c..08b2116 100644 --- a/net/http/transport_security_state_static_unittest.template +++ b/net/http/transport_security_state_static_unittest.template
@@ -8,6 +8,7 @@ #include <stdint.h> +#include "base/stl_util.h" #include "net/http/transport_security_state_source.h" [[SPKI_HASHES]] @@ -37,5 +38,5 @@ kHSTSRootPosition, kExpectCTReportURIs, kPinsets, - arraysize(kPinsets) + base::size(kPinsets) };
diff --git a/net/http/url_security_manager_unittest.cc b/net/http/url_security_manager_unittest.cc index ac0b87c..97dda33 100644 --- a/net/http/url_security_manager_unittest.cc +++ b/net/http/url_security_manager_unittest.cc
@@ -6,6 +6,7 @@ #include <utility> +#include "base/stl_util.h" #include "net/base/net_errors.h" #include "net/http/http_auth_filter.h" #include "testing/gtest/include/gtest/gtest.h" @@ -54,7 +55,7 @@ url_security_manager->SetDefaultWhitelist(std::move(auth_filter)); ASSERT_TRUE(url_security_manager.get()); - for (size_t i = 0; i < arraysize(kTestDataList); ++i) { + for (size_t i = 0; i < base::size(kTestDataList); ++i) { GURL gurl(kTestDataList[i].url); bool can_use_default = url_security_manager->CanUseDefaultCredentials(gurl); @@ -74,7 +75,7 @@ url_security_manager->SetDelegateWhitelist(std::move(auth_filter)); ASSERT_TRUE(url_security_manager.get()); - for (size_t i = 0; i < arraysize(kTestDataList); ++i) { + for (size_t i = 0; i < base::size(kTestDataList); ++i) { GURL gurl(kTestDataList[i].url); bool can_delegate = url_security_manager->CanDelegate(gurl); EXPECT_EQ(kTestDataList[i].succeeds_in_whitelist, can_delegate) @@ -88,7 +89,7 @@ URLSecurityManager::Create()); ASSERT_TRUE(url_security_manager.get()); - for (size_t i = 0; i < arraysize(kTestDataList); ++i) { + for (size_t i = 0; i < base::size(kTestDataList); ++i) { GURL gurl(kTestDataList[i].url); bool can_delegate = url_security_manager->CanDelegate(gurl); EXPECT_FALSE(can_delegate);
diff --git a/net/log/net_log_unittest.cc b/net/log/net_log_unittest.cc index 38405db..7a82814 100644 --- a/net/log/net_log_unittest.cc +++ b/net/log/net_log_unittest.cc
@@ -10,7 +10,7 @@ #include "base/bind.h" #include "base/callback.h" -#include "base/macros.h" +#include "base/stl_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/simple_thread.h" #include "base/values.h" @@ -249,14 +249,14 @@ base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); - for (size_t i = 0; i < arraysize(threads); ++i) { + for (size_t i = 0; i < base::size(threads); ++i) { threads[i].Init(net_log, &start_event); threads[i].Start(); } start_event.Signal(); - for (size_t i = 0; i < arraysize(threads); ++i) + for (size_t i = 0; i < base::size(threads); ++i) threads[i].Join(); } @@ -267,7 +267,7 @@ // Attach some observers. Since they're created after |net_log|, they'll // safely detach themselves on destruction. CountingObserver observers[3]; - for (size_t i = 0; i < arraysize(observers); ++i) { + for (size_t i = 0; i < base::size(observers); ++i) { net_log.AddObserver(&observers[i], NetLogCaptureMode::IncludeSocketBytes()); } @@ -277,7 +277,7 @@ // Check that each observer saw the emitted events. const int kTotalEvents = kThreads * kEvents; - for (size_t i = 0; i < arraysize(observers); ++i) + for (size_t i = 0; i < base::size(observers); ++i) EXPECT_EQ(kTotalEvents, observers[i].count()); }
diff --git a/net/network_error_logging/network_error_logging_service.cc b/net/network_error_logging/network_error_logging_service.cc index f651615..383426ae 100644 --- a/net/network_error_logging/network_error_logging_service.cc +++ b/net/network_error_logging/network_error_logging_service.cc
@@ -13,6 +13,7 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/rand_util.h" +#include "base/stl_util.h" #include "base/time/default_tick_clock.h" #include "base/time/tick_clock.h" #include "base/time/time.h" @@ -142,7 +143,7 @@ void GetPhaseAndTypeFromNetError(Error error, std::string* phase_out, std::string* type_out) { - for (size_t i = 0; i < arraysize(kErrorTypes); ++i) { + for (size_t i = 0; i < base::size(kErrorTypes); ++i) { DCHECK(kErrorTypes[i].phase != nullptr); DCHECK(kErrorTypes[i].type != nullptr); if (kErrorTypes[i].error == error) {
diff --git a/net/nqe/network_quality_estimator.cc b/net/nqe/network_quality_estimator.cc index 003160f..eda8bf5 100644 --- a/net/nqe/network_quality_estimator.cc +++ b/net/nqe/network_quality_estimator.cc
@@ -93,11 +93,11 @@ static const char* const kSuffixes[] = { "0_20", "20_60", "60_140", "140_300", "300_620", "620_1260", "1260_2540", "2540_5100", "5100_Infinity"}; - for (size_t i = 0; i < arraysize(kSuffixes) - 1; ++i) { + for (size_t i = 0; i < base::size(kSuffixes) - 1; ++i) { if (rtt_milliseconds <= (20 * (2 << i) - 20)) return kSuffixes[i]; } - return kSuffixes[arraysize(kSuffixes) - 1]; + return kSuffixes[base::size(kSuffixes) - 1]; } // Returns the suffix of the histogram that should be used for recording the @@ -113,11 +113,11 @@ static const char* const kSuffixes[] = { "0_20", "20_60", "60_140", "140_300", "300_620", "620_1260", "1260_2540", "2540_5100", "5100_Infinity"}; - for (size_t i = 0; i < arraysize(kSuffixes) - 1; ++i) { + for (size_t i = 0; i < base::size(kSuffixes) - 1; ++i) { if (observed_throughput_kbps <= (20 * (2 << i) - 20)) return kSuffixes[i]; } - return kSuffixes[arraysize(kSuffixes) - 1]; + return kSuffixes[base::size(kSuffixes) - 1]; } void RecordRTTAccuracy(base::StringPiece prefix,
diff --git a/net/nqe/network_quality_observation_source.cc b/net/nqe/network_quality_observation_source.cc index 03be170..97a9ae0 100644 --- a/net/nqe/network_quality_observation_source.cc +++ b/net/nqe/network_quality_observation_source.cc
@@ -5,6 +5,7 @@ #include "net/nqe/network_quality_observation_source.h" #include "base/logging.h" +#include "base/stl_util.h" namespace net { @@ -22,7 +23,7 @@ "H2Pings"}; static_assert(static_cast<size_t>(NETWORK_QUALITY_OBSERVATION_SOURCE_MAX) == - arraysize(kObservationSourceMapping), + base::size(kObservationSourceMapping), "unhandled network quality observation source"); } // namespace @@ -45,4 +46,4 @@ } // namespace nqe -} // namespace net \ No newline at end of file +} // namespace net
diff --git a/net/proxy_resolution/pac_file_fetcher_impl.cc b/net/proxy_resolution/pac_file_fetcher_impl.cc index 41c67a80..d5ac977c 100644 --- a/net/proxy_resolution/pac_file_fetcher_impl.cc +++ b/net/proxy_resolution/pac_file_fetcher_impl.cc
@@ -9,6 +9,7 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/data_url.h" @@ -52,7 +53,7 @@ static const char* const kSupportedPacMimeTypes[] = { "application/x-ns-proxy-autoconfig", "application/x-javascript-config", }; - for (size_t i = 0; i < arraysize(kSupportedPacMimeTypes); ++i) { + for (size_t i = 0; i < base::size(kSupportedPacMimeTypes); ++i) { if (base::LowerCaseEqualsASCII(mime_type, kSupportedPacMimeTypes[i])) return true; }
diff --git a/net/proxy_resolution/pac_file_fetcher_impl_unittest.cc b/net/proxy_resolution/pac_file_fetcher_impl_unittest.cc index 9db5fce8..7db2739e 100644 --- a/net/proxy_resolution/pac_file_fetcher_impl_unittest.cc +++ b/net/proxy_resolution/pac_file_fetcher_impl_unittest.cc
@@ -10,12 +10,12 @@ #include "base/compiler_specific.h" #include "base/files/file_path.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" @@ -441,7 +441,7 @@ // Try fetching URLs that are 101 bytes large. We should abort the request // after 50 bytes have been read, and fail with a too large error. - for (size_t i = 0; i < arraysize(urls); ++i) { + for (size_t i = 0; i < base::size(urls); ++i) { const GURL& url = urls[i]; base::string16 text; TestCompletionCallback callback;
diff --git a/net/proxy_resolution/proxy_config_service_linux_unittest.cc b/net/proxy_resolution/proxy_config_service_linux_unittest.cc index d22b825bc..cc63ce6 100644 --- a/net/proxy_resolution/proxy_config_service_linux_unittest.cc +++ b/net/proxy_resolution/proxy_config_service_linux_unittest.cc
@@ -18,6 +18,7 @@ #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/synchronization/lock.h" @@ -752,7 +753,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "] %s", i, tests[i].description.c_str())); std::unique_ptr<MockEnvironment> env(new MockEnvironment); @@ -1081,7 +1082,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "] %s", i, tests[i].description.c_str())); std::unique_ptr<MockEnvironment> env(new MockEnvironment); @@ -1690,7 +1691,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "] %s", i, tests[i].description.c_str())); std::unique_ptr<MockEnvironment> env(new MockEnvironment);
diff --git a/net/proxy_resolution/proxy_config_service_win_unittest.cc b/net/proxy_resolution/proxy_config_service_win_unittest.cc index fec338e..147e86c 100644 --- a/net/proxy_resolution/proxy_config_service_win_unittest.cc +++ b/net/proxy_resolution/proxy_config_service_win_unittest.cc
@@ -4,6 +4,7 @@ #include "net/proxy_resolution/proxy_config_service_win.h" +#include "base/stl_util.h" #include "net/base/net_errors.h" #include "net/proxy_resolution/proxy_config.h" #include "net/proxy_resolution/proxy_config_service_common_unittest.h" @@ -196,7 +197,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = { tests[i].ie_config.auto_detect, const_cast<wchar_t*>(tests[i].ie_config.auto_config_url),
diff --git a/net/proxy_resolution/proxy_config_unittest.cc b/net/proxy_resolution/proxy_config_unittest.cc index 51b5703..2902fd8f 100644 --- a/net/proxy_resolution/proxy_config_unittest.cc +++ b/net/proxy_resolution/proxy_config_unittest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "net/proxy_resolution/proxy_config.h" +#include "base/stl_util.h" #include "net/proxy_resolution/proxy_config_service_common_unittest.h" #include "net/proxy_resolution/proxy_info.h" #include "testing/gtest/include/gtest/gtest.h" @@ -308,7 +309,7 @@ ProxyConfig config; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { config.proxy_rules().ParseFromString(tests[i].proxy_rules); EXPECT_EQ(tests[i].type, config.proxy_rules().type);
diff --git a/net/proxy_resolution/proxy_list_unittest.cc b/net/proxy_resolution/proxy_list_unittest.cc index 18ca3790..50cbc59 100644 --- a/net/proxy_resolution/proxy_list_unittest.cc +++ b/net/proxy_resolution/proxy_list_unittest.cc
@@ -6,6 +6,7 @@ #include <vector> +#include "base/stl_util.h" #include "net/base/net_errors.h" #include "net/base/proxy_server.h" #include "net/log/net_log_with_source.h" @@ -64,7 +65,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { ProxyList list; list.SetFromPacString(tests[i].pac_input); EXPECT_EQ(tests[i].pac_output, list.ToPacString()); @@ -90,7 +91,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { ProxyList list; list.SetFromPacString(tests[i].pac_input); list.RemoveProxiesWithoutScheme(tests[i].filter);
diff --git a/net/proxy_resolution/proxy_resolver_v8.cc b/net/proxy_resolution/proxy_resolver_v8.cc index 7a426d1..a843839 100644 --- a/net/proxy_resolution/proxy_resolver_v8.cc +++ b/net/proxy_resolution/proxy_resolver_v8.cc
@@ -13,7 +13,7 @@ #include "base/debug/leak_annotations.h" #include "base/lazy_instance.h" #include "base/logging.h" -#include "base/macros.h" +#include "base/stl_util.h" #include "base/strings/string_tokenizer.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -470,7 +470,7 @@ v8::TryCatch try_catch(isolate_); v8::Local<v8::Value> ret; if (!v8::Function::Cast(*function) - ->Call(context, context->Global(), arraysize(argv), argv) + ->Call(context, context->Global(), base::size(argv), argv) .ToLocal(&ret)) { DCHECK(try_catch.HasCaught()); HandleError(try_catch.Message());
diff --git a/net/proxy_resolution/proxy_resolver_v8_tracing_unittest.cc b/net/proxy_resolution/proxy_resolver_v8_tracing_unittest.cc index 73d8c4f..b126648 100644 --- a/net/proxy_resolution/proxy_resolver_v8_tracing_unittest.cc +++ b/net/proxy_resolution/proxy_resolver_v8_tracing_unittest.cc
@@ -10,6 +10,7 @@ #include "base/files/file_util.h" #include "base/path_service.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" @@ -1021,7 +1022,7 @@ resolver0.get(), resolver1.get(), resolver2.get(), resolver3.get(), }; - const size_t kNumResolvers = arraysize(resolver); + const size_t kNumResolvers = base::size(resolver); const size_t kNumIterations = 20; const size_t kNumResults = kNumResolvers * kNumIterations; TestCompletionCallback callback[kNumResults];
diff --git a/net/proxy_resolution/proxy_resolver_v8_tracing_wrapper_unittest.cc b/net/proxy_resolution/proxy_resolver_v8_tracing_wrapper_unittest.cc index 99de6bc..9814eb71 100644 --- a/net/proxy_resolution/proxy_resolver_v8_tracing_wrapper_unittest.cc +++ b/net/proxy_resolution/proxy_resolver_v8_tracing_wrapper_unittest.cc
@@ -189,7 +189,7 @@ log.GetEntries(&entries_list[0]); request_log.GetEntries(&entries_list[1]); - for (size_t list_i = 0; list_i < arraysize(entries_list); list_i++) { + for (size_t list_i = 0; list_i < base::size(entries_list); list_i++) { const TestNetLogEntry::List& entries = entries_list[list_i]; EXPECT_EQ(2u, entries.size()); EXPECT_TRUE(LogContainsEvent(entries, 0, @@ -244,7 +244,7 @@ log.GetEntries(&entries_list[0]); request_log.GetEntries(&entries_list[1]); - for (size_t list_i = 0; list_i < arraysize(entries_list); list_i++) { + for (size_t list_i = 0; list_i < base::size(entries_list); list_i++) { const TestNetLogEntry::List& entries = entries_list[list_i]; EXPECT_EQ(50u, entries.size()); for (size_t i = 0; i < entries.size(); ++i) { @@ -291,7 +291,7 @@ log.GetEntries(&entries_list[0]); request_log.GetEntries(&entries_list[1]); - for (size_t list_i = 0; list_i < arraysize(entries_list); list_i++) { + for (size_t list_i = 0; list_i < base::size(entries_list); list_i++) { const TestNetLogEntry::List& entries = entries_list[list_i]; EXPECT_EQ(1000u, entries.size()); for (size_t i = 0; i < entries.size(); ++i) { @@ -367,7 +367,7 @@ log.GetEntries(&entries_list[0]); request_log.GetEntries(&entries_list[1]); - for (size_t list_i = 0; list_i < arraysize(entries_list); list_i++) { + for (size_t list_i = 0; list_i < base::size(entries_list); list_i++) { const TestNetLogEntry::List& entries = entries_list[list_i]; EXPECT_EQ(1u, entries.size()); EXPECT_TRUE(LogContainsEvent(entries, 0, @@ -474,7 +474,7 @@ log.GetEntries(&entries_list[0]); request_log.GetEntries(&entries_list[1]); - for (size_t list_i = 0; list_i < arraysize(entries_list); list_i++) { + for (size_t list_i = 0; list_i < base::size(entries_list); list_i++) { const TestNetLogEntry::List& entries = entries_list[list_i]; EXPECT_EQ(1u, entries.size()); EXPECT_TRUE(LogContainsEvent(entries, 0, @@ -1143,7 +1143,7 @@ resolver0.get(), resolver1.get(), resolver2.get(), resolver3.get(), }; - const size_t kNumResolvers = arraysize(resolver); + const size_t kNumResolvers = base::size(resolver); const size_t kNumIterations = 20; const size_t kNumResults = kNumResolvers * kNumIterations; TestCompletionCallback callback[kNumResults];
diff --git a/net/proxy_resolution/proxy_resolver_v8_unittest.cc b/net/proxy_resolution/proxy_resolver_v8_unittest.cc index b242392..7ea786a 100644 --- a/net/proxy_resolution/proxy_resolver_v8_unittest.cc +++ b/net/proxy_resolution/proxy_resolver_v8_unittest.cc
@@ -6,6 +6,7 @@ #include "base/compiler_specific.h" #include "base/files/file_util.h" #include "base/path_service.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -211,7 +212,7 @@ // TODO(eroman): Should 'null' be considered equivalent to "DIRECT" ? "return_null.js"}; - for (size_t i = 0; i < arraysize(filenames); ++i) { + for (size_t i = 0; i < base::size(filenames); ++i) { ASSERT_THAT(CreateResolver(filenames[i]), IsOk()); MockJSBindings bindings;
diff --git a/net/proxy_resolution/proxy_server_unittest.cc b/net/proxy_resolution/proxy_server_unittest.cc index 67fadd6..e90bd3c 100644 --- a/net/proxy_resolution/proxy_server_unittest.cc +++ b/net/proxy_resolution/proxy_server_unittest.cc
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/macros.h" #include "net/base/proxy_server.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { @@ -131,7 +131,7 @@ "HTTPS 1.2.3.4:10"}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { ProxyServer uri = ProxyServer::FromURI(tests[i].input_uri, ProxyServer::SCHEME_HTTP); EXPECT_TRUE(uri.is_valid()); @@ -172,7 +172,7 @@ "http:", // ambiguous, but will fail because of bad port. }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { ProxyServer uri = ProxyServer::FromURI(tests[i], ProxyServer::SCHEME_HTTP); EXPECT_FALSE(uri.is_valid()); EXPECT_FALSE(uri.is_direct()); @@ -189,7 +189,7 @@ " \tfoopy:80 ", }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { ProxyServer uri = ProxyServer::FromURI(tests[i], ProxyServer::SCHEME_HTTP); EXPECT_EQ("foopy:80", uri.ToURI()); } @@ -247,7 +247,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { ProxyServer uri = ProxyServer::FromPacString(tests[i].input_pac); EXPECT_TRUE(uri.is_valid()); EXPECT_EQ(tests[i].expected_uri, uri.ToURI()); @@ -263,7 +263,7 @@ "DIRECT foopy:10", // direct cannot have host/port. }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { ProxyServer uri = ProxyServer::FromPacString(tests[i]); EXPECT_FALSE(uri.is_valid()); } @@ -303,7 +303,7 @@ }, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { // Parse the expected inputs to ProxyServer instances. const ProxyServer server1 = ProxyServer::FromURI(tests[i].server1, ProxyServer::SCHEME_HTTP);
diff --git a/net/quic/quic_chromium_client_stream_test.cc b/net/quic/quic_chromium_client_stream_test.cc index f495b1b9..979be06 100644 --- a/net/quic/quic_chromium_client_stream_test.cc +++ b/net/quic/quic_chromium_client_stream_test.cc
@@ -8,6 +8,7 @@ #include "base/memory/ptr_util.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" @@ -297,7 +298,7 @@ handle_->OnFinRead(); const char kData1[] = "hello world"; - const size_t kDataLen = arraysize(kData1); + const size_t kDataLen = base::size(kData1); // All data written. EXPECT_CALL(session_, WritevData(stream_, stream_->id(), _, _, _)) @@ -624,7 +625,7 @@ TEST_P(QuicChromiumClientStreamTest, WriteStreamData) { const char kData1[] = "hello world"; - const size_t kDataLen = arraysize(kData1); + const size_t kDataLen = base::size(kData1); // All data written. EXPECT_CALL(session_, WritevData(stream_, stream_->id(), _, _, _)) @@ -637,7 +638,7 @@ TEST_P(QuicChromiumClientStreamTest, WriteStreamDataAsync) { const char kData1[] = "hello world"; - const size_t kDataLen = arraysize(kData1); + const size_t kDataLen = base::size(kData1); // No data written. EXPECT_CALL(session_, WritevData(stream_, stream_->id(), _, _, _)) @@ -752,7 +753,7 @@ base::RunLoop().RunUntilIdle(); // Now explicitly read the data. - int data_len = arraysize(data) - 1; + int data_len = base::size(data) - 1; scoped_refptr<IOBuffer> buffer = base::MakeRefCounted<IOBuffer>(data_len + 1); ASSERT_EQ(data_len, stream2->Read(buffer.get(), data_len + 1)); EXPECT_EQ(quic::QuicStringPiece(data),
diff --git a/net/quic/quic_flags_list.h b/net/quic/quic_flags_list.h index 517e112..71861b04 100644 --- a/net/quic/quic_flags_list.h +++ b/net/quic/quic_flags_list.h
@@ -169,10 +169,6 @@ FLAGS_quic_reloadable_flag_quic_donot_retransmit_old_window_update2, true) -// If ture, make QuicSession::GetStream faster by skipping the lookup into -// static stream map, when possible. -QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_session_faster_get_stream, true) - // If true, disable QUIC version 35. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_disable_version_35, false) // If true, then QuicCryptoServerConfig::ProcessClientHelloAfterGetProof() will @@ -282,11 +278,6 @@ false) // If true, public reset packets sent from GFE will include a kEPID tag. -QUIC_FLAG(bool, - FLAGS_quic_reloadable_flag_quic_enable_server_epid_in_public_reset, - true) - -// If true, public reset packets sent from GFE will include a kEPID tag. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_fix_spurious_ack_alarm, false) // If true, QuicSpdyStream::WritevBody() will convert iovs into QuicMemSliceSpan @@ -299,12 +290,6 @@ FLAGS_quic_reloadable_flag_quic_bbr_startup_rate_reduction, false) -// If true, enable the fix for the bug where v44 packets are rejected -// by a lower-version connection close. -QUIC_FLAG(bool, - FLAGS_quic_reloadable_flag_quic_fix_reject_by_session_type, - true) - // If true, only send version negotiation packets when they are at least // 1200 bytes. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_limit_version_negotiation, true) @@ -332,3 +317,9 @@ bool, FLAGS_quic_reloadable_flag_quic_connection_do_not_add_to_write_blocked_list_if_disconnected, false) + +// Changes internal in-memory representation of QUIC connection IDs to network +// byte order. +QUIC_FLAG(bool, + FLAGS_quic_restart_flag_quic_connection_ids_network_byte_order, + false)
diff --git a/net/quic/quic_http_stream_test.cc b/net/quic/quic_http_stream_test.cc index d01cfb162..54e53b6 100644 --- a/net/quic/quic_http_stream_test.cc +++ b/net/quic/quic_http_stream_test.cc
@@ -11,6 +11,7 @@ #include "base/memory/ptr_util.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" @@ -1336,7 +1337,7 @@ stream_->ReadResponseBody(read_buffer_.get(), read_buffer_->size(), callback_.callback())); ProcessPacket(ConstructServerDataPacket(4, false, kFin, - arraysize(kResponseBody) - 1, "")); + base::size(kResponseBody) - 1, "")); EXPECT_EQ(0, stream_->ReadResponseBody(read_buffer_.get(), read_buffer_->size(), callback_.callback()));
diff --git a/net/quic/quic_stream_factory_fuzzer.cc b/net/quic/quic_stream_factory_fuzzer.cc index 6e4f9d06..5be455ff 100644 --- a/net/quic/quic_stream_factory_fuzzer.cc +++ b/net/quic/quic_stream_factory_fuzzer.cc
@@ -6,6 +6,7 @@ #include "base/test/fuzzed_data_provider.h" +#include "base/stl_util.h" #include "net/base/test_completion_callback.h" #include "net/cert/ct_policy_enforcer.h" #include "net/cert/do_nothing_ct_verifier.h" @@ -57,7 +58,7 @@ cert_verifier = std::make_unique<MockCertVerifier>(); cert_transparency_verifier = std::make_unique<DoNothingCTVerifier>(); verify_details.cert_verify_result.verified_cert = - X509Certificate::CreateFromBytes(kCertData, arraysize(kCertData)); + X509Certificate::CreateFromBytes(kCertData, base::size(kCertData)); CHECK(verify_details.cert_verify_result.verified_cert); verify_details.cert_verify_result.is_issued_by_known_root = true; }
diff --git a/net/reporting/reporting_header_parser_unittest.cc b/net/reporting/reporting_header_parser_unittest.cc index 6c900e0..253b5ec 100644 --- a/net/reporting/reporting_header_parser_unittest.cc +++ b/net/reporting/reporting_header_parser_unittest.cc
@@ -8,6 +8,7 @@ #include <vector> #include "base/json/json_reader.h" +#include "base/stl_util.h" #include "base/test/simple_test_tick_clock.h" #include "base/time/time.h" #include "base/values.h" @@ -81,7 +82,7 @@ "{\"max_age\":1, \"endpoints\": [{\"url\":\"https://b/\"}]}]", "wrapped in list"}}; - for (size_t i = 0; i < arraysize(kInvalidHeaderTestCases); ++i) { + for (size_t i = 0; i < base::size(kInvalidHeaderTestCases); ++i) { auto& test_case = kInvalidHeaderTestCases[i]; ParseHeader(kUrl_, test_case.header_value);
diff --git a/net/server/http_server_unittest.cc b/net/server/http_server_unittest.cc index ca6062a..1b63016 100644 --- a/net/server/http_server_unittest.cc +++ b/net/server/http_server_unittest.cc
@@ -18,12 +18,12 @@ #include "base/format_macros.h" #include "base/location.h" #include "base/logging.h" -#include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -324,7 +324,7 @@ {"HeaderWithNonASCII", ": ", "\xf7"}, }; std::string headers; - for (size_t i = 0; i < arraysize(kHeaders); ++i) { + for (size_t i = 0; i < base::size(kHeaders); ++i) { headers += std::string(kHeaders[i][0]) + kHeaders[i][1] + kHeaders[i][2] + "\r\n"; } @@ -333,7 +333,7 @@ RunUntilRequestsReceived(1); ASSERT_EQ("", GetRequest(0).data); - for (size_t i = 0; i < arraysize(kHeaders); ++i) { + for (size_t i = 0; i < base::size(kHeaders); ++i) { std::string field = base::ToLowerASCII(std::string(kHeaders[i][0])); std::string value = kHeaders[i][2]; ASSERT_EQ(1u, GetRequest(0).headers.count(field)) << field; @@ -352,7 +352,7 @@ {"LastHeader", ": ", "5"}, }; std::string headers; - for (size_t i = 0; i < arraysize(kHeaders); ++i) { + for (size_t i = 0; i < base::size(kHeaders); ++i) { headers += std::string(kHeaders[i][0]) + kHeaders[i][1] + kHeaders[i][2] + "\r\n"; } @@ -361,7 +361,7 @@ RunUntilRequestsReceived(1); ASSERT_EQ("", GetRequest(0).data); - for (size_t i = 0; i < arraysize(kHeaders); ++i) { + for (size_t i = 0; i < base::size(kHeaders); ++i) { std::string field = base::ToLowerASCII(std::string(kHeaders[i][0])); std::string value = (field == "duplicateheader") ? "2,4" : kHeaders[i][2]; ASSERT_EQ(1u, GetRequest(0).headers.count(field)) << field; @@ -384,7 +384,7 @@ "HeaderWithNonASCII: \xf7", }; std::string headers; - for (size_t i = 0; i < arraysize(kHeaders); ++i) { + for (size_t i = 0; i < base::size(kHeaders); ++i) { headers += std::string(kHeaders[i]) + "\r\n"; } @@ -525,7 +525,7 @@ "GET /test \r\n\r\n", }; - for (size_t i = 0; i < arraysize(kBadProtocolRequests); ++i) { + for (size_t i = 0; i < base::size(kBadProtocolRequests); ++i) { TestHttpClient client; ASSERT_THAT(client.ConnectAndWait(server_address_), IsOk());
diff --git a/net/socket/client_socket_pool_base_unittest.cc b/net/socket/client_socket_pool_base_unittest.cc index 858942e1..486fd62 100644 --- a/net/socket/client_socket_pool_base_unittest.cc +++ b/net/socket/client_socket_pool_base_unittest.cc
@@ -13,12 +13,12 @@ #include "base/callback.h" #include "base/location.h" #include "base/logging.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/threading/platform_thread.h" @@ -1232,7 +1232,7 @@ callback.callback(), pool_.get(), NetLogWithSource())); ClientSocketHandle handles[4]; - for (size_t i = 0; i < arraysize(handles); ++i) { + for (size_t i = 0; i < base::size(handles); ++i) { TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, @@ -1244,7 +1244,7 @@ // One will be stalled, cancel all the handles now. // This should hit the OnAvailableSocketSlot() code where we previously had // stalled groups, but no longer have any. - for (size_t i = 0; i < arraysize(handles); ++i) + for (size_t i = 0; i < base::size(handles); ++i) handles[i].Reset(); }
diff --git a/net/socket/client_socket_pool_manager.cc b/net/socket/client_socket_pool_manager.cc index cb8d4dd8..a29a6cf 100644 --- a/net/socket/client_socket_pool_manager.cc +++ b/net/socket/client_socket_pool_manager.cc
@@ -7,6 +7,7 @@ #include <memory> #include "base/logging.h" +#include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "net/base/load_flags.h" #include "net/http/http_proxy_client_socket_pool.h" @@ -30,7 +31,7 @@ 256 // WEBSOCKET_SOCKET_POOL }; -static_assert(arraysize(g_max_sockets_per_pool) == +static_assert(base::size(g_max_sockets_per_pool) == HttpNetworkSession::NUM_SOCKET_POOL_TYPES, "max sockets per pool length mismatch"); @@ -47,7 +48,7 @@ 255 // WEBSOCKET_SOCKET_POOL }; -static_assert(arraysize(g_max_sockets_per_group) == +static_assert(base::size(g_max_sockets_per_group) == HttpNetworkSession::NUM_SOCKET_POOL_TYPES, "max sockets per group length mismatch"); @@ -59,7 +60,7 @@ kDefaultMaxSocketsPerProxyServer // WEBSOCKET_SOCKET_POOL }; -static_assert(arraysize(g_max_sockets_per_proxy_server) == +static_assert(base::size(g_max_sockets_per_proxy_server) == HttpNetworkSession::NUM_SOCKET_POOL_TYPES, "max sockets per proxy server length mismatch");
diff --git a/net/socket/sequenced_socket_data_unittest.cc b/net/socket/sequenced_socket_data_unittest.cc index 2761b0c6..5a57c6e0 100644 --- a/net/socket/sequenced_socket_data_unittest.cc +++ b/net/socket/sequenced_socket_data_unittest.cc
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "net/base/completion_once_callback.h" #include "net/base/io_buffer.h" #include "net/base/test_completion_callback.h" @@ -34,13 +35,13 @@ namespace { const char kMsg1[] = "\0hello!\xff"; -const int kLen1 = arraysize(kMsg1); +const int kLen1 = base::size(kMsg1); const char kMsg2[] = "\0a2345678\0"; -const int kLen2 = arraysize(kMsg2); +const int kLen2 = base::size(kMsg2); const char kMsg3[] = "bye!"; -const int kLen3 = arraysize(kMsg3); +const int kLen3 = base::size(kMsg3); const char kMsg4[] = "supercalifragilisticexpialidocious"; -const int kLen4 = arraysize(kMsg4); +const int kLen4 = base::size(kMsg4); // Helper class for starting the next operation operation reentrantly after the // previous operation completed asynchronously. When OnIOComplete is called, @@ -676,7 +677,7 @@ "Expected: (data.length()) >= (expected_data.length())", "Value of: actual_data == expected_data\n Actual: false\nExpected: true", "Expected equality of these values:\n rv"}; - ASSERT_EQ(arraysize(kExpectedFailures), + ASSERT_EQ(base::size(kExpectedFailures), static_cast<size_t>(gtest_failures.size())); for (int i = 0; i < gtest_failures.size(); ++i) {
diff --git a/net/socket/socks5_client_socket.cc b/net/socket/socks5_client_socket.cc index 57465b6..383092b 100644 --- a/net/socket/socks5_client_socket.cc +++ b/net/socket/socks5_client_socket.cc
@@ -9,6 +9,7 @@ #include "base/callback_helpers.h" #include "base/compiler_specific.h" #include "base/format_macros.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/sys_byteorder.h" #include "base/trace_event/trace_event.h" @@ -281,8 +282,8 @@ } if (buffer_.empty()) { - buffer_ = std::string(kSOCKS5GreetWriteData, - arraysize(kSOCKS5GreetWriteData)); + buffer_ = + std::string(kSOCKS5GreetWriteData, base::size(kSOCKS5GreetWriteData)); bytes_sent_ = 0; }
diff --git a/net/socket/socks_client_socket.cc b/net/socket/socks_client_socket.cc index 0814dc9..ede3b356 100644 --- a/net/socket/socks_client_socket.cc +++ b/net/socket/socks_client_socket.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/compiler_specific.h" +#include "base/stl_util.h" #include "base/sys_byteorder.h" #include "net/base/io_buffer.h" #include "net/log/net_log.h" @@ -348,7 +349,7 @@ std::string handshake_data(reinterpret_cast<char*>(&request), sizeof(request)); - handshake_data.append(kEmptyUserId, arraysize(kEmptyUserId)); + handshake_data.append(kEmptyUserId, base::size(kEmptyUserId)); return handshake_data; }
diff --git a/net/socket/ssl_client_socket_pool_unittest.cc b/net/socket/ssl_client_socket_pool_unittest.cc index eb26226..5ccf8a95 100644 --- a/net/socket/ssl_client_socket_pool_unittest.cc +++ b/net/socket/ssl_client_socket_pool_unittest.cc
@@ -6,6 +6,7 @@ #include "base/callback.h" #include "base/compiler_specific.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" @@ -850,7 +851,7 @@ }; host_resolver_.set_synchronous_mode(true); - for (size_t i = 0; i < arraysize(test_hosts); i++) { + for (size_t i = 0; i < base::size(test_hosts); i++) { host_resolver_.rules()->AddIPLiteralRule( test_hosts[i].name, test_hosts[i].iplist, std::string()); @@ -910,7 +911,7 @@ }; host_resolver_.set_synchronous_mode(true); - for (size_t i = 0; i < arraysize(test_hosts); i++) { + for (size_t i = 0; i < base::size(test_hosts); i++) { host_resolver_.rules()->AddIPLiteralRule( test_hosts[i].name, test_hosts[i].iplist, std::string());
diff --git a/net/socket/ssl_client_socket_unittest.cc b/net/socket/ssl_client_socket_unittest.cc index 7b6ada75..e3f1b39 100644 --- a/net/socket/ssl_client_socket_unittest.cc +++ b/net/socket/ssl_client_socket_unittest.cc
@@ -13,10 +13,10 @@ #include "base/callback_helpers.h" #include "base/files/file_util.h" #include "base/location.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" @@ -1106,7 +1106,7 @@ const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; static const int kRequestTextSize = - static_cast<int>(arraysize(request_text) - 1); + static_cast<int>(base::size(request_text) - 1); scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(kRequestTextSize); memcpy(request_buffer->data(), request_text, kRequestTextSize); @@ -1578,12 +1578,12 @@ const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(base::size(request_text) - 1); - memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); + memcpy(request_buffer->data(), request_text, base::size(request_text) - 1); rv = callback.GetResult( - sock->Write(request_buffer.get(), arraysize(request_text) - 1, + sock->Write(request_buffer.get(), base::size(request_text) - 1, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS)); - EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); + EXPECT_EQ(static_cast<int>(base::size(request_text) - 1), rv); scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(4096); int64_t unencrypted_bytes_read = 0; @@ -1666,7 +1666,7 @@ const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; static const int kRequestTextSize = - static_cast<int>(arraysize(request_text) - 1); + static_cast<int>(base::size(request_text) - 1); scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(kRequestTextSize); memcpy(request_buffer->data(), request_text, kRequestTextSize); @@ -1723,7 +1723,7 @@ const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; static const int kRequestTextSize = - static_cast<int>(arraysize(request_text) - 1); + static_cast<int>(base::size(request_text) - 1); scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(kRequestTextSize); memcpy(request_buffer->data(), request_text, kRequestTextSize); @@ -1795,7 +1795,7 @@ const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; static const int kRequestTextSize = - static_cast<int>(arraysize(request_text) - 1); + static_cast<int>(base::size(request_text) - 1); scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(kRequestTextSize); memcpy(request_buffer->data(), request_text, kRequestTextSize); @@ -1984,7 +1984,7 @@ // Send a request so there is something to read from the socket. const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; static const int kRequestTextSize = - static_cast<int>(arraysize(request_text) - 1); + static_cast<int>(base::size(request_text) - 1); scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(kRequestTextSize); memcpy(request_buffer->data(), request_text, kRequestTextSize); @@ -2168,13 +2168,13 @@ const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(base::size(request_text) - 1); - memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); + memcpy(request_buffer->data(), request_text, base::size(request_text) - 1); TestCompletionCallback callback; rv = callback.GetResult( - sock_->Write(request_buffer.get(), arraysize(request_text) - 1, + sock_->Write(request_buffer.get(), base::size(request_text) - 1, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS)); - EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); + EXPECT_EQ(static_cast<int>(base::size(request_text) - 1), rv); scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(1); do { @@ -2207,13 +2207,13 @@ const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n"; scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(base::size(request_text) - 1); - memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); + memcpy(request_buffer->data(), request_text, base::size(request_text) - 1); rv = callback.GetResult( - sock->Write(request_buffer.get(), arraysize(request_text) - 1, + sock->Write(request_buffer.get(), base::size(request_text) - 1, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS)); ASSERT_GT(rv, 0); - ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); + ASSERT_EQ(static_cast<int>(base::size(request_text) - 1), rv); // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of // data (the max SSL record size) at a time. Ensure that at least 15K worth @@ -2241,13 +2241,13 @@ const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(base::size(request_text) - 1); - memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); + memcpy(request_buffer->data(), request_text, base::size(request_text) - 1); TestCompletionCallback callback; rv = callback.GetResult( - sock_->Write(request_buffer.get(), arraysize(request_text) - 1, + sock_->Write(request_buffer.get(), base::size(request_text) - 1, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS)); - EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); + EXPECT_EQ(static_cast<int>(base::size(request_text) - 1), rv); // Do a partial read and then exit. This test should not crash! scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(512); @@ -2277,12 +2277,12 @@ const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(base::size(request_text) - 1); - memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); + memcpy(request_buffer->data(), request_text, base::size(request_text) - 1); rv = callback.GetResult( - sock->Write(request_buffer.get(), arraysize(request_text) - 1, + sock->Write(request_buffer.get(), base::size(request_text) - 1, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS)); - EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); + EXPECT_EQ(static_cast<int>(base::size(request_text) - 1), rv); TestNetLogEntry::List entries; log.GetEntries(&entries); @@ -2322,10 +2322,10 @@ // All reads and writes complete synchronously (async=false). MockRead data_reads[] = { - MockRead(SYNCHRONOUS, - reinterpret_cast<const char*>(application_data), - arraysize(application_data)), - MockRead(SYNCHRONOUS, OK), }; + MockRead(SYNCHRONOUS, reinterpret_cast<const char*>(application_data), + base::size(application_data)), + MockRead(SYNCHRONOUS, OK), + }; StaticSocketDataProvider data(data_reads, base::span<MockWrite>()); @@ -2359,7 +2359,7 @@ ASSERT_TRUE(StartTestServer(ssl_options)); SSLConfig ssl_config; - for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i) + for (size_t i = 0; i < base::size(kCiphersToDisable); ++i) ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]); int rv; @@ -2872,7 +2872,7 @@ EXPECT_FALSE(sock_->WasEverUsed()); const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n"; - const size_t kRequestLen = arraysize(kRequestText) - 1; + const size_t kRequestLen = base::size(kRequestText) - 1; scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(kRequestLen); memcpy(request_buffer->data(), kRequestText, kRequestLen); @@ -2951,7 +2951,7 @@ // Write a partial HTTP request. const char kRequestText[] = "GET / HTTP/1.0"; - const size_t kRequestLen = arraysize(kRequestText) - 1; + const size_t kRequestLen = base::size(kRequestText) - 1; scoped_refptr<IOBuffer> request_buffer = base::MakeRefCounted<IOBuffer>(kRequestLen); memcpy(request_buffer->data(), kRequestText, kRequestLen);
diff --git a/net/socket/ssl_server_socket_unittest.cc b/net/socket/ssl_server_socket_unittest.cc index 74448621..ae0d823 100644 --- a/net/socket/ssl_server_socket_unittest.cc +++ b/net/socket/ssl_server_socket_unittest.cc
@@ -26,9 +26,9 @@ #include "base/files/file_util.h" #include "base/location.h" #include "base/logging.h" -#include "base/macros.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" @@ -1177,7 +1177,7 @@ 0xcca9, // ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 }; client_ssl_config_.disabled_cipher_suites.assign( - kEcdheCiphers, kEcdheCiphers + arraysize(kEcdheCiphers)); + kEcdheCiphers, kEcdheCiphers + base::size(kEcdheCiphers)); // Legacy RSA key exchange ciphers only exist in TLS 1.2 and below. client_ssl_config_.version_max = SSL_PROTOCOL_VERSION_TLS1_2; @@ -1255,7 +1255,7 @@ 0xcca9, // ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 }; client_ssl_config_.disabled_cipher_suites.assign( - kEcdheCiphers, kEcdheCiphers + arraysize(kEcdheCiphers)); + kEcdheCiphers, kEcdheCiphers + base::size(kEcdheCiphers)); // TLS 1.3 always works with SSLPrivateKey. client_ssl_config_.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
diff --git a/net/socket/transport_client_socket_pool_unittest.cc b/net/socket/transport_client_socket_pool_unittest.cc index 47ed224..b0bf833 100644 --- a/net/socket/transport_client_socket_pool_unittest.cc +++ b/net/socket/transport_client_socket_pool_unittest.cc
@@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" -#include "base/macros.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/threading/platform_thread.h" #include "build/build_config.h" #include "net/base/completion_once_callback.h" @@ -920,7 +920,7 @@ case2_types }; - for (size_t index = 0; index < arraysize(cases); ++index) { + for (size_t index = 0; index < base::size(cases); ++index) { client_socket_factory_.set_client_socket_types(cases[index], 2); EXPECT_EQ(0, pool_.IdleSocketCount());
diff --git a/net/socket/udp_socket_unittest.cc b/net/socket/udp_socket_unittest.cc index a948c93..7b6419e 100644 --- a/net/socket/udp_socket_unittest.cc +++ b/net/socket/udp_socket_unittest.cc
@@ -9,11 +9,11 @@ #include "base/bind.h" #include "base/containers/circular_deque.h" #include "base/location.h" -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/scoped_clear_last_error.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "net/base/io_buffer.h" @@ -501,7 +501,7 @@ {"2001:db8:0::42", "::1", true}, #endif }; - for (size_t i = 0; i < arraysize(tests); i++) { + for (size_t i = 0; i < base::size(tests); i++) { SCOPED_TRACE(std::string("Connecting from ") + tests[i].local_address + std::string(" to ") + tests[i].remote_address);
diff --git a/net/socket/websocket_transport_client_socket_pool_unittest.cc b/net/socket/websocket_transport_client_socket_pool_unittest.cc index 668892a..ab5b0aa 100644 --- a/net/socket/websocket_transport_client_socket_pool_unittest.cc +++ b/net/socket/websocket_transport_client_socket_pool_unittest.cc
@@ -10,9 +10,9 @@ #include "base/bind_helpers.h" #include "base/callback.h" #include "base/location.h" -#include "base/macros.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" @@ -499,7 +499,7 @@ MockTransportClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET}; client_socket_factory_.set_client_socket_types(case_types, - arraysize(case_types)); + base::size(case_types)); EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); @@ -663,7 +663,7 @@ MockTransportClientSocketFactory::MOCK_CLIENT_SOCKET}; client_socket_factory_.set_client_socket_types(case_types, - arraysize(case_types)); + base::size(case_types)); // Resolve an AddressList with two IPv6 addresses and then an IPv4 address. host_resolver_->rules()->AddIPLiteralRule( @@ -698,7 +698,7 @@ MockTransportClientSocketFactory::MOCK_CLIENT_SOCKET}; client_socket_factory_.set_client_socket_types(case_types, - arraysize(case_types)); + base::size(case_types)); // Resolve an AddressList with two IPv6 addresses and then an IPv4 address. host_resolver_->rules()->AddIPLiteralRule( @@ -955,7 +955,7 @@ MockTransportClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET }; client_socket_factory_.set_client_socket_types(first_type, - arraysize(first_type)); + base::size(first_type)); // The rest of the sockets will connect synchronously. client_socket_factory_.set_default_client_socket_type( MockTransportClientSocketFactory::MOCK_CLIENT_SOCKET); @@ -1022,7 +1022,7 @@ MockTransportClientSocketFactory::MOCK_CLIENT_SOCKET, MockTransportClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET}; client_socket_factory_.set_client_socket_types(socket_types, - arraysize(socket_types)); + base::size(socket_types)); EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk()); // Socket has been "handed out". EXPECT_TRUE(request(0)->handle()->socket()); @@ -1046,7 +1046,7 @@ MockTransportClientSocketFactory::MOCK_CLIENT_SOCKET}; client_socket_factory_.set_client_socket_types(socket_types, - arraysize(socket_types)); + base::size(socket_types)); EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
diff --git a/net/spdy/bidirectional_stream_spdy_impl_unittest.cc b/net/spdy/bidirectional_stream_spdy_impl_unittest.cc index 6ab93ce0..73d0611 100644 --- a/net/spdy/bidirectional_stream_spdy_impl_unittest.cc +++ b/net/spdy/bidirectional_stream_spdy_impl_unittest.cc
@@ -7,8 +7,8 @@ #include <string> #include "base/containers/span.h" -#include "base/macros.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/time/time.h" @@ -40,7 +40,7 @@ namespace { const char kBodyData[] = "Body data"; -const size_t kBodyDataSize = arraysize(kBodyData); +const size_t kBodyDataSize = base::size(kBodyData); // Size of the buffer to be allocated for each read. const size_t kReadBufferSize = 4096;
diff --git a/net/spdy/fuzzing/hpack_fuzz_util_test.cc b/net/spdy/fuzzing/hpack_fuzz_util_test.cc index ffcdf9c..78d569d4 100644 --- a/net/spdy/fuzzing/hpack_fuzz_util_test.cc +++ b/net/spdy/fuzzing/hpack_fuzz_util_test.cc
@@ -10,6 +10,7 @@ #include "base/files/file.h" #include "base/files/file_util.h" #include "base/path_service.h" +#include "base/stl_util.h" #include "net/third_party/spdy/platform/api/spdy_string_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -68,7 +69,7 @@ "fin"; HpackFuzzUtil::Input input; - input.input.assign(fixture, arraysize(fixture) - 1); + input.input.assign(fixture, base::size(fixture) - 1); SpdyStringPiece block; @@ -141,11 +142,11 @@ TEST(HpackFuzzUtilTest, FlipBitsMutatesBuffer) { char buffer[] = "testbuffer1234567890"; - SpdyString unmodified(buffer, arraysize(buffer) - 1); + SpdyString unmodified(buffer, base::size(buffer) - 1); EXPECT_EQ(unmodified, buffer); HpackFuzzUtil::FlipBits(reinterpret_cast<uint8_t*>(buffer), - arraysize(buffer) - 1, 1); + base::size(buffer) - 1, 1); EXPECT_NE(unmodified, buffer); }
diff --git a/net/spdy/spdy_buffer_unittest.cc b/net/spdy/spdy_buffer_unittest.cc index d843a7e..8343f26 100644 --- a/net/spdy/spdy_buffer_unittest.cc +++ b/net/spdy/spdy_buffer_unittest.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/memory/ref_counted.h" +#include "base/stl_util.h" #include "net/base/io_buffer.h" #include "net/third_party/spdy/core/spdy_protocol.h" #include "testing/gtest/include/gtest/gtest.h" @@ -21,7 +22,7 @@ namespace { const char kData[] = "hello!\0hi."; -const size_t kDataSize = arraysize(kData); +const size_t kDataSize = base::size(kData); class SpdyBufferTest : public ::testing::Test {};
diff --git a/net/spdy/spdy_http_stream_unittest.cc b/net/spdy/spdy_http_stream_unittest.cc index 9e61035..4ee7ac8 100644 --- a/net/spdy/spdy_http_stream_unittest.cc +++ b/net/spdy/spdy_http_stream_unittest.cc
@@ -596,7 +596,7 @@ // chunk becomes available while a write is pending. TEST_F(SpdyHttpStreamTest, DelayedSendChunkedPost) { const char kUploadData1[] = "12345678"; - const int kUploadData1Size = arraysize(kUploadData1)-1; + const int kUploadData1Size = base::size(kUploadData1) - 1; spdy::SpdySerializedFrame req( spdy_util_.ConstructChunkedSpdyPost(nullptr, 0)); spdy::SpdySerializedFrame chunk1(spdy_util_.ConstructSpdyDataFrame(1, false));
diff --git a/net/spdy/spdy_network_transaction_unittest.cc b/net/spdy/spdy_network_transaction_unittest.cc index 7a6db3e2..86aa4e7 100644 --- a/net/spdy/spdy_network_transaction_unittest.cc +++ b/net/spdy/spdy_network_transaction_unittest.cc
@@ -12,6 +12,7 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/test_file_util.h" @@ -2198,7 +2199,7 @@ "transfer-encoding", "chunked" }; spdy::SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( - headers, arraysize(headers) / 2, 2, 1, "https://www.example.org/1")); + headers, base::size(headers) / 2, 2, 1, "https://www.example.org/1")); spdy::SpdySerializedFrame body(spdy_util_.ConstructSpdyDataFrame(1, true)); MockRead reads[] = { CreateMockRead(resp, 1), CreateMockRead(push, 2), CreateMockRead(body, 4), @@ -2313,7 +2314,7 @@ CreateMockRead(resp, 1), MockRead(ASYNC, ERR_IO_PENDING, 2), // Force a pause MockRead(ASYNC, reinterpret_cast<const char*>(kGetBodyFrame2), - arraysize(kGetBodyFrame2), 3), + base::size(kGetBodyFrame2), 3), MockRead(ASYNC, ERR_IO_PENDING, 4), // Force a pause MockRead(ASYNC, 0, 0, 5), // EOF }; @@ -2553,7 +2554,7 @@ const char* const kExtraHeaders[] = {"location", "https://www.foo.com/index.php"}; spdy::SpdySerializedFrame resp0(spdy_util_.ConstructSpdyReplyError( - "301", kExtraHeaders, arraysize(kExtraHeaders) / 2, 1)); + "301", kExtraHeaders, base::size(kExtraHeaders) / 2, 1)); MockRead reads0[] = {CreateMockRead(resp0, 1), MockRead(ASYNC, 0, 3)}; SequencedSocketData data0(reads0, writes0); @@ -3921,7 +3922,7 @@ 3, {"status", "200", "hello", "bye", "cookie", "val1; val2"}}}; - for (size_t i = 0; i < arraysize(test_cases); ++i) { + for (size_t i = 0; i < base::size(test_cases); ++i) { SpdyTestUtil spdy_test_util; spdy::SpdySerializedFrame req( spdy_test_util.ConstructSpdyGet(nullptr, 0, 1, LOWEST)); @@ -4007,7 +4008,7 @@ {spdy::kHttp2StatusHeader, "200", spdy::kHttp2PathHeader, "/index.php", "vary", "friend,enemy", nullptr}}}}; - for (size_t i = 0; i < arraysize(test_cases); ++i) { + for (size_t i = 0; i < base::size(test_cases); ++i) { SpdyTestUtil spdy_test_util; // Construct the request. @@ -4106,7 +4107,7 @@ }, }; - for (size_t i = 0; i < arraysize(test_cases); ++i) { + for (size_t i = 0; i < base::size(test_cases); ++i) { SpdyTestUtil spdy_test_util; spdy::SpdySerializedFrame req( @@ -5115,12 +5116,13 @@ spdy::SpdySerializedFrame body(spdy_util_.ConstructSpdyDataFrame(1, true)); MockWrite writes[] = { - MockWrite(SYNCHRONOUS, kConnect443, arraysize(kConnect443) - 1, 0), + MockWrite(SYNCHRONOUS, kConnect443, base::size(kConnect443) - 1, 0), CreateMockWrite(req, 2), }; MockRead reads[] = { - MockRead(SYNCHRONOUS, kHTTP200, arraysize(kHTTP200) - 1, 1), - CreateMockRead(resp, 3), CreateMockRead(body, 4), + MockRead(SYNCHRONOUS, kHTTP200, base::size(kHTTP200) - 1, 1), + CreateMockRead(resp, 3), + CreateMockRead(body, 4), MockRead(ASYNC, 0, 0, 5), }; SequencedSocketData data(reads, writes); @@ -5228,11 +5230,11 @@ spdy::SpdySerializedFrame body2(spdy_util_2.ConstructSpdyDataFrame(1, true)); MockWrite writes2[] = { - MockWrite(SYNCHRONOUS, kConnect443, arraysize(kConnect443) - 1, 0), + MockWrite(SYNCHRONOUS, kConnect443, base::size(kConnect443) - 1, 0), CreateMockWrite(req2, 2), }; MockRead reads2[] = { - MockRead(SYNCHRONOUS, kHTTP200, arraysize(kHTTP200) - 1, 1), + MockRead(SYNCHRONOUS, kHTTP200, base::size(kHTTP200) - 1, 1), CreateMockRead(resp2, 3), CreateMockRead(body2, 4), MockRead(ASYNC, 0, 5) // EOF }; @@ -5370,7 +5372,7 @@ "authorization", "Basic Zm9vOmJhcg==" }; spdy::SpdySerializedFrame req_get_authorization(spdy_util_.ConstructSpdyGet( - kExtraAuthorizationHeaders, arraysize(kExtraAuthorizationHeaders) / 2, 3, + kExtraAuthorizationHeaders, base::size(kExtraAuthorizationHeaders) / 2, 3, LOWEST)); MockWrite spdy_writes[] = { CreateMockWrite(req_get, 0), CreateMockWrite(req_get_authorization, 3), @@ -5386,7 +5388,7 @@ spdy::SpdySerializedFrame resp_authentication( spdy_util_.ConstructSpdyReplyError( "401", kExtraAuthenticationHeaders, - arraysize(kExtraAuthenticationHeaders) / 2, 1)); + base::size(kExtraAuthenticationHeaders) / 2, 1)); spdy::SpdySerializedFrame body_authentication( spdy_util_.ConstructSpdyDataFrame(1, true)); spdy::SpdySerializedFrame resp_data( @@ -7470,10 +7472,10 @@ spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1)); spdy::SpdySerializedFrame body(spdy_util_.ConstructSpdyDataFrame(1, true)); MockRead reads[] = {MockRead(ASYNC, origin_frame_on_stream_zero, - arraysize(origin_frame_on_stream_zero), 1), + base::size(origin_frame_on_stream_zero), 1), CreateMockRead(resp, 2), MockRead(ASYNC, origin_frame_on_stream_one, - arraysize(origin_frame_on_stream_one), 3), + base::size(origin_frame_on_stream_one), 3), CreateMockRead(body, 4), MockRead(ASYNC, 0, 5)}; SequencedSocketData data(reads, writes);
diff --git a/net/spdy/spdy_read_queue_unittest.cc b/net/spdy/spdy_read_queue_unittest.cc index 025fb1f..2f144d0 100644 --- a/net/spdy/spdy_read_queue_unittest.cc +++ b/net/spdy/spdy_read_queue_unittest.cc
@@ -20,7 +20,7 @@ namespace { const char kData[] = "SPDY read queue test data.\0Some more data."; -const size_t kDataSize = arraysize(kData); +const size_t kDataSize = base::size(kData); // Enqueues |data| onto |queue| in chunks of at most |max_buffer_size| // bytes.
diff --git a/net/spdy/spdy_session_fuzzer.cc b/net/spdy/spdy_session_fuzzer.cc index e495905..93a9429 100644 --- a/net/spdy/spdy_session_fuzzer.cc +++ b/net/spdy/spdy_session_fuzzer.cc
@@ -3,8 +3,8 @@ // found in the LICENSE file. #include "base/logging.h" -#include "base/macros.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/test/fuzzed_data_provider.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" @@ -109,7 +109,7 @@ net::SSLSocketDataProvider ssl_provider(net::ASYNC, net::OK); ssl_provider.ssl_info.cert = - net::X509Certificate::CreateFromBytes(kCertData, arraysize(kCertData)); + net::X509Certificate::CreateFromBytes(kCertData, base::size(kCertData)); CHECK(ssl_provider.ssl_info.cert); socket_factory.AddSSLSocketDataProvider(&ssl_provider);
diff --git a/net/spdy/spdy_session_pool_unittest.cc b/net/spdy/spdy_session_pool_unittest.cc index 354842d..36461432 100644 --- a/net/spdy/spdy_session_pool_unittest.cc +++ b/net/spdy/spdy_session_pool_unittest.cc
@@ -9,6 +9,7 @@ #include "base/memory/ref_counted.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/test/metrics/histogram_tester.h" #include "base/trace_event/memory_allocator_dump.h" #include "base/trace_event/process_memory_dump.h" @@ -353,7 +354,7 @@ }; session_deps_.host_resolver->set_synchronous_mode(true); - for (size_t i = 0; i < arraysize(test_hosts); i++) { + for (size_t i = 0; i < base::size(test_hosts); i++) { session_deps_.host_resolver->rules()->AddIPLiteralRule( test_hosts[i].name, test_hosts[i].iplist, std::string()); @@ -545,7 +546,7 @@ // Populate the HostResolver cache. session_deps_.host_resolver->set_synchronous_mode(true); - for (size_t i = 0; i < arraysize(test_hosts); i++) { + for (size_t i = 0; i < base::size(test_hosts); i++) { session_deps_.host_resolver->rules()->AddIPLiteralRule( test_hosts[i].name, test_hosts[i].iplist, std::string()); @@ -627,7 +628,7 @@ // Populate the HostResolver cache. session_deps_.host_resolver->set_synchronous_mode(true); - for (size_t i = 0; i < arraysize(test_hosts); i++) { + for (size_t i = 0; i < base::size(test_hosts); i++) { session_deps_.host_resolver->rules()->AddIPLiteralRule( test_hosts[i].name, test_hosts[i].iplist, std::string()); @@ -996,7 +997,7 @@ // Populate the HostResolver cache. session_deps_.host_resolver->set_synchronous_mode(true); - for (size_t i = 0; i < arraysize(test_hosts); i++) { + for (size_t i = 0; i < base::size(test_hosts); i++) { session_deps_.host_resolver->rules()->AddIPLiteralRule( test_hosts[i].name, test_hosts[i].iplist, std::string());
diff --git a/net/spdy/spdy_session_unittest.cc b/net/spdy/spdy_session_unittest.cc index 43fe9cf..9a691151 100644 --- a/net/spdy/spdy_session_unittest.cc +++ b/net/spdy/spdy_session_unittest.cc
@@ -65,7 +65,7 @@ const char kPushedUrl[] = "https://www.example.org/a.dat"; const char kBodyData[] = "Body data"; -const size_t kBodyDataSize = arraysize(kBodyData); +const size_t kBodyDataSize = base::size(kBodyData); const base::StringPiece kBodyDataStringPiece(kBodyData, kBodyDataSize); static base::TimeDelta g_time_delta; @@ -6891,7 +6891,7 @@ {1, {"vary", "fooaccept-encoding"}, 5}, {1, {"vary", "foo, accept-encodingbar"}, 5}}; - for (size_t i = 0; i < arraysize(test_cases); ++i) { + for (size_t i = 0; i < base::size(test_cases); ++i) { spdy::SpdyHeaderBlock headers; for (size_t j = 0; j < test_cases[i].num_headers; ++j) { headers[test_cases[i].headers[2 * j]] = test_cases[i].headers[2 * j + 1];
diff --git a/net/spdy/spdy_stream_unittest.cc b/net/spdy/spdy_stream_unittest.cc index e58cd0b..d29a5b96 100644 --- a/net/spdy/spdy_stream_unittest.cc +++ b/net/spdy/spdy_stream_unittest.cc
@@ -16,6 +16,7 @@ #include "base/memory/ref_counted.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_piece.h" #include "net/base/request_priority.h" #include "net/http/http_request_info.h" @@ -50,7 +51,7 @@ const char kPushUrl[] = "https://www.example.org/push"; const char kPostBody[] = "\0hello!\xff"; -const size_t kPostBodyLength = arraysize(kPostBody); +const size_t kPostBodyLength = base::size(kPostBody); const base::StringPiece kPostBodyStringPiece(kPostBody, kPostBodyLength); static base::TimeTicks g_time_now; @@ -571,7 +572,7 @@ const char* const kExtraHeaders[] = {"X-UpperCase", "yes"}; spdy::SpdySerializedFrame reply(spdy_util_.ConstructSpdyGetReply( - kExtraHeaders, arraysize(kExtraHeaders) / 2, 1)); + kExtraHeaders, base::size(kExtraHeaders) / 2, 1)); AddRead(reply); spdy::SpdySerializedFrame rst( @@ -625,7 +626,7 @@ const char* const kExtraHeaders[] = {"X-UpperCase", "yes"}; spdy::SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( - kExtraHeaders, arraysize(kExtraHeaders) / 2, 2, 1, kPushUrl)); + kExtraHeaders, base::size(kExtraHeaders) / 2, 2, 1, kPushUrl)); AddRead(push); spdy::SpdySerializedFrame priority(
diff --git a/net/spdy/spdy_test_util_common.h b/net/spdy/spdy_test_util_common.h index 87780221..8db758d7 100644 --- a/net/spdy/spdy_test_util_common.h +++ b/net/spdy/spdy_test_util_common.h
@@ -13,8 +13,8 @@ #include <string> #include <vector> -#include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/stl_util.h" #include "base/strings/string_piece.h" #include "crypto/ec_private_key.h" #include "crypto/ec_signature_creator.h" @@ -62,7 +62,7 @@ // data frames. const char kDefaultUrl[] = "https://www.example.org/"; const char kUploadData[] = "hello!"; -const int kUploadDataSize = arraysize(kUploadData)-1; +const int kUploadDataSize = base::size(kUploadData) - 1; // While HTTP/2 protocol defines default SETTINGS_MAX_HEADER_LIST_SIZE_FOR_TEST // to be unlimited, BufferedSpdyFramer constructor requires a value.
diff --git a/net/spdy/spdy_write_queue_unittest.cc b/net/spdy/spdy_write_queue_unittest.cc index bf881e1..b561ae9 100644 --- a/net/spdy/spdy_write_queue_unittest.cc +++ b/net/spdy/spdy_write_queue_unittest.cc
@@ -11,6 +11,7 @@ #include "base/logging.h" #include "base/memory/ref_counted.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "net/base/request_priority.h" #include "net/log/net_log_with_source.h" @@ -51,7 +52,7 @@ class RequeingBufferProducer : public SpdyBufferProducer { public: explicit RequeingBufferProducer(SpdyWriteQueue* queue) { - buffer_ = std::make_unique<SpdyBuffer>(kOriginal, arraysize(kOriginal)); + buffer_ = std::make_unique<SpdyBuffer>(kOriginal, base::size(kOriginal)); buffer_->AddConsumeCallback( base::Bind(RequeingBufferProducer::ConsumeCallback, queue)); } @@ -68,7 +69,8 @@ static void ConsumeCallback(SpdyWriteQueue* queue, size_t size, SpdyBuffer::ConsumeSource source) { - auto buffer = std::make_unique<SpdyBuffer>(kRequeued, arraysize(kRequeued)); + auto buffer = + std::make_unique<SpdyBuffer>(kRequeued, base::size(kRequeued)); auto buffer_producer = std::make_unique<SimpleBufferProducer>(std::move(buffer)); @@ -267,13 +269,13 @@ for (int i = 0; i < 100; ++i) { write_queue.Enqueue(DEFAULT_PRIORITY, spdy::SpdyFrameType::HEADERS, - IntToProducer(i), streams[i % arraysize(streams)], + IntToProducer(i), streams[i % base::size(streams)], TRAFFIC_ANNOTATION_FOR_TESTS); } write_queue.RemovePendingWritesForStreamsAfter(stream1->stream_id()); - for (int i = 0; i < 100; i += arraysize(streams)) { + for (int i = 0; i < 100; i += base::size(streams)) { spdy::SpdyFrameType frame_type = spdy::SpdyFrameType::DATA; std::unique_ptr<SpdyBufferProducer> frame_producer; base::WeakPtr<SpdyStream> stream;
diff --git a/net/ssl/client_cert_store_mac.cc b/net/ssl/client_cert_store_mac.cc index 20cd532..c7ab20a 100644 --- a/net/ssl/client_cert_store_mac.cc +++ b/net/ssl/client_cert_store_mac.cc
@@ -22,6 +22,7 @@ #include "base/logging.h" #include "base/mac/mac_logging.h" #include "base/mac/scoped_cftyperef.h" +#include "base/stl_util.h" #include "base/strings/sys_string_conversions.h" #include "base/synchronization/lock.h" #include "base/task_runner_util.h" @@ -360,7 +361,7 @@ kSecClassIdentity, kSecMatchLimitAll, kCFBooleanTrue, kCFBooleanTrue, }; ScopedCFTypeRef<CFDictionaryRef> query(CFDictionaryCreate( - kCFAllocatorDefault, kKeys, kValues, arraysize(kValues), + kCFAllocatorDefault, kKeys, kValues, base::size(kValues), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); ScopedCFTypeRef<CFArrayRef> result; {
diff --git a/net/ssl/ssl_cipher_suite_names_unittest.cc b/net/ssl/ssl_cipher_suite_names_unittest.cc index 733ca0f..8a810e0 100644 --- a/net/ssl/ssl_cipher_suite_names_unittest.cc +++ b/net/ssl/ssl_cipher_suite_names_unittest.cc
@@ -4,7 +4,7 @@ #include "net/ssl/ssl_cipher_suite_names.h" -#include "base/macros.h" +#include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "net/ssl/ssl_connection_status_flags.h" #include "testing/gtest/include/gtest/gtest.h" @@ -126,7 +126,7 @@ "0xBEEFY", }; - for (size_t i = 0; i < arraysize(cipher_strings); ++i) { + for (size_t i = 0; i < base::size(cipher_strings); ++i) { uint16_t cipher_suite = 0; EXPECT_FALSE(ParseSSLCipherString(cipher_strings[i], &cipher_suite)); }
diff --git a/net/test/url_request/url_request_failed_job.cc b/net/test/url_request/url_request_failed_job.cc index d4c0bf92..d3955d6 100644 --- a/net/test/url_request/url_request_failed_job.cc +++ b/net/test/url_request/url_request_failed_job.cc
@@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/location.h" #include "base/logging.h" -#include "base/macros.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/net_errors.h" @@ -31,7 +31,7 @@ "readasync", // READ_ASYNC }; -static_assert(arraysize(kFailurePhase) == +static_assert(base::size(kFailurePhase) == URLRequestFailedJob::FailurePhase::MAX_FAILURE_PHASE, "kFailurePhase must match FailurePhase enum"); @@ -47,7 +47,7 @@ int net_error = OK; URLRequestFailedJob::FailurePhase phase = URLRequestFailedJob::FailurePhase::MAX_FAILURE_PHASE; - for (size_t i = 0; i < arraysize(kFailurePhase); i++) { + for (size_t i = 0; i < base::size(kFailurePhase); i++) { std::string phase_error_string; if (GetValueForKeyInQuery(request->url(), kFailurePhase[i], &phase_error_string)) {
diff --git a/net/third_party/quic/core/chlo_extractor_test.cc b/net/third_party/quic/core/chlo_extractor_test.cc index 721ce9e..fbd1b96 100644 --- a/net/third_party/quic/core/chlo_extractor_test.cc +++ b/net/third_party/quic/core/chlo_extractor_test.cc
@@ -46,7 +46,7 @@ class ChloExtractorTest : public QuicTest { public: ChloExtractorTest() { - header_.destination_connection_id = QuicConnectionIdFromUInt64(42); + header_.destination_connection_id = TestConnectionId(); header_.destination_connection_id_length = PACKET_8BYTE_CONNECTION_ID; header_.version_flag = true; header_.version = AllSupportedVersions().front();
diff --git a/net/third_party/quic/core/congestion_control/bandwidth_sampler.cc b/net/third_party/quic/core/congestion_control/bandwidth_sampler.cc index d765575b..461b227 100644 --- a/net/third_party/quic/core/congestion_control/bandwidth_sampler.cc +++ b/net/third_party/quic/core/congestion_control/bandwidth_sampler.cc
@@ -120,11 +120,18 @@ // always larger than the time of the previous packet, otherwise division by // zero or integer underflow can occur. if (ack_time <= sent_packet.last_acked_packet_ack_time) { - QUIC_LOG(DFATAL) - << "Time of the previously acked packet:" - << sent_packet.last_acked_packet_ack_time.ToDebuggingValue() - << " is larger than the ack time of the current packet:" - << ack_time.ToDebuggingValue(); + // TODO(wub): Compare this code count before and after fixing clock jitter + // issue. + if (sent_packet.last_acked_packet_ack_time == sent_packet.sent_time) { + // This is the 1st packet after quiescense. + QUIC_CODE_COUNT_N(quic_prev_ack_time_larger_than_current_ack_time, 1, 2); + } else { + QUIC_CODE_COUNT_N(quic_prev_ack_time_larger_than_current_ack_time, 2, 2); + } + QUIC_LOG(ERROR) << "Time of the previously acked packet:" + << sent_packet.last_acked_packet_ack_time.ToDebuggingValue() + << " is larger than the ack time of the current packet:" + << ack_time.ToDebuggingValue(); return BandwidthSample(); } QuicBandwidth ack_rate = QuicBandwidth::FromBytesAndTimeDelta(
diff --git a/net/third_party/quic/core/congestion_control/bbr_sender_test.cc b/net/third_party/quic/core/congestion_control/bbr_sender_test.cc index 789a2ba..6e9cc3da 100644 --- a/net/third_party/quic/core/congestion_control/bbr_sender_test.cc +++ b/net/third_party/quic/core/congestion_control/bbr_sender_test.cc
@@ -73,22 +73,22 @@ "BBR sender", "Receiver", Perspective::IS_CLIENT, - /*connection_id=*/QuicConnectionIdFromUInt64(42)), + /*connection_id=*/TestConnectionId(42)), competing_sender_(&simulator_, "Competing sender", "Competing receiver", Perspective::IS_CLIENT, - /*connection_id=*/QuicConnectionIdFromUInt64(43)), + /*connection_id=*/TestConnectionId(43)), receiver_(&simulator_, "Receiver", "BBR sender", Perspective::IS_SERVER, - /*connection_id=*/QuicConnectionIdFromUInt64(42)), + /*connection_id=*/TestConnectionId(42)), competing_receiver_(&simulator_, "Competing receiver", "Competing sender", Perspective::IS_SERVER, - /*connection_id=*/QuicConnectionIdFromUInt64(43)), + /*connection_id=*/TestConnectionId(43)), receiver_multiplexer_("Receiver multiplexer", {&receiver_, &competing_receiver_}) { rtt_stats_ = bbr_sender_.connection()->sent_packet_manager().GetRttStats();
diff --git a/net/third_party/quic/core/congestion_control/send_algorithm_test.cc b/net/third_party/quic/core/congestion_control/send_algorithm_test.cc index 8d27da67..a161ecaf 100644 --- a/net/third_party/quic/core/congestion_control/send_algorithm_test.cc +++ b/net/third_party/quic/core/congestion_control/send_algorithm_test.cc
@@ -157,12 +157,12 @@ "QUIC sender", "Receiver", Perspective::IS_CLIENT, - QuicConnectionIdFromUInt64(42)), + TestConnectionId()), receiver_(&simulator_, "Receiver", "QUIC sender", Perspective::IS_SERVER, - QuicConnectionIdFromUInt64(42)) { + TestConnectionId()) { rtt_stats_ = quic_sender_.connection()->sent_packet_manager().GetRttStats(); sender_ = SendAlgorithmInterface::Create( simulator_.GetClock(), rtt_stats_,
diff --git a/net/third_party/quic/core/crypto/crypto_server_test.cc b/net/third_party/quic/core/crypto/crypto_server_test.cc index a2ba41b2..14a9fa5 100644 --- a/net/third_party/quic/core/crypto/crypto_server_test.cc +++ b/net/third_party/quic/core/crypto/crypto_server_test.cc
@@ -314,12 +314,12 @@ const char* error_substr) { QuicSocketAddress server_address; QuicConnectionId server_designated_connection_id = - QuicConnectionIdFromUInt64(rand_for_id_generation_.RandUint64()); + TestConnectionId(rand_for_id_generation_.RandUint64()); bool called; config_.ProcessClientHello( result, /*reject_only=*/false, - /*connection_id=*/QuicConnectionIdFromUInt64(1), server_address, - client_address_, supported_versions_.front(), supported_versions_, + /*connection_id=*/TestConnectionId(1), server_address, client_address_, + supported_versions_.front(), supported_versions_, use_stateless_rejects_, server_designated_connection_id, &clock_, rand_, &compressed_certs_cache_, params_, signed_config_, /*total_framing_overhead=*/50, chlo_packet_size_,
diff --git a/net/third_party/quic/core/crypto/quic_crypto_client_config.cc b/net/third_party/quic/core/crypto/quic_crypto_client_config.cc index bbcbe27a..361bec2 100644 --- a/net/third_party/quic/core/crypto/quic_crypto_client_config.cc +++ b/net/third_party/quic/core/crypto/quic_crypto_client_config.cc
@@ -516,9 +516,8 @@ CryptoHandshakeMessage* out, QuicString* error_details) const { DCHECK(error_details != nullptr); - // TODO(dschinazi) b/120240679 - remove this endianness swap - connection_id = QuicConnectionIdFromUInt64( - QuicEndian::HostToNet64(QuicConnectionIdToUInt64(connection_id))); + const uint64_t connection_id64_net = + QuicEndian::HostToNet64(QuicConnectionIdToUInt64(connection_id)); FillInchoateClientHello(server_id, preferred_version, cached, rand, /* demand_x509_proof= */ true, out_params, out); @@ -643,7 +642,8 @@ const QuicData& client_hello_serialized = out->GetSerialized(); hkdf_input.append(QuicCryptoConfig::kCETVLabel, strlen(QuicCryptoConfig::kCETVLabel) + 1); - hkdf_input.append(connection_id.data(), connection_id.length()); + hkdf_input.append(reinterpret_cast<const char*>(&connection_id64_net), + sizeof(connection_id64_net)); hkdf_input.append(client_hello_serialized.data(), client_hello_serialized.length()); hkdf_input.append(cached->server_config()); @@ -694,8 +694,9 @@ // out_params->hkdf_input_suffix // out_params->initial_crypters out_params->hkdf_input_suffix.clear(); - out_params->hkdf_input_suffix.append(connection_id.data(), - connection_id.length()); + out_params->hkdf_input_suffix.append( + reinterpret_cast<const char*>(&connection_id64_net), + sizeof(connection_id64_net)); const QuicData& client_hello_serialized = out->GetSerialized(); out_params->hkdf_input_suffix.append(client_hello_serialized.data(), client_hello_serialized.length());
diff --git a/net/third_party/quic/core/crypto/quic_crypto_client_config_test.cc b/net/third_party/quic/core/crypto/quic_crypto_client_config_test.cc index aa1aeae3..fb249af 100644 --- a/net/third_party/quic/core/crypto/quic_crypto_client_config_test.cc +++ b/net/third_party/quic/core/crypto/quic_crypto_client_config_test.cc
@@ -83,7 +83,7 @@ EXPECT_FALSE(state.has_server_designated_connection_id()); uint64_t conn_id = 1234; - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); state.add_server_designated_connection_id(connection_id); EXPECT_TRUE(state.has_server_designated_connection_id()); EXPECT_EQ(connection_id, state.GetNextServerDesignatedConnectionId()); @@ -91,18 +91,18 @@ // Allow the ID to be set multiple times. It's unusual that this would // happen, but not impossible. - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); state.add_server_designated_connection_id(connection_id); EXPECT_TRUE(state.has_server_designated_connection_id()); EXPECT_EQ(connection_id, state.GetNextServerDesignatedConnectionId()); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); state.add_server_designated_connection_id(connection_id); EXPECT_EQ(connection_id, state.GetNextServerDesignatedConnectionId()); EXPECT_FALSE(state.has_server_designated_connection_id()); // Test FIFO behavior. - const QuicConnectionId first_cid = QuicConnectionIdFromUInt64(0xdeadbeef); - const QuicConnectionId second_cid = QuicConnectionIdFromUInt64(0xfeedbead); + const QuicConnectionId first_cid = TestConnectionId(0xdeadbeef); + const QuicConnectionId second_cid = TestConnectionId(0xfeedbead); state.add_server_designated_connection_id(first_cid); state.add_server_designated_connection_id(second_cid); EXPECT_TRUE(state.has_server_designated_connection_id()); @@ -295,7 +295,7 @@ TlsClientHandshaker::CreateSslCtx()); QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> params( new QuicCryptoNegotiatedParameters); - QuicConnectionId kConnectionId = QuicConnectionIdFromUInt64(1234); + QuicConnectionId kConnectionId = TestConnectionId(1234); QuicString error_details; MockRandom rand; CryptoHandshakeMessage chlo; @@ -539,9 +539,9 @@ // Create a dummy reject message and mark it as stateless. CryptoHandshakeMessage rej; crypto_test_utils::FillInDummyReject(&rej, /* stateless */ true); - const QuicConnectionId kConnectionId = QuicConnectionIdFromUInt64(0xdeadbeef); + const QuicConnectionId kConnectionId = TestConnectionId(0xdeadbeef); const QuicString server_nonce = "SERVER_NONCE"; - const uint64_t kConnectionId64 = QuicConnectionIdToUInt64(kConnectionId); + const uint64_t kConnectionId64 = TestConnectionIdToUInt64(kConnectionId); rej.SetValue(kRCID, kConnectionId64); rej.SetStringPiece(kServerNonceTag, server_nonce); @@ -557,8 +557,8 @@ AllSupportedTransportVersions().front(), "", &cached, out_params, &error)); EXPECT_TRUE(cached.has_server_designated_connection_id()); - EXPECT_EQ(QuicConnectionIdFromUInt64(QuicEndian::NetToHost64( - QuicConnectionIdToUInt64(kConnectionId))), + EXPECT_EQ(TestConnectionId(QuicEndian::NetToHost64( + TestConnectionIdToUInt64(kConnectionId))), cached.GetNextServerDesignatedConnectionId()); EXPECT_EQ(server_nonce, cached.GetNextServerNonce()); }
diff --git a/net/third_party/quic/core/crypto/quic_crypto_server_config.cc b/net/third_party/quic/core/crypto/quic_crypto_server_config.cc index 9a673ef..2a5e6c76 100644 --- a/net/third_party/quic/core/crypto/quic_crypto_server_config.cc +++ b/net/third_party/quic/core/crypto/quic_crypto_server_config.cc
@@ -1016,12 +1016,18 @@ params->sni = QuicHostnameUtils::NormalizeHostname(sni_tmp.get()); } + // connection_id is already passed in in network byte order + // TODO(dschinazi) b/120240679 - move the endianness swap from + // ProcessClientHelloAfterGetProof to here. + const uint64_t connection_id64_net = QuicConnectionIdToUInt64(connection_id); + QuicString hkdf_suffix; const QuicData& client_hello_serialized = client_hello.GetSerialized(); - hkdf_suffix.reserve(connection_id.length() + + hkdf_suffix.reserve(sizeof(connection_id64_net) + client_hello_serialized.length() + requested_config->serialized.size()); - hkdf_suffix.append(connection_id.data(), connection_id.length()); + hkdf_suffix.append(reinterpret_cast<const char*>(&connection_id64_net), + sizeof(connection_id64_net)); hkdf_suffix.append(client_hello_serialized.data(), client_hello_serialized.length()); hkdf_suffix.append(requested_config->serialized); @@ -1044,7 +1050,8 @@ QuicString hkdf_input; hkdf_input.append(QuicCryptoConfig::kCETVLabel, strlen(QuicCryptoConfig::kCETVLabel) + 1); - hkdf_input.append(connection_id.data(), connection_id.length()); + hkdf_input.append(reinterpret_cast<const char*>(&connection_id64_net), + sizeof(connection_id64_net)); hkdf_input.append(client_hello_copy_serialized.data(), client_hello_copy_serialized.length()); hkdf_input.append(requested_config->serialized); @@ -1711,7 +1718,8 @@ out->SetStringPiece(kPROF, signed_config.proof.signature); if (should_return_sct) { if (cert_sct.empty()) { - QUIC_LOG_EVERY_N_SEC(WARNING, 60) << "SCT is expected but it is empty."; + QUIC_LOG_EVERY_N_SEC(WARNING, 60) + << "SCT is expected but it is empty. sni :" << params->sni; } else { out->SetStringPiece(kCertificateSCTTag, cert_sct); }
diff --git a/net/third_party/quic/core/http/end_to_end_test.cc b/net/third_party/quic/core/http/end_to_end_test.cc index 353ab380..e5b49e5be 100644 --- a/net/third_party/quic/core/http/end_to_end_test.cc +++ b/net/third_party/quic/core/http/end_to_end_test.cc
@@ -2253,8 +2253,8 @@ stateless_reset_token = config->ReceivedStatelessResetToken(); } // Send the public reset. - QuicConnectionId incorrect_connection_id = QuicConnectionIdFromUInt64( - QuicConnectionIdToUInt64(client_connection->connection_id()) + 1); + QuicConnectionId incorrect_connection_id = TestConnectionId( + TestConnectionIdToUInt64(client_connection->connection_id()) + 1); QuicPublicResetPacket header; header.connection_id = incorrect_connection_id; QuicFramer framer(server_supported_versions_, QuicTime::Zero(), @@ -2302,8 +2302,8 @@ ASSERT_TRUE(Initialize()); // Send the public reset. - QuicConnectionId incorrect_connection_id = QuicConnectionIdFromUInt64( - QuicConnectionIdToUInt64( + QuicConnectionId incorrect_connection_id = TestConnectionId( + TestConnectionIdToUInt64( client_->client()->client_session()->connection()->connection_id()) + 1); QuicPublicResetPacket header; @@ -2333,8 +2333,8 @@ // Send the version negotiation packet. QuicConnection* client_connection = client_->client()->client_session()->connection(); - QuicConnectionId incorrect_connection_id = QuicConnectionIdFromUInt64( - QuicConnectionIdToUInt64(client_connection->connection_id()) + 1); + QuicConnectionId incorrect_connection_id = TestConnectionId( + TestConnectionIdToUInt64(client_connection->connection_id()) + 1); std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( incorrect_connection_id, @@ -3214,7 +3214,7 @@ QuicConfig* config = client_->client()->session()->config(); EXPECT_TRUE(config->HasReceivedStatelessResetToken()); // TODO(dschinazi) b/120240679 - convert connection ID to UInt128 - EXPECT_EQ(QuicConnectionIdToUInt64( + EXPECT_EQ(TestConnectionIdToUInt64( client_->client()->session()->connection()->connection_id()), config->ReceivedStatelessResetToken()); client_->Disconnect();
diff --git a/net/third_party/quic/core/http/quic_server_session_base_test.cc b/net/third_party/quic/core/http/quic_server_session_base_test.cc index 90e483ab..07520d37 100644 --- a/net/third_party/quic/core/http/quic_server_session_base_test.cc +++ b/net/third_party/quic/core/http/quic_server_session_base_test.cc
@@ -648,7 +648,7 @@ chlo.SetVector(kCOPT, QuicTagVector{kSREJ}); std::vector<ParsedQuicVersion> packet_version_list = {GetParam()}; std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( - QuicConnectionIdFromUInt64(1), EmptyQuicConnectionId(), true, false, 1, + TestConnectionId(1), EmptyQuicConnectionId(), true, false, 1, QuicString(chlo.GetSerialized().AsStringPiece()), PACKET_8BYTE_CONNECTION_ID, PACKET_0BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, &packet_version_list)); @@ -656,7 +656,7 @@ EXPECT_CALL(stream_helper_, CanAcceptClientHello(_, _, _, _, _)) .WillOnce(testing::Return(true)); EXPECT_CALL(stream_helper_, GenerateConnectionIdForReject(_)) - .WillOnce(testing::Return(QuicConnectionIdFromUInt64(12345))); + .WillOnce(testing::Return(TestConnectionId(12345))); // Set the current packet QuicConnectionPeer::SetCurrentPacket(session_->connection(),
diff --git a/net/third_party/quic/core/quic_buffered_packet_store_test.cc b/net/third_party/quic/core/quic_buffered_packet_store_test.cc index 0596cce9..2ab65c0c4 100644 --- a/net/third_party/quic/core/quic_buffered_packet_store_test.cc +++ b/net/third_party/quic/core/quic_buffered_packet_store_test.cc
@@ -71,7 +71,7 @@ }; TEST_F(QuicBufferedPacketStoreTest, SimpleEnqueueAndDeliverPacket) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); store_.EnqueuePacket(connection_id, false, packet_, server_address_, client_address_, false, "", invalid_version_); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); @@ -94,7 +94,7 @@ TEST_F(QuicBufferedPacketStoreTest, DifferentPacketAddressOnOneConnection) { QuicSocketAddress addr_with_new_port(QuicIpAddress::Any4(), 256); - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); store_.EnqueuePacket(connection_id, false, packet_, server_address_, client_address_, false, "", invalid_version_); store_.EnqueuePacket(connection_id, false, packet_, server_address_, @@ -111,7 +111,7 @@ EnqueueAndDeliverMultiplePacketsOnMultipleConnections) { size_t num_connections = 10; for (uint64_t conn_id = 1; conn_id <= num_connections; ++conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); store_.EnqueuePacket(connection_id, false, packet_, server_address_, client_address_, false, "", invalid_version_); store_.EnqueuePacket(connection_id, false, packet_, server_address_, @@ -120,7 +120,7 @@ // Deliver packets in reversed order. for (uint64_t conn_id = num_connections; conn_id > 0; --conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); std::list<BufferedPacket> queue = store_.DeliverPackets(connection_id).buffered_packets; ASSERT_EQ(2u, queue.size()); @@ -132,7 +132,7 @@ // Tests that for one connection, only limited number of packets can be // buffered. size_t num_packets = kDefaultMaxUndecryptablePackets + 1; - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); // Arrived CHLO packet shouldn't affect how many non-CHLO pacekts store can // keep. EXPECT_EQ(QuicBufferedPacketStore::SUCCESS, @@ -161,7 +161,7 @@ // connections. const size_t kNumConnections = kMaxConnectionsWithoutCHLO + 1; for (uint64_t conn_id = 1; conn_id <= kNumConnections; ++conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); EnqueuePacketResult result = store_.EnqueuePacket(connection_id, false, packet_, server_address_, client_address_, false, "", invalid_version_); @@ -173,7 +173,7 @@ } // Store only keeps early arrived packets upto |kNumConnections| connections. for (uint64_t conn_id = 1; conn_id <= kNumConnections; ++conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); std::list<BufferedPacket> queue = store_.DeliverPackets(connection_id).buffered_packets; if (conn_id <= kMaxConnectionsWithoutCHLO) { @@ -192,16 +192,16 @@ kDefaultMaxConnectionsInStore - kMaxConnectionsWithoutCHLO + 1; for (uint64_t conn_id = 1; conn_id <= num_chlos; ++conn_id) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, - store_.EnqueuePacket(QuicConnectionIdFromUInt64(conn_id), false, - packet_, server_address_, client_address_, - true, "", valid_version_)); + store_.EnqueuePacket(TestConnectionId(conn_id), false, packet_, + server_address_, client_address_, true, "", + valid_version_)); } // Send data packets on another |kMaxConnectionsWithoutCHLO| connections. // Store should only be able to buffer till it's full. for (uint64_t conn_id = num_chlos + 1; conn_id <= (kDefaultMaxConnectionsInStore + 1); ++conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); EnqueuePacketResult result = store_.EnqueuePacket(connection_id, false, packet_, server_address_, client_address_, true, "", valid_version_); @@ -216,7 +216,7 @@ TEST_F(QuicBufferedPacketStoreTest, EnqueueChloOnTooManyDifferentConnections) { // Buffer data packets on different connections upto limit. for (uint64_t conn_id = 1; conn_id <= kMaxConnectionsWithoutCHLO; ++conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_EQ( EnqueuePacketResult::SUCCESS, store_.EnqueuePacket(connection_id, false, packet_, server_address_, @@ -226,7 +226,7 @@ // Buffer CHLOs on other connections till store is full. for (size_t i = kMaxConnectionsWithoutCHLO + 1; i <= kDefaultMaxConnectionsInStore + 1; ++i) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(i); + QuicConnectionId connection_id = TestConnectionId(i); EnqueuePacketResult rs = store_.EnqueuePacket(connection_id, false, packet_, server_address_, client_address_, true, "", valid_version_); @@ -245,10 +245,10 @@ // delivered at last. EXPECT_EQ(EnqueuePacketResult::SUCCESS, store_.EnqueuePacket( - /*connection_id=*/QuicConnectionIdFromUInt64(1), false, packet_, + /*connection_id=*/TestConnectionId(1), false, packet_, server_address_, client_address_, true, "", valid_version_)); EXPECT_TRUE(store_.HasChloForConnection( - /*connection_id=*/QuicConnectionIdFromUInt64(1))); + /*connection_id=*/TestConnectionId(1))); QuicConnectionId delivered_conn_id; for (size_t i = 0; @@ -258,12 +258,12 @@ // Only CHLO is buffered. EXPECT_EQ(1u, store_.DeliverPacketsForNextConnection(&delivered_conn_id) .buffered_packets.size()); - EXPECT_EQ(QuicConnectionIdFromUInt64(i + kMaxConnectionsWithoutCHLO + 1), + EXPECT_EQ(TestConnectionId(i + kMaxConnectionsWithoutCHLO + 1), delivered_conn_id); } else { EXPECT_EQ(2u, store_.DeliverPacketsForNextConnection(&delivered_conn_id) .buffered_packets.size()); - EXPECT_EQ(QuicConnectionIdFromUInt64(1u), delivered_conn_id); + EXPECT_EQ(TestConnectionId(1u), delivered_conn_id); } } EXPECT_FALSE(store_.HasChlosBuffered()); @@ -272,13 +272,13 @@ // Tests that store expires long-staying connections appropriately for // connections both with and without CHLOs. TEST_F(QuicBufferedPacketStoreTest, PacketQueueExpiredBeforeDelivery) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); store_.EnqueuePacket(connection_id, false, packet_, server_address_, client_address_, false, "", invalid_version_); EXPECT_EQ(EnqueuePacketResult::SUCCESS, store_.EnqueuePacket(connection_id, false, packet_, server_address_, client_address_, true, "", valid_version_)); - QuicConnectionId connection_id2 = QuicConnectionIdFromUInt64(2); + QuicConnectionId connection_id2 = TestConnectionId(2); EXPECT_EQ( EnqueuePacketResult::SUCCESS, store_.EnqueuePacket(connection_id2, false, packet_, server_address_, @@ -286,7 +286,7 @@ // CHLO on connection 3 arrives 1ms later. clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); - QuicConnectionId connection_id3 = QuicConnectionIdFromUInt64(3); + QuicConnectionId connection_id3 = TestConnectionId(3); // Use different client address to differetiate packets from different // connections. QuicSocketAddress another_client_address(QuicIpAddress::Any4(), 255); @@ -321,7 +321,7 @@ // Test the alarm is reset by enqueueing 2 packets for 4th connection and wait // for them to expire. - QuicConnectionId connection_id4 = QuicConnectionIdFromUInt64(4); + QuicConnectionId connection_id4 = TestConnectionId(4); store_.EnqueuePacket(connection_id4, false, packet_, server_address_, client_address_, false, "", invalid_version_); store_.EnqueuePacket(connection_id4, false, packet_, server_address_, @@ -336,7 +336,7 @@ } TEST_F(QuicBufferedPacketStoreTest, SimpleDiscardPackets) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); // Enqueue some packets store_.EnqueuePacket(connection_id, false, packet_, server_address_, @@ -362,7 +362,7 @@ } TEST_F(QuicBufferedPacketStoreTest, DiscardWithCHLOs) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); // Enqueue some packets, which include a CHLO store_.EnqueuePacket(connection_id, false, packet_, server_address_, @@ -390,8 +390,8 @@ } TEST_F(QuicBufferedPacketStoreTest, MultipleDiscardPackets) { - QuicConnectionId connection_id_1 = QuicConnectionIdFromUInt64(1); - QuicConnectionId connection_id_2 = QuicConnectionIdFromUInt64(2); + QuicConnectionId connection_id_1 = TestConnectionId(1); + QuicConnectionId connection_id_2 = TestConnectionId(2); // Enqueue some packets for two connection IDs store_.EnqueuePacket(connection_id_1, false, packet_, server_address_, @@ -429,7 +429,7 @@ TEST_F(QuicBufferedPacketStoreTest, DiscardPacketsEmpty) { // Check that DiscardPackets on an unknown connection ID is safe and does // nothing. - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(11235); + QuicConnectionId connection_id = TestConnectionId(11235); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id);
diff --git a/net/third_party/quic/core/quic_connection.cc b/net/third_party/quic/core/quic_connection.cc index c5dc744..3c1251a 100644 --- a/net/third_party/quic/core/quic_connection.cc +++ b/net/third_party/quic/core/quic_connection.cc
@@ -623,6 +623,7 @@ // Store the new version. framer_.set_version(received_version); + framer_.InferPacketHeaderTypeFromVersion(); version_negotiation_state_ = NEGOTIATED_VERSION; visitor_->OnSuccessfulVersionNegotiation(received_version); @@ -787,6 +788,7 @@ } else { DCHECK_EQ(header.version, version()); version_negotiation_state_ = NEGOTIATED_VERSION; + framer_.InferPacketHeaderTypeFromVersion(); visitor_->OnSuccessfulVersionNegotiation(version()); if (debug_visitor_ != nullptr) { debug_visitor_->OnSuccessfulVersionNegotiation(version());
diff --git a/net/third_party/quic/core/quic_connection_id.cc b/net/third_party/quic/core/quic_connection_id.cc index ee818d4..a3cb9766f 100644 --- a/net/third_party/quic/core/quic_connection_id.cc +++ b/net/third_party/quic/core/quic_connection_id.cc
@@ -4,52 +4,94 @@ #include "net/third_party/quic/core/quic_connection_id.h" +#include <cstdint> +#include <cstring> #include <iomanip> #include "net/third_party/quic/platform/api/quic_endian.h" +#include "net/third_party/quic/platform/api/quic_flag_utils.h" +#include "net/third_party/quic/platform/api/quic_flags.h" #include "net/third_party/quic/platform/api/quic_logging.h" #include "net/third_party/quic/platform/api/quic_text_utils.h" namespace quic { -QuicConnectionId::QuicConnectionId() : id64_(0) {} +namespace { + +bool QuicConnectionIdUseNetworkByteOrder() { + const bool res = GetQuicRestartFlag(quic_connection_ids_network_byte_order); + if (res) { + QUIC_RESTART_FLAG_COUNT(quic_connection_ids_network_byte_order); + } + return res; +} + +} // namespace + +QuicConnectionId::QuicConnectionId() : QuicConnectionId(0) {} QuicConnectionId::QuicConnectionId(uint64_t connection_id64) - : id64_(connection_id64) {} + : length_(sizeof(uint64_t)) { + if (!QuicConnectionIdUseNetworkByteOrder()) { + id64_ = connection_id64; + return; + } + const uint64_t connection_id64_net = QuicEndian::HostToNet64(connection_id64); + memcpy(&data_, &connection_id64_net, sizeof(connection_id64_net)); +} QuicConnectionId::~QuicConnectionId() {} uint64_t QuicConnectionId::ToUInt64() const { - return id64_; + if (!QuicConnectionIdUseNetworkByteOrder()) { + return id64_; + } + uint64_t connection_id64_net; + memcpy(&connection_id64_net, &data_, sizeof(connection_id64_net)); + return QuicEndian::NetToHost64(connection_id64_net); } -const char* QuicConnectionId::data() const { - return reinterpret_cast<const char*>(&id64_); -} - -char* QuicConnectionId::mutable_data() { - return reinterpret_cast<char*>(&id64_); -} - -QuicConnectionIdLength QuicConnectionId::length() const { - return PACKET_8BYTE_CONNECTION_ID; +uint8_t QuicConnectionId::length() const { + return length_; } bool QuicConnectionId::IsEmpty() const { - return id64_ == 0; + return *this == QuicConnectionId(); } size_t QuicConnectionId::Hash() const { - return id64_; + if (!QuicConnectionIdUseNetworkByteOrder()) { + return id64_; + } + uint64_t data_bytes[3] = {0, 0, 0}; + static_assert(sizeof(data_bytes) >= sizeof(data_), "sizeof(data_) changed"); + memcpy(data_bytes, data_, length_); + // This Hash function is designed to return the same value + // as ToUInt64() when the connection ID length is 64 bits. + return QuicEndian::NetToHost64(sizeof(uint64_t) ^ length_ ^ data_bytes[0] ^ + data_bytes[1] ^ data_bytes[2]); +} + +QuicString QuicConnectionId::ToString() const { + if (!QuicConnectionIdUseNetworkByteOrder()) { + return QuicTextUtils::Uint64ToString(id64_); + } + if (IsEmpty()) { + return QuicString("0"); + } + return QuicTextUtils::HexEncode(data_, length_); } std::ostream& operator<<(std::ostream& os, const QuicConnectionId& v) { - os << v.id64_; + os << v.ToString(); return os; } bool QuicConnectionId::operator==(const QuicConnectionId& v) const { - return id64_ == v.id64_; + if (!QuicConnectionIdUseNetworkByteOrder()) { + return id64_ == v.id64_; + } + return length_ == v.length_ && memcmp(data_, v.data_, length_) == 0; } bool QuicConnectionId::operator!=(const QuicConnectionId& v) const { @@ -57,7 +99,16 @@ } bool QuicConnectionId::operator<(const QuicConnectionId& v) const { - return id64_ < v.id64_; + if (!QuicConnectionIdUseNetworkByteOrder()) { + return id64_ < v.id64_; + } + if (length_ < v.length_) { + return true; + } + if (length_ > v.length_) { + return false; + } + return memcmp(data_, v.data_, length_) < 0; } QuicConnectionId EmptyQuicConnectionId() {
diff --git a/net/third_party/quic/core/quic_connection_id.h b/net/third_party/quic/core/quic_connection_id.h index 42b84f4..7d25898 100644 --- a/net/third_party/quic/core/quic_connection_id.h +++ b/net/third_party/quic/core/quic_connection_id.h
@@ -28,14 +28,8 @@ ~QuicConnectionId(); - // Immutable pointer to the connection ID bytes. - const char* data() const; - - // Mutable pointer to the connection ID bytes. - char* mutable_data(); - // Always returns 8. - QuicConnectionIdLength length() const; + uint8_t length() const; // Returns whether the connection ID is zero. bool IsEmpty() const; @@ -46,6 +40,10 @@ // Hash() is required to use connection IDs as keys in hash tables. size_t Hash() const; + // Generates an ASCII string that represents + // the contents of the connection ID, or "0" if it is empty. + QuicString ToString() const; + // operator<< allows easily logging connection IDs. friend QUIC_EXPORT_PRIVATE std::ostream& operator<<( std::ostream& os, @@ -59,11 +57,8 @@ private: // The connection ID is currently represented in host byte order in |id64_|. // In the future, it will be saved in the first |length_| bytes of |data_|. - // - // Fields currently commented out since they trigger -Wunused-private-field - // in Chromium build: - // uint8_t data_[kQuicMaxConnectionIdLength]; - // QuicConnectionIdLength length_; + char data_[kQuicMaxConnectionIdLength]; + uint8_t length_; uint64_t id64_; // host byte order };
diff --git a/net/third_party/quic/core/quic_connection_test.cc b/net/third_party/quic/core/quic_connection_test.cc index a313f98..dd5eb9c 100644 --- a/net/third_party/quic/core/quic_connection_test.cc +++ b/net/third_party/quic/core/quic_connection_test.cc
@@ -800,7 +800,7 @@ class QuicConnectionTest : public QuicTestWithParam<TestParams> { protected: QuicConnectionTest() - : connection_id_(QuicConnectionIdFromUInt64(42)), + : connection_id_(TestConnectionId()), framer_(SupportedVersions(version()), QuicTime::Zero(), Perspective::IS_CLIENT), @@ -1913,8 +1913,7 @@ } TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(42); - TestConnection connection(connection_id, kPeerAddress, helper_.get(), + TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(), alarm_factory_.get(), writer_.get(), Perspective::IS_SERVER, version()); EXPECT_EQ(Perspective::IS_SERVER, connection.perspective()); @@ -1998,7 +1997,7 @@ } TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) { - const QuicConnectionId connection_id = QuicConnectionIdFromUInt64(17); + const QuicConnectionId connection_id = TestConnectionId(17); const QuicByteCount lower_max_packet_size = 1240; writer_->set_max_packet_size(lower_max_packet_size); TestConnection connection(connection_id, kPeerAddress, helper_.get(), @@ -7593,6 +7592,40 @@ QuicConnectionPeer::GetCurrentPacketContent(&connection_)); } +// Regression test for b/120791670 +TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) { + // This test mimics a problematic scenario where an IETF QUIC connection + // receives a Google QUIC packet and continue processing it using Google QUIC + // wire format. + if (version().transport_version <= QUIC_VERSION_43) { + return; + } + set_perspective(Perspective::IS_SERVER); + QuicStreamFrame stream_frame( + QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u, + QuicStringPiece()); + EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); + EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); + ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress, + kPeerAddress); + + // Let connection process a Google QUIC packet. + peer_framer_.set_version_for_tests( + ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43)); + std::unique_ptr<QuicPacket> packet(ConstructDataPacket(2, !kHasStopWaiting)); + char buffer[kMaxPacketSize]; + size_t encrypted_length = peer_framer_.EncryptPayload( + ENCRYPTION_NONE, 2, *packet, buffer, kMaxPacketSize); + // Make sure no stream frame is processed. + EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0); + connection_.ProcessUdpPacket( + kSelfAddress, kPeerAddress, + QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false)); + + EXPECT_EQ(2u, connection_.GetStats().packets_received); + EXPECT_EQ(1u, connection_.GetStats().packets_processed); +} + } // namespace } // namespace test } // namespace quic
diff --git a/net/third_party/quic/core/quic_constants.h b/net/third_party/quic/core/quic_constants.h index 7a22fdf..fe15bda 100644 --- a/net/third_party/quic/core/quic_constants.h +++ b/net/third_party/quic/core/quic_constants.h
@@ -219,7 +219,7 @@ const size_t kQuicConnectionIdLength = 8; // Minimum length of random bytes in IETF stateless reset packet. -const size_t kMinRandomBytesLengthInStatelessReset = 20; +const size_t kMinRandomBytesLengthInStatelessReset = 24; // Maximum length allowed for the token in a NEW_TOKEN frame. const size_t kMaxNewTokenTokenLength = 0xffff;
diff --git a/net/third_party/quic/core/quic_crypto_client_stream_test.cc b/net/third_party/quic/core/quic_crypto_client_stream_test.cc index 0b285cfe..4c1cd66 100644 --- a/net/third_party/quic/core/quic_crypto_client_stream_test.cc +++ b/net/third_party/quic/core/quic_crypto_client_stream_test.cc
@@ -511,7 +511,7 @@ ASSERT_TRUE(client_state->has_server_designated_connection_id()); QuicConnectionId server_designated_id = client_state->GetNextServerDesignatedConnectionId(); - QuicConnectionId expected_id = QuicConnectionIdFromUInt64( + QuicConnectionId expected_id = TestConnectionId( server_session_->connection()->random_generator()->RandUint64()); EXPECT_EQ(expected_id, server_designated_id); EXPECT_FALSE(client_state->has_server_designated_connection_id());
diff --git a/net/third_party/quic/core/quic_crypto_server_stream_test.cc b/net/third_party/quic/core/quic_crypto_server_stream_test.cc index 6794884..77ceb5cc 100644 --- a/net/third_party/quic/core/quic_crypto_server_stream_test.cc +++ b/net/third_party/quic/core/quic_crypto_server_stream_test.cc
@@ -277,8 +277,8 @@ ASSERT_TRUE(client_state->has_server_designated_connection_id()); const QuicConnectionId server_designated_connection_id = client_state->GetNextServerDesignatedConnectionId(); - const QuicConnectionId expected_id = QuicConnectionIdFromUInt64( - server_connection_->random_generator()->RandUint64()); + const QuicConnectionId expected_id = + TestConnectionId(server_connection_->random_generator()->RandUint64()); EXPECT_EQ(expected_id, server_designated_connection_id); EXPECT_FALSE(client_state->has_server_designated_connection_id()); ASSERT_TRUE(client_state->IsComplete(QuicWallTime::FromUNIXSeconds(0))); @@ -308,8 +308,8 @@ ASSERT_TRUE(client_state->has_server_designated_connection_id()); const QuicConnectionId server_designated_connection_id = client_state->GetNextServerDesignatedConnectionId(); - const QuicConnectionId expected_id = QuicConnectionIdFromUInt64( - server_connection_->random_generator()->RandUint64()); + const QuicConnectionId expected_id = + TestConnectionId(server_connection_->random_generator()->RandUint64()); EXPECT_EQ(expected_id, server_designated_connection_id); EXPECT_FALSE(client_state->has_server_designated_connection_id()); ASSERT_TRUE(client_state->IsComplete(QuicWallTime::FromUNIXSeconds(0)));
diff --git a/net/third_party/quic/core/quic_data_writer_test.cc b/net/third_party/quic/core/quic_data_writer_test.cc index 395d96a..fbba0d6 100644 --- a/net/third_party/quic/core/quic_data_writer_test.cc +++ b/net/third_party/quic/core/quic_data_writer_test.cc
@@ -248,7 +248,7 @@ TEST_P(QuicDataWriterTest, WriteConnectionId) { QuicConnectionId connection_id = - QuicConnectionIdFromUInt64(UINT64_C(0x0011223344556677)); + TestConnectionId(UINT64_C(0x0011223344556677)); char big_endian[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, };
diff --git a/net/third_party/quic/core/quic_dispatcher.cc b/net/third_party/quic/core/quic_dispatcher.cc index bccdda8..90444a0 100644 --- a/net/third_party/quic/core/quic_dispatcher.cc +++ b/net/third_party/quic/core/quic_dispatcher.cc
@@ -736,71 +736,53 @@ QuicErrorCode error_code, const QuicString& error_details, QuicTimeWaitListManager::TimeWaitAction action) { - if (GetQuicReloadableFlag(quic_fix_reject_by_session_type)) { - if (format != IETF_QUIC_LONG_HEADER_PACKET) { - QUIC_DVLOG(1) << "Statelessly terminating " << connection_id - << " based on a non-ietf-long packet, action:" << action - << ", error_code:" << error_code - << ", error_details:" << error_details; - time_wait_list_manager_->AddConnectionIdToTimeWait( - connection_id, format != GOOGLE_QUIC_PACKET, action, - /*termination_packets=*/nullptr); - return; - } + if (format != IETF_QUIC_LONG_HEADER_PACKET) { + QUIC_DVLOG(1) << "Statelessly terminating " << connection_id + << " based on a non-ietf-long packet, action:" << action + << ", error_code:" << error_code + << ", error_details:" << error_details; + time_wait_list_manager_->AddConnectionIdToTimeWait( + connection_id, format != GOOGLE_QUIC_PACKET, action, + /*termination_packets=*/nullptr); + return; + } - // If the version is known and supported by framer, send a connection close. - if (framer_.IsSupportedVersion(version)) { - QUIC_DVLOG(1) - << "Statelessly terminating " << connection_id - << " based on an ietf-long packet, which has a supported version:" - << version << ", error_code:" << error_code - << ", error_details:" << error_details; - // Set framer_ to the packet's version such that the connection close can - // be processed by the client. - ParsedQuicVersion original_version = framer_.version(); - framer_.set_version(version); - - StatelessConnectionTerminator terminator(connection_id, &framer_, - helper_.get(), - time_wait_list_manager_.get()); - // This also adds the connection to time wait list. - terminator.CloseConnection(error_code, error_details, true); - - // Restore framer_ to the original version, as if nothing changed in it. - framer_.set_version(original_version); - return; - } - + // If the version is known and supported by framer, send a connection close. + if (framer_.IsSupportedVersion(version)) { QUIC_DVLOG(1) << "Statelessly terminating " << connection_id - << " based on an ietf-long packet, which has an unsupported version:" + << " based on an ietf-long packet, which has a supported version:" << version << ", error_code:" << error_code << ", error_details:" << error_details; - // Version is unknown or unsupported by framer, send a version negotiation - // with an empty version list, which can be understood by the client. - std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; - termination_packets.push_back(QuicFramer::BuildVersionNegotiationPacket( - connection_id, /*ietf_quic=*/true, - ParsedQuicVersionVector{UnsupportedQuicVersion()})); - time_wait_list_manager()->AddConnectionIdToTimeWait( - connection_id, /*ietf_quic=*/true, - QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, - &termination_packets); - return; - } + // Set framer_ to the packet's version such that the connection close can be + // processed by the client. + ParsedQuicVersion original_version = framer_.version(); + framer_.set_version(version); - if (format == IETF_QUIC_LONG_HEADER_PACKET) { - // Send connection close for IETF long header packet, and this also adds - // connection to time wait list. StatelessConnectionTerminator terminator( connection_id, &framer_, helper_.get(), time_wait_list_manager_.get()); + // This also adds the connection to time wait list. terminator.CloseConnection(error_code, error_details, true); + + // Restore framer_ to the original version, as if nothing changed in it. + framer_.set_version(original_version); return; } - time_wait_list_manager_->AddConnectionIdToTimeWait( - connection_id, format != GOOGLE_QUIC_PACKET, action, - /*termination_packets=*/nullptr); + QUIC_DVLOG(1) + << "Statelessly terminating " << connection_id + << " based on an ietf-long packet, which has an unsupported version:" + << version << ", error_code:" << error_code + << ", error_details:" << error_details; + // Version is unknown or unsupported by framer, send a version negotiation + // with an empty version list, which can be understood by the client. + std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; + termination_packets.push_back(QuicFramer::BuildVersionNegotiationPacket( + connection_id, /*ietf_quic=*/true, + ParsedQuicVersionVector{UnsupportedQuicVersion()})); + time_wait_list_manager()->AddConnectionIdToTimeWait( + connection_id, /*ietf_quic=*/true, + QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, &termination_packets); } void QuicDispatcher::OnPacket() {} @@ -1074,10 +1056,7 @@ EnqueuePacketResult rs = buffered_packets_.EnqueuePacket( connection_id, ietf_quic, *current_packet_, current_self_address_, current_peer_address_, /*is_chlo=*/false, - /*alpn=*/"", - GetQuicReloadableFlag(quic_fix_reject_by_session_type) - ? version - : UnsupportedQuicVersion()); + /*alpn=*/"", version); if (rs != EnqueuePacketResult::SUCCESS) { OnBufferPacketFailure(rs, connection_id); }
diff --git a/net/third_party/quic/core/quic_dispatcher_test.cc b/net/third_party/quic/core/quic_dispatcher_test.cc index 78c6624..919cc7f 100644 --- a/net/third_party/quic/core/quic_dispatcher_test.cc +++ b/net/third_party/quic/core/quic_dispatcher_test.cc
@@ -375,21 +375,21 @@ server_address_ = QuicSocketAddress(QuicIpAddress::Any4(), 5); EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(1), client_address, + CreateQuicSession(TestConnectionId(1), client_address, QuicStringPiece(""), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(1), - client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(1), client_address, + &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(1), packet); + ValidatePacket(TestConnectionId(1), packet); }))); - EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(1), _)); + EXPECT_CALL(*dispatcher_, + ShouldCreateOrBufferPacketForConnection(TestConnectionId(1), _)); ProcessPacket( - client_address, QuicConnectionIdFromUInt64(1), true, + client_address, TestConnectionId(1), true, ParsedQuicVersion(PROTOCOL_TLS1_3, CurrentSupportedVersions().front().transport_version), SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, @@ -403,48 +403,46 @@ server_address_ = QuicSocketAddress(QuicIpAddress::Any4(), 5); EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(1), client_address, + CreateQuicSession(TestConnectionId(1), client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(1), - client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(1), client_address, + &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(1), packet); + ValidatePacket(TestConnectionId(1), packet); }))); - EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(1), _)); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(1), true, - SerializeCHLO()); + EXPECT_CALL(*dispatcher_, + ShouldCreateOrBufferPacketForConnection(TestConnectionId(1), _)); + ProcessPacket(client_address, TestConnectionId(1), true, SerializeCHLO()); EXPECT_EQ(client_address, dispatcher_->current_peer_address()); EXPECT_EQ(server_address_, dispatcher_->current_self_address()); EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(2), client_address, + CreateQuicSession(TestConnectionId(2), client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(2), - client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(2), client_address, + &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(2), packet); + ValidatePacket(TestConnectionId(2), packet); }))); - EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(2), _)); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(2), true, - SerializeCHLO()); + EXPECT_CALL(*dispatcher_, + ShouldCreateOrBufferPacketForConnection(TestConnectionId(2), _)); + ProcessPacket(client_address, TestConnectionId(2), true, SerializeCHLO()); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(1) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(1), packet); + ValidatePacket(TestConnectionId(1), packet); }))); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(1), false, "data"); + ProcessPacket(client_address, TestConnectionId(1), false, "data"); } // Regression test of b/93325907. @@ -453,11 +451,11 @@ server_address_ = QuicSocketAddress(QuicIpAddress::Any4(), 5); EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(1), client_address, + CreateQuicSession(TestConnectionId(1), client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(1), - client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(1), client_address, + &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); // Verify both packets 1 and 2 are processed by connection 1. EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), @@ -465,12 +463,12 @@ .Times(2) .WillRepeatedly( WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(1), packet); + ValidatePacket(TestConnectionId(1), packet); }))); - EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(1), _)); + EXPECT_CALL(*dispatcher_, + ShouldCreateOrBufferPacketForConnection(TestConnectionId(1), _)); ProcessPacket( - client_address, QuicConnectionIdFromUInt64(1), true, + client_address, TestConnectionId(1), true, ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, CurrentSupportedVersions().front().transport_version), SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, @@ -478,7 +476,7 @@ // Packet number 256 with packet number length 1 would be considered as 0 in // dispatcher. ProcessPacket( - client_address, QuicConnectionIdFromUInt64(1), false, + client_address, TestConnectionId(1), false, ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, CurrentSupportedVersions().front().transport_version), "", PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_PACKET_NUMBER, 256); @@ -499,8 +497,8 @@ QuicTransportVersion version = static_cast<QuicTransportVersion>(QuicTransportVersionMin() - 1); ParsedQuicVersion parsed_version(PROTOCOL_QUIC_CRYPTO, version); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(1), true, - parsed_version, SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, + ProcessPacket(client_address, TestConnectionId(1), true, parsed_version, + SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); } @@ -521,8 +519,8 @@ // Truncate to 1100 bytes of payload which results in a packet just // under 1200 bytes after framing, packet, and encryption overhead. QuicString truncated_chlo = chlo.substr(0, 1100); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(1), true, - parsed_version, truncated_chlo, PACKET_8BYTE_CONNECTION_ID, + ProcessPacket(client_address, TestConnectionId(1), true, parsed_version, + truncated_chlo, PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); } @@ -532,19 +530,18 @@ EXPECT_CALL(*dispatcher_, CreateQuicSession(_, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(1), - client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(1), client_address, + &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(1), packet); + ValidatePacket(TestConnectionId(1), packet); }))); - EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(1), _)); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(1), true, - SerializeCHLO()); + EXPECT_CALL(*dispatcher_, + ShouldCreateOrBufferPacketForConnection(TestConnectionId(1), _)); + ProcessPacket(client_address, TestConnectionId(1), true, SerializeCHLO()); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); @@ -557,7 +554,7 @@ // Create a new session. QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( @@ -567,11 +564,11 @@ EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(1), packet); + ValidatePacket(TestConnectionId(1), packet); }))); - EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(1), _)); + EXPECT_CALL(*dispatcher_, + ShouldCreateOrBufferPacketForConnection(TestConnectionId(1), _)); ProcessPacket(client_address, connection_id, true, SerializeCHLO()); // Now close the connection, which should add it to the time wait list. @@ -594,7 +591,7 @@ CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); // Dispatcher forwards all packets for this connection_id to the time wait // list manager. EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, QuicStringPiece("hq"), _)) @@ -614,32 +611,31 @@ // dispatcher_ should drop this packet. EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(1), client_address, + CreateQuicSession(TestConnectionId(1), client_address, QuicStringPiece("hq"), _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _, _, _)) .Times(0); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(1), true, - SerializeCHLO()); + ProcessPacket(client_address, TestConnectionId(1), true, SerializeCHLO()); } TEST_F(QuicDispatcherTest, OKSeqNoPacketProcessed) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); server_address_ = QuicSocketAddress(QuicIpAddress::Any4(), 5); EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(1), client_address, + CreateQuicSession(TestConnectionId(1), client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(1), - client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(1), client_address, + &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(1), packet); + ValidatePacket(TestConnectionId(1), packet); }))); // A packet whose packet number is the largest that is allowed to start a @@ -657,17 +653,17 @@ CreateTimeWaitListManager(); SetQuicRestartFlag(quic_enable_accept_random_ipn, false); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); // Dispatcher forwards this packet for this connection_id to the time wait // list manager. EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, QuicStringPiece("hq"), _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, - ProcessPacket(_, _, QuicConnectionIdFromUInt64(1), _)) + ProcessPacket(_, _, TestConnectionId(1), _)) .Times(1); EXPECT_CALL(*time_wait_list_manager_, - ProcessPacket(_, _, QuicConnectionIdFromUInt64(2), _)) + ProcessPacket(_, _, TestConnectionId(2), _)) .Times(1); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _, _, _)) .Times(2); @@ -676,7 +672,7 @@ ProcessPacket(client_address, connection_id, true, SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, QuicDispatcher::kMaxReasonableInitialPacketNumber + 1); - connection_id = QuicConnectionIdFromUInt64(2); + connection_id = TestConnectionId(2); SetQuicRestartFlag(quic_enable_accept_random_ipn, true); ProcessPacket(client_address, connection_id, true, SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, @@ -696,7 +692,7 @@ QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); server_address_ = QuicSocketAddress(QuicIpAddress::Any4(), 5); uint64_t conn_id = 1; - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) @@ -706,7 +702,7 @@ static_cast<QuicTransportVersion>(QuicTransportVersionMin() - 1)); ProcessPacket(client_address, connection_id, true, version, SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( @@ -726,7 +722,7 @@ QuicVersionMin().transport_version), SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( @@ -747,7 +743,7 @@ // Turn off version 46. SetQuicReloadableFlag(quic_enable_version_46, false); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .Times(0); @@ -758,7 +754,7 @@ // Turn on version 46. SetQuicReloadableFlag(quic_enable_version_46, true); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( @@ -780,7 +776,7 @@ // Turn off version 45. SetQuicReloadableFlag(quic_enable_version_45, false); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .Times(0); @@ -791,7 +787,7 @@ // Turn on version 45. SetQuicReloadableFlag(quic_enable_version_45, true); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( @@ -813,7 +809,7 @@ // Turn off version 44. SetQuicReloadableFlag(quic_enable_version_44, false); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .Times(0); @@ -824,7 +820,7 @@ // Turn on version 44. SetQuicReloadableFlag(quic_enable_version_44, true); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( @@ -846,7 +842,7 @@ // Turn off version 43. SetQuicReloadableFlag(quic_enable_version_43, false); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .Times(0); @@ -857,7 +853,7 @@ // Turn on version 43. SetQuicReloadableFlag(quic_enable_version_43, true); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( @@ -879,7 +875,7 @@ // Turn off version 35. SetQuicReloadableFlag(quic_disable_version_35, true); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .Times(0); @@ -890,7 +886,7 @@ // Turn on version 35. SetQuicReloadableFlag(quic_disable_version_35, false); - connection_id = QuicConnectionIdFromUInt64(++conn_id); + connection_id = TestConnectionId(++conn_id); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( @@ -1045,7 +1041,7 @@ CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return( @@ -1098,7 +1094,7 @@ CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); if (GetParam().enable_stateless_rejects_via_flag) { EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, client_address, _, _)) @@ -1150,7 +1146,7 @@ CreateTimeWaitListManager(); const QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); - const QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + const QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection(connection_id, _)) @@ -1203,7 +1199,7 @@ CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, QuicStringPiece("hq"), _)) .Times(0); if (CurrentSupportedVersions()[0].transport_version > QUIC_VERSION_43) { @@ -1256,34 +1252,32 @@ EXPECT_CALL(*dispatcher_, CreateQuicSession(_, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(1), - client_address, &helper_, &alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(1), client_address, + &helper_, &alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(1), packet); + ValidatePacket(TestConnectionId(1), packet); }))); EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(1), _)); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(1), true, - SerializeCHLO()); + TestConnectionId(1), _)); + ProcessPacket(client_address, TestConnectionId(1), true, SerializeCHLO()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, client_address, QuicStringPiece("hq"), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(2), - client_address, &helper_, &alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(2), client_address, + &helper_, &alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(2), packet); + ValidatePacket(TestConnectionId(2), packet); }))); EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(2), _)); - ProcessPacket(client_address, QuicConnectionIdFromUInt64(2), true, - SerializeCHLO()); + TestConnectionId(2), _)); + ProcessPacket(client_address, TestConnectionId(2), true, SerializeCHLO()); blocked_list_ = QuicDispatcherPeer::GetWriteBlockedList(dispatcher_.get()); } @@ -1641,7 +1635,7 @@ InSequence s; QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); server_address_ = QuicSocketAddress(QuicIpAddress::Any4(), 5); - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id = TestConnectionId(1); // A bunch of non-CHLO should be buffered upon arrival, and the first one // should trigger ShouldCreateOrBufferPacketForConnection(). EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection(conn_id, _)) @@ -1685,7 +1679,7 @@ size_t kNumConnections = kMaxConnectionsWithoutCHLO + 1; for (size_t i = 1; i <= kNumConnections; ++i) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), i); - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(i); + QuicConnectionId conn_id = TestConnectionId(i); EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection(conn_id, _)); ProcessPacket(client_address, conn_id, true, @@ -1696,7 +1690,7 @@ // Pop out the packet on last connection as it shouldn't be enqueued in store // as well. - data_connection_map_[QuicConnectionIdFromUInt64(kNumConnections)].pop_front(); + data_connection_map_[TestConnectionId(kNumConnections)].pop_front(); // Reset session creation counter to ensure processing CHLO can always // create session. @@ -1705,7 +1699,7 @@ // Process CHLOs to create session for these connections. for (size_t i = 1; i <= kNumConnections; ++i) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), i); - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(i); + QuicConnectionId conn_id = TestConnectionId(i); if (i == kNumConnections) { EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection(conn_id, _)); @@ -1733,7 +1727,7 @@ // Tests that store delivers empty packet list if CHLO arrives firstly. TEST_P(BufferedPacketStoreTest, DeliverEmptyPackets) { - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id = TestConnectionId(1); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection(conn_id, _)); @@ -1754,7 +1748,7 @@ InSequence s; QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); server_address_ = QuicSocketAddress(QuicIpAddress::Any4(), 5); - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id = TestConnectionId(1); ProcessPacket(client_address, conn_id, true, QuicStrCat("data packet ", 2), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, /*packet_number=*/2); @@ -1790,7 +1784,7 @@ QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); server_address_ = QuicSocketAddress(QuicIpAddress::Any4(), 5); - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id = TestConnectionId(1); ProcessPacket(client_address, conn_id, true, QuicStrCat("data packet ", 2), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, /*packet_number=*/2); @@ -1820,13 +1814,13 @@ kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore + 1; for (uint64_t conn_id = 1; conn_id <= kNumCHLOs; ++conn_id) { EXPECT_CALL(*dispatcher_, ShouldCreateOrBufferPacketForConnection( - QuicConnectionIdFromUInt64(conn_id), _)); + TestConnectionId(conn_id), _)); if (conn_id <= kMaxNumSessionsToCreate) { EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(conn_id), - client_addr_, QuicStringPiece(), _)) + CreateQuicSession(TestConnectionId(conn_id), client_addr_, + QuicStringPiece(), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(conn_id), + dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); @@ -1835,21 +1829,19 @@ ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(conn_id), packet); + ValidatePacket(TestConnectionId(conn_id), packet); }))); } - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(conn_id), true, + ProcessPacket(client_addr_, TestConnectionId(conn_id), true, SerializeFullCHLO()); if (conn_id <= kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore && conn_id > kMaxNumSessionsToCreate) { - EXPECT_TRUE( - store->HasChloForConnection(QuicConnectionIdFromUInt64(conn_id))); + EXPECT_TRUE(store->HasChloForConnection(TestConnectionId(conn_id))); } else { // First |kMaxNumSessionsToCreate| CHLOs should be passed to new // connections immediately, and the last CHLO should be dropped as the // store is full. - EXPECT_FALSE( - store->HasChloForConnection(QuicConnectionIdFromUInt64(conn_id))); + EXPECT_FALSE(store->HasChloForConnection(TestConnectionId(conn_id))); } } @@ -1859,32 +1851,31 @@ conn_id <= kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore; ++conn_id) { EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(conn_id), - client_addr_, QuicStringPiece(), _)) + CreateQuicSession(TestConnectionId(conn_id), client_addr_, + QuicStringPiece(), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(conn_id), - client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, + &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(conn_id), packet); + ValidatePacket(TestConnectionId(conn_id), packet); }))); } EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(kNumCHLOs), - client_addr_, QuicStringPiece(), _)) + CreateQuicSession(TestConnectionId(kNumCHLOs), client_addr_, + QuicStringPiece(), _)) .Times(0); while (store->HasChlosBuffered()) { dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate); } - EXPECT_EQ( - QuicConnectionIdFromUInt64(static_cast<size_t>(kMaxNumSessionsToCreate) + - kDefaultMaxConnectionsInStore), - session1_->connection_id()); + EXPECT_EQ(TestConnectionId(static_cast<size_t>(kMaxNumSessionsToCreate) + + kDefaultMaxConnectionsInStore), + session1_->connection_id()); } // Duplicated CHLO shouldn't be buffered. @@ -1894,10 +1885,10 @@ // Last CHLO will be buffered. Others will create connection right away. if (conn_id <= kMaxNumSessionsToCreate) { EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(conn_id), - client_addr_, QuicStringPiece(), _)) + CreateQuicSession(TestConnectionId(conn_id), client_addr_, + QuicStringPiece(), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(conn_id), + dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); @@ -1906,15 +1897,15 @@ ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(conn_id), packet); + ValidatePacket(TestConnectionId(conn_id), packet); }))); } - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(conn_id), true, + ProcessPacket(client_addr_, TestConnectionId(conn_id), true, SerializeFullCHLO()); } // Retransmit CHLO on last connection should be dropped. QuicConnectionId last_connection = - QuicConnectionIdFromUInt64(kMaxNumSessionsToCreate + 1); + TestConnectionId(kMaxNumSessionsToCreate + 1); ProcessPacket(client_addr_, last_connection, true, SerializeFullCHLO()); size_t packets_buffered = 2; @@ -1939,16 +1930,15 @@ TEST_P(BufferedPacketStoreTest, BufferNonChloPacketsUptoLimitWithChloBuffered) { uint64_t last_conn_id = kMaxNumSessionsToCreate + 1; - QuicConnectionId last_connection_id = - QuicConnectionIdFromUInt64(last_conn_id); + QuicConnectionId last_connection_id = TestConnectionId(last_conn_id); for (uint64_t conn_id = 1; conn_id <= last_conn_id; ++conn_id) { // Last CHLO will be buffered. Others will create connection right away. if (conn_id <= kMaxNumSessionsToCreate) { EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(conn_id), - client_addr_, QuicStringPiece(), _)) + CreateQuicSession(TestConnectionId(conn_id), client_addr_, + QuicStringPiece(), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(conn_id), + dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); @@ -1957,10 +1947,10 @@ ProcessUdpPacket(_, _, _)) .WillRepeatedly(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(conn_id), packet); + ValidatePacket(TestConnectionId(conn_id), packet); }))); } - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(conn_id), true, + ProcessPacket(client_addr_, TestConnectionId(conn_id), true, SerializeFullCHLO()); } @@ -1997,9 +1987,8 @@ QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); uint64_t conn_id = 1; - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(conn_id), true, - "data packet", PACKET_8BYTE_CONNECTION_ID, - PACKET_4BYTE_PACKET_NUMBER, + ProcessPacket(client_addr_, TestConnectionId(conn_id), true, "data packet", + PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, /*packet_number=*/1); // Fill packet buffer to full with CHLOs on other connections. Need to feed // extra CHLOs because the first |kMaxNumSessionsToCreate| are going to create @@ -2009,10 +1998,10 @@ ++conn_id) { if (conn_id <= kMaxNumSessionsToCreate + 1) { EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(conn_id), - client_addr_, QuicStringPiece(), _)) + CreateQuicSession(TestConnectionId(conn_id), client_addr_, + QuicStringPiece(), _)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(conn_id), + dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); @@ -2021,20 +2010,20 @@ ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(conn_id), packet); + ValidatePacket(TestConnectionId(conn_id), packet); }))); } - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(conn_id), true, + ProcessPacket(client_addr_, TestConnectionId(conn_id), true, SerializeFullCHLO()); } EXPECT_FALSE(store->HasChloForConnection( - /*connection_id=*/QuicConnectionIdFromUInt64(1))); + /*connection_id=*/TestConnectionId(1))); // CHLO on connection 1 should still be buffered. - ProcessPacket(client_addr_, /*connection_id=*/QuicConnectionIdFromUInt64(1), - true, SerializeFullCHLO()); + ProcessPacket(client_addr_, /*connection_id=*/TestConnectionId(1), true, + SerializeFullCHLO()); EXPECT_TRUE(store->HasChloForConnection( - /*connection_id=*/QuicConnectionIdFromUInt64(1))); + /*connection_id=*/TestConnectionId(1))); } // Regression test for b/117874922. @@ -2050,10 +2039,10 @@ supported_versions[(conn_id - 1) % supported_versions.size()]; if (conn_id <= kMaxNumSessionsToCreate) { EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(conn_id), - client_addr_, QuicStringPiece(), version)) + CreateQuicSession(TestConnectionId(conn_id), client_addr_, + QuicStringPiece(), version)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(conn_id), + dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); @@ -2062,11 +2051,11 @@ ProcessUdpPacket(_, _, _)) .WillRepeatedly(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(conn_id), packet); + ValidatePacket(TestConnectionId(conn_id), packet); }))); } - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(conn_id), true, - version, SerializeFullCHLO(), PACKET_8BYTE_CONNECTION_ID, + ProcessPacket(client_addr_, TestConnectionId(conn_id), true, version, + SerializeFullCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); } @@ -2076,17 +2065,17 @@ ParsedQuicVersion version = supported_versions[(conn_id - 1) % supported_versions.size()]; EXPECT_CALL(*dispatcher_, - CreateQuicSession(QuicConnectionIdFromUInt64(conn_id), - client_addr_, QuicStringPiece(), version)) + CreateQuicSession(TestConnectionId(conn_id), client_addr_, + QuicStringPiece(), version)) .WillOnce(testing::Return(CreateSession( - dispatcher_.get(), config_, QuicConnectionIdFromUInt64(conn_id), - client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, + dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, + &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillRepeatedly(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { - ValidatePacket(QuicConnectionIdFromUInt64(conn_id), packet); + ValidatePacket(TestConnectionId(conn_id), packet); }))); } dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate); @@ -2197,7 +2186,7 @@ // Test a simple situation of connections which the StatelessRejector will // accept. TEST_F(AsyncGetProofTest, BasicAccept) { - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id = TestConnectionId(1); testing::MockFunction<void(int check_point)> check; { @@ -2243,8 +2232,8 @@ } TEST_F(AsyncGetProofTest, RestorePacketContext) { - QuicConnectionId conn_id_1 = QuicConnectionIdFromUInt64(1); - QuicConnectionId conn_id_2 = QuicConnectionIdFromUInt64(2); + QuicConnectionId conn_id_1 = TestConnectionId(1); + QuicConnectionId conn_id_2 = TestConnectionId(2); testing::MockFunction<void(int check_point)> check; { @@ -2330,7 +2319,7 @@ TEST_F(AsyncGetProofTest, BasicReject) { CreateTimeWaitListManager(); - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id = TestConnectionId(1); testing::MockFunction<void(int check_point)> check; { @@ -2367,8 +2356,8 @@ // Test a situation with multiple interleaved connections which the // StatelessRejector will accept. TEST_F(AsyncGetProofTest, MultipleAccept) { - QuicConnectionId conn_id_1 = QuicConnectionIdFromUInt64(1); - QuicConnectionId conn_id_2 = QuicConnectionIdFromUInt64(2); + QuicConnectionId conn_id_1 = TestConnectionId(1); + QuicConnectionId conn_id_2 = TestConnectionId(2); QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); @@ -2452,8 +2441,8 @@ TEST_F(AsyncGetProofTest, MultipleReject) { CreateTimeWaitListManager(); - QuicConnectionId conn_id_1 = QuicConnectionIdFromUInt64(1); - QuicConnectionId conn_id_2 = QuicConnectionIdFromUInt64(2); + QuicConnectionId conn_id_1 = TestConnectionId(1); + QuicConnectionId conn_id_2 = TestConnectionId(2); QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); @@ -2523,7 +2512,7 @@ TEST_F(AsyncGetProofTest, MultipleIdenticalReject) { CreateTimeWaitListManager(); - QuicConnectionId conn_id_1 = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id_1 = TestConnectionId(1); QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); @@ -2568,7 +2557,7 @@ TEST_F(AsyncGetProofTest, BufferTimeout) { CreateTimeWaitListManager(); - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id = TestConnectionId(1); QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); QuicBufferedPacketStorePeer::set_clock(store, mock_helper_.GetClock()); @@ -2620,7 +2609,7 @@ // out of the time wait manager while CHLO validation is still pending. This // *should* be impossible, but anything can happen with timing conditions. TEST_F(AsyncGetProofTest, TimeWaitTimeout) { - QuicConnectionId conn_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId conn_id = TestConnectionId(1); QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); QuicBufferedPacketStorePeer::set_clock(store, mock_helper_.GetClock()); @@ -2703,7 +2692,7 @@ ParsedQuicVersion chlo_version(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_39); chlo_.SetVersion(kVER, chlo_version); // Send a CHLO with v39. Dispatcher framer's version is set to v39. - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(1), true, chlo_version, + ProcessPacket(client_addr_, TestConnectionId(1), true, chlo_version, SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); @@ -2712,7 +2701,7 @@ chlo_.SetVersion(kVER, chlo_version); // Invalidate the cached serialized form. chlo_.MarkDirty(); - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(2), true, chlo_version, + ProcessPacket(client_addr_, TestConnectionId(2), true, chlo_version, SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); ASSERT_EQ(GetFakeProofSource()->NumPendingCallbacks(), 2); @@ -2730,7 +2719,7 @@ // Process a packet of v44. ParsedQuicVersion chlo_version(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_44); chlo_.SetVersion(kVER, chlo_version); - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(1), true, chlo_version, + ProcessPacket(client_addr_, TestConnectionId(1), true, chlo_version, SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); EXPECT_NE(GOOGLE_QUIC_PACKET, dispatcher_->GetLastPacketFormat()); @@ -2740,7 +2729,7 @@ chlo_.SetVersion(kVER, chlo_version); // Invalidate the cached serialized form. chlo_.MarkDirty(); - ProcessPacket(client_addr_, QuicConnectionIdFromUInt64(2), true, chlo_version, + ProcessPacket(client_addr_, TestConnectionId(2), true, chlo_version, SerializeCHLO(), PACKET_8BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, 1); EXPECT_EQ(GOOGLE_QUIC_PACKET, dispatcher_->GetLastPacketFormat());
diff --git a/net/third_party/quic/core/quic_framer.cc b/net/third_party/quic/core/quic_framer.cc index 0b2323ab..7500f6a 100644 --- a/net/third_party/quic/core/quic_framer.cc +++ b/net/third_party/quic/core/quic_framer.cc
@@ -253,7 +253,9 @@ last_timestamp_(QuicTime::Delta::Zero()), data_producer_(nullptr), process_stateless_reset_at_client_only_( - GetQuicReloadableFlag(quic_process_stateless_reset_at_client_only)) { + GetQuicReloadableFlag(quic_process_stateless_reset_at_client_only)), + infer_packet_header_type_from_version_(perspective == + Perspective::IS_CLIENT) { DCHECK(!supported_versions.empty()); version_ = supported_versions_[0]; decrypter_ = QuicMakeUnique<NullDecrypter>(perspective); @@ -1111,9 +1113,7 @@ } reset.SetStringPiece(kCADR, serialized_address); } - if (GetQuicReloadableFlag(quic_enable_server_epid_in_public_reset) && - !packet.endpoint_id.empty()) { - QUIC_RELOADABLE_FLAG_COUNT(quic_enable_server_epid_in_public_reset); + if (!packet.endpoint_id.empty()) { reset.SetStringPiece(kEPID, packet.endpoint_id); } const QuicData& reset_serialized = reset.GetSerialized(); @@ -1160,6 +1160,7 @@ QuicDataWriter writer(len, buffer.get(), NETWORK_BYTE_ORDER); uint8_t type = 0; + type |= FLAGS_FIXED_BIT; type |= FLAGS_SHORT_HEADER_RESERVED_1; type |= FLAGS_SHORT_HEADER_RESERVED_2; type |= PacketNumberLengthToShortHeaderType(PACKET_1BYTE_PACKET_NUMBER); @@ -1174,6 +1175,7 @@ random_bytes_length)) { return nullptr; } + QUIC_RELOADABLE_FLAG_COUNT(quic_more_random_bytes_in_stateless_reset); } else { // Append an random packet number. QuicPacketNumber random_packet_number = @@ -1274,7 +1276,7 @@ QuicDataReader reader(packet.data(), packet.length(), endianness()); bool last_packet_is_ietf_quic = false; - if (perspective_ == Perspective::IS_CLIENT) { + if (infer_packet_header_type_from_version_) { last_packet_is_ietf_quic = version_.transport_version > QUIC_VERSION_43; } else if (!reader.IsDoneReading()) { uint8_t type = reader.PeekByte(); @@ -1980,13 +1982,6 @@ header->form = type & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET : IETF_QUIC_SHORT_HEADER_PACKET; if (header->form == IETF_QUIC_LONG_HEADER_PACKET) { - // Get long packet type. - header->long_packet_type = - static_cast<QuicLongHeaderType>(type & kQuicLongHeaderTypeMask); - if (header->long_packet_type < ZERO_RTT_PROTECTED || - header->long_packet_type > INITIAL) { - header->long_packet_type = VERSION_NEGOTIATION; - } QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: " << QuicUtils::QuicLongHeaderTypetoString( header->long_packet_type); @@ -2003,6 +1998,32 @@ header->source_connection_id_length = perspective_ == Perspective::IS_CLIENT ? PACKET_8BYTE_CONNECTION_ID : PACKET_0BYTE_CONNECTION_ID; + // Read version tag. + QuicVersionLabel version_label; + if (!reader->ReadTag(&version_label)) { + set_detailed_error("Unable to read protocol version."); + return false; + } + // TODO(rch): Use ReadUInt32() once QUIC_VERSION_35 is removed. + version_label = QuicEndian::NetToHost32(version_label); + if (!version_label) { + // Version label is 0 indicating this is a version negotiation packet. + header->long_packet_type = VERSION_NEGOTIATION; + } else { + header->version = ParseQuicVersionLabel(version_label); + header->long_packet_type = + static_cast<QuicLongHeaderType>(type & kQuicLongHeaderTypeMask); + if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED && + (header->long_packet_type < ZERO_RTT_PROTECTED || + header->long_packet_type > INITIAL)) { + set_detailed_error("Illegal long header type value."); + return false; + } + } + if (header->long_packet_type != VERSION_NEGOTIATION) { + // Do not save version of version negotiation packet. + last_version_label_ = version_label; + } } else { QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header"; QuicShortHeaderType short_type = @@ -2030,26 +2051,7 @@ QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length; } - QuicVersionLabel version_label; if (header->form == IETF_QUIC_LONG_HEADER_PACKET) { - // Read version tag. - if (!reader->ReadTag(&version_label)) { - set_detailed_error("Unable to read protocol version."); - return false; - } - // TODO(rch): Use ReadUInt32() once QUIC_VERSION_35 is removed. - version_label = QuicEndian::NetToHost32(version_label); - if (header->long_packet_type == VERSION_NEGOTIATION && version_label) { - // Version negotiation is identified by the version field. - set_detailed_error("Illegal long header type value."); - return false; - } - header->version = ParseQuicVersionLabel(version_label); - if (header->long_packet_type != VERSION_NEGOTIATION) { - // Do not save version of version negotiation packet. - last_version_label_ = version_label; - } - // Read and validate connection ID length. uint8_t connection_id_length; if (!reader->ReadBytes(&connection_id_length, 1)) { @@ -5027,5 +5029,13 @@ return type_byte; } +void QuicFramer::InferPacketHeaderTypeFromVersion() { + // This function should only be called when server connection negotiates the + // version. + DCHECK(perspective_ == Perspective::IS_SERVER && + !infer_packet_header_type_from_version_); + infer_packet_header_type_from_version_ = true; +} + #undef ENDPOINT // undef for jumbo builds } // namespace quic
diff --git a/net/third_party/quic/core/quic_framer.h b/net/third_party/quic/core/quic_framer.h index c5b6e432..1059eed 100644 --- a/net/third_party/quic/core/quic_framer.h +++ b/net/third_party/quic/core/quic_framer.h
@@ -489,6 +489,9 @@ version_ = versions[0]; } + // Tell framer to infer packet header type from version_. + void InferPacketHeaderTypeFromVersion(); + // Returns true if data with |offset| of stream |id| starts with 'CHLO'. bool StartsWithChlo(QuicStreamId id, QuicStreamOffset offset) const; @@ -867,6 +870,11 @@ // Latched value of quic_process_stateless_reset_at_client_only flag. const bool process_stateless_reset_at_client_only_; + + // If true, framer infers packet header type (IETF/GQUIC) from version_. + // Otherwise, framer infers packet header type from first byte of a received + // packet. + bool infer_packet_header_type_from_version_; }; } // namespace quic
diff --git a/net/third_party/quic/core/quic_framer_test.cc b/net/third_party/quic/core/quic_framer_test.cc index cacf39f..03e7925 100644 --- a/net/third_party/quic/core/quic_framer_test.cc +++ b/net/third_party/quic/core/quic_framer_test.cc
@@ -43,10 +43,14 @@ // Use fields in which each byte is distinct to ensure that every byte is // framed correctly. The values are otherwise arbitrary. -const QuicConnectionId kConnectionId = - QuicConnectionIdFromUInt64(UINT64_C(0xFEDCBA9876543210)); -const QuicConnectionId kConnectionIdPlusOne = - QuicConnectionIdFromUInt64(UINT64_C(0xFEDCBA9876543210) + 1); +QuicConnectionId FramerTestConnectionId() { + return TestConnectionId(UINT64_C(0xFEDCBA9876543210)); +} + +QuicConnectionId FramerTestConnectionIdPlusOne() { + return TestConnectionId(UINT64_C(0xFEDCBA9876543211)); +} + const QuicPacketNumber kPacketNumber = UINT64_C(0x12345678); const QuicPacketNumber kSmallLargestObserved = UINT16_C(0x1234); const QuicPacketNumber kSmallMissingPacket = UINT16_C(0x1233); @@ -765,7 +769,8 @@ ASSERT_TRUE(visitor_.header_.get()); // Make sure we've parsed the packet header, so we can send an error. - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); // Make sure the correct error is propagated. EXPECT_EQ(QUIC_PACKET_TOO_LARGE, framer_.error()); } @@ -810,7 +815,8 @@ EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(QUIC_MISSING_PAYLOAD, framer_.error()); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); @@ -849,7 +855,8 @@ EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(QUIC_MISSING_PAYLOAD, framer_.error()); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_TRUE(visitor_.header_->version_flag); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); @@ -858,7 +865,8 @@ } TEST_P(QuicFramerTest, PacketHeaderWith0ByteConnectionId) { - QuicFramerPeer::SetLastSerializedConnectionId(&framer_, kConnectionId); + QuicFramerPeer::SetLastSerializedConnectionId(&framer_, + FramerTestConnectionId()); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); // clang-format off @@ -903,7 +911,8 @@ EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(QUIC_MISSING_PAYLOAD, framer_.error()); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); @@ -972,7 +981,8 @@ EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(QUIC_MISSING_PAYLOAD, framer_.error()); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_TRUE(visitor_.header_->version_flag); EXPECT_EQ(GetParam(), visitor_.header_->version); @@ -1032,7 +1042,8 @@ EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(QUIC_MISSING_PAYLOAD, framer_.error()); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); @@ -1091,7 +1102,8 @@ EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(QUIC_MISSING_PAYLOAD, framer_.error()); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); @@ -1137,7 +1149,8 @@ EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(QUIC_MISSING_PAYLOAD, framer_.error()); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); @@ -1150,7 +1163,7 @@ // Test the case when a packet is received from the past and future packet // numbers are still calculated relative to the largest received packet. QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber - 2; @@ -1164,7 +1177,8 @@ QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber - 2, visitor_.header_->packet_number); @@ -1177,7 +1191,8 @@ QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(encrypted1)); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); @@ -1190,7 +1205,8 @@ QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(encrypted2)); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber - 256, visitor_.header_->packet_number); @@ -1203,7 +1219,8 @@ QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(encrypted3)); ASSERT_TRUE(visitor_.header_.get()); - EXPECT_EQ(kConnectionId, visitor_.header_->destination_connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.header_->destination_connection_id); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber - 1, visitor_.header_->packet_number); } @@ -4739,7 +4756,8 @@ EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); ASSERT_EQ(QUIC_NO_ERROR, framer_.error()); ASSERT_TRUE(visitor_.public_reset_packet_.get()); - EXPECT_EQ(kConnectionId, visitor_.public_reset_packet_->connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.public_reset_packet_->connection_id); EXPECT_EQ(kNonceProof, visitor_.public_reset_packet_->nonce_proof); EXPECT_EQ( IpAddressFamily::IP_UNSPEC, @@ -4793,7 +4811,8 @@ EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); ASSERT_EQ(QUIC_NO_ERROR, framer_.error()); ASSERT_TRUE(visitor_.public_reset_packet_.get()); - EXPECT_EQ(kConnectionId, visitor_.public_reset_packet_->connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.public_reset_packet_->connection_id); EXPECT_EQ(kNonceProof, visitor_.public_reset_packet_->nonce_proof); EXPECT_EQ( IpAddressFamily::IP_UNSPEC, @@ -4891,7 +4910,8 @@ EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); ASSERT_EQ(QUIC_NO_ERROR, framer_.error()); ASSERT_TRUE(visitor_.public_reset_packet_.get()); - EXPECT_EQ(kConnectionId, visitor_.public_reset_packet_->connection_id); + EXPECT_EQ(FramerTestConnectionId(), + visitor_.public_reset_packet_->connection_id); EXPECT_EQ(kNonceProof, visitor_.public_reset_packet_->nonce_proof); EXPECT_EQ("4.31.198.44", visitor_.public_reset_packet_->client_address.host().ToString()); @@ -5059,7 +5079,7 @@ TEST_P(QuicFramerTest, BuildPaddingFramePacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -5134,7 +5154,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -5276,7 +5296,7 @@ TEST_P(QuicFramerTest, Build4ByteSequenceNumberPaddingFramePacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number_length = PACKET_4BYTE_PACKET_NUMBER; @@ -5349,7 +5369,7 @@ TEST_P(QuicFramerTest, Build2ByteSequenceNumberPaddingFramePacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number_length = PACKET_2BYTE_PACKET_NUMBER; @@ -5422,7 +5442,7 @@ TEST_P(QuicFramerTest, Build1ByteSequenceNumberPaddingFramePacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number_length = PACKET_1BYTE_PACKET_NUMBER; @@ -5480,7 +5500,7 @@ TEST_P(QuicFramerTest, BuildStreamFramePacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -5596,7 +5616,7 @@ TEST_P(QuicFramerTest, BuildStreamFramePacketWithVersionFlag) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = true; if (framer_.transport_version() > QUIC_VERSION_43) { @@ -5743,7 +5763,7 @@ p_size = QUIC_ARRAYSIZE(packet44); } - QuicConnectionId connection_id = kConnectionId; + QuicConnectionId connection_id = FramerTestConnectionId(); std::unique_ptr<QuicEncryptedPacket> data( framer_.BuildVersionNegotiationPacket( connection_id, framer_.transport_version() > QUIC_VERSION_43, @@ -5754,7 +5774,7 @@ TEST_P(QuicFramerTest, BuildAckFramePacketOneAckBlock) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -5869,7 +5889,7 @@ TEST_P(QuicFramerTest, BuildAckFramePacketOneAckBlockMaxLength) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -5984,7 +6004,7 @@ TEST_P(QuicFramerTest, BuildAckFramePacketMultipleAckBlocks) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -6173,7 +6193,7 @@ TEST_P(QuicFramerTest, BuildAckFramePacketMaxAckBlocks) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -6579,7 +6599,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -6636,7 +6656,7 @@ TEST_P(QuicFramerTest, BuildRstFramePacketQuic) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -6751,7 +6771,7 @@ TEST_P(QuicFramerTest, BuildCloseFramePacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -6877,7 +6897,7 @@ TEST_P(QuicFramerTest, BuildTruncatedCloseFramePacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7117,7 +7137,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7166,7 +7186,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7242,7 +7262,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7348,7 +7368,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7533,7 +7553,7 @@ TEST_P(QuicFramerTest, BuildWindowUpdatePacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7639,7 +7659,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7683,7 +7703,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7721,7 +7741,7 @@ TEST_P(QuicFramerTest, BuildBlockedPacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7813,7 +7833,7 @@ TEST_P(QuicFramerTest, BuildPingPacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7879,7 +7899,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -7922,7 +7942,7 @@ // padded PING packet. TEST_P(QuicFramerTest, BuildConnectivityProbingPacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8007,7 +8027,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8063,7 +8083,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8109,7 +8129,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8157,7 +8177,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8210,7 +8230,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8262,7 +8282,7 @@ // Test that the MTU discovery packet is serialized correctly as a PING packet. TEST_P(QuicFramerTest, BuildMtuDiscoveryPacket) { QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8325,12 +8345,8 @@ TEST_P(QuicFramerTest, BuildPublicResetPacket) { QuicPublicResetPacket reset_packet; - reset_packet.connection_id = kConnectionId; + reset_packet.connection_id = FramerTestConnectionId(); reset_packet.nonce_proof = kNonceProof; - if (!GetQuicReloadableFlag(quic_enable_server_epid_in_public_reset)) { - // If the flag is off, EPID shouldn't be serialized even if it's set. - reset_packet.endpoint_id = "FakeServerId"; - } // clang-format off unsigned char packet[] = { @@ -8366,7 +8382,7 @@ TEST_P(QuicFramerTest, BuildPublicResetPacketWithClientAddress) { QuicPublicResetPacket reset_packet; - reset_packet.connection_id = kConnectionId; + reset_packet.connection_id = FramerTestConnectionId(); reset_packet.nonce_proof = kNonceProof; reset_packet.client_address = QuicSocketAddress(QuicIpAddress::Loopback4(), 0x1234); @@ -8414,11 +8430,8 @@ } TEST_P(QuicFramerTest, BuildPublicResetPacketWithEndpointId) { - if (!GetQuicReloadableFlag(quic_enable_server_epid_in_public_reset)) { - return; - } QuicPublicResetPacket reset_packet; - reset_packet.connection_id = kConnectionId; + reset_packet.connection_id = FramerTestConnectionId(); reset_packet.nonce_proof = kNonceProof; reset_packet.endpoint_id = "FakeServerId"; @@ -8499,7 +8512,7 @@ // clang-format off unsigned char packet[] = { // type (short header, 1 byte packet number) - 0x30, + 0x70, // random packet number 0xFE, // stateless reset token @@ -8508,7 +8521,7 @@ }; // clang-format on std::unique_ptr<QuicEncryptedPacket> data( - framer_.BuildIetfStatelessResetPacket(kConnectionId, + framer_.BuildIetfStatelessResetPacket(FramerTestConnectionId(), kTestStatelessResetToken)); ASSERT_TRUE(data != nullptr); // Skip packet number byte which is random in stateless reset packet. @@ -8686,7 +8699,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8725,7 +8738,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -8765,7 +8778,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9003,7 +9016,7 @@ ParsedQuicVersionVector versions; versions.push_back(framer_.version()); std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( - QuicConnectionIdFromUInt64(42), EmptyQuicConnectionId(), false, false, + TestConnectionId(), EmptyQuicConnectionId(), false, false, kTestQuicStreamId, kTestString, PACKET_8BYTE_CONNECTION_ID, PACKET_0BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, &versions)); @@ -9039,7 +9052,7 @@ ParsedQuicVersionVector versions; versions.push_back(framer_.version()); std::unique_ptr<QuicEncryptedPacket> packet(ConstructMisFramedEncryptedPacket( - QuicConnectionIdFromUInt64(42), EmptyQuicConnectionId(), false, false, + TestConnectionId(), EmptyQuicConnectionId(), false, false, kTestQuicStreamId, kTestString, PACKET_8BYTE_CONNECTION_ID, PACKET_0BYTE_CONNECTION_ID, PACKET_4BYTE_PACKET_NUMBER, &versions, Perspective::IS_CLIENT)); @@ -9251,7 +9264,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9336,7 +9349,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9420,7 +9433,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9501,7 +9514,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9578,7 +9591,8 @@ EXPECT_EQ(0u, visitor_.stream_frames_.size()); - EXPECT_EQ(kConnectionIdPlusOne, visitor_.new_connection_id_.connection_id); + EXPECT_EQ(FramerTestConnectionIdPlusOne(), + visitor_.new_connection_id_.connection_id); EXPECT_EQ(0x11u, visitor_.new_connection_id_.sequence_number); EXPECT_EQ(kTestStatelessResetToken, visitor_.new_connection_id_.stateless_reset_token); @@ -9594,7 +9608,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9603,7 +9617,7 @@ frame.sequence_number = 0x11; // Use this value to force a 4-byte encoded variable length connection ID // in the frame. - frame.connection_id = kConnectionIdPlusOne; + frame.connection_id = FramerTestConnectionIdPlusOne(); frame.stateless_reset_token = kTestStatelessResetToken; QuicFrames frames = {QuicFrame(&frame)}; @@ -9693,7 +9707,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9782,7 +9796,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9867,7 +9881,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -9949,7 +9963,7 @@ } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; @@ -10024,8 +10038,7 @@ QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(&application_close))); - QuicNewConnectionIdFrame new_connection_id(5, QuicConnectionIdFromUInt64(42), - 1, 101111); + QuicNewConnectionIdFrame new_connection_id(5, TestConnectionId(), 1, 101111); EXPECT_EQ(QuicFramer::GetNewConnectionIdFrameSize(new_connection_id), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(&new_connection_id))); @@ -10746,7 +10759,7 @@ return; } QuicPacketHeader header; - header.destination_connection_id = kConnectionId; + header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber;
diff --git a/net/third_party/quic/core/quic_ietf_framer_test.cc b/net/third_party/quic/core/quic_ietf_framer_test.cc index 617b99d..304689f 100644 --- a/net/third_party/quic/core/quic_ietf_framer_test.cc +++ b/net/third_party/quic/core/quic_ietf_framer_test.cc
@@ -1094,8 +1094,7 @@ char packet_buffer[kNormalPacketBufferSize]; QuicNewConnectionIdFrame transmit_frame; - transmit_frame.connection_id = - QuicConnectionIdFromUInt64(UINT64_C(0x0edcba9876543201)); + transmit_frame.connection_id = TestConnectionId(UINT64_C(0x0edcba9876543201)); transmit_frame.sequence_number = 0x01020304; // The token is defined as a uint128 -- a 16-byte integer. // The value is set in this manner because we want each
diff --git a/net/third_party/quic/core/quic_packet_creator_test.cc b/net/third_party/quic/core/quic_packet_creator_test.cc index 10a0aa4..dfc6dab 100644 --- a/net/third_party/quic/core/quic_packet_creator_test.cc +++ b/net/third_party/quic/core/quic_packet_creator_test.cc
@@ -141,7 +141,7 @@ client_framer_(SupportedVersions(GetParam().version), QuicTime::Zero(), Perspective::IS_CLIENT), - connection_id_(QuicConnectionIdFromUInt64(2)), + connection_id_(TestConnectionId(2)), data_("foo"), creator_(connection_id_, &client_framer_, &delegate_, &producer_), serialized_packet_(creator_.NoPacket()) {
diff --git a/net/third_party/quic/core/quic_packet_generator_test.cc b/net/third_party/quic/core/quic_packet_generator_test.cc index 3b5c26c..7dea9fc 100644 --- a/net/third_party/quic/core/quic_packet_generator_test.cc +++ b/net/third_party/quic/core/quic_packet_generator_test.cc
@@ -149,7 +149,7 @@ : framer_(AllSupportedVersions(), QuicTime::Zero(), Perspective::IS_CLIENT), - generator_(QuicConnectionIdFromUInt64(42), + generator_(TestConnectionId(), &framer_, &random_generator_, &delegate_,
diff --git a/net/third_party/quic/core/quic_packet_reader.cc b/net/third_party/quic/core/quic_packet_reader.cc index e6d53ef..39d74435 100644 --- a/net/third_party/quic/core/quic_packet_reader.cc +++ b/net/third_party/quic/core/quic_packet_reader.cc
@@ -97,6 +97,9 @@ return false; // recvmmsg failed. } + bool use_quic_time = + GetQuicReloadableFlag(quic_use_quic_time_for_received_timestamp); + QuicTime fallback_timestamp(QuicTime::Zero()); QuicWallTime fallback_walltimestamp = QuicWallTime::Zero(); for (int i = 0; i < packets_read; ++i) { if (mmsg_hdr_[i].msg_len == 0) { @@ -130,13 +133,27 @@ // This isn't particularly desirable, but not all platforms support socket // timestamping. - if (packet_walltimestamp.IsZero()) { - if (fallback_walltimestamp.IsZero()) { - fallback_walltimestamp = clock.WallNow(); + QuicTime timestamp(QuicTime::Zero()); + if (!use_quic_time) { + if (packet_walltimestamp.IsZero()) { + if (fallback_walltimestamp.IsZero()) { + fallback_walltimestamp = clock.WallNow(); + } + packet_walltimestamp = fallback_walltimestamp; } - packet_walltimestamp = fallback_walltimestamp; + timestamp = clock.ConvertWallTimeToQuicTime(packet_walltimestamp); + + } else { + QUIC_RELOADABLE_FLAG_COUNT(quic_use_quic_time_for_received_timestamp); + if (packet_walltimestamp.IsZero()) { + if (!fallback_timestamp.IsInitialized()) { + fallback_timestamp = clock.Now(); + } + timestamp = fallback_timestamp; + } else { + timestamp = clock.ConvertWallTimeToQuicTime(packet_walltimestamp); + } } - QuicTime timestamp = clock.ConvertWallTimeToQuicTime(packet_walltimestamp); int ttl = 0; bool has_ttl = QuicSocketUtils::GetTtlFromMsghdr(&mmsg_hdr_[i].msg_hdr, &ttl);
diff --git a/net/third_party/quic/core/quic_sent_packet_manager.cc b/net/third_party/quic/core/quic_sent_packet_manager.cc index 1f7f9a40..c997830 100644 --- a/net/third_party/quic/core/quic_sent_packet_manager.cc +++ b/net/third_party/quic/core/quic_sent_packet_manager.cc
@@ -855,6 +855,9 @@ << largest_acked; return false; } + if (transmission_info.sent_time > ack_receive_time) { + QUIC_CODE_COUNT(quic_receive_acked_before_sending); + } QuicTime::Delta send_delta = ack_receive_time - transmission_info.sent_time; rtt_stats_.UpdateRtt(send_delta, ack_delay_time, ack_receive_time);
diff --git a/net/third_party/quic/core/quic_session.cc b/net/third_party/quic/core/quic_session.cc index 7d259f9..92b8ca5e 100644 --- a/net/third_party/quic/core/quic_session.cc +++ b/net/third_party/quic/core/quic_session.cc
@@ -73,14 +73,10 @@ is_handshake_confirmed_(false), goaway_sent_(false), goaway_received_(false), - faster_get_stream_(GetQuicReloadableFlag(quic_session_faster_get_stream)), control_frame_manager_(this), last_message_id_(0), closed_streams_clean_up_alarm_(nullptr), supported_versions_(supported_versions) { - if (faster_get_stream_) { - QUIC_RELOADABLE_FLAG_COUNT(quic_session_faster_get_stream); - } closed_streams_clean_up_alarm_ = QuicWrapUnique<QuicAlarm>(connection_->alarm_factory()->CreateAlarm( new ClosedStreamsCleanUpDelegate(this))); @@ -110,14 +106,13 @@ void QuicSession::RegisterStaticStream(QuicStreamId id, QuicStream* stream) { static_stream_map_[id] = stream; - if (faster_get_stream_) { - QUIC_BUG_IF(id > - largest_static_stream_id_ + - QuicUtils::StreamIdDelta(connection_->transport_version())) - << ENDPOINT << "Static stream registered out of order: " << id - << " vs: " << largest_static_stream_id_; - largest_static_stream_id_ = std::max(id, largest_static_stream_id_); - } + QUIC_BUG_IF(id > + largest_static_stream_id_ + + QuicUtils::StreamIdDelta(connection_->transport_version())) + << ENDPOINT << "Static stream registered out of order: " << id + << " vs: " << largest_static_stream_id_; + largest_static_stream_id_ = std::max(id, largest_static_stream_id_); + if (connection_->transport_version() == QUIC_VERSION_99) { v99_streamid_manager_.RegisterStaticStream(id); } @@ -1219,19 +1214,13 @@ } QuicStream* QuicSession::GetStream(QuicStreamId id) const { - if (faster_get_stream_) { - if (id <= largest_static_stream_id_) { - auto static_stream = static_stream_map_.find(id); - if (static_stream != static_stream_map_.end()) { - return static_stream->second; - } - } - } else { + if (id <= largest_static_stream_id_) { auto static_stream = static_stream_map_.find(id); if (static_stream != static_stream_map_.end()) { return static_stream->second; } } + auto active_stream = dynamic_stream_map_.find(id); if (active_stream != dynamic_stream_map_.end()) { return active_stream->second.get();
diff --git a/net/third_party/quic/core/quic_session.h b/net/third_party/quic/core/quic_session.h index 2dc343fb..7a1330ac4 100644 --- a/net/third_party/quic/core/quic_session.h +++ b/net/third_party/quic/core/quic_session.h
@@ -597,9 +597,6 @@ // Whether a GoAway has been received. bool goaway_received_; - // Latched value of quic_session_faster_get_stream flag. - const bool faster_get_stream_; - QuicControlFrameManager control_frame_manager_; // Id of latest successfully sent message.
diff --git a/net/third_party/quic/core/quic_time_wait_list_manager_test.cc b/net/third_party/quic/core/quic_time_wait_list_manager_test.cc index 1c5f85e5..c6414c6a 100644 --- a/net/third_party/quic/core/quic_time_wait_list_manager_test.cc +++ b/net/third_party/quic/core/quic_time_wait_list_manager_test.cc
@@ -132,7 +132,7 @@ protected: QuicTimeWaitListManagerTest() : time_wait_list_manager_(&writer_, &visitor_, &clock_, &alarm_factory_), - connection_id_(QuicConnectionIdFromUInt64(45)), + connection_id_(TestConnectionId(45)), peer_address_(TestPeerIPAddress(), kTestPort), writer_is_blocked_(false) {} @@ -352,7 +352,7 @@ // Add connection_ids such that their expiry time is time_wait_period_. for (uint64_t conn_id = 1; conn_id <= kOldConnectionIdCount; ++conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::DO_NOTHING); } @@ -365,7 +365,7 @@ clock_.AdvanceTime(time_wait_period); for (uint64_t conn_id = kOldConnectionIdCount + 1; conn_id <= kConnectionIdCount; ++conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::DO_NOTHING); } @@ -381,7 +381,7 @@ time_wait_list_manager_.CleanUpOldConnectionIds(); for (uint64_t conn_id = 1; conn_id <= kConnectionIdCount; ++conn_id) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(conn_id); + QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_EQ(conn_id > kOldConnectionIdCount, IsConnectionIdInTimeWait(connection_id)) << "kOldConnectionIdCount: " << kOldConnectionIdCount @@ -392,7 +392,7 @@ } TEST_F(QuicTimeWaitListManagerTest, SendQueuedPackets) { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(1); + QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::SEND_STATELESS_RESET); QuicPacketNumber packet_number = 234; @@ -418,7 +418,7 @@ // write packet should not be called since we are write blocked but the // should be queued. - QuicConnectionId other_connection_id = QuicConnectionIdFromUInt64(2); + QuicConnectionId other_connection_id = TestConnectionId(2); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(other_connection_id)); AddConnectionId(other_connection_id, QuicTimeWaitListManager::SEND_STATELESS_RESET); @@ -483,9 +483,8 @@ // Simple randomization: the values of connection_ids are randomly swapped. // If the container is broken, the test will be 50% flaky. const uint64_t conn_id1 = QuicRandom::GetInstance()->RandUint64() % 2; - const QuicConnectionId connection_id1 = QuicConnectionIdFromUInt64(conn_id1); - const QuicConnectionId connection_id2 = - QuicConnectionIdFromUInt64(1 - conn_id1); + const QuicConnectionId connection_id1 = TestConnectionId(conn_id1); + const QuicConnectionId connection_id2 = TestConnectionId(1 - conn_id1); // 1 will hash lower than 2, but we add it later. They should come out in the // add order, not hash order. @@ -517,8 +516,7 @@ // Add exactly the maximum number of connections for (int64_t i = 0; i < FLAGS_quic_time_wait_list_max_connections; ++i) { ++current_conn_id; - QuicConnectionId current_connection_id = - QuicConnectionIdFromUInt64(current_conn_id); + QuicConnectionId current_connection_id = TestConnectionId(current_conn_id); EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(current_connection_id)); @@ -531,9 +529,8 @@ // will evict the oldest one. for (int64_t i = 0; i < FLAGS_quic_time_wait_list_max_connections; ++i) { ++current_conn_id; - QuicConnectionId current_connection_id = - QuicConnectionIdFromUInt64(current_conn_id); - const QuicConnectionId id_to_evict = QuicConnectionIdFromUInt64( + QuicConnectionId current_connection_id = TestConnectionId(current_conn_id); + const QuicConnectionId id_to_evict = TestConnectionId( current_conn_id - FLAGS_quic_time_wait_list_max_connections); EXPECT_TRUE(IsConnectionIdInTimeWait(id_to_evict)); EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id));
diff --git a/net/third_party/quic/core/quic_trace_visitor_test.cc b/net/third_party/quic/core/quic_trace_visitor_test.cc index fd349ac..b78dbab5 100644 --- a/net/third_party/quic/core/quic_trace_visitor_test.cc +++ b/net/third_party/quic/core/quic_trace_visitor_test.cc
@@ -6,6 +6,7 @@ #include "net/third_party/quic/core/quic_constants.h" #include "net/third_party/quic/platform/api/quic_test.h" +#include "net/third_party/quic/test_tools/quic_test_utils.h" #include "net/third_party/quic/test_tools/simulator/quic_endpoint.h" #include "net/third_party/quic/test_tools/simulator/simulator.h" #include "net/third_party/quic/test_tools/simulator/switch.h" @@ -23,7 +24,7 @@ class QuicTraceVisitorTest : public QuicTest { public: QuicTraceVisitorTest() { - QuicConnectionId connection_id = QuicConnectionIdFromUInt64(42); + QuicConnectionId connection_id = test::TestConnectionId(); simulator::Simulator simulator; simulator::QuicEndpoint client(&simulator, "Client", "Server", Perspective::IS_CLIENT, connection_id);
diff --git a/net/third_party/quic/core/quic_types.h b/net/third_party/quic/core/quic_types.h index b2f8287c..9de19129 100644 --- a/net/third_party/quic/core/quic_types.h +++ b/net/third_party/quic/core/quic_types.h
@@ -488,9 +488,8 @@ // Bits 4 and 5: Reserved bits for short header. FLAGS_SHORT_HEADER_RESERVED_1 = 1 << 4, FLAGS_SHORT_HEADER_RESERVED_2 = 1 << 5, - // Bit 6: Indicates the key phase, which allows the receipt of the packet to - // identify the packet protection keys that are used to protect the packet. - FLAGS_KEY_PHASE_BIT = 1 << 6, + // Bit 6: the 'QUIC' bit. + FLAGS_FIXED_BIT = 1 << 6, // Bit 7: Indicates the header is long or short header. FLAGS_LONG_HEADER = 1 << 7, };
diff --git a/net/third_party/quic/core/stateless_rejector_test.cc b/net/third_party/quic/core/stateless_rejector_test.cc index 49c2edd..8c341ce 100644 --- a/net/third_party/quic/core/stateless_rejector_test.cc +++ b/net/third_party/quic/core/stateless_rejector_test.cc
@@ -27,9 +27,9 @@ namespace test { namespace { -const QuicConnectionId kConnectionId = QuicConnectionIdFromUInt64(42); -const QuicConnectionId kServerDesignateConnectionId = - QuicConnectionIdFromUInt64(24); +QuicConnectionId TestServerDesignatedConnectionId() { + return TestConnectionId(24); +} // All four combinations of the two flags involved. enum FlagsMode { ENABLED, STATELESS_DISABLED, CHEAP_DISABLED, BOTH_DISABLED }; @@ -181,8 +181,8 @@ {{"PDMD", "X509"}, {"COPT", "SREJ"}}); // clang-format on - rejector_->OnChlo(GetParam().version.transport_version, kConnectionId, - kServerDesignateConnectionId, client_hello); + rejector_->OnChlo(GetParam().version.transport_version, TestConnectionId(), + TestServerDesignatedConnectionId(), client_hello); if (GetParam().flags != ENABLED) { EXPECT_EQ(StatelessRejector::UNSUPPORTED, rejector_->state()); @@ -210,8 +210,8 @@ kClientHelloMinimumSize); // clang-format on - rejector_->OnChlo(GetParam().version.transport_version, kConnectionId, - kServerDesignateConnectionId, client_hello); + rejector_->OnChlo(GetParam().version.transport_version, TestConnectionId(), + TestServerDesignatedConnectionId(), client_hello); EXPECT_EQ(StatelessRejector::UNSUPPORTED, rejector_->state()); } @@ -230,8 +230,8 @@ kClientHelloMinimumSize); // clang-format on - rejector_->OnChlo(GetParam().version.transport_version, kConnectionId, - kServerDesignateConnectionId, client_hello); + rejector_->OnChlo(GetParam().version.transport_version, TestConnectionId(), + TestServerDesignatedConnectionId(), client_hello); if (GetParam().flags != ENABLED) { EXPECT_EQ(StatelessRejector::UNSUPPORTED, rejector_->state()); return; @@ -272,8 +272,8 @@ kClientHelloMinimumSize); // clang-format on - rejector_->OnChlo(GetParam().version.transport_version, kConnectionId, - kServerDesignateConnectionId, client_hello); + rejector_->OnChlo(GetParam().version.transport_version, TestConnectionId(), + TestServerDesignatedConnectionId(), client_hello); if (GetParam().flags != ENABLED) { EXPECT_EQ(StatelessRejector::UNSUPPORTED, rejector_->state()); return;
diff --git a/net/third_party/quic/quartc/quartc_factory.cc b/net/third_party/quic/quartc/quartc_factory.cc index bb596660..ff01c6ca 100644 --- a/net/third_party/quic/quartc/quartc_factory.cc +++ b/net/third_party/quic/quartc/quartc_factory.cc
@@ -46,6 +46,15 @@ SetQuicFlag(&FLAGS_quic_buffered_data_threshold, std::numeric_limits<int>::max()); + // TODO(b/117157454): Perform version negotiation for Quartc outside of + // QuicSession/QuicConnection. Currently default of + // quic_restart_flag_quic_no_server_conn_ver_negotiation2 is false, + // but we fail blueprint test that sets all QUIC flags to true. + // + // Forcing flag to false to pass blueprint tests, but eventually we'll have + // to implement negotiation outside of QuicConnection. + SetQuicRestartFlag(quic_no_server_conn_ver_negotiation2, false); + std::unique_ptr<QuicConnection> quic_connection = CreateQuicConnection(perspective, writer.get()); @@ -124,6 +133,10 @@ copt.push_back(k1RTT); // Exit STARTUP after 1 RTT with no gains. copt.push_back(kIW10); // 10-packet (14600 byte) initial cwnd. + if (!quartc_session_config.enable_tail_loss_probe) { + copt.push_back(kNTLP); + } + quic_connection->set_fill_up_link_during_probing(true); // TODO(b/112192153): Test and possible enable slower startup when pipe
diff --git a/net/third_party/quic/quartc/quartc_factory.h b/net/third_party/quic/quartc/quartc_factory.h index ab40858..c5207f1 100644 --- a/net/third_party/quic/quartc/quartc_factory.h +++ b/net/third_party/quic/quartc/quartc_factory.h
@@ -51,6 +51,11 @@ // Congestion control type used for this session. Only BBR and GoogCC are // supported. CongestionControlType congestion_control_type = kBBR; + + // Tail loss probes (TLP) are enabled by default, but it may be useful to + // disable them in tests. We can also consider disabling them in production + // if we discover that tail loss probes add overhead in low bitrate audio. + bool enable_tail_loss_probe = true; }; // Factory that creates instances of QuartcSession. Implements the
diff --git a/net/third_party/quic/quartc/quartc_session_test.cc b/net/third_party/quic/quartc/quartc_session_test.cc index 0ed5ec9c..6215052 100644 --- a/net/third_party/quic/quartc/quartc_session_test.cc +++ b/net/third_party/quic/quartc/quartc_session_test.cc
@@ -113,12 +113,6 @@ ~QuartcSessionTest() override {} void Init() { - // To enable SendMessage. - // TODO(b/119779614): Currently QuartcSession test creates quic connection - // directly, so we have to set version to enable SendMessag. QuartcSession - // test should use QuartcFactory, which already sets required version. - SetQuicReloadableFlag(quic_enable_version_45, true); - client_transport_ = QuicMakeUnique<simulator::SimulatedQuartcPacketTransport>( &simulator_, "client_transport", "server_transport", @@ -136,11 +130,6 @@ QuicBandwidth::FromKBitsPerSecond(10 * 1000), QuicTime::Delta::FromMilliseconds(10)); - client_writer_ = QuicMakeUnique<QuartcPacketWriter>(client_transport_.get(), - kDefaultMaxPacketSize); - server_writer_ = QuicMakeUnique<QuartcPacketWriter>(server_transport_.get(), - kDefaultMaxPacketSize); - client_stream_delegate_ = QuicMakeUnique<FakeQuartcStreamDelegate>(); client_session_delegate_ = QuicMakeUnique<FakeQuartcSessionDelegate>( client_stream_delegate_.get()); @@ -148,44 +137,32 @@ server_stream_delegate_ = QuicMakeUnique<FakeQuartcStreamDelegate>(); server_session_delegate_ = QuicMakeUnique<FakeQuartcSessionDelegate>( server_stream_delegate_.get()); + + QuartcFactoryConfig factory_config; + factory_config.alarm_factory = simulator_.GetAlarmFactory(); + factory_config.clock = simulator_.GetClock(); + quartc_factory_ = QuicMakeUnique<QuartcFactory>(factory_config); } - // The parameters are used to control whether the handshake will success or - // not. - void CreateClientAndServerSessions() { + // Note that input session config will apply to both server and client. + // Perspective and packet_transport will be overwritten. + void CreateClientAndServerSessions( + const QuartcSessionConfig& session_config) { Init(); - client_peer_ = - CreateSession(Perspective::IS_CLIENT, std::move(client_writer_)); + + QuartcSessionConfig client_session_config = session_config; + client_session_config.perspective = Perspective::IS_CLIENT; + client_session_config.packet_transport = client_transport_.get(); + client_peer_ = quartc_factory_->CreateQuartcSession(client_session_config); client_peer_->SetDelegate(client_session_delegate_.get()); - server_peer_ = - CreateSession(Perspective::IS_SERVER, std::move(server_writer_)); + + QuartcSessionConfig server_session_config = session_config; + server_session_config.perspective = Perspective::IS_SERVER; + server_session_config.packet_transport = server_transport_.get(); + server_peer_ = quartc_factory_->CreateQuartcSession(server_session_config); server_peer_->SetDelegate(server_session_delegate_.get()); } - std::unique_ptr<QuartcSession> CreateSession( - Perspective perspective, - std::unique_ptr<QuartcPacketWriter> writer) { - std::unique_ptr<QuicConnection> quic_connection = - CreateConnection(perspective, writer.get()); - QuicString remote_fingerprint_value = "value"; - QuicConfig config; - - return QuicMakeUnique<QuartcSession>( - std::move(quic_connection), config, CurrentSupportedVersions(), - remote_fingerprint_value, perspective, &simulator_, - simulator_.GetClock(), std::move(writer)); - } - - std::unique_ptr<QuicConnection> CreateConnection(Perspective perspective, - QuartcPacketWriter* writer) { - QuicIpAddress ip; - ip.FromString("0.0.0.0"); - return QuicMakeUnique<QuicConnection>( - EmptyQuicConnectionId(), QuicSocketAddress(ip, 0), &simulator_, - simulator_.GetAlarmFactory(), writer, /*owns_writer=*/false, - perspective, ParsedVersionOfIndex(CurrentSupportedVersions(), 0)); - } - // Runs all tasks scheduled in the next 200 ms. void RunTasks() { simulator_.RunFor(QuicTime::Delta::FromMilliseconds(200)); } @@ -344,13 +321,13 @@ protected: simulator::Simulator simulator_; + std::unique_ptr<QuartcFactory> quartc_factory_; + std::unique_ptr<simulator::SimulatedQuartcPacketTransport> client_transport_; std::unique_ptr<simulator::SimulatedQuartcPacketTransport> server_transport_; std::unique_ptr<simulator::CountingPacketFilter> client_filter_; std::unique_ptr<simulator::SymmetricLink> client_server_link_; - std::unique_ptr<QuartcPacketWriter> client_writer_; - std::unique_ptr<QuartcPacketWriter> server_writer_; std::unique_ptr<QuartcSession> client_peer_; std::unique_ptr<QuartcSession> server_peer_; @@ -361,32 +338,32 @@ }; TEST_F(QuartcSessionTest, SendReceiveStreams) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); StartHandshake(); TestSendReceiveStreams(); } TEST_F(QuartcSessionTest, SendReceiveMessages) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); StartHandshake(); TestSendReceiveMessage(); } TEST_F(QuartcSessionTest, SendReceiveQueuedMessages) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); StartHandshake(); TestSendReceiveQueuedMessages(/*direction_from_server=*/true); TestSendReceiveQueuedMessages(/*direction_from_server=*/false); } TEST_F(QuartcSessionTest, SendMessageFails) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); StartHandshake(); TestSendLongMessage(); } TEST_F(QuartcSessionTest, PreSharedKeyHandshake) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); client_peer_->SetPreSharedKey("foo"); server_peer_->SetPreSharedKey("foo"); StartHandshake(); @@ -396,13 +373,13 @@ // Test that data streams are not created before handshake. TEST_F(QuartcSessionTest, CannotCreateDataStreamBeforeHandshake) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); EXPECT_EQ(nullptr, server_peer_->CreateOutgoingBidirectionalStream()); EXPECT_EQ(nullptr, client_peer_->CreateOutgoingBidirectionalStream()); } TEST_F(QuartcSessionTest, CancelQuartcStream) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); StartHandshake(); ASSERT_TRUE(client_peer_->IsCryptoHandshakeConfirmed()); ASSERT_TRUE(server_peer_->IsCryptoHandshakeConfirmed()); @@ -424,7 +401,7 @@ // QuartcPacketTransport and remove // SimulatedQuartcPacketTransport::last_packet_number(). TEST_F(QuartcSessionTest, WriterGivesPacketNumberToTransport) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); StartHandshake(); ASSERT_TRUE(client_peer_->IsCryptoHandshakeConfirmed()); ASSERT_TRUE(server_peer_->IsCryptoHandshakeConfirmed()); @@ -445,7 +422,7 @@ } TEST_F(QuartcSessionTest, CloseConnection) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); StartHandshake(); ASSERT_TRUE(client_peer_->IsCryptoHandshakeConfirmed()); ASSERT_TRUE(server_peer_->IsCryptoHandshakeConfirmed()); @@ -457,7 +434,7 @@ } TEST_F(QuartcSessionTest, StreamRetransmissionEnabled) { - CreateClientAndServerSessions(); + CreateClientAndServerSessions(QuartcSessionConfig()); StartHandshake(); ASSERT_TRUE(client_peer_->IsCryptoHandshakeConfirmed()); ASSERT_TRUE(server_peer_->IsCryptoHandshakeConfirmed()); @@ -481,7 +458,16 @@ } TEST_F(QuartcSessionTest, StreamRetransmissionDisabled) { - CreateClientAndServerSessions(); + // Disable tail loss probe, otherwise test maybe flaky because dropped + // message will be retransmitted to detect tail loss. + QuartcSessionConfig session_config; + session_config.enable_tail_loss_probe = false; + CreateClientAndServerSessions(session_config); + + // Disable probing retransmissions, otherwise test maybe flaky because dropped + // message will be retransmitted to to probe for more bandwidth. + client_peer_->connection()->set_fill_up_link_during_probing(false); + StartHandshake(); ASSERT_TRUE(client_peer_->IsCryptoHandshakeConfirmed()); ASSERT_TRUE(server_peer_->IsCryptoHandshakeConfirmed());
diff --git a/net/third_party/quic/test_tools/crypto_test_utils.cc b/net/third_party/quic/test_tools/crypto_test_utils.cc index 1363f00..78581d6 100644 --- a/net/third_party/quic/test_tools/crypto_test_utils.cc +++ b/net/third_party/quic/test_tools/crypto_test_utils.cc
@@ -308,9 +308,8 @@ result) { result_ = result; crypto_config_->ProcessClientHello( - result_, /*reject_only=*/false, QuicConnectionIdFromUInt64(1), - server_addr_, client_addr_, AllSupportedVersions().front(), - AllSupportedVersions(), + result_, /*reject_only=*/false, TestConnectionId(1), server_addr_, + client_addr_, AllSupportedVersions().front(), AllSupportedVersions(), /*use_stateless_rejects=*/true, /*server_designated_connection_id=*/EmptyQuicConnectionId(), clock_, QuicRandom::GetInstance(), compressed_certs_cache_, params_,
diff --git a/net/third_party/quic/test_tools/crypto_test_utils_test.cc b/net/third_party/quic/test_tools/crypto_test_utils_test.cc index ede4a83..069ea23 100644 --- a/net/third_party/quic/test_tools/crypto_test_utils_test.cc +++ b/net/third_party/quic/test_tools/crypto_test_utils_test.cc
@@ -60,8 +60,8 @@ result_ = result; crypto_config_->ProcessClientHello( result_, /*reject_only=*/false, - /*connection_id=*/QuicConnectionIdFromUInt64(1), server_addr_, - client_addr_, AllSupportedVersions().front(), AllSupportedVersions(), + /*connection_id=*/TestConnectionId(1), server_addr_, client_addr_, + AllSupportedVersions().front(), AllSupportedVersions(), /*use_stateless_rejects=*/true, /*server_designated_connection_id=*/EmptyQuicConnectionId(), clock_, QuicRandom::GetInstance(), compressed_certs_cache_, params_,
diff --git a/net/third_party/quic/test_tools/quic_framer_peer.cc b/net/third_party/quic/test_tools/quic_framer_peer.cc index 62a4f18..74f4a62 100644 --- a/net/third_party/quic/test_tools/quic_framer_peer.cc +++ b/net/third_party/quic/test_tools/quic_framer_peer.cc
@@ -39,6 +39,8 @@ void QuicFramerPeer::SetPerspective(QuicFramer* framer, Perspective perspective) { framer->perspective_ = perspective; + framer->infer_packet_header_type_from_version_ = + perspective == Perspective::IS_CLIENT; } // static
diff --git a/net/third_party/quic/test_tools/quic_test_utils.cc b/net/third_party/quic/test_tools/quic_test_utils.cc index 6351d21..09387448 100644 --- a/net/third_party/quic/test_tools/quic_test_utils.cc +++ b/net/third_party/quic/test_tools/quic_test_utils.cc
@@ -34,6 +34,20 @@ namespace quic { namespace test { +QuicConnectionId TestConnectionId() { + // Chosen by fair dice roll. + // Guaranteed to be random. + return TestConnectionId(42); +} + +QuicConnectionId TestConnectionId(uint64_t connection_number) { + return QuicConnectionIdFromUInt64(connection_number); +} + +uint64_t TestConnectionIdToUInt64(QuicConnectionId connection_id) { + return QuicConnectionIdToUInt64(connection_id); +} + QuicAckFrame InitAckFrame(const std::vector<QuicAckBlock>& ack_blocks) { DCHECK_GT(ack_blocks.size(), 0u); @@ -341,8 +355,7 @@ MockQuicConnection::MockQuicConnection(MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, Perspective perspective) - : MockQuicConnection(QuicConnectionIdFromUInt64(QuicEndian::NetToHost64( - QuicConnectionIdToUInt64(kTestConnectionId))), + : MockQuicConnection(TestConnectionId(), QuicSocketAddress(TestPeerIPAddress(), kTestPort), helper, alarm_factory, @@ -353,8 +366,7 @@ MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, Perspective perspective) - : MockQuicConnection(QuicConnectionIdFromUInt64(QuicEndian::NetToHost64( - QuicConnectionIdToUInt64(kTestConnectionId))), + : MockQuicConnection(TestConnectionId(), address, helper, alarm_factory, @@ -377,8 +389,7 @@ MockAlarmFactory* alarm_factory, Perspective perspective, const ParsedQuicVersionVector& supported_versions) - : MockQuicConnection(QuicConnectionIdFromUInt64(QuicEndian::NetToHost64( - QuicConnectionIdToUInt64(kTestConnectionId))), + : MockQuicConnection(TestConnectionId(), QuicSocketAddress(TestPeerIPAddress(), kTestPort), helper, alarm_factory,
diff --git a/net/third_party/quic/test_tools/quic_test_utils.h b/net/third_party/quic/test_tools/quic_test_utils.h index fdd24353..7f8aefe 100644 --- a/net/third_party/quic/test_tools/quic_test_utils.h +++ b/net/third_party/quic/test_tools/quic_test_utils.h
@@ -36,8 +36,16 @@ namespace test { -static const QuicConnectionId kTestConnectionId = - QuicConnectionIdFromUInt64(42); +// A generic predictable connection ID suited for testing. +QuicConnectionId TestConnectionId(); + +// A generic predictable connection ID suited for testing, generated from a +// given number, such as an index. +QuicConnectionId TestConnectionId(uint64_t connection_number); + +// Extracts the connection number passed to TestConnectionId(). +uint64_t TestConnectionIdToUInt64(QuicConnectionId connection_id); + static const uint16_t kTestPort = 12345; static const uint32_t kInitialStreamFlowControlWindowForTest = 1024 * 1024; // 1 MB
diff --git a/net/third_party/quic/test_tools/quic_test_utils_test.cc b/net/third_party/quic/test_tools/quic_test_utils_test.cc index 95a3638..e4b5c40 100644 --- a/net/third_party/quic/test_tools/quic_test_utils_test.cc +++ b/net/third_party/quic/test_tools/quic_test_utils_test.cc
@@ -12,6 +12,16 @@ class QuicTestUtilsTest : public QuicTest {}; +TEST_F(QuicTestUtilsTest, ConnectionId) { + EXPECT_NE(EmptyQuicConnectionId(), TestConnectionId()); + EXPECT_NE(EmptyQuicConnectionId(), TestConnectionId(1)); + EXPECT_EQ(TestConnectionId(), TestConnectionId()); + EXPECT_EQ(TestConnectionId(33), TestConnectionId(33)); + EXPECT_NE(TestConnectionId(0xdead), TestConnectionId(0xbeef)); + EXPECT_EQ(0x1337u, TestConnectionIdToUInt64(TestConnectionId(0x1337))); + EXPECT_NE(0xdeadu, TestConnectionIdToUInt64(TestConnectionId(0xbeef))); +} + TEST_F(QuicTestUtilsTest, BasicApproxEq) { ExpectApproxEq(10, 10, 1e-6f); ExpectApproxEq(1000, 1001, 0.01f);
diff --git a/net/third_party/quic/test_tools/simulator/quic_endpoint.cc b/net/third_party/quic/test_tools/simulator/quic_endpoint.cc index 41fdf14..6057e6c 100644 --- a/net/third_party/quic/test_tools/simulator/quic_endpoint.cc +++ b/net/third_party/quic/test_tools/simulator/quic_endpoint.cc
@@ -125,7 +125,7 @@ // TODO(dschinazi) b/120240679 - convert directly from CID to string QuicString identifier = QuicStrCat(perspective_prefix, - QuicConnectionIdToUInt64(connection_.connection_id())); + test::TestConnectionIdToUInt64(connection_.connection_id())); QuicRecordTestOutput(identifier, trace_visitor_->trace()->SerializeAsString()); }
diff --git a/net/third_party/quic/test_tools/simulator/quic_endpoint_test.cc b/net/third_party/quic/test_tools/simulator/quic_endpoint_test.cc index ef112ec..5979bd49 100644 --- a/net/third_party/quic/test_tools/simulator/quic_endpoint_test.cc +++ b/net/third_party/quic/test_tools/simulator/quic_endpoint_test.cc
@@ -54,11 +54,9 @@ // Test transmission from one host to another. TEST_F(QuicEndpointTest, OneWayTransmission) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", - Perspective::IS_CLIENT, - QuicConnectionIdFromUInt64(42)); + Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", - Perspective::IS_SERVER, - QuicConnectionIdFromUInt64(42)); + Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); @@ -91,11 +89,9 @@ // Test the situation in which the writer becomes write-blocked. TEST_F(QuicEndpointTest, WriteBlocked) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", - Perspective::IS_CLIENT, - QuicConnectionIdFromUInt64(42)); + Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", - Perspective::IS_SERVER, - QuicConnectionIdFromUInt64(42)); + Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); @@ -132,11 +128,9 @@ // directions. TEST_F(QuicEndpointTest, TwoWayTransmission) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", - Perspective::IS_CLIENT, - QuicConnectionIdFromUInt64(42)); + Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", - Perspective::IS_SERVER, - QuicConnectionIdFromUInt64(42)); + Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); @@ -164,22 +158,22 @@ SetQuicReloadableFlag(quic_bbr_one_mss_conservation, false); auto endpoint_a = QuicMakeUnique<QuicEndpoint>( &simulator_, "Endpoint A", "Endpoint D (A)", Perspective::IS_CLIENT, - QuicConnectionIdFromUInt64(42)); + test::TestConnectionId(42)); auto endpoint_b = QuicMakeUnique<QuicEndpoint>( &simulator_, "Endpoint B", "Endpoint D (B)", Perspective::IS_CLIENT, - QuicConnectionIdFromUInt64(43)); + test::TestConnectionId(43)); auto endpoint_c = QuicMakeUnique<QuicEndpoint>( &simulator_, "Endpoint C", "Endpoint D (C)", Perspective::IS_CLIENT, - QuicConnectionIdFromUInt64(44)); + test::TestConnectionId(44)); auto endpoint_d_a = QuicMakeUnique<QuicEndpoint>( &simulator_, "Endpoint D (A)", "Endpoint A", Perspective::IS_SERVER, - QuicConnectionIdFromUInt64(42)); + test::TestConnectionId(42)); auto endpoint_d_b = QuicMakeUnique<QuicEndpoint>( &simulator_, "Endpoint D (B)", "Endpoint B", Perspective::IS_SERVER, - QuicConnectionIdFromUInt64(43)); + test::TestConnectionId(43)); auto endpoint_d_c = QuicMakeUnique<QuicEndpoint>( &simulator_, "Endpoint D (C)", "Endpoint C", Perspective::IS_SERVER, - QuicConnectionIdFromUInt64(44)); + test::TestConnectionId(44)); QuicEndpointMultiplexer endpoint_d( "Endpoint D", {endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()});
diff --git a/net/tools/cachetool/cachetool.cc b/net/tools/cachetool/cachetool.cc index 326f960..650e5d0 100644 --- a/net/tools/cachetool/cachetool.cc +++ b/net/tools/cachetool/cachetool.cc
@@ -11,10 +11,10 @@ #include "base/files/file_path.h" #include "base/format_macros.h" #include "base/logging.h" -#include "base/macros.h" #include "base/md5.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" @@ -232,7 +232,7 @@ return ""; std::cout.flush(); size_t command_id = static_cast<size_t>(std::cin.get()); - if (command_id >= arraysize(kCommandNames)) { + if (command_id >= base::size(kCommandNames)) { ReturnFailure("Unknown command."); return ""; }
diff --git a/net/tools/cert_verify_tool/verify_using_cert_verify_proc.cc b/net/tools/cert_verify_tool/verify_using_cert_verify_proc.cc index 9bfbf619..11e9e9a 100644 --- a/net/tools/cert_verify_tool/verify_using_cert_verify_proc.cc +++ b/net/tools/cert_verify_tool/verify_using_cert_verify_proc.cc
@@ -6,6 +6,7 @@ #include <iostream> +#include "base/stl_util.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -50,7 +51,7 @@ std::string FingerPrintCryptoBuffer(const CRYPTO_BUFFER* cert_handle) { net::SHA256HashValue hash = net::X509Certificate::CalculateFingerprint256(cert_handle); - return base::HexEncode(hash.data, arraysize(hash.data)); + return base::HexEncode(hash.data, base::size(hash.data)); } // Returns a textual representation of the Subject of |cert|.
diff --git a/net/tools/crash_cache/crash_cache.cc b/net/tools/crash_cache/crash_cache.cc index d55cf00..fd7fc91 100644 --- a/net/tools/crash_cache/crash_cache.cc +++ b/net/tools/crash_cache/crash_cache.cc
@@ -17,6 +17,7 @@ #include "base/path_service.h" #include "base/process/kill.h" #include "base/process/launch.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -115,7 +116,7 @@ "remove_load2", "remove_load3" }; - static_assert(arraysize(folders) == disk_cache::MAX_CRASH, "sync folders"); + static_assert(base::size(folders) == disk_cache::MAX_CRASH, "sync folders"); DCHECK(action > disk_cache::NO_CRASH && action < disk_cache::MAX_CRASH); *full_path = path.AppendASCII(folders[action]);
diff --git a/net/tools/quic/quic_simple_server_test.cc b/net/tools/quic/quic_simple_server_test.cc index 50151f8..0df75865 100644 --- a/net/tools/quic/quic_simple_server_test.cc +++ b/net/tools/quic/quic_simple_server_test.cc
@@ -4,6 +4,7 @@ #include "net/tools/quic/quic_simple_server.h" +#include "base/stl_util.h" #include "net/third_party/quic/core/crypto/quic_random.h" #include "net/third_party/quic/core/quic_crypto_stream.h" #include "net/third_party/quic/core/quic_utils.h" @@ -72,7 +73,7 @@ // private flags 0x00}; quic::QuicReceivedPacket encrypted_valid_packet( - reinterpret_cast<char*>(valid_packet), arraysize(valid_packet), + reinterpret_cast<char*>(valid_packet), base::size(valid_packet), quic::QuicTime::Zero(), false); EXPECT_CALL(dispatcher_, ProcessPacket(_, _, _)).Times(1);
diff --git a/net/tools/tld_cleanup/tld_cleanup_util.cc b/net/tools/tld_cleanup/tld_cleanup_util.cc index 72db0a9..bf177ca1 100644 --- a/net/tools/tld_cleanup/tld_cleanup_util.cc +++ b/net/tools/tld_cleanup/tld_cleanup_util.cc
@@ -6,6 +6,7 @@ #include "base/files/file_util.h" #include "base/logging.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "url/gurl.h" @@ -140,8 +141,8 @@ size_t line_end = 0; bool is_private = false; RuleMap extra_rules; - int begin_private_length = arraysize(kBeginPrivateDomainsComment) - 1; - int end_private_length = arraysize(kEndPrivateDomainsComment) - 1; + int begin_private_length = base::size(kBeginPrivateDomainsComment) - 1; + int end_private_length = base::size(kEndPrivateDomainsComment) - 1; while (line_start < data.size()) { if (line_start + begin_private_length < data.size() && !data.compare(line_start, begin_private_length,
diff --git a/net/url_request/url_request_job_manager.cc b/net/url_request/url_request_job_manager.cc index ab244be..7fe0edf2 100644 --- a/net/url_request/url_request_job_manager.cc +++ b/net/url_request/url_request_job_manager.cc
@@ -7,6 +7,7 @@ #include <algorithm> #include "base/memory/singleton.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "net/base/load_flags.h" @@ -75,7 +76,7 @@ return job; // See if the request should be handled by a built-in protocol factory. - for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) { + for (size_t i = 0; i < base::size(kBuiltinFactories); ++i) { if (scheme == kBuiltinFactories[i].scheme) { URLRequestJob* new_job = (kBuiltinFactories[i].factory)(request, network_delegate, scheme); @@ -143,7 +144,7 @@ // static bool URLRequestJobManager::SupportsScheme(const std::string& scheme) { - for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) { + for (size_t i = 0; i < base::size(kBuiltinFactories); ++i) { if (base::LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme)) return true; }
diff --git a/net/url_request/url_request_simple_job_unittest.cc b/net/url_request/url_request_simple_job_unittest.cc index 02638c9..214dcf9 100644 --- a/net/url_request/url_request_simple_job_unittest.cc +++ b/net/url_request/url_request_simple_job_unittest.cc
@@ -8,9 +8,9 @@ #include <utility> #include "base/bind_helpers.h" -#include "base/macros.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "net/base/request_priority.h" @@ -37,7 +37,7 @@ static_assert(kRangeFirstPosition > 0 && kRangeFirstPosition < kRangeLastPosition && kRangeLastPosition < - static_cast<int>(arraysize(kTestData) - 1), + static_cast<int>(base::size(kTestData) - 1), "invalid range"); class MockSimpleJob : public URLRequestSimpleJob {
diff --git a/net/url_request/url_request_test_job.cc b/net/url_request/url_request_test_job.cc index cec55fc..5353577 100644 --- a/net/url_request/url_request_test_job.cc +++ b/net/url_request/url_request_test_job.cc
@@ -94,7 +94,7 @@ "HTTP/1.1 200 OK\n" "Content-type: text/html\n" "\n"; - return std::string(kHeaders, arraysize(kHeaders)); + return std::string(kHeaders, base::size(kHeaders)); } // static getter for redirect response headers @@ -103,7 +103,7 @@ "HTTP/1.1 302 MOVED\n" "Location: somewhere\n" "\n"; - return std::string(kHeaders, arraysize(kHeaders)); + return std::string(kHeaders, base::size(kHeaders)); } // static getter for redirect response headers @@ -133,7 +133,7 @@ static const char kHeaders[] = "HTTP/1.1 500 BOO HOO\n" "\n"; - return std::string(kHeaders, arraysize(kHeaders)); + return std::string(kHeaders, base::size(kHeaders)); } // static
diff --git a/net/url_request/url_request_throttler_simulation_unittest.cc b/net/url_request/url_request_throttler_simulation_unittest.cc index 48ff6698..b52ce78 100644 --- a/net/url_request/url_request_throttler_simulation_unittest.cc +++ b/net/url_request/url_request_throttler_simulation_unittest.cc
@@ -18,8 +18,8 @@ #include <vector> #include "base/environment.h" -#include "base/macros.h" #include "base/rand_util.h" +#include "base/stl_util.h" #include "base/test/scoped_task_environment.h" #include "base/time/time.h" #include "net/base/request_priority.h" @@ -708,7 +708,7 @@ // If things don't converge by the time we've done 100K trials, then // clearly one or more of the expected intervals are wrong. while (global_stats.num_runs < 100000) { - for (size_t i = 0; i < arraysize(trials); ++i) { + for (size_t i = 0; i < base::size(trials); ++i) { ++global_stats.num_runs; ++trials[i].stats.num_runs; double ratio_unprotected = SimulateDowntime( @@ -736,7 +736,7 @@ // Print individual trial results for optional manual evaluation. double max_increase_ratio = 0.0; - for (size_t i = 0; i < arraysize(trials); ++i) { + for (size_t i = 0; i < base::size(trials); ++i) { double increase_ratio; trials[i].stats.DidConverge(&increase_ratio); max_increase_ratio = std::max(max_increase_ratio, increase_ratio);
diff --git a/net/url_request/url_request_throttler_unittest.cc b/net/url_request/url_request_throttler_unittest.cc index 15d3bb4..c9e1db4 100644 --- a/net/url_request/url_request_throttler_unittest.cc +++ b/net/url_request/url_request_throttler_unittest.cc
@@ -247,7 +247,7 @@ TimeAndBool(now_ - lifetime, true, __LINE__), TimeAndBool(now_ - (lifetime + kFiveMs), true, __LINE__)}; - for (unsigned int i = 0; i < arraysize(test_values); ++i) { + for (unsigned int i = 0; i < base::size(test_values); ++i) { entry_->set_exponential_backoff_release_time(test_values[i].time); EXPECT_EQ(entry_->IsEntryOutdated(), test_values[i].result) << "Test case #" << i << " line " << test_values[i].line << " failed"; @@ -353,7 +353,7 @@ std::string("http://www.example.com:1234/"), __LINE__)}; - for (unsigned int i = 0; i < arraysize(test_values); ++i) { + for (unsigned int i = 0; i < base::size(test_values); ++i) { std::string temp = manager.DoGetUrlIdFromUrl(test_values[i].url); EXPECT_EQ(temp, test_values[i].result) << "Test case #" << i << " line " << test_values[i].line << " failed";
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 951c087d..a3c511d6 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -30,7 +30,6 @@ #include "base/format_macros.h" #include "base/json/json_reader.h" #include "base/location.h" -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" @@ -38,6 +37,7 @@ #include "base/power_monitor/power_monitor_source.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" @@ -3960,7 +3960,7 @@ req->set_upload(CreateSimpleUploadData(kData)); HttpRequestHeaders headers; headers.SetHeader(HttpRequestHeaders::kContentLength, - base::NumberToString(arraysize(kData) - 1)); + base::NumberToString(base::size(kData) - 1)); headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain"); req->SetExtraRequestHeaders(headers); } @@ -4211,7 +4211,7 @@ BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS, BlockingNetworkDelegate::ON_HEADERS_RECEIVED }; - static const size_t blocking_stages_length = arraysize(blocking_stages); + static const size_t blocking_stages_length = base::size(blocking_stages); ASSERT_TRUE(http_test_server()->Start()); @@ -4497,7 +4497,7 @@ r->set_upload(CreateSimpleUploadData(kData)); HttpRequestHeaders headers; headers.SetHeader(HttpRequestHeaders::kContentLength, - base::NumberToString(arraysize(kData) - 1)); + base::NumberToString(base::size(kData) - 1)); r->SetExtraRequestHeaders(headers); // Quit after hitting the redirect, so can check the headers. @@ -5249,7 +5249,7 @@ // M - Medium length (between C & U). // S - Small length (smaller than both C & U). const char test_parameters[] = "CULMS"; - const int num_tests = arraysize(test_parameters)- 1; // Skip NULL. + const int num_tests = base::size(test_parameters) - 1; // Skip NULL. // C & U should be OK. // L & M are larger than the data sent, and show an error. // S has too little data, but we seem to accept it. @@ -8186,7 +8186,7 @@ req->set_upload(CreateSimpleUploadData(kData)); HttpRequestHeaders headers; headers.SetHeader(HttpRequestHeaders::kContentLength, - base::NumberToString(arraysize(kData) - 1)); + base::NumberToString(base::size(kData) - 1)); req->SetExtraRequestHeaders(headers); std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob( @@ -8213,7 +8213,7 @@ req->set_upload(CreateSimpleUploadData(kData)); HttpRequestHeaders headers; headers.SetHeader(HttpRequestHeaders::kContentLength, - base::NumberToString(arraysize(kData) - 1)); + base::NumberToString(base::size(kData) - 1)); req->SetExtraRequestHeaders(headers); std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob( @@ -8396,7 +8396,7 @@ {"/echoheader?Accept-Charset", "None"}, {"/echoheader?User-Agent", ""}}; - for (size_t i = 0; i < arraysize(tests); i++) { + for (size_t i = 0; i < base::size(tests); i++) { TestDelegate d; std::unique_ptr<URLRequest> req(context.CreateRequest( http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
diff --git a/net/websockets/websocket_basic_stream_test.cc b/net/websockets/websocket_basic_stream_test.cc index b3a0e88..9121703 100644 --- a/net/websockets/websocket_basic_stream_test.cc +++ b/net/websockets/websocket_basic_stream_test.cc
@@ -15,7 +15,7 @@ #include "base/big_endian.h" #include "base/containers/span.h" -#include "base/macros.h" +#include "base/stl_util.h" #include "net/base/test_completion_callback.h" #include "net/log/test_net_log.h" #include "net/socket/socket_tag.h" @@ -33,7 +33,7 @@ #define WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(name, value) \ const char k##name[] = value; \ - const size_t k##name##Size = arraysize(k##name) - 1; + const size_t k##name##Size = base::size(k##name) - 1; WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(SampleFrame, "\x81\x06Sample"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT( @@ -828,7 +828,7 @@ // reserved flag(s) set on the first chunk when split. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, ReservedFlagCleared) { static const char kReservedFlagFrame[] = "\x41\x05Hello"; - const size_t kReservedFlagFrameSize = arraysize(kReservedFlagFrame) - 1; + const size_t kReservedFlagFrameSize = base::size(kReservedFlagFrame) - 1; const size_t kChunkSize = 5; CreateChunkedRead(ASYNC,
diff --git a/net/websockets/websocket_channel.cc b/net/websockets/websocket_channel.cc index 7b435771..5c44c53 100644 --- a/net/websockets/websocket_channel.cc +++ b/net/websockets/websocket_channel.cc
@@ -15,11 +15,11 @@ #include "base/bind.h" #include "base/containers/circular_deque.h" #include "base/location.h" -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/numerics/safe_conversions.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" @@ -80,7 +80,7 @@ 5000, 65536, // Codes above 5000 are invalid. }; const int* const kInvalidRangesEnd = - kInvalidRanges + arraysize(kInvalidRanges); + kInvalidRanges + base::size(kInvalidRanges); DCHECK_GE(code, 0); DCHECK_LT(code, 65536);
diff --git a/net/websockets/websocket_channel_test.cc b/net/websockets/websocket_channel_test.cc index 48500572..c7fbb58a0 100644 --- a/net/websockets/websocket_channel_test.cc +++ b/net/websockets/websocket_channel_test.cc
@@ -20,10 +20,10 @@ #include "base/callback.h" #include "base/callback_helpers.h" #include "base/location.h" -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/completion_once_callback.h" @@ -128,7 +128,7 @@ '\b', // backspace '\'', // single-quote, special in PHP }; -const size_t kBinaryBlobSize = arraysize(kBinaryBlob); +const size_t kBinaryBlobSize = base::size(kBinaryBlob); // The amount of quota a new connection gets by default. // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
diff --git a/net/websockets/websocket_deflate_parameters_test.cc b/net/websockets/websocket_deflate_parameters_test.cc index 5149779b..bc6e282 100644 --- a/net/websockets/websocket_deflate_parameters_test.cc +++ b/net/websockets/websocket_deflate_parameters_test.cc
@@ -7,7 +7,7 @@ #include <string> #include <vector> -#include "base/macros.h" +#include "base/stl_util.h" #include "net/websockets/websocket_extension_parser.h" #include "testing/gtest/include/gtest/gtest.h" @@ -218,7 +218,7 @@ {"; hogefuga", kUnknownParameter}, }; return std::vector<InitializeTestParameter>( - parameters, parameters + arraysize(parameters)); + parameters, parameters + base::size(parameters)); } const CompatibilityTestParameter kCompatibilityTestParameters[] = {
diff --git a/net/websockets/websocket_extension_parser_test.cc b/net/websockets/websocket_extension_parser_test.cc index f726b3e..c4bc1713 100644 --- a/net/websockets/websocket_extension_parser_test.cc +++ b/net/websockets/websocket_extension_parser_test.cc
@@ -6,6 +6,7 @@ #include <string> +#include "base/stl_util.h" #include "net/websockets/websocket_extension.h" #include "testing/gtest/include/gtest/gtest.h" @@ -142,7 +143,7 @@ "foo; bar=\"baz\\" // ends with backslash }; - for (size_t i = 0; i < arraysize(patterns); ++i) { + for (size_t i = 0; i < base::size(patterns); ++i) { WebSocketExtensionParser parser; EXPECT_FALSE(parser.Parse(patterns[i])); EXPECT_EQ(0U, parser.extensions().size());
diff --git a/net/websockets/websocket_frame_parser_test.cc b/net/websockets/websocket_frame_parser_test.cc index 2dcf4fbb..6ff9668 100644 --- a/net/websockets/websocket_frame_parser_test.cc +++ b/net/websockets/websocket_frame_parser_test.cc
@@ -8,6 +8,7 @@ #include <algorithm> #include <vector> +#include "base/stl_util.h" #include "net/base/io_buffer.h" #include "testing/gtest/include/gtest/gtest.h" @@ -16,13 +17,13 @@ namespace { const char kHello[] = "Hello, world!"; -const uint64_t kHelloLength = arraysize(kHello) - 1; +const uint64_t kHelloLength = base::size(kHello) - 1; const char kHelloFrame[] = "\x81\x0DHello, world!"; -const uint64_t kHelloFrameLength = arraysize(kHelloFrame) - 1; +const uint64_t kHelloFrameLength = base::size(kHelloFrame) - 1; const char kMaskedHelloFrame[] = "\x81\x8D\xDE\xAD\xBE\xEF" "\x96\xC8\xD2\x83\xB1\x81\x9E\x98\xB1\xDF\xD2\x8B\xFF"; -const uint64_t kMaskedHelloFrameLength = arraysize(kMaskedHelloFrame) - 1; +const uint64_t kMaskedHelloFrameLength = base::size(kMaskedHelloFrame) - 1; struct FrameHeaderTestCase { const char* frame_header; @@ -45,7 +46,7 @@ { "\x81\x7F\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 10, UINT64_C(0x7FFFFFFFFFFFFFFF), kWebSocketErrorMessageTooBig } }; -const int kNumFrameHeaderTests = arraysize(kFrameHeaderTests); +const int kNumFrameHeaderTests = base::size(kFrameHeaderTests); TEST(WebSocketFrameParserTest, DecodeNormalFrame) { WebSocketFrameParser parser; @@ -123,7 +124,7 @@ { "\x81\x05" "Ninth", 7, "Ninth", 5 }, { "\x81\x05" "Tenth", 7, "Tenth", 5 } }; - static const int kNumInputs = arraysize(kInputs); + static const int kNumInputs = base::size(kInputs); std::vector<char> input; // Concatenate all frames. @@ -429,7 +430,7 @@ { "\x81\x7F\x00\x00\x00\x00\x00\x00\x00\x00", 10 }, { "\x81\x7E\x00\x00\x00\x00\x00\x00\xFF\xFF", 10 }, }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); for (int i = 0; i < kNumTests; ++i) { const char* frame_header = kTests[i].frame_header; @@ -477,7 +478,7 @@ { "\x8E\x00", 2, 0xE }, { "\x8F\x00", 2, 0xF } }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); for (int i = 0; i < kNumTests; ++i) { const char* frame_header = kTests[i].frame_header; @@ -530,7 +531,7 @@ { "\x71\x00", 2, false, true, true, true }, { "\xF1\x00", 2, true, true, true, true } }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); for (int i = 0; i < kNumTests; ++i) { const char* frame_header = kTests[i].frame_header;
diff --git a/net/websockets/websocket_frame_perftest.cc b/net/websockets/websocket_frame_perftest.cc index bd1de1c6..55ff21d 100644 --- a/net/websockets/websocket_frame_perftest.cc +++ b/net/websockets/websocket_frame_perftest.cc
@@ -7,7 +7,7 @@ #include <algorithm> #include <vector> -#include "base/macros.h" +#include "base/stl_util.h" #include "base/test/perf_time_logger.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,7 +19,7 @@ const int kLongPayloadSize = 1 << 16; const char kMaskingKey[] = "\xFE\xED\xBE\xEF"; -static_assert(arraysize(kMaskingKey) == +static_assert(base::size(kMaskingKey) == WebSocketFrameHeader::kMaskingKeyLength + 1, "incorrect masking key size"); @@ -44,8 +44,8 @@ TEST_F(WebSocketFrameTestMaskBenchmark, BenchmarkMaskShortPayload) { static const char kShortPayload[] = "Short Payload"; - Benchmark( - "Frame_mask_short_payload", kShortPayload, arraysize(kShortPayload)); + Benchmark("Frame_mask_short_payload", kShortPayload, + base::size(kShortPayload)); } TEST_F(WebSocketFrameTestMaskBenchmark, BenchmarkMaskLongPayload) {
diff --git a/net/websockets/websocket_frame_test.cc b/net/websockets/websocket_frame_test.cc index 25a0e0c..24fa405 100644 --- a/net/websockets/websocket_frame_test.cc +++ b/net/websockets/websocket_frame_test.cc
@@ -8,8 +8,8 @@ #include <algorithm> #include <vector> -#include "base/macros.h" #include "base/memory/aligned_memory.h" +#include "base/stl_util.h" #include "net/base/net_errors.h" #include "testing/gtest/include/gtest/gtest.h" @@ -32,7 +32,7 @@ { "\x81\x7F\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 10, UINT64_C(0x7FFFFFFFFFFFFFFF) } }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); for (int i = 0; i < kNumTests; ++i) { WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText); @@ -53,7 +53,7 @@ TEST(WebSocketFrameHeaderTest, FrameLengthsWithMasking) { static const char kMaskingKey[] = "\xDE\xAD\xBE\xEF"; static_assert( - arraysize(kMaskingKey) - 1 == WebSocketFrameHeader::kMaskingKeyLength, + base::size(kMaskingKey) - 1 == WebSocketFrameHeader::kMaskingKeyLength, "incorrect masking key size"); struct TestCase { @@ -71,7 +71,7 @@ { "\x81\xFF\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xDE\xAD\xBE\xEF", 14, UINT64_C(0x7FFFFFFFFFFFFFFF) } }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); WebSocketMaskingKey masking_key; std::copy(kMaskingKey, @@ -120,7 +120,7 @@ { "\x8E\x00", 2, 0xE }, { "\x8F\x00", 2, 0xF } }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); for (int i = 0; i < kNumTests; ++i) { WebSocketFrameHeader header(kTests[i].opcode); @@ -156,7 +156,7 @@ { "\x71\x00", 2, false, true, true, true }, { "\xF1\x00", 2, true, true, true, true } }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); for (int i = 0; i < kNumTests; ++i) { WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText); @@ -197,7 +197,7 @@ { UINT64_C(0x10000), true, 14u }, { UINT64_C(0x7FFFFFFFFFFFFFFF), true, 14u } }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); for (int i = 0; i < kNumTests; ++i) { WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText); @@ -236,7 +236,7 @@ { "\x00\x00\x00\x00", 0, "FooBar", "FooBar", 6 }, { "\xFF\xFF\xFF\xFF", 0, "FooBar", "\xB9\x90\x90\xBD\x9E\x8D", 6 }, }; - static const int kNumTests = arraysize(kTests); + static const int kNumTests = base::size(kTests); for (int i = 0; i < kNumTests; ++i) { WebSocketMaskingKey masking_key; @@ -286,7 +286,7 @@ "\xda\xa8\x4b\x75\xa1\xcb\xa9\x77\x19\x4d\x6e\xdf\xc8\x08\x1c\xb6" "\x6d\xfb\x38\x04\x44\xd5\xba\x57\x9f\x76\xb0\x2e\x07\x91\xe6\xa8" }; - static const size_t kTestInputSize = arraysize(kTestInput) - 1; + static const size_t kTestInputSize = base::size(kTestInput) - 1; static const char kTestOutput[] = { "\xef\xcd\x47\xa5\xcb\x36\x12\x1d\xcb\xd7\xad\x72\xeb\x5d\x0d\xb5" "\xbb\x36\x80\xf5\x2e\x16\x76\x6d\x9b\x2c\x34\x34\xa9\xe0\x68\xc8" @@ -295,7 +295,7 @@ "\x08\x12\x11\xcb\x73\x71\xf3\xc9\xcb\xf7\x34\x61\x1a\xb2\x46\x08" "\xbf\x41\x62\xba\x96\x6f\xe0\xe9\x4d\xcc\xea\x90\xd5\x2b\xbc\x16" }; - static_assert(arraysize(kTestInput) == arraysize(kTestOutput), + static_assert(base::size(kTestInput) == base::size(kTestOutput), "output and input arrays should have the same length"); std::unique_ptr<char, base::AlignedFreeDeleter> scratch(static_cast<char*>( base::AlignedAlloc(kScratchBufferSize, kMaxVectorAlignment)));
diff --git a/net/websockets/websocket_stream_test.cc b/net/websockets/websocket_stream_test.cc index 501f967..ea98e67c 100644 --- a/net/websockets/websocket_stream_test.cc +++ b/net/websockets/websocket_stream_test.cc
@@ -11,11 +11,11 @@ #include "base/compiler_specific.h" #include "base/containers/span.h" -#include "base/macros.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_samples.h" #include "base/metrics/statistics_recorder.h" #include "base/run_loop.h" +#include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" @@ -207,7 +207,7 @@ "user-agent", "", "accept-encoding", "gzip, deflate", "accept-language", "en-us,fr"}; frames_.push_back(spdy_util_.ConstructSpdyGet( - kExtraRequestHeaders, arraysize(kExtraRequestHeaders) / 2, 1, + kExtraRequestHeaders, base::size(kExtraRequestHeaders) / 2, 1, DEFAULT_PRIORITY)); AddWrite(&frames_.back());
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index 6065220..28edeb6 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -144,6 +144,8 @@ #define SK_USE_LEGACY_DISTANCE_FIELDS #endif +#define SK_LEGACY_TESSELLATOR_CPU_COVERAGE + #ifndef SK_SUPPORT_LEGACY_PAINT_TEXTMEASURE #define SK_SUPPORT_LEGACY_PAINT_TEXTMEASURE #endif
diff --git a/storage/browser/fileapi/async_file_util_adapter.cc b/storage/browser/fileapi/async_file_util_adapter.cc index 4c46da8..e1cf9bca 100644 --- a/storage/browser/fileapi/async_file_util_adapter.cc +++ b/storage/browser/fileapi/async_file_util_adapter.cc
@@ -59,8 +59,21 @@ void GetFileInfo(FileSystemFileUtil* file_util, FileSystemOperationContext* context, - const FileSystemURL& url) { + const FileSystemURL& url, + bool calculate_total_size) { error_ = file_util->GetFileInfo(context, url, &file_info_, &platform_path_); + if (error_ == base::File::FILE_OK && calculate_total_size && + file_info_.is_directory) { + file_info_.size = 0; + auto enumerator = file_util->CreateFileEnumerator(context, url, true); + base::FilePath path = enumerator->Next(); + while (!path.empty()) { + if (!enumerator->IsDirectory()) { + file_info_.size += enumerator->Size(); + } + path = enumerator->Next(); + } + } } void CreateSnapshotFile(FileSystemFileUtil* file_util, @@ -95,8 +108,8 @@ AsyncFileUtil::ReadDirectoryCallback callback) { base::File::Info file_info; base::FilePath platform_path; - base::File::Error error = file_util->GetFileInfo( - context, url, &file_info, &platform_path); + base::File::Error error = + file_util->GetFileInfo(context, url, &file_info, &platform_path); if (error == base::File::FILE_OK && !file_info.is_directory) error = base::File::FILE_ERROR_NOT_A_DIRECTORY; @@ -114,7 +127,7 @@ const size_t kResultChunkSize = 100; std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator> file_enum( - file_util->CreateFileEnumerator(context, url)); + file_util->CreateFileEnumerator(context, url, false)); base::FilePath current; while (!(current = file_enum->Next()).empty()) { @@ -207,14 +220,17 @@ void AsyncFileUtilAdapter::GetFileInfo( std::unique_ptr<FileSystemOperationContext> context, const FileSystemURL& url, - int /* fields */, + int fields, GetFileInfoCallback callback) { FileSystemOperationContext* context_ptr = context.release(); GetFileInfoHelper* helper = new GetFileInfoHelper; + bool calculate_total_size = + (fields & FileSystemOperation::GET_METADATA_FIELD_TOTAL_SIZE); const bool success = context_ptr->task_runner()->PostTaskAndReply( FROM_HERE, BindOnce(&GetFileInfoHelper::GetFileInfo, Unretained(helper), - sync_file_util_.get(), base::Owned(context_ptr), url), + sync_file_util_.get(), base::Owned(context_ptr), url, + calculate_total_size), BindOnce(&GetFileInfoHelper::ReplyFileInfo, Owned(helper), std::move(callback))); DCHECK(success);
diff --git a/storage/browser/fileapi/async_file_util_adapter.h b/storage/browser/fileapi/async_file_util_adapter.h index 7a6add4..1a1d303 100644 --- a/storage/browser/fileapi/async_file_util_adapter.h +++ b/storage/browser/fileapi/async_file_util_adapter.h
@@ -58,7 +58,7 @@ StatusCallback callback) override; void GetFileInfo(std::unique_ptr<FileSystemOperationContext> context, const FileSystemURL& url, - int /* fields */, + int fields, GetFileInfoCallback callback) override; void ReadDirectory(std::unique_ptr<FileSystemOperationContext> context, const FileSystemURL& url,
diff --git a/storage/browser/fileapi/dragged_file_util.cc b/storage/browser/fileapi/dragged_file_util.cc index 5ddd394..9f913f2 100644 --- a/storage/browser/fileapi/dragged_file_util.cc +++ b/storage/browser/fileapi/dragged_file_util.cc
@@ -24,32 +24,51 @@ namespace { -// Simply enumerate each path from a given fileinfo set. -// Used to enumerate top-level paths of an isolated filesystem. +// Enumerate each path from a given fileinfo set. +// Used to enumerate top-level or recursive paths of an isolated filesystem. class SetFileEnumerator : public FileSystemFileUtil::AbstractFileEnumerator { public: - explicit SetFileEnumerator(const std::vector<FileInfo>& files) - : files_(files) { + SetFileEnumerator(const std::vector<FileInfo>& files, bool recursive) + : files_(files), recursive_(recursive) { file_iter_ = files_.begin(); } ~SetFileEnumerator() override = default; // AbstractFileEnumerator overrides. base::FilePath Next() override { - if (file_iter_ == files_.end()) - return base::FilePath(); - base::FilePath platform_file = (file_iter_++)->path; - NativeFileUtil::GetFileInfo(platform_file, &file_info_); - return platform_file; + if (recursive_enumerator_) { + base::FilePath platform_file = recursive_enumerator_->Next(); + if (platform_file.empty()) { + recursive_enumerator_.reset(); + } else { + file_info_.is_directory = recursive_enumerator_->IsDirectory(); + file_info_.size = recursive_enumerator_->Size(); + file_info_.last_modified = recursive_enumerator_->LastModifiedTime(); + return platform_file; + } + } + if (file_iter_ != files_.end()) { + base::FilePath platform_file = (file_iter_++)->path; + NativeFileUtil::GetFileInfo(platform_file, &file_info_); + if (recursive_ && file_info_.is_directory) { + recursive_enumerator_ = + NativeFileUtil::CreateFileEnumerator(platform_file, recursive_); + } + return platform_file; + } + return base::FilePath(); } int64_t Size() override { return file_info_.size; } bool IsDirectory() override { return file_info_.is_directory; } base::Time LastModifiedTime() override { return file_info_.last_modified; } private: - std::vector<FileInfo> files_; + const std::vector<FileInfo> files_; + const bool recursive_; std::vector<FileInfo>::const_iterator file_iter_; base::File::Info file_info_; + std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator> + recursive_enumerator_; }; } // namespace @@ -91,17 +110,18 @@ std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator> DraggedFileUtil::CreateFileEnumerator(FileSystemOperationContext* context, - const FileSystemURL& root) { + const FileSystemURL& root, + bool recursive) { DCHECK(root.is_valid()); if (!root.path().empty()) - return LocalFileUtil::CreateFileEnumerator(context, root); + return LocalFileUtil::CreateFileEnumerator(context, root, recursive); // Root path case. std::vector<FileInfo> toplevels; IsolatedContext::GetInstance()->GetDraggedFileInfo( root.filesystem_id(), &toplevels); return std::unique_ptr<AbstractFileEnumerator>( - new SetFileEnumerator(toplevels)); + new SetFileEnumerator(toplevels, recursive)); } } // namespace storage
diff --git a/storage/browser/fileapi/dragged_file_util.h b/storage/browser/fileapi/dragged_file_util.h index cbd33b30c..f5168a3 100644 --- a/storage/browser/fileapi/dragged_file_util.h +++ b/storage/browser/fileapi/dragged_file_util.h
@@ -30,7 +30,8 @@ base::FilePath* platform_path) override; std::unique_ptr<AbstractFileEnumerator> CreateFileEnumerator( FileSystemOperationContext* context, - const FileSystemURL& root_url) override; + const FileSystemURL& root_url, + bool recursive) override; private: DISALLOW_COPY_AND_ASSIGN(DraggedFileUtil);
diff --git a/storage/browser/fileapi/dragged_file_util_unittest.cc b/storage/browser/fileapi/dragged_file_util_unittest.cc index e004cf0..298f59a 100644 --- a/storage/browser/fileapi/dragged_file_util_unittest.cc +++ b/storage/browser/fileapi/dragged_file_util_unittest.cc
@@ -30,6 +30,7 @@ #include "storage/browser/test/async_file_test_helper.h" #include "storage/browser/test/fileapi_test_file_set.h" #include "storage/browser/test/test_file_system_context.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using content::AsyncFileTestHelper; @@ -553,4 +554,68 @@ } } +TEST_F(DraggedFileUtilTest, EnumerateTest) { + FileSystemURL url = + GetFileSystemURL(base::FilePath(FILE_PATH_LITERAL("dir a"))); + auto enumerator = file_util()->CreateFileEnumerator( + GetOperationContext().get(), url, false); + std::vector<base::FilePath> contents; + for (base::FilePath path = enumerator->Next(); !path.empty(); + path = enumerator->Next()) { + base::FilePath relative; + root_path() + .Append(base::FilePath(FILE_PATH_LITERAL("a"))) + .AppendRelativePath(path, &relative); + contents.push_back(relative); + } + EXPECT_THAT(contents, testing::UnorderedElementsAre( + base::FilePath(FILE_PATH_LITERAL("dir a/dir A")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/file 0")) + .NormalizePathSeparators())); +} + +TEST_F(DraggedFileUtilTest, EnumerateRecursivelyTest) { + FileSystemURL url = + GetFileSystemURL(base::FilePath(FILE_PATH_LITERAL("dir a"))); + auto enumerator = + file_util()->CreateFileEnumerator(GetOperationContext().get(), url, true); + std::vector<base::FilePath> contents; + for (base::FilePath path = enumerator->Next(); !path.empty(); + path = enumerator->Next()) { + base::FilePath relative; + root_path() + .Append(base::FilePath(FILE_PATH_LITERAL("a"))) + .AppendRelativePath(path, &relative); + contents.push_back(relative); + } + EXPECT_THAT( + contents, + testing::UnorderedElementsAre( + base::FilePath(FILE_PATH_LITERAL("dir a/dir A")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/file 0")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d/dir e")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d/dir e/dir f")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d/dir e/dir g")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d/dir e/dir g/file 0")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d/dir e/dir g/file 1")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d/dir e/dir g/file 2")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d/dir e/dir g/file 3")) + .NormalizePathSeparators(), + base::FilePath(FILE_PATH_LITERAL("dir a/dir d/dir e/dir h")) + .NormalizePathSeparators())); +} + } // namespace content
diff --git a/storage/browser/fileapi/file_system_file_util.h b/storage/browser/fileapi/file_system_file_util.h index d2448436..57a0735 100644 --- a/storage/browser/fileapi/file_system_file_util.h +++ b/storage/browser/fileapi/file_system_file_util.h
@@ -101,7 +101,8 @@ // instance. virtual std::unique_ptr<AbstractFileEnumerator> CreateFileEnumerator( FileSystemOperationContext* context, - const FileSystemURL& root_url) = 0; + const FileSystemURL& root_url, + bool recursive) = 0; // Maps |file_system_url| given |context| into |local_file_path| // which represents physical file location on the host OS.
diff --git a/storage/browser/fileapi/file_system_operation.h b/storage/browser/fileapi/file_system_operation.h index 5b02db07..14ca1eb7 100644 --- a/storage/browser/fileapi/file_system_operation.h +++ b/storage/browser/fileapi/file_system_operation.h
@@ -226,9 +226,18 @@ // Fields requested for the GetMetadata method. Used as a bitmask. enum GetMetadataField { GET_METADATA_FIELD_NONE = 0, + + // Returns the size of the target. Undefined for directories. + // See also GET_METADATA_FIELD_TOTAL_SIZE. GET_METADATA_FIELD_SIZE = 1 << 0, + GET_METADATA_FIELD_IS_DIRECTORY = 1 << 1, - GET_METADATA_FIELD_LAST_MODIFIED = 1 << 2 + + GET_METADATA_FIELD_LAST_MODIFIED = 1 << 2, + + // If the target is directory, then total size of directory contents + // is returned, otherwise it's identical to GET_METADATA_FIELD_SIZE. + GET_METADATA_FIELD_TOTAL_SIZE = 1 << 3, }; // Used for Write().
diff --git a/storage/browser/fileapi/local_file_util.cc b/storage/browser/fileapi/local_file_util.cc index 40996baf..951bfac 100644 --- a/storage/browser/fileapi/local_file_util.cc +++ b/storage/browser/fileapi/local_file_util.cc
@@ -30,11 +30,11 @@ public: LocalFileEnumerator(const base::FilePath& platform_root_path, const base::FilePath& virtual_root_path, + bool recursive, int file_type) - : file_enum_(platform_root_path, false /* recursive */, file_type), + : file_enum_(platform_root_path, recursive, file_type), platform_root_path_(platform_root_path), - virtual_root_path_(virtual_root_path) { - } + virtual_root_path_(virtual_root_path) {} ~LocalFileEnumerator() override = default; @@ -138,14 +138,15 @@ std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator> LocalFileUtil::CreateFileEnumerator(FileSystemOperationContext* context, - const FileSystemURL& root_url) { + const FileSystemURL& root_url, + bool recursive) { base::FilePath file_path; if (GetLocalFilePath(context, root_url, &file_path) != base::File::FILE_OK) { return base::WrapUnique(new EmptyFileEnumerator); } return std::make_unique<LocalFileEnumerator>( - file_path, root_url.path(), + file_path, root_url.path(), recursive, base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES); }
diff --git a/storage/browser/fileapi/local_file_util.h b/storage/browser/fileapi/local_file_util.h index 6406a30..47c98367 100644 --- a/storage/browser/fileapi/local_file_util.h +++ b/storage/browser/fileapi/local_file_util.h
@@ -47,7 +47,8 @@ base::FilePath* platform_file) override; std::unique_ptr<AbstractFileEnumerator> CreateFileEnumerator( FileSystemOperationContext* context, - const FileSystemURL& root_url) override; + const FileSystemURL& root_url, + bool recursive) override; base::File::Error GetLocalFilePath(FileSystemOperationContext* context, const FileSystemURL& file_system_url, base::FilePath* local_file_path) override;
diff --git a/storage/browser/fileapi/obfuscated_file_util.cc b/storage/browser/fileapi/obfuscated_file_util.cc index 36af9ac..0b51251 100644 --- a/storage/browser/fileapi/obfuscated_file_util.cc +++ b/storage/browser/fileapi/obfuscated_file_util.cc
@@ -409,16 +409,8 @@ if (!db->GetFileWithPath(url.path(), &file_id)) return base::File::FILE_ERROR_NOT_FOUND; FileInfo local_info; - return GetFileInfoInternal(db, context, url, - file_id, &local_info, - file_info, platform_file_path); -} - -std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator> -ObfuscatedFileUtil::CreateFileEnumerator(FileSystemOperationContext* context, - const FileSystemURL& root_url) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return CreateFileEnumerator(context, root_url, false /* recursive */); + return GetFileInfoInternal(db, context, url, file_id, &local_info, file_info, + platform_file_path); } base::File::Error ObfuscatedFileUtil::GetLocalFilePath(
diff --git a/storage/browser/fileapi/obfuscated_file_util.h b/storage/browser/fileapi/obfuscated_file_util.h index 742ffbd..77a4c432 100644 --- a/storage/browser/fileapi/obfuscated_file_util.h +++ b/storage/browser/fileapi/obfuscated_file_util.h
@@ -122,7 +122,8 @@ base::FilePath* platform_file) override; std::unique_ptr<AbstractFileEnumerator> CreateFileEnumerator( FileSystemOperationContext* context, - const FileSystemURL& root_url) override; + const FileSystemURL& root_url, + bool recursive) override; base::File::Error GetLocalFilePath(FileSystemOperationContext* context, const FileSystemURL& file_system_url, base::FilePath* local_path) override; @@ -152,12 +153,6 @@ base::File::Info* file_info, base::FilePath* platform_path) override; - // Same as the other CreateFileEnumerator, but with recursive support. - std::unique_ptr<AbstractFileEnumerator> CreateFileEnumerator( - FileSystemOperationContext* context, - const FileSystemURL& root_url, - bool recursive); - // Returns true if the directory |url| is empty. bool IsDirectoryEmpty( FileSystemOperationContext* context,
diff --git a/testing/libfuzzer/reproducing.md b/testing/libfuzzer/reproducing.md index 8fcfcf0..10ad0f2b 100644 --- a/testing/libfuzzer/reproducing.md +++ b/testing/libfuzzer/reproducing.md
@@ -1,21 +1,32 @@ # Reproducing libFuzzer and AFL crashes -libFuzzer and AFL crashes can be reproduced easily with the [ClusterFuzz Reproduce Tool]. However, -if you are unable to use the tool (e.g. unsupported platform, some other tool issue), you can still -reproduce the crash manually using the steps below: +libFuzzer and AFL crashes can be reproduced easily with the +[ClusterFuzz Reproduce Tool]. However, if you are unable to use the tool (e.g. +unsupported platform, some other tool issue), you can still reproduce the crash +manually using the steps below: *** note -**Requirements:** For Windows, you must convert the forward slashes (/) to backslashes (\\) in -the commands below and use `set` command instead of `export` to set the environment variable (step 4). -Note that these commands are intended to be used with cmd.exe, not PowerShell. +**Requirements:** For Windows, you must convert the forward slashes (/) to +backslashes (\\) in the commands below and use `set` command instead of `export` +to set the environment variable (step 4). Note that these commands are intended +to be used with cmd.exe, not PowerShell. *** +[TOC] + +## Crashes reported as Reproducible + +The majority of the bugs reported by ClusterFuzz have **Reproducible** label. +That means there is a testcase that can be used to reliably reproduce the crash. + 1. Download the testcase from ClusterFuzz. If you are CCed on an issue filed by - ClusterFuzz, a link to it is next to "Reproducer testcase" in the bug description. + ClusterFuzz, a link to it is next to "Reproducer testcase" in the bug + description. For the rest of this walkthrough, we call the path of this file: `$TESTCASE_PATH` and the fuzz target you want to reproduce a - crash on: `$FUZZER_NAME` (provided as "Fuzz target binary" in the bug description). + crash on: `$FUZZER_NAME` (provided as "Fuzz target binary" in the bug + description). 2. Generate gn build configuration: @@ -23,8 +34,8 @@ gn args out/fuzz ``` -This will open up an editor. Copy the gn configuration paramaters from the values -provided in `GN Config` section in the ClusterFuzz testcase report. + This will open up an editor. Copy the gn configuration parameters from the + values provided in `GN Config` section in the ClusterFuzz testcase report. 3. Build the fuzzer: @@ -33,10 +44,10 @@ autoninja -C out/fuzz $FUZZER_NAME ``` -4. Set the `*SAN_OPTIONS` environment variable as provided in the `Crash Stacktrace` section in the -testcase report. -Here is an example value of `ASAN_OPTIONS` that is similar to its value on -ClusterFuzz: +4. Set the `*SAN_OPTIONS` environment variable as provided in the + `Crash Stacktrace` section in the testcase report. + Here is an example value of `ASAN_OPTIONS` that is similar to its value on + ClusterFuzz: ``` export ASAN_OPTIONS=redzone=256:print_summary=1:handle_sigill=1:allocator_release_to_os_interval_ms=500:print_suppressions=0:strict_memcmp=1:allow_user_segv_handler=0:use_sigaltstack=1:handle_sigfpe=1:handle_sigbus=1:detect_stack_use_after_return=0:alloc_dealloc_mismatch=0:detect_leaks=0:print_scariness=1:allocator_may_return_null=1:handle_abort=1:check_malloc_usable_size=0:detect_container_overflow=0:quarantine_size_mb=256:detect_odr_violation=0:symbolize=1:handle_segv=1:fast_unwind_on_fatal=1 @@ -52,6 +63,49 @@ [File a bug] if you run into any issues. +## Crashes reported as Unreproducible + +ClusterFuzz generally does not report issues that it cannot reliably reproduce, +unless the following condition is met. If a certain crash is occurring often +enough, such a crash might be reported with **Unreproducible** label and an +explicit clarification that there is no convenient way to reproduce it. There +are two ways to work with such crashes. + +1. Try a speculative fix based on the stacktrace. Once the fix is landed, wait a + couple days and then check Crash Statistics section on the ClusterFuzz + testcase report page. If the fix works out, you will see that the crash is + not happening anymore. If the crash does not occur again for a little while, + ClusterFuzz will automatically close the issue as Verified. + +2. (libFuzzer only) Try to reproduce the whole fuzzing session. This workflow is + very similar to the one described above for the **Reproducible** crashes. The + only differences are: + + * On step 1, instead of downloading a single testcase, you need to download + corpus backup. This can be done using the following command: +``` +gsutil cp gs://clusterfuzz-libfuzzer-backup/corpus/libfuzzer/$FUZZER_NAME/latest.zip . +``` + + * Alternatively, you can navigate to the following URL in your browser and + download the `latest.zip` file: +``` +https://pantheon.corp.google.com/storage/browser/clusterfuzz-libfuzzer-backup/corpus/libfuzzer/$FUZZER_NAME +``` + + * Create an empty directory and unpack the corpus into it. + * Follow steps 2-4 in the **Reproducible** section above. + * On step 5, use the following command: + +``` +out/fuzz/$FUZZER_NAME -timeout=25 -rss_limit_mb=2048 -print_final_stats=1 $CORPUS_DIRECTORY_FROM_THE_PREVIOUS_STEP +``` + + * Wait and hope that the fuzzer will crash. + +Waiting for a crash to occur may take some time (up to 1hr), but if it happens, +you will be able to test the fix locally and/or somehow debug the issue. + [ClusterFuzz Reproduce Tool]: https://github.com/google/clusterfuzz-tools [File a bug]: https://bugs.chromium.org/p/chromium/issues/entry?component=Tools%3EStability%3ElibFuzzer&comment=What%20problem%20are%20you%20seeing [here]: getting_started.md#symbolize-stacktrace
diff --git a/third_party/blink/common/client_hints/client_hints.cc b/third_party/blink/common/client_hints/client_hints.cc index a340bd0..a4bc77c 100644 --- a/third_party/blink/common/client_hints/client_hints.cc +++ b/third_party/blink/common/client_hints/client_hints.cc
@@ -4,7 +4,7 @@ #include "third_party/blink/public/common/client_hints/client_hints.h" -#include "base/macros.h" +#include "base/stl_util.h" namespace blink { @@ -13,7 +13,7 @@ "rtt", "downlink", "ect"}; const size_t kClientHintsHeaderMappingCount = - arraysize(kClientHintsHeaderMapping); + base::size(kClientHintsHeaderMapping); const char* const kWebEffectiveConnectionTypeMapping[] = { "4g" /* Unknown */, "4g" /* Offline */, "slow-2g" /* Slow 2G */, @@ -21,6 +21,6 @@ }; const size_t kWebEffectiveConnectionTypeMappingCount = - arraysize(kWebEffectiveConnectionTypeMapping); + base::size(kWebEffectiveConnectionTypeMapping); } // namespace blink
diff --git a/third_party/blink/common/mime_util/mime_util.cc b/third_party/blink/common/mime_util/mime_util.cc index f166710..48f984e 100644 --- a/third_party/blink/common/mime_util/mime_util.cc +++ b/third_party/blink/common/mime_util/mime_util.cc
@@ -8,7 +8,7 @@ #include "base/containers/hash_tables.h" #include "base/lazy_instance.h" -#include "base/macros.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "net/base/mime_util.h" @@ -126,13 +126,13 @@ }; MimeUtil::MimeUtil() { - for (size_t i = 0; i < arraysize(kSupportedNonImageTypes); ++i) + for (size_t i = 0; i < base::size(kSupportedNonImageTypes); ++i) non_image_types_.insert(kSupportedNonImageTypes[i]); - for (size_t i = 0; i < arraysize(kSupportedImageTypes); ++i) + for (size_t i = 0; i < base::size(kSupportedImageTypes); ++i) image_types_.insert(kSupportedImageTypes[i]); - for (size_t i = 0; i < arraysize(kUnsupportedTextTypes); ++i) + for (size_t i = 0; i < base::size(kUnsupportedTextTypes); ++i) unsupported_text_types_.insert(kUnsupportedTextTypes[i]); - for (size_t i = 0; i < arraysize(kSupportedJavascriptTypes); ++i) { + for (size_t i = 0; i < base::size(kSupportedJavascriptTypes); ++i) { javascript_types_.insert(kSupportedJavascriptTypes[i]); non_image_types_.insert(kSupportedJavascriptTypes[i]); }
diff --git a/third_party/blink/common/origin_trials/trial_token_unittest.cc b/third_party/blink/common/origin_trials/trial_token_unittest.cc index 6d585a4..a3d7fd24 100644 --- a/third_party/blink/common/origin_trials/trial_token_unittest.cc +++ b/third_party/blink/common/origin_trials/trial_token_unittest.cc
@@ -6,7 +6,7 @@ #include <memory> -#include "base/macros.h" +#include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/test/simple_test_clock.h" @@ -561,19 +561,19 @@ invalid_timestamp_(base::Time::FromDoubleT(kInvalidTimestamp)), expected_signature_( std::string(reinterpret_cast<const char*>(kSampleTokenSignature), - arraysize(kSampleTokenSignature))), + base::size(kSampleTokenSignature))), expected_subdomain_signature_(std::string( reinterpret_cast<const char*>(kSampleSubdomainTokenSignature), - arraysize(kSampleSubdomainTokenSignature))), + base::size(kSampleSubdomainTokenSignature))), expected_nonsubdomain_signature_(std::string( reinterpret_cast<const char*>(kSampleNonSubdomainTokenSignature), - arraysize(kSampleNonSubdomainTokenSignature))), + base::size(kSampleNonSubdomainTokenSignature))), correct_public_key_( base::StringPiece(reinterpret_cast<const char*>(kTestPublicKey), - arraysize(kTestPublicKey))), + base::size(kTestPublicKey))), incorrect_public_key_( base::StringPiece(reinterpret_cast<const char*>(kTestPublicKey2), - arraysize(kTestPublicKey2))) {} + base::size(kTestPublicKey2))) {} protected: OriginTrialTokenStatus Extract(const std::string& token_text, @@ -712,7 +712,7 @@ ASSERT_EQ(OriginTrialTokenStatus::kSuccess, status); std::string expected_signature( std::string(reinterpret_cast<const char*>(kLargeValidTokenSignature), - arraysize(kLargeValidTokenSignature))); + base::size(kLargeValidTokenSignature))); EXPECT_EQ(expected_signature, token_signature); }
diff --git a/third_party/blink/common/origin_trials/trial_token_validator_unittest.cc b/third_party/blink/common/origin_trials/trial_token_validator_unittest.cc index 2b219e7..c9017607a 100644 --- a/third_party/blink/common/origin_trials/trial_token_validator_unittest.cc +++ b/third_party/blink/common/origin_trials/trial_token_validator_unittest.cc
@@ -9,8 +9,8 @@ #include <string> #include "base/bind.h" -#include "base/macros.h" #include "base/memory/ptr_util.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/test/simple_test_clock.h" #include "base/time/time.h" @@ -124,7 +124,7 @@ } base::StringPiece GetPublicKey() const override { return base::StringPiece(reinterpret_cast<const char*>(key_), - arraysize(kTestPublicKey)); + base::size(kTestPublicKey)); } bool IsFeatureDisabled(base::StringPiece feature) const override { return disabled_features_.count(feature.as_string()) > 0; @@ -158,10 +158,10 @@ insecure_origin_(url::Origin::Create(GURL(kInsecureOrigin))), valid_token_signature_( std::string(reinterpret_cast<const char*>(kSampleTokenSignature), - arraysize(kSampleTokenSignature))), + base::size(kSampleTokenSignature))), expired_token_signature_( std::string(reinterpret_cast<const char*>(kExpiredTokenSignature), - arraysize(kExpiredTokenSignature))), + base::size(kExpiredTokenSignature))), response_headers_(new net::HttpResponseHeaders("")) { TrialTokenValidator::SetOriginTrialPolicyGetter( base::BindRepeating([](OriginTrialPolicy* policy) { return policy; },
diff --git a/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc b/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc index 39c41dc8..c5a387c0 100644 --- a/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc +++ b/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc
@@ -104,15 +104,8 @@ arguments = {ScriptValue::From(script_state_of_listener, js_event)}; } - const bool is_beforeunload_event = - event.IsBeforeUnloadEvent() && - event.type() == event_type_names::kBeforeunload; - const bool is_print_event = - // TODO(yukishiino): Should check event.Is{Before,After}PrintEvent. - event.type() == event_type_names::kBeforeprint || - event.type() == event_type_names::kAfterprint; if (!event_handler_->IsRunnableOrThrowException( - (is_beforeunload_event || is_print_event) + event.ShouldDispatchEvenWhenExecutionContextIsPaused() ? V8EventHandlerNonNull::IgnorePause::kIgnore : V8EventHandlerNonNull::IgnorePause::kDontIgnore)) { return; @@ -164,6 +157,9 @@ // then return value will never be false, since in such cases // return value will have been coerced into either null or a // DOMString. + const bool is_beforeunload_event = + event.IsBeforeUnloadEvent() && + event.type() == event_type_names::kBeforeunload; if (is_beforeunload_event) { if (result_for_beforeunload) { event.preventDefault();
diff --git a/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc b/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc index 005f2db..015cf69 100644 --- a/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc +++ b/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc
@@ -54,22 +54,29 @@ // object, let element be null, and document be eventTarget's associated // Document. Element* element = nullptr; + const LocalDOMWindow* window = nullptr; Document* document = nullptr; - Node* node = event_target.ToNode(); - const DOMWindow* window = event_target.ToDOMWindow(); - if (node && node->IsElementNode()) { - element = ToElement(node); - document = &node->GetDocument(); - } else if (node && node->IsDocumentNode()) { - // Attributes for |blink::HTMLBodyElement| is treated as ones for - // |blink::Document| unlike the definition in standards. - document = &node->GetDocument(); + if (Node* node = event_target.ToNode()) { + if (node->IsDocumentNode()) { + // Some of content attributes for |HTMLBodyElement| are treated as ones + // for |Document| unlike the definition in HTML standard. Those content + // attributes are not listed in the Window-reflecting body element event + // handler set. + // https://html.spec.whatwg.org/C/#window-reflecting-body-element-event-handler-set + document = &node->GetDocument(); + } else { + element = ToElement(node); + document = &node->GetDocument(); + } + // EventTarget::GetExecutionContext() sometimes returns the document which + // created the EventTarget, and sometimes returns the document to which + // the EventTarget is currently attached. The former might be different + // from |document|. } else { - // TODO(crbug.com/891635): Add these checks here: - // DCHECK(window); - // DCHECK(event_target.ToLocalDOMWindow()); - // DCHECK_EQ(event_target.ToLocalDOMWindow()->document(), document); - document = To<Document>(execution_context_of_event_target); + window = event_target.ToLocalDOMWindow(); + DCHECK(window); + document = window->document(); + DCHECK_EQ(document, To<Document>(execution_context_of_event_target)); } DCHECK(document); @@ -83,7 +90,7 @@ v8::Context::Scope event_target_context_scope(v8_context_of_event_target); // Step 2. If scripting is disabled for document, then return null. - if (!document->AllowInlineEventHandler(node, this, source_url_, + if (!document->AllowInlineEventHandler(element, this, source_url_, position_.line_)) return v8::Null(GetIsolate()); @@ -126,7 +133,7 @@ // SVG requires to introduce evt as an alias to event in event handlers. // See ANNOTATION 3: https://www.w3.org/TR/SVG/interact.html#SVGEvents parameter_list[parameter_list_size++] = - V8String(isolate, node && node->IsSVGElement() ? "evt" : "event"); + V8String(isolate, element && element->IsSVGElement() ? "evt" : "event"); parameter_list[parameter_list_size++] = V8String(isolate, "source"); parameter_list[parameter_list_size++] = V8String(isolate, "lineno"); parameter_list[parameter_list_size++] = V8String(isolate, "colno"); @@ -135,7 +142,7 @@ // SVG requires to introduce evt as an alias to event in event handlers. // See ANNOTATION 3: https://www.w3.org/TR/SVG/interact.html#SVGEvents parameter_list[parameter_list_size++] = - V8String(isolate, node && node->IsSVGElement() ? "evt" : "event"); + V8String(isolate, element && element->IsSVGElement() ? "evt" : "event"); } DCHECK_LE(parameter_list_size, base::size(parameter_list)); @@ -159,8 +166,7 @@ V8String(isolate, source_url_), v8::Integer::New(isolate, position_.line_.ZeroBasedInt()), v8::Integer::New(isolate, position_.column_.ZeroBasedInt()), - // TODO(yukiy): consider which value should be passed here. - v8::True(isolate)); + v8::True(isolate)); // True as |SanitizeScriptErrors::kDoNotSanitize| v8::ScriptCompiler::Source source(V8String(isolate, script_body_), origin); v8::Local<v8::Function> compiled_function;
diff --git a/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc b/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc index ba7f69cd..0bcdc0b 100644 --- a/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc +++ b/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc
@@ -48,17 +48,8 @@ v8::Local<v8::Value> js_event) { // Step 10: Call a listener with event's currentTarget as receiver and event // and handle errors if thrown. - const bool is_beforeunload_event = - event.IsBeforeUnloadEvent() && - event.type() == event_type_names::kBeforeunload; - const bool is_print_event = - // TODO(yukishiino): Should check event.Is{Before,After}PrintEvent. - event.type() == event_type_names::kBeforeprint || - event.type() == event_type_names::kAfterprint; - const bool is_media_query_list_event = - event.InterfaceName() == event_interface_names::kMediaQueryListEvent; if (!event_listener_->IsRunnableOrThrowException( - (is_beforeunload_event || is_print_event || is_media_query_list_event) + event.ShouldDispatchEvenWhenExecutionContextIsPaused() ? V8EventListener::IgnorePause::kIgnore : V8EventListener::IgnorePause::kDontIgnore)) { return;
diff --git a/third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h b/third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h index d718c74b..b6aba65 100644 --- a/third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h +++ b/third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h
@@ -26,7 +26,7 @@ enum class SanitizeScriptErrors { // "muted errors" is false kDoNotSanitize, - // *muted errors" is true + // "muted errors" is true kSanitize };
diff --git a/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc b/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc index 1fac6f4..9c38e63d 100644 --- a/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc +++ b/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc
@@ -35,12 +35,11 @@ #include "third_party/blink/renderer/bindings/core/v8/script_source_code.h" #include "third_party/blink/renderer/bindings/core/v8/script_value.h" #include "third_party/blink/renderer/bindings/core/v8/source_location.h" -#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" -#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h" -#include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_function.h" #include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/use_counter.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" @@ -53,9 +52,8 @@ ScheduledAction* ScheduledAction::Create(ScriptState* script_state, ExecutionContext* target, - const ScriptValue& handler, + V8Function* handler, const Vector<ScriptValue>& arguments) { - DCHECK(handler.IsFunction()); if (!script_state->World().IsWorkerWorld()) { if (!BindingSecurity::ShouldAllowAccessToFrame( EnteredDOMWindow(script_state->GetIsolate()), @@ -84,21 +82,39 @@ return MakeGarbageCollected<ScheduledAction>(script_state, handler); } +ScheduledAction::ScheduledAction(ScriptState* script_state, + V8Function* function, + const Vector<ScriptValue>& arguments) + : script_state_(ScriptStateProtectingContext::Create(script_state)), + function_(function), + arguments_(arguments) {} + +ScheduledAction::ScheduledAction(ScriptState* script_state, const String& code) + : script_state_(ScriptStateProtectingContext::Create(script_state)), + code_(code) {} + +ScheduledAction::ScheduledAction(ScriptState* script_state) + : script_state_(ScriptStateProtectingContext::Create(script_state)) {} + ScheduledAction::~ScheduledAction() { // Verify that owning DOMTimer has eagerly disposed. - DCHECK(info_.IsEmpty()); + DCHECK(!script_state_); + DCHECK(!function_); + DCHECK(arguments_.IsEmpty()); + DCHECK(code_.IsNull()); } void ScheduledAction::Dispose() { - code_ = String(); - info_.Clear(); - function_.Clear(); script_state_->Reset(); script_state_.Clear(); + function_.Clear(); + arguments_.clear(); + code_ = String(); } void ScheduledAction::Trace(blink::Visitor* visitor) { visitor->Trace(script_state_); + visitor->Trace(function_); } void ScheduledAction::Execute(ExecutionContext* context) { @@ -128,47 +144,14 @@ } } -ScheduledAction::ScheduledAction(ScriptState* script_state, - const ScriptValue& function, - const Vector<ScriptValue>& arguments) - : ScheduledAction(script_state) { - DCHECK(function.IsFunction()); - function_.Set(script_state->GetIsolate(), - v8::Local<v8::Function>::Cast(function.V8Value())); - info_.ReserveCapacity(arguments.size()); - for (const ScriptValue& argument : arguments) - info_.Append(argument.V8Value()); -} - -ScheduledAction::ScheduledAction(ScriptState* script_state, const String& code) - : ScheduledAction(script_state) { - code_ = code; -} - -ScheduledAction::ScheduledAction(ScriptState* script_state) - : script_state_(ScriptStateProtectingContext::Create(script_state)), - info_(script_state->GetIsolate()) {} - void ScheduledAction::Execute(LocalFrame* frame) { DCHECK(script_state_->ContextIsValid()); + // https://html.spec.whatwg.org/C/#timer-initialisation-steps TRACE_EVENT0("v8", "ScheduledAction::execute"); - if (!function_.IsEmpty()) { + if (function_) { DVLOG(1) << "ScheduledAction::execute " << this << ": have function"; - v8::Local<v8::Function> function = - function_.NewLocal(script_state_->GetIsolate()); - ScriptState* script_state_for_func = - ScriptState::From(function->CreationContext()); - if (!script_state_for_func->ContextIsValid()) { - DVLOG(1) << "ScheduledAction::execute " << this - << ": function's context is empty"; - return; - } - Vector<v8::Local<v8::Value>> info; - CreateLocalHandlesForArgs(&info); - V8ScriptRunner::CallFunction( - function, frame->GetDocument(), script_state_->GetContext()->Global(), - info.size(), info.data(), script_state_->GetIsolate()); + function_->InvokeAndReportException(frame->DomWindow(), arguments_); } else { DVLOG(1) << "ScheduledAction::execute " << this << ": executing from source"; @@ -188,29 +171,12 @@ } void ScheduledAction::Execute(WorkerGlobalScope* worker) { + DCHECK(script_state_->ContextIsValid()); DCHECK(worker->GetThread()->IsCurrentThread()); - if (!script_state_->ContextIsValid()) { - DVLOG(1) << "ScheduledAction::execute " << this << ": context is empty"; - return; - } - - if (!function_.IsEmpty()) { - ScriptState::Scope scope(script_state_->Get()); - v8::Local<v8::Function> function = - function_.NewLocal(script_state_->GetIsolate()); - ScriptState* script_state_for_func = - ScriptState::From(function->CreationContext()); - if (!script_state_for_func->ContextIsValid()) { - DVLOG(1) << "ScheduledAction::execute " << this - << ": function's context is empty"; - return; - } - Vector<v8::Local<v8::Value>> info; - CreateLocalHandlesForArgs(&info); - V8ScriptRunner::CallFunction( - function, worker, script_state_->GetContext()->Global(), info.size(), - info.data(), script_state_->GetIsolate()); + // https://html.spec.whatwg.org/C/#timer-initialisation-steps + if (function_) { + function_->InvokeAndReportException(worker, arguments_); } else { // We're using |SanitizeScriptErrors::kDoNotSanitize| to keep the existing // behavior, but this causes failures on @@ -223,12 +189,4 @@ } } -void ScheduledAction::CreateLocalHandlesForArgs( - Vector<v8::Local<v8::Value>>* handles) { - wtf_size_t handle_count = SafeCast<wtf_size_t>(info_.Size()); - handles->ReserveCapacity(handle_count); - for (wtf_size_t i = 0; i < handle_count; ++i) - handles->push_back(info_.Get(i)); -} - } // namespace blink
diff --git a/third_party/blink/renderer/bindings/core/v8/scheduled_action.h b/third_party/blink/renderer/bindings/core/v8/scheduled_action.h index efc73bf..c49fe28b0 100644 --- a/third_party/blink/renderer/bindings/core/v8/scheduled_action.h +++ b/third_party/blink/renderer/bindings/core/v8/scheduled_action.h
@@ -31,9 +31,8 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCHEDULED_ACTION_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCHEDULED_ACTION_H_ -#include "third_party/blink/renderer/bindings/core/v8/v8_persistent_value_vector.h" -#include "third_party/blink/renderer/platform/bindings/scoped_persistent.h" -#include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/bindings/name_client.h" +#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/forward.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -41,47 +40,50 @@ namespace blink { -class LocalFrame; class ExecutionContext; +class LocalFrame; +class ScriptState; +class ScriptStateProtectingContext; class ScriptValue; +class V8Function; class WorkerGlobalScope; -class ScheduledAction final - : public GarbageCollectedFinalized<ScheduledAction> { +class ScheduledAction final : public GarbageCollectedFinalized<ScheduledAction>, + public NameClient { WTF_MAKE_NONCOPYABLE(ScheduledAction); public: static ScheduledAction* Create(ScriptState*, ExecutionContext* target, - const ScriptValue& handler, + V8Function* handler, const Vector<ScriptValue>& arguments); static ScheduledAction* Create(ScriptState*, ExecutionContext* target, const String& handler); - ScheduledAction(ScriptState*, - const ScriptValue& handler, - const Vector<ScriptValue>& arguments); - ScheduledAction(ScriptState*, const String& handler); - + explicit ScheduledAction(ScriptState*, + V8Function* handler, + const Vector<ScriptValue>& arguments); + explicit ScheduledAction(ScriptState*, const String& handler); // Creates an empty ScheduledAction. explicit ScheduledAction(ScriptState*); ~ScheduledAction(); + void Dispose(); void Trace(blink::Visitor*); + const char* NameInHeapSnapshot() const override { return "ScheduledAction"; } void Execute(ExecutionContext*); private: void Execute(LocalFrame*); void Execute(WorkerGlobalScope*); - void CreateLocalHandlesForArgs(Vector<v8::Local<v8::Value>>* handles); Member<ScriptStateProtectingContext> script_state_; - ScopedPersistent<v8::Function> function_; - V8PersistentValueVector<v8::Value> info_; + TraceWrapperMember<V8Function> function_; + Vector<ScriptValue> arguments_; String code_; };
diff --git a/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.cc.tmpl b/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.cc.tmpl index f17e0f58..6456a79 100644 --- a/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.cc.tmpl
@@ -24,6 +24,7 @@ #include "third_party/blink/renderer/core/style_property_shorthand.h" +#include "base/stl_util.h" // for base::size() #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -41,7 +42,7 @@ static StylePropertyShorthand {{property.name.to_lower_camel_case()}}Longhands( {{property.property_id}}, {{property.name.to_lower_camel_case()}}Properties, - arraysize({{property.name.to_lower_camel_case()}}Properties)); + base::size({{property.name.to_lower_camel_case()}}Properties)); return {{property.name.to_lower_camel_case()}}Longhands; } {% endfor %} @@ -53,7 +54,7 @@ &GetCSSPropertyOffsetDistance(), &GetCSSPropertyOffsetRotate(), }; - DEFINE_STATIC_LOCAL(StylePropertyShorthand, offsetLonghands, (CSSPropertyOffset, offsetProperties, arraysize(offsetProperties))); + DEFINE_STATIC_LOCAL(StylePropertyShorthand, offsetLonghands, (CSSPropertyOffset, offsetProperties, base::size(offsetProperties))); return offsetLonghands; }
diff --git a/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl b/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl index 96ede7f..46dc718 100644 --- a/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl
@@ -5,6 +5,7 @@ #include "third_party/blink/renderer/core/{{namespace|lower}}_element_factory.h" +#include "base/stl_util.h" // for base::size() #include "third_party/blink/renderer/core/{{namespace|lower}}_names.h" {% for header in tags|groupby('interface_header') %} #include "{{header[0]}}" @@ -56,7 +57,7 @@ { {{cpp_namespace}}::{{tag|symbol}}Tag, {{namespace}}{{tag|symbol}}Constructor }, {% endfor %} }; - for (size_t i = 0; i < arraysize(data); i++) + for (size_t i = 0; i < base::size(data); i++) g_{{namespace}}_constructors->Set(data[i].tag.LocalName(), data[i].func); }
diff --git a/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl b/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl index 9d0a310..acd9e0f 100644 --- a/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl
@@ -5,6 +5,7 @@ #include "{{this_include_path}}" +#include "base/stl_util.h" // for base::size() #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" namespace blink { @@ -33,7 +34,7 @@ {% endfor %} }; - for (size_t i = 0; i < arraysize(kNames); ++i) { + for (size_t i = 0; i < base::size(kNames); ++i) { StringImpl* impl = StringImpl::CreateStatic(kNames[i].name, kNames[i].length, kNames[i].hash); void* address = reinterpret_cast<AtomicString*>(&{{suffix|lower}}names_storage) + i; new (address) AtomicString(impl);
diff --git a/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl b/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl index eacbbd4..6fbf1ae5 100644 --- a/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl
@@ -7,6 +7,7 @@ #include <memory> +#include "base/stl_util.h" // for base::size() #include "third_party/blink/renderer/platform/wtf/static_constructors.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -76,7 +77,7 @@ size_t tag_i = 0; {% endif %} size_t attr_i = 0; - for (size_t i = 0; i < arraysize(kNames); ++i) { + for (size_t i = 0; i < base::size(kNames); ++i) { StringImpl* impl = StringImpl::CreateStatic(kNames[i].name, kNames[i].length, kNames[i].hash); {% if tags %} if (kNames[i].is_tag) {
diff --git a/third_party/blink/renderer/core/accessibility/ax_object_cache.cc b/third_party/blink/renderer/core/accessibility/ax_object_cache.cc index 8910b9bfe..8d5ba4bc 100644 --- a/third_party/blink/renderer/core/accessibility/ax_object_cache.cc +++ b/third_party/blink/renderer/core/accessibility/ax_object_cache.cc
@@ -31,6 +31,7 @@ #include <memory> #include "base/memory/ptr_util.h" +#include "base/stl_util.h" #include "third_party/blink/public/web/web_ax_enums.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/node.h" @@ -77,7 +78,7 @@ static ARIAWidgetSet* CreateARIARoleWidgetSet() { ARIAWidgetSet* widget_set = new HashSet<String, CaseFoldingHash>(); - for (size_t i = 0; i < arraysize(g_aria_widgets); ++i) + for (size_t i = 0; i < base::size(g_aria_widgets); ++i) widget_set->insert(String(g_aria_widgets[i])); return widget_set; } @@ -111,7 +112,8 @@ }; bool HasInteractiveARIAAttribute(const Element& element) { - for (size_t i = 0; i < arraysize(g_aria_interactive_widget_attributes); ++i) { + for (size_t i = 0; i < base::size(g_aria_interactive_widget_attributes); + ++i) { const char* attribute = g_aria_interactive_widget_attributes[i]; if (element.hasAttribute(attribute)) { return true;
diff --git a/third_party/blink/renderer/core/animation/animation_input_helpers.cc b/third_party/blink/renderer/core/animation/animation_input_helpers.cc index 3e215ff..557ed22d 100644 --- a/third_party/blink/renderer/core/animation/animation_input_helpers.cc +++ b/third_party/blink/renderer/core/animation/animation_input_helpers.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/animation/animation_input_helpers.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/animation/property_handle.h" #include "third_party/blink/renderer/core/css/css_value_list.h" #include "third_party/blink/renderer/core/css/parser/css_parser.h" @@ -200,7 +201,7 @@ &svg_names::kYChannelSelectorAttr, &svg_names::kZAttr, }; - for (size_t i = 0; i < arraysize(attributes); i++) { + for (size_t i = 0; i < base::size(attributes); i++) { DCHECK(!SVGElement::IsAnimatableCSSProperty(*attributes[i])); supported_attributes.Set(*attributes[i], attributes[i]); }
diff --git a/third_party/blink/renderer/core/css/css_computed_style_declaration.cc b/third_party/blink/renderer/core/css/css_computed_style_declaration.cc index 163d8275..742d04f 100644 --- a/third_party/blink/renderer/core/css/css_computed_style_declaration.cc +++ b/third_party/blink/renderer/core/css/css_computed_style_declaration.cc
@@ -24,6 +24,7 @@ #include "third_party/blink/renderer/core/css/css_computed_style_declaration.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/computed_style_css_value_mapping.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_primitive_value.h" @@ -199,7 +200,7 @@ DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ()); if (properties.IsEmpty()) { CSSProperty::FilterEnabledCSSPropertiesIntoVector( - kComputedPropertyArray, arraysize(kComputedPropertyArray), properties); + kComputedPropertyArray, base::size(kComputedPropertyArray), properties); } return properties; }
diff --git a/third_party/blink/renderer/core/css/css_gradient_value.cc b/third_party/blink/renderer/core/css/css_gradient_value.cc index 8e7d83f..e210029 100644 --- a/third_party/blink/renderer/core/css/css_gradient_value.cc +++ b/third_party/blink/renderer/core/css/css_gradient_value.cc
@@ -29,6 +29,8 @@ #include <algorithm> #include <tuple> #include <utility> + +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/css_calculation_value.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h" @@ -1203,7 +1205,7 @@ unsigned corner_index = 0; float distance = (point - corners[corner_index]).DiagonalLength(); - for (unsigned i = 1; i < arraysize(corners); ++i) { + for (unsigned i = 1; i < base::size(corners); ++i) { float new_distance = (point - corners[i]).DiagonalLength(); if (compare(new_distance, distance)) { corner_index = i;
diff --git a/third_party/blink/renderer/core/css/css_selector.cc b/third_party/blink/renderer/core/css/css_selector.cc index 8b651b9b..6a6519c2 100644 --- a/third_party/blink/renderer/core/css/css_selector.cc +++ b/third_party/blink/renderer/core/css/css_selector.cc
@@ -28,6 +28,8 @@ #include <algorithm> #include <memory> + +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/css_markup.h" #include "third_party/blink/renderer/core/css/css_selector_list.h" #include "third_party/blink/renderer/core/css/parser/css_parser_context.h" @@ -419,11 +421,11 @@ if (has_arguments) { pseudo_type_map = kPseudoTypeWithArgumentsMap; pseudo_type_map_end = - kPseudoTypeWithArgumentsMap + arraysize(kPseudoTypeWithArgumentsMap); + kPseudoTypeWithArgumentsMap + base::size(kPseudoTypeWithArgumentsMap); } else { pseudo_type_map = kPseudoTypeWithoutArgumentsMap; pseudo_type_map_end = kPseudoTypeWithoutArgumentsMap + - arraysize(kPseudoTypeWithoutArgumentsMap); + base::size(kPseudoTypeWithoutArgumentsMap); } const NameToPseudoStruct* match = std::lower_bound( pseudo_type_map, pseudo_type_map_end, name,
diff --git a/third_party/blink/renderer/core/css/font_face_cache_test.cc b/third_party/blink/renderer/core/css/font_face_cache_test.cc index b80e262..0cc922c 100644 --- a/third_party/blink/renderer/core/css/font_face_cache_test.cc +++ b/third_party/blink/renderer/core/css/font_face_cache_test.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "third_party/blink/renderer/core/css/font_face_cache.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/css/css_font_face_src_value.h" #include "third_party/blink/renderer/core/css/css_font_family_value.h" @@ -11,7 +13,6 @@ #include "third_party/blink/renderer/core/css/css_segmented_font_face.h" #include "third_party/blink/renderer/core/css/css_value_list.h" #include "third_party/blink/renderer/core/css/font_face.h" -#include "third_party/blink/renderer/core/css/font_face_cache.h" #include "third_party/blink/renderer/core/css/style_rule.h" #include "third_party/blink/renderer/core/testing/page_test_base.h" @@ -70,7 +71,7 @@ CSSPropertyValue(GetCSSPropertyFontFamily(), *family_name), CSSPropertyValue(GetCSSPropertySrc(), *src_value_list)}; MutableCSSPropertyValueSet* font_face_descriptor = - MutableCSSPropertyValueSet::Create(properties, arraysize(properties)); + MutableCSSPropertyValueSet::Create(properties, base::size(properties)); font_face_descriptor->SetProperty(CSSPropertyFontStretch, stretch); font_face_descriptor->SetProperty(CSSPropertyFontStyle, style);
diff --git a/third_party/blink/renderer/core/css/media_query_list_event.h b/third_party/blink/renderer/core/css/media_query_list_event.h index c150a53..834144f 100644 --- a/third_party/blink/renderer/core/css/media_query_list_event.h +++ b/third_party/blink/renderer/core/css/media_query_list_event.h
@@ -60,6 +60,19 @@ return event_interface_names::kMediaQueryListEvent; } + // beforeprint/afterprint events need to be dispatched while the execution + // context is paused. When printing, window.print() invoked by beforeprint/ + // afterprint event listeners should have no effect, hence the event dispatch + // needs to be done during the pause. + // Accordingly, MediaQueryListEvent is also expected to be dispatched while + // printing. + bool ShouldDispatchEvenWhenExecutionContextIsPaused() const override { + // TODO(thestig,yukishiino): Probably it's better to return true only when + // we're actually printing. It's possible that execution contexts are + // paused for other reasons (e.g. other modal dialogs). + return true; + } + void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); visitor->Trace(media_query_list_);
diff --git a/third_party/blink/renderer/core/css/properties/css_property_base_custom.cc b/third_party/blink/renderer/core/css/properties/css_property_base_custom.cc index 11ba397..3748065 100644 --- a/third_party/blink/renderer/core/css/properties/css_property_base_custom.cc +++ b/third_party/blink/renderer/core/css/properties/css_property_base_custom.cc
@@ -6,6 +6,7 @@ #include "third_party/blink/renderer/core/css/properties/css_property.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/style/svg_computed_style.h" #include "third_party/blink/renderer/core/style_property_shorthand.h" @@ -16,8 +17,9 @@ static const CSSProperty* kProperties[4] = { &GetCSSPropertyBorderTop(), &GetCSSPropertyBorderRight(), &GetCSSPropertyBorderBottom(), &GetCSSPropertyBorderLeft()}; - DEFINE_STATIC_LOCAL(StylePropertyShorthand, border_directions, - (CSSPropertyBorder, kProperties, arraysize(kProperties))); + DEFINE_STATIC_LOCAL( + StylePropertyShorthand, border_directions, + (CSSPropertyBorder, kProperties, base::size(kProperties))); return border_directions; }
diff --git a/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc b/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc index 9ac731d0..6090928 100644 --- a/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc +++ b/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/css/properties/shorthands/border.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/css_initial_value.h" #include "third_party/blink/renderer/core/css/parser/css_parser_context.h" #include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h" @@ -52,7 +53,7 @@ static const CSSProperty* kProperties[3] = {&GetCSSPropertyBorderRight(), &GetCSSPropertyBorderBottom(), &GetCSSPropertyBorderLeft()}; - for (size_t i = 0; i < arraysize(kProperties); ++i) { + for (size_t i = 0; i < base::size(kProperties); ++i) { const CSSValue* value_for_side = kProperties[i]->CSSValueFromComputedStyle( style, layout_object, styled_node, allow_visited_style); if (!DataEquivalent(value, value_for_side)) {
diff --git a/third_party/blink/renderer/core/css/style_property_serializer.cc b/third_party/blink/renderer/core/css/style_property_serializer.cc index 1d94c51..ea3d503 100644 --- a/third_party/blink/renderer/core/css/style_property_serializer.cc +++ b/third_party/blink/renderer/core/css/style_property_serializer.cc
@@ -24,6 +24,8 @@ #include "third_party/blink/renderer/core/css/style_property_serializer.h" #include <bitset> + +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/css_custom_property_declaration.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_markup.h" @@ -1037,7 +1039,7 @@ const StylePropertyShorthand& color) const { const StylePropertyShorthand properties[3] = {width, style, color}; StringBuilder result; - for (size_t i = 0; i < arraysize(properties); ++i) { + for (size_t i = 0; i < base::size(properties); ++i) { String value = GetCommonValue(properties[i]); if (value.IsNull()) return String(); @@ -1056,7 +1058,7 @@ &GetCSSPropertyBorderImageSource(), &GetCSSPropertyBorderImageSlice(), &GetCSSPropertyBorderImageWidth(), &GetCSSPropertyBorderImageOutset(), &GetCSSPropertyBorderImageRepeat()}; - size_t length = arraysize(properties); + size_t length = base::size(properties); for (size_t i = 0; i < length; ++i) { const CSSValue& value = *property_set_.GetPropertyCSSValue(*properties[i]); if (!result.IsEmpty())
diff --git a/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc b/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc index 685c6bd2..7548c82 100644 --- a/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc +++ b/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc
@@ -21,6 +21,8 @@ #include "third_party/blink/renderer/core/style_property_shorthand.h" +#include "base/stl_util.h" + namespace blink { const StylePropertyShorthand& animationShorthandForParsing() { @@ -44,7 +46,7 @@ &GetCSSPropertyAnimationName()}; static StylePropertyShorthand webkit_animation_longhands_for_parsing( CSSPropertyAnimation, kAnimationPropertiesForParsing, - arraysize(kAnimationPropertiesForParsing)); + base::size(kAnimationPropertiesForParsing)); return webkit_animation_longhands_for_parsing; } @@ -57,7 +59,7 @@ &GetCSSPropertyTransitionDelay(), &GetCSSPropertyTransitionProperty()}; static StylePropertyShorthand transition_longhands( CSSPropertyTransition, kTransitionProperties, - arraysize(kTransitionProperties)); + base::size(kTransitionProperties)); return transition_longhands; }
diff --git a/third_party/blink/renderer/core/dom/events/event.h b/third_party/blink/renderer/core/dom/events/event.h index 654b6fa..c0570f71f 100644 --- a/third_party/blink/renderer/core/dom/events/event.h +++ b/third_party/blink/renderer/core/dom/events/event.h
@@ -308,6 +308,13 @@ legacy_did_listeners_throw_flag_ = true; } + // In general, event listeners do not run when related execution contexts are + // paused. However, when this function returns true, event listeners ignore + // the pause and run. + virtual bool ShouldDispatchEvenWhenExecutionContextIsPaused() const { + return false; + } + virtual DispatchEventResult DispatchEvent(EventDispatcher&); void Trace(blink::Visitor*) override;
diff --git a/third_party/blink/renderer/core/editing/commands/editing_command_test.cc b/third_party/blink/renderer/core/editing/commands/editing_command_test.cc index ece012f..fdd281e 100644 --- a/third_party/blink/renderer/core/editing/commands/editing_command_test.cc +++ b/third_party/blink/renderer/core/editing/commands/editing_command_test.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/stl_util.h" #include "third_party/blink/public/platform/web_editing_command_type.h" #include "third_party/blink/renderer/core/editing/commands/editor_command.h" #include "third_party/blink/renderer/core/editing/commands/editor_command_names.h" @@ -26,7 +27,7 @@ }; // Test all commands except WebEditingCommandType::Invalid. static_assert( - arraysize(kCommandNameEntries) + 1 == + base::size(kCommandNameEntries) + 1 == static_cast<size_t>(WebEditingCommandType::kNumberOfCommandTypes), "must test all valid WebEditingCommandType"); @@ -35,7 +36,7 @@ class EditingCommandTest : public EditingTestBase {}; TEST_F(EditingCommandTest, EditorCommandOrder) { - for (size_t i = 1; i < arraysize(kCommandNameEntries); ++i) { + for (size_t i = 1; i < base::size(kCommandNameEntries); ++i) { EXPECT_GT(0, strcasecmp(kCommandNameEntries[i - 1].name, kCommandNameEntries[i].name)) << "EDITOR_COMMAND_MAP must be case-folding ordered. Incorrect index:"
diff --git a/third_party/blink/renderer/core/editing/commands/editor_command.cc b/third_party/blink/renderer/core/editing/commands/editor_command.cc index ccb6ef7..12a1440 100644 --- a/third_party/blink/renderer/core/editing/commands/editor_command.cc +++ b/third_party/blink/renderer/core/editing/commands/editor_command.cc
@@ -90,7 +90,7 @@ }; // Handles all commands except WebEditingCommandType::Invalid. static_assert( - arraysize(kCommandNameEntries) + 1 == + base::size(kCommandNameEntries) + 1 == static_cast<size_t>(WebEditingCommandType::kNumberOfCommandTypes), "must handle all valid WebEditingCommandType"); @@ -1787,7 +1787,7 @@ }; // Handles all commands except WebEditingCommandType::Invalid. static_assert( - arraysize(kEditorCommands) + 1 == + base::size(kEditorCommands) + 1 == static_cast<size_t>(WebEditingCommandType::kNumberOfCommandTypes), "must handle all valid WebEditingCommandType"); @@ -1798,7 +1798,7 @@ int command_index = static_cast<int>(command_type) - 1; DCHECK(command_index >= 0 && - command_index < static_cast<int>(arraysize(kEditorCommands))); + command_index < static_cast<int>(base::size(kEditorCommands))); return &kEditorCommands[command_index]; }
diff --git a/third_party/blink/renderer/core/editing/editing_style.cc b/third_party/blink/renderer/core/editing/editing_style.cc index 14f3e07..3a318172 100644 --- a/third_party/blink/renderer/core/editing/editing_style.cc +++ b/third_party/blink/renderer/core/editing/editing_style.cc
@@ -26,6 +26,7 @@ #include "third_party/blink/renderer/core/editing/editing_style.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/css_color_value.h" #include "third_party/blink/renderer/core/css/css_computed_style_declaration.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" @@ -98,7 +99,7 @@ DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ()); if (properties.IsEmpty()) { CSSProperty::FilterEnabledCSSPropertiesIntoVector( - kStaticEditingProperties, arraysize(kStaticEditingProperties), + kStaticEditingProperties, base::size(kStaticEditingProperties), properties); for (wtf_size_t index = 0; index < properties.size(); index++) { if (properties[index]->IDEquals(CSSPropertyTextDecoration)) { @@ -114,7 +115,7 @@ DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ()); if (properties.IsEmpty()) { CSSProperty::FilterEnabledCSSPropertiesIntoVector( - kStaticEditingProperties, arraysize(kStaticEditingProperties), + kStaticEditingProperties, base::size(kStaticEditingProperties), properties); for (wtf_size_t index = 0; index < properties.size();) { if (!properties[index]->IsInherited()) { @@ -712,7 +713,7 @@ DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ()); if (properties.IsEmpty()) { CSSProperty::FilterEnabledCSSPropertiesIntoVector( - kStaticBlockProperties, arraysize(kStaticBlockProperties), properties); + kStaticBlockProperties, base::size(kStaticBlockProperties), properties); } return properties; } @@ -837,7 +838,7 @@ }; if (should_ignore_text_only_properties == kIgnoreTextOnlyProperties) { difference->RemovePropertiesInSet(kTextOnlyProperties, - arraysize(kTextOnlyProperties)); + base::size(kTextOnlyProperties)); } if (difference->IsEmpty())
diff --git a/third_party/blink/renderer/core/editing/iterators/search_buffer_test.cc b/third_party/blink/renderer/core/editing/iterators/search_buffer_test.cc index 2a5d4864..2411961 100644 --- a/third_party/blink/renderer/core/editing/iterators/search_buffer_test.cc +++ b/third_party/blink/renderer/core/editing/iterators/search_buffer_test.cc
@@ -30,6 +30,7 @@ #include "third_party/blink/renderer/core/editing/iterators/search_buffer.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/dom/range.h" #include "third_party/blink/renderer/core/editing/ephemeral_range.h" #include "third_party/blink/renderer/core/editing/testing/editing_test_base.h" @@ -71,7 +72,7 @@ static const UChar* invalid_u_strings[] = {kInvalid1, kInvalid2, kInvalid3}; - for (size_t i = 0; i < arraysize(invalid_u_strings); ++i) { + for (size_t i = 0; i < base::size(invalid_u_strings); ++i) { String invalid_target(invalid_u_strings[i]); EphemeralRange found_range = FindPlainText(EphemeralRange(range), invalid_target, 0);
diff --git a/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc b/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc index 298c557..789bf35 100644 --- a/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc +++ b/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc
@@ -27,6 +27,7 @@ #include "third_party/blink/renderer/core/editing/serializers/markup_formatter.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/dom/cdata_section.h" #include "third_party/blink/renderer/core/dom/comment.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -114,11 +115,11 @@ if (source.Is8Bit()) { AppendCharactersReplacingEntitiesInternal( result, source.Characters8() + offset, length, kEntityMaps, - arraysize(kEntityMaps), entity_mask); + base::size(kEntityMaps), entity_mask); } else { AppendCharactersReplacingEntitiesInternal( result, source.Characters16() + offset, length, kEntityMaps, - arraysize(kEntityMaps), entity_mask); + base::size(kEntityMaps), entity_mask); } }
diff --git a/third_party/blink/renderer/core/editing/state_machines/state_machine_util.cc b/third_party/blink/renderer/core/editing/state_machines/state_machine_util.cc index 64fe6ae2..9f3c4eb 100644 --- a/third_party/blink/renderer/core/editing/state_machines/state_machine_util.cc +++ b/third_party/blink/renderer/core/editing/state_machines/state_machine_util.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/editing/state_machines/state_machine_util.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/text/character.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/text/character_names.h" @@ -27,7 +28,7 @@ // Returns true if the code point has Indic_Syllabic_Category=Virama property. // See http://www.unicode.org/Public/9.0.0/ucd/IndicSyllabicCategory-9.0.0d2.txt bool IsIndicSyllabicCategoryVirama(uint32_t code_point) { - const int length = arraysize(kIndicSyllabicCategoryViramaList); + const int length = base::size(kIndicSyllabicCategoryViramaList); return std::binary_search(kIndicSyllabicCategoryViramaList, kIndicSyllabicCategoryViramaList + length, code_point);
diff --git a/third_party/blink/renderer/core/events/BUILD.gn b/third_party/blink/renderer/core/events/BUILD.gn index 3a4a613b..2247cd3 100644 --- a/third_party/blink/renderer/core/events/BUILD.gn +++ b/third_party/blink/renderer/core/events/BUILD.gn
@@ -6,12 +6,14 @@ blink_core_sources("events") { sources = [ + "after_print_event.h", "animation_event.cc", "animation_event.h", "animation_playback_event.cc", "animation_playback_event.h", "application_cache_error_event.cc", "application_cache_error_event.h", + "before_print_event.h", "before_text_inserted_event.cc", "before_text_inserted_event.h", "before_unload_event.cc",
diff --git a/third_party/blink/renderer/core/events/after_print_event.h b/third_party/blink/renderer/core/events/after_print_event.h new file mode 100644 index 0000000..5fad32c --- /dev/null +++ b/third_party/blink/renderer/core/events/after_print_event.h
@@ -0,0 +1,34 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_AFTER_PRINT_EVENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_AFTER_PRINT_EVENT_H_ + +#include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/event_type_names.h" + +namespace blink { + +class AfterPrintEvent final : public Event { + public: + static AfterPrintEvent* Create() { + return MakeGarbageCollected<AfterPrintEvent>(); + } + + AfterPrintEvent() + : Event(event_type_names::kAfterprint, Bubbles::kNo, Cancelable::kNo) {} + ~AfterPrintEvent() override = default; + + // beforeprint/afterprint events need to be dispatched while the execution + // context is paused. When printing, window.print() invoked by beforeprint/ + // afterprint event listeners should have no effect, hence the event dispatch + // needs to be done during the pause. + bool ShouldDispatchEvenWhenExecutionContextIsPaused() const override { + return true; + } +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_AFTER_PRINT_EVENT_H_
diff --git a/third_party/blink/renderer/core/events/before_print_event.h b/third_party/blink/renderer/core/events/before_print_event.h new file mode 100644 index 0000000..20b02b7 --- /dev/null +++ b/third_party/blink/renderer/core/events/before_print_event.h
@@ -0,0 +1,34 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_BEFORE_PRINT_EVENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_BEFORE_PRINT_EVENT_H_ + +#include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/event_type_names.h" + +namespace blink { + +class BeforePrintEvent final : public Event { + public: + static BeforePrintEvent* Create() { + return MakeGarbageCollected<BeforePrintEvent>(); + } + + BeforePrintEvent() + : Event(event_type_names::kBeforeprint, Bubbles::kNo, Cancelable::kNo) {} + ~BeforePrintEvent() override = default; + + // beforeprint/afterprint events need to be dispatched while the execution + // context is paused. When printing, window.print() invoked by beforeprint/ + // afterprint event listeners should have no effect, hence the event dispatch + // needs to be done during the pause. + bool ShouldDispatchEvenWhenExecutionContextIsPaused() const override { + return true; + } +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_BEFORE_PRINT_EVENT_H_
diff --git a/third_party/blink/renderer/core/events/before_unload_event.h b/third_party/blink/renderer/core/events/before_unload_event.h index 39d9fb8..2782808 100644 --- a/third_party/blink/renderer/core/events/before_unload_event.h +++ b/third_party/blink/renderer/core/events/before_unload_event.h
@@ -52,6 +52,13 @@ return event_interface_names::kBeforeUnloadEvent; } + // A confirmation dialog for leaving a page is expected to be shown + // regardless of the state of the page. So, beforeunload's event + // listeners should always run regardless of pause. + bool ShouldDispatchEvenWhenExecutionContextIsPaused() const override { + return true; + } + void Trace(blink::Visitor*) override; private:
diff --git a/third_party/blink/renderer/core/events/input_event.cc b/third_party/blink/renderer/core/events/input_event.cc index 26f6064..9b4eb53 100644 --- a/third_party/blink/renderer/core/events/input_event.cc +++ b/third_party/blink/renderer/core/events/input_event.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/events/input_event.h" +#include "base/stl_util.h" #include "third_party/blink/public/platform/web_editing_command_type.h" #include "third_party/blink/renderer/core/dom/events/event_dispatcher.h" #include "third_party/blink/renderer/core/dom/range.h" @@ -59,7 +60,7 @@ }; static_assert( - arraysize(kInputTypeStringNameMap) == + base::size(kInputTypeStringNameMap) == static_cast<size_t>(InputEvent::InputType::kNumberOfInputTypes), "must handle all InputEvent::InputType");
diff --git a/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc b/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc index 9149e70..23bcc09 100644 --- a/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc +++ b/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc
@@ -33,6 +33,7 @@ #include <memory> #include "base/memory/ptr_util.h" +#include "base/stl_util.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/platform.h" @@ -92,7 +93,7 @@ "invisible_iframe.html", "visible_iframe.html", "zero_sized_iframe.html", }; - for (size_t i = 0; i < arraysize(iframe_support_files); ++i) { + for (size_t i = 0; i < base::size(iframe_support_files); ++i) { RegisterMockedUrl(url_root, iframe_support_files[i]); }
diff --git a/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc b/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc index 4f11dc7f..e8f5c98 100644 --- a/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc +++ b/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc
@@ -481,6 +481,12 @@ it.value->UpdateAllOverlayLifecyclePhases(); } +void WebDevToolsAgentImpl::PaintOverlays(GraphicsContext& context) { + DCHECK(RuntimeEnabledFeatures::CompositeAfterPaintEnabled()); + for (auto& it : overlay_agents_) + it.value->PaintOverlay(context); +} + void WebDevToolsAgentImpl::DispatchBufferedTouchEvents() { for (auto& it : overlay_agents_) it.value->DispatchBufferedTouchEvents();
diff --git a/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h b/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h index 7102c7f..aae7408 100644 --- a/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h +++ b/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h
@@ -45,6 +45,7 @@ namespace blink { class ClientMessageLoopAdapter; +class GraphicsContext; class GraphicsLayer; class InspectedFrames; class InspectorNetworkAgent; @@ -80,7 +81,11 @@ void WillBeDestroyed(); void FlushProtocolNotifications(); + + bool HasOverlays() const { return !overlay_agents_.IsEmpty(); } void UpdateOverlays(); + void PaintOverlays(GraphicsContext&); // For CompositeAfterPaint. + bool HandleInputEvent(const WebInputEvent&); void DispatchBufferedTouchEvents(); void BindRequest(mojom::blink::DevToolsAgentHostAssociatedPtrInfo,
diff --git a/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc b/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc index ff21921..5d68324 100644 --- a/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc +++ b/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/public/web/web_frame_content_dumper.h" +#include "base/stl_util.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_view.h" @@ -47,7 +48,7 @@ // The separator between frames when the frames are converted to plain text. const LChar kFrameSeparator[] = {'\n', '\n'}; - const size_t frame_separator_length = arraysize(kFrameSeparator); + const size_t frame_separator_length = base::size(kFrameSeparator); // Recursively walk the children. const FrameTree& frame_tree = frame->Tree();
diff --git a/third_party/blink/renderer/core/exported/web_frame_test.cc b/third_party/blink/renderer/core/exported/web_frame_test.cc index 72d0d17..a4af77c1 100644 --- a/third_party/blink/renderer/core/exported/web_frame_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_test.cc
@@ -1882,7 +1882,7 @@ "viewport-auto-initial-scale.html", "viewport-target-densitydpi-device-and-fixed-width.html"}; float page_scale_factors[] = {0.5f, 1.0f}; - for (size_t i = 0; i < arraysize(pages); ++i) + for (size_t i = 0; i < base::size(pages); ++i) RegisterMockedHttpURLLoad(pages[i]); FixedLayoutTestWebViewClient client; @@ -1891,7 +1891,7 @@ int viewport_height = 300; float enforced_page_scale_factor = 0.75f; - for (size_t i = 0; i < arraysize(pages); ++i) { + for (size_t i = 0; i < base::size(pages); ++i) { for (int quirk_enabled = 0; quirk_enabled <= 1; ++quirk_enabled) { frame_test_helpers::WebViewHelper web_view_helper; web_view_helper.InitializeAndLoad(base_url_ + pages[i], nullptr, &client, @@ -1904,7 +1904,7 @@ web_view_helper.Resize(WebSize(viewport_width, viewport_height)); float expected_page_scale_factor = - quirk_enabled && i < arraysize(page_scale_factors) + quirk_enabled && i < base::size(page_scale_factors) ? page_scale_factors[i] : enforced_page_scale_factor; EXPECT_EQ(expected_page_scale_factor, @@ -2756,7 +2756,7 @@ int viewport_width = 640; int viewport_height = 480; - for (size_t i = 0; i < arraysize(device_scale_factors); ++i) { + for (size_t i = 0; i < base::size(device_scale_factors); ++i) { float device_scale_factor = device_scale_factors[i]; float device_dpi = device_scale_factor * 160.0f; client.screen_info_.device_scale_factor = device_scale_factor; @@ -2804,7 +2804,7 @@ int viewport_width = 640; int viewport_height = 480; - for (size_t i = 0; i < arraysize(device_scale_factors); ++i) { + for (size_t i = 0; i < base::size(device_scale_factors); ++i) { client.screen_info_.device_scale_factor = device_scale_factors[i]; frame_test_helpers::WebViewHelper web_view_helper; @@ -2847,7 +2847,7 @@ int viewport_width = 640; int viewport_height = 480; - for (size_t i = 0; i < arraysize(device_scale_factors); ++i) { + for (size_t i = 0; i < base::size(device_scale_factors); ++i) { client.screen_info_.device_scale_factor = device_scale_factors[i]; frame_test_helpers::WebViewHelper web_view_helper;
diff --git a/third_party/blink/renderer/core/exported/web_view_test.cc b/third_party/blink/renderer/core/exported/web_view_test.cc index 1ed18690..2254964 100644 --- a/third_party/blink/renderer/core/exported/web_view_test.cc +++ b/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -34,6 +34,7 @@ #include <memory> #include <string> +#include "base/stl_util.h" #include "base/time/time.h" #include "build/build_config.h" #include "cc/trees/layer_tree_host.h" @@ -1778,7 +1779,7 @@ Element* current_focus = nullptr; Element* next_focus = nullptr; int next_previous_flags; - for (size_t i = 0; i < arraysize(focused_elements); ++i) { + for (size_t i = 0; i < base::size(focused_elements); ++i) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = @@ -1798,7 +1799,7 @@ EXPECT_EQ(current_focus, document->FocusedElement()); // Backward Navigation in form1 with PREVIOUS - for (size_t i = arraysize(focused_elements); i-- > 0;) { + for (size_t i = base::size(focused_elements); i-- > 0;) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = @@ -1997,7 +1998,7 @@ Element* current_focus = nullptr; Element* next_focus = nullptr; int next_previous_flags; - for (size_t i = 0; i < arraysize(focused_elements); ++i) { + for (size_t i = 0; i < base::size(focused_elements); ++i) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = @@ -2017,7 +2018,7 @@ EXPECT_EQ(current_focus, document->FocusedElement()); // Backward Navigation in form1 with PREVIOUS - for (size_t i = arraysize(focused_elements); i-- > 0;) { + for (size_t i = base::size(focused_elements); i-- > 0;) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = @@ -2098,7 +2099,7 @@ Element* current_focus = nullptr; Element* next_focus = nullptr; int next_previous_flags; - for (size_t i = 0; i < arraysize(focused_elements); ++i) { + for (size_t i = 0; i < base::size(focused_elements); ++i) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = @@ -2119,7 +2120,7 @@ // Backward Navigation in form with PREVIOUS which has tabindex attribute // which differs visual order. - for (size_t i = arraysize(focused_elements); i-- > 0;) { + for (size_t i = base::size(focused_elements); i-- > 0;) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = @@ -2188,7 +2189,7 @@ Element* current_focus = nullptr; Element* next_focus = nullptr; int next_previous_flags; - for (size_t i = 0; i < arraysize(focused_elements); ++i) { + for (size_t i = 0; i < base::size(focused_elements); ++i) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = @@ -2209,7 +2210,7 @@ // Backward Navigation in form with PREVIOUS which has has // disabled/enabled elements which will gets skipped during navigation. - for (size_t i = arraysize(focused_elements); i-- > 0;) { + for (size_t i = base::size(focused_elements); i-- > 0;) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags =
diff --git a/third_party/blink/renderer/core/fetch/fetch_data_loader_test.cc b/third_party/blink/renderer/core/fetch/fetch_data_loader_test.cc index 783bfce..65e9f6f 100644 --- a/third_party/blink/renderer/core/fetch/fetch_data_loader_test.cc +++ b/third_party/blink/renderer/core/fetch/fetch_data_loader_test.cc
@@ -5,6 +5,8 @@ #include "third_party/blink/renderer/core/fetch/fetch_data_loader.h" #include <memory> + +#include "base/stl_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/fetch/bytes_consumer_for_data_consumer_handle.h" @@ -55,7 +57,7 @@ "Quick brown fox\r\n" "--boundary--\r\n"; constexpr size_t kQuickBrownFoxFormDataLength = - arraysize(kQuickBrownFoxFormData) - 1u; + base::size(kQuickBrownFoxFormData) - 1u; TEST(FetchDataLoaderTest, LoadAsBlob) { Checkpoint checkpoint;
diff --git a/third_party/blink/renderer/core/fetch/fetch_header_list_test.cc b/third_party/blink/renderer/core/fetch/fetch_header_list_test.cc index 8ebaecb..4adad47 100644 --- a/third_party/blink/renderer/core/fetch/fetch_header_list_test.cc +++ b/third_party/blink/renderer/core/fetch/fetch_header_list_test.cc
@@ -5,6 +5,8 @@ #include "third_party/blink/renderer/core/fetch/fetch_header_list.h" #include <utility> + +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -23,7 +25,7 @@ std::make_pair("ConTenT-TyPe", "application/xml"), std::make_pair("ConTenT-TyPe", "foo"), std::make_pair("X-Foo", "bar"), }; - EXPECT_EQ(arraysize(expectedHeaders), headerList->size()); + EXPECT_EQ(base::size(expectedHeaders), headerList->size()); size_t i = 0; for (const auto& header : headerList->List()) { EXPECT_EQ(expectedHeaders[i].first, header.first); @@ -46,7 +48,7 @@ std::make_pair("some-header", "some value"), std::make_pair("X-Foo", "bar"), }; - EXPECT_EQ(arraysize(expectedHeaders), headerList->size()); + EXPECT_EQ(base::size(expectedHeaders), headerList->size()); size_t i = 0; for (const auto& header : headerList->List()) { EXPECT_EQ(expectedHeaders[i].first, header.first); @@ -68,7 +70,7 @@ const std::pair<String, String> expectedHeaders[] = { std::make_pair("X-Foo", "bar"), }; - EXPECT_EQ(arraysize(expectedHeaders), headerList->size()); + EXPECT_EQ(base::size(expectedHeaders), headerList->size()); size_t i = 0; for (const auto& header : headerList->List()) { EXPECT_EQ(expectedHeaders[i].first, header.first); @@ -113,7 +115,7 @@ std::make_pair("x-foo", "bar")}; const Vector<FetchHeaderList::Header> sortedAndCombined = headerList->SortAndCombine(); - EXPECT_EQ(arraysize(expectedHeaders), sortedAndCombined.size()); + EXPECT_EQ(base::size(expectedHeaders), sortedAndCombined.size()); size_t i = 0; for (const auto& headerPair : headerList->SortAndCombine()) { EXPECT_EQ(expectedHeaders[i].first, headerPair.first);
diff --git a/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc b/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc index 805c763..dadbfd4 100644 --- a/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc +++ b/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc
@@ -5,6 +5,7 @@ #include "third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h" #include "base/memory/scoped_refptr.h" +#include "base/stl_util.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/system/data_pipe_utils.h" #include "testing/gmock/include/gmock/gmock.h" @@ -148,12 +149,12 @@ TEST_F(FormDataBytesConsumerTest, TwoPhaseReadFromArrayBuffer) { constexpr unsigned char kData[] = {0x21, 0xfe, 0x00, 0x00, 0xff, 0xa3, 0x42, 0x30, 0x42, 0x99, 0x88}; - DOMArrayBuffer* buffer = DOMArrayBuffer::Create(kData, arraysize(kData)); + DOMArrayBuffer* buffer = DOMArrayBuffer::Create(kData, base::size(kData)); auto result = (MakeGarbageCollected<BytesConsumerTestUtil::TwoPhaseReader>( MakeGarbageCollected<FormDataBytesConsumer>(buffer))) ->Run(); Vector<char> expected; - expected.Append(kData, arraysize(kData)); + expected.Append(kData, base::size(kData)); EXPECT_EQ(Result::kDone, result.first); EXPECT_EQ(expected, result.second); @@ -163,7 +164,7 @@ constexpr unsigned char kData[] = {0x21, 0xfe, 0x00, 0x00, 0xff, 0xa3, 0x42, 0x30, 0x42, 0x99, 0x88}; constexpr size_t kOffset = 1, kSize = 4; - DOMArrayBuffer* buffer = DOMArrayBuffer::Create(kData, arraysize(kData)); + DOMArrayBuffer* buffer = DOMArrayBuffer::Create(kData, base::size(kData)); auto result = (MakeGarbageCollected<BytesConsumerTestUtil::TwoPhaseReader>( MakeGarbageCollected<FormDataBytesConsumer>( DOMUint8Array::Create(buffer, kOffset, kSize))))
diff --git a/third_party/blink/renderer/core/fetch/multipart_parser.cc b/third_party/blink/renderer/core/fetch/multipart_parser.cc index 4a31123..4be2be0 100644 --- a/third_party/blink/renderer/core/fetch/multipart_parser.cc +++ b/third_party/blink/renderer/core/fetch/multipart_parser.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/fetch/multipart_parser.h" +#include "base/stl_util.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/network/http_names.h" #include "third_party/blink/renderer/platform/network/http_parsers.h" @@ -18,10 +19,10 @@ constexpr char kCloseDelimiterSuffix[] = "--\r\n"; constexpr size_t kCloseDelimiterSuffixSize = - arraysize(kCloseDelimiterSuffix) - 1u; + base::size(kCloseDelimiterSuffix) - 1u; constexpr size_t kDashBoundaryOffset = 2u; // The length of "\r\n". constexpr char kDelimiterSuffix[] = "\r\n"; -constexpr size_t kDelimiterSuffixSize = arraysize(kDelimiterSuffix) - 1u; +constexpr size_t kDelimiterSuffixSize = base::size(kDelimiterSuffix) - 1u; } // namespace
diff --git a/third_party/blink/renderer/core/frame/dom_timer.cc b/third_party/blink/renderer/core/frame/dom_timer.cc index 7373a276..419c2da 100644 --- a/third_party/blink/renderer/core/frame/dom_timer.cc +++ b/third_party/blink/renderer/core/frame/dom_timer.cc
@@ -28,6 +28,7 @@ #include "base/single_thread_task_runner.h" #include "third_party/blink/public/platform/task_type.h" +#include "third_party/blink/renderer/bindings/core/v8/scheduled_action.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/inspector/inspector_trace_events.h" #include "third_party/blink/renderer/core/probe/core_probes.h" @@ -174,6 +175,9 @@ action->Execute(context); + // Eagerly clear out |action|'s resources. + action->Dispose(); + // ExecutionContext might be already gone when we executed action->execute(). ExecutionContext* execution_context = GetExecutionContext(); if (!execution_context) @@ -182,8 +186,6 @@ execution_context->Timers()->SetTimerNestingLevel(0); // Eagerly unregister as ExecutionContext observer. ClearContext(); - // Eagerly clear out |action|'s resources. - action->Dispose(); } scoped_refptr<base::SingleThreadTaskRunner> DOMTimer::TimerTaskRunner() const {
diff --git a/third_party/blink/renderer/core/frame/dom_timer.h b/third_party/blink/renderer/core/frame/dom_timer.h index 5636c07d..bdc85435 100644 --- a/third_party/blink/renderer/core/frame/dom_timer.h +++ b/third_party/blink/renderer/core/frame/dom_timer.h
@@ -28,20 +28,23 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_TIMER_H_ #include "base/memory/scoped_refptr.h" -#include "third_party/blink/renderer/bindings/core/v8/scheduled_action.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h" #include "third_party/blink/renderer/core/dom/user_gesture_indicator.h" +#include "third_party/blink/renderer/platform/bindings/name_client.h" +#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/timer.h" namespace blink { class ExecutionContext; +class ScheduledAction; class CORE_EXPORT DOMTimer final : public GarbageCollectedFinalized<DOMTimer>, public ContextLifecycleObserver, - public TimerBase { + public TimerBase, + public NameClient { USING_GARBAGE_COLLECTED_MIXIN(DOMTimer); public: @@ -69,11 +72,12 @@ // already have been finalized & must not be accessed. EAGERLY_FINALIZE(); void Trace(blink::Visitor*) override; + const char* NameInHeapSnapshot() const override { return "DOMTimer"; } void Stop() override; private: - friend class DOMTimerCoordinator; // For create(). + friend class DOMTimerCoordinator; // For Create(). static DOMTimer* Create(ExecutionContext* context, ScheduledAction* action, @@ -90,7 +94,7 @@ int timeout_id_; int nesting_level_; - Member<ScheduledAction> action_; + TraceWrapperMember<ScheduledAction> action_; scoped_refptr<UserGestureToken> user_gesture_token_; };
diff --git a/third_party/blink/renderer/core/frame/dom_timer_coordinator.h b/third_party/blink/renderer/core/frame/dom_timer_coordinator.h index 03c35bce..e15c6c5 100644 --- a/third_party/blink/renderer/core/frame/dom_timer_coordinator.h +++ b/third_party/blink/renderer/core/frame/dom_timer_coordinator.h
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/single_thread_task_runner.h" +#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/time.h" @@ -59,7 +60,7 @@ private: int NextID(); - using TimeoutMap = HeapHashMap<int, Member<DOMTimer>>; + using TimeoutMap = HeapHashMap<int, TraceWrapperMember<DOMTimer>>; TimeoutMap timers_; int circular_sequential_id_;
diff --git a/third_party/blink/renderer/core/frame/frame_overlay.cc b/third_party/blink/renderer/core/frame/frame_overlay.cc index 34f701e..b8338c30 100644 --- a/third_party/blink/renderer/core/frame/frame_overlay.cc +++ b/third_party/blink/renderer/core/frame/frame_overlay.cc
@@ -69,8 +69,10 @@ } void FrameOverlay::Update() { - if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) + if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) { + delegate_->Invalidate(); return; + } auto* local_root_frame_widget = WebLocalFrameImpl::FromFrame(frame_)->LocalRootFrameWidget();
diff --git a/third_party/blink/renderer/core/frame/frame_overlay.h b/third_party/blink/renderer/core/frame/frame_overlay.h index 800541a..b77c3923 100644 --- a/third_party/blink/renderer/core/frame/frame_overlay.h +++ b/third_party/blink/renderer/core/frame/frame_overlay.h
@@ -53,6 +53,9 @@ virtual void PaintFrameOverlay(const FrameOverlay&, GraphicsContext&, const IntSize& view_size) const = 0; + // For CompositeAfterPaint. Invalidates composited layers managed by the + // delegate if any. + virtual void Invalidate() {} }; static std::unique_ptr<FrameOverlay> Create( @@ -71,6 +74,9 @@ return layer_.get(); } + // FrameOverlay is always the same size as the viewport. + IntSize Size() const; + // DisplayItemClient methods. String DebugName() const final { return "FrameOverlay"; } LayoutRect VisualRect() const override; @@ -88,9 +94,6 @@ private: FrameOverlay(LocalFrame*, std::unique_ptr<FrameOverlay::Delegate>); - // FrameOverlay is always the same size as the viewport. - IntSize Size() const; - Persistent<LocalFrame> frame_; std::unique_ptr<FrameOverlay::Delegate> delegate_; std::unique_ptr<GraphicsLayer> layer_;
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index e905b58..8bd7868 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -2716,7 +2716,12 @@ if (!paint_controller_) paint_controller_ = PaintController::Create(); - if (GetLayoutView()->Layer()->NeedsRepaint()) { + // TODO(crbug.com/917911): Painting of overlays should not force repainting + // of the frame contents. + auto* web_local_frame_impl = WebLocalFrameImpl::FromFrame(frame_); + bool has_dev_tools_overlays = + web_local_frame_impl && web_local_frame_impl->HasDevToolsOverlays(); + if (GetLayoutView()->Layer()->NeedsRepaint() || has_dev_tools_overlays) { GraphicsContext graphics_context(*paint_controller_); if (RuntimeEnabledFeatures::PrintBrowserEnabled()) graphics_context.SetPrinting(true); @@ -2743,6 +2748,13 @@ view.frame_->PaintFrameColorOverlay(graphics_context); }); + // Devtools overlays query the inspected page's paint data so this update + // needs to be after other paintings. + if (has_dev_tools_overlays) { + web_local_frame_impl->UpdateDevToolsOverlays(); + web_local_frame_impl->PaintDevToolsOverlays(graphics_context); + } + paint_controller_->CommitNewDisplayItems(); } } else { @@ -2782,6 +2794,12 @@ frame_->PaintFrameColorOverlay(); ForAllChildLocalFrameViews( [](LocalFrameView& view) { view.frame_->PaintFrameColorOverlay(); }); + + // Devtools overlays query the inspected page's paint data so this update + // needs to be after other paintings. Because devtools overlays can add + // layers, this needs to be before layers are collected. + if (auto* web_local_frame_impl = WebLocalFrameImpl::FromFrame(frame_)) + web_local_frame_impl->UpdateDevToolsOverlays(); } ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) { @@ -2790,12 +2808,6 @@ layout_view->Layer()->ClearNeedsRepaintRecursively(); }); - // Devtools overlays query the inspected page's paint data so this update - // needs to be after the lifecycle advance to kPaintClean. Because devtools - // overlays can add layers, this needs to be before layers are collected. - if (auto* web_local_frame_impl = WebLocalFrameImpl::FromFrame(frame_)) - web_local_frame_impl->UpdateDevToolsOverlays(); - if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() && !RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) { // BlinkGenPropertyTrees just needs a transient PaintController to
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index bca23d8..02d7573 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -94,7 +94,6 @@ #include "base/macros.h" #include "build/build_config.h" - #include "third_party/blink/public/common/frame/frame_owner_element_type.h" #include "third_party/blink/public/platform/interface_registry.h" #include "third_party/blink/public/platform/task_type.h" @@ -167,6 +166,8 @@ #include "third_party/blink/renderer/core/editing/text_affinity.h" #include "third_party/blink/renderer/core/editing/visible_position.h" #include "third_party/blink/renderer/core/editing/writing_direction.h" +#include "third_party/blink/renderer/core/events/after_print_event.h" +#include "third_party/blink/renderer/core/events/before_print_event.h" #include "third_party/blink/renderer/core/exported/local_frame_client_impl.h" #include "third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h" #include "third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h" @@ -1474,6 +1475,9 @@ void WebLocalFrameImpl::DispatchPrintEventRecursively( const AtomicString& event_type) { + DCHECK(event_type == event_type_names::kBeforeprint || + event_type == event_type_names::kAfterprint); + HeapVector<Member<Frame>> frames; for (Frame* frame = frame_; frame; frame = frame->Tree().TraverseNext(frame_)) frames.push_back(frame); @@ -1485,7 +1489,10 @@ } if (!frame->Tree().IsDescendantOf(frame_)) continue; - ToLocalFrame(frame)->DomWindow()->DispatchEvent(*Event::Create(event_type)); + Event* event = event_type == event_type_names::kBeforeprint + ? static_cast<Event*>(BeforePrintEvent::Create()) + : static_cast<Event*>(AfterPrintEvent::Create()); + ToLocalFrame(frame)->DomWindow()->DispatchEvent(*event); } } @@ -1840,11 +1847,21 @@ GetTextFinder()->IncreaseMarkerVersion(); } +bool WebLocalFrameImpl::HasDevToolsOverlays() const { + return dev_tools_agent_ && dev_tools_agent_->HasOverlays(); +} + void WebLocalFrameImpl::UpdateDevToolsOverlays() { if (dev_tools_agent_) dev_tools_agent_->UpdateOverlays(); } +void WebLocalFrameImpl::PaintDevToolsOverlays(GraphicsContext& context) { + DCHECK(RuntimeEnabledFeatures::CompositeAfterPaintEnabled()); + if (dev_tools_agent_) + dev_tools_agent_->PaintOverlays(context); +} + void WebLocalFrameImpl::CreateFrameView() { TRACE_EVENT0("blink", "WebLocalFrameImpl::createFrameView");
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.h b/third_party/blink/renderer/core/frame/web_local_frame_impl.h index 99644b9..d5dc3158 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.h +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.h
@@ -357,7 +357,9 @@ void DidChangeContentsSize(const IntSize&); + bool HasDevToolsOverlays() const; void UpdateDevToolsOverlays(); + void PaintDevToolsOverlays(GraphicsContext&); // For CompositeAfterPaint. void CreateFrameView();
diff --git a/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc b/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc index 85b95794..17970335 100644 --- a/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc +++ b/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc
@@ -32,6 +32,7 @@ #include "third_party/blink/renderer/core/frame/window_or_worker_global_scope.h" +#include "third_party/blink/renderer/bindings/core/v8/scheduled_action.h" #include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script.h" #include "third_party/blink/renderer/bindings/core/v8/v8_gc_for_context_dispose.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -128,7 +129,7 @@ int WindowOrWorkerGlobalScope::setTimeout( ScriptState* script_state, EventTarget& event_target, - const ScriptValue& handler, + V8Function* handler, int timeout, const Vector<ScriptValue>& arguments) { ExecutionContext* execution_context = event_target.GetExecutionContext(); @@ -191,7 +192,7 @@ int WindowOrWorkerGlobalScope::setInterval( ScriptState* script_state, EventTarget& event_target, - const ScriptValue& handler, + V8Function* handler, int timeout, const Vector<ScriptValue>& arguments) { ExecutionContext* execution_context = event_target.GetExecutionContext();
diff --git a/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h b/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h index 2126c4a5..0cb1db2 100644 --- a/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h +++ b/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h
@@ -47,6 +47,7 @@ class ScriptState; class ScriptValue; class StringOrTrustedScript; +class V8Function; typedef HTMLImageElementOrSVGImageElementOrHTMLVideoElementOrHTMLCanvasElementOrBlobOrImageDataOrImageBitmapOrOffscreenCanvas ImageBitmapSourceUnion; @@ -64,7 +65,7 @@ static int setTimeout(ScriptState*, EventTarget&, - const ScriptValue& handler, + V8Function* handler, int timeout, const Vector<ScriptValue>& arguments); static int setTimeout(ScriptState*, @@ -80,7 +81,7 @@ const Vector<ScriptValue>&); static int setInterval(ScriptState*, EventTarget&, - const ScriptValue& handler, + V8Function* handler, int timeout, const Vector<ScriptValue>&); static int setInterval(ScriptState*,
diff --git a/third_party/blink/renderer/core/frame/window_or_worker_global_scope.idl b/third_party/blink/renderer/core/frame/window_or_worker_global_scope.idl index e5cd3c3..e19ec9076 100644 --- a/third_party/blink/renderer/core/frame/window_or_worker_global_scope.idl +++ b/third_party/blink/renderer/core/frame/window_or_worker_global_scope.idl
@@ -47,13 +47,11 @@ [RaisesException] DOMString btoa(DOMString btoa); [RaisesException] DOMString atob(DOMString atob); - // TODO(yukishiino): Use TimerHandler (or Function at least) to implement - // setTimeout and setInterval. // https://html.spec.whatwg.org/C/webappapis.html#windoworworkerglobalscope-mixin - [CallWith=ScriptState, RuntimeCallStatsCounter=WindowSetTimeout] long setTimeout(CallbackFunctionTreatedAsScriptValue handler, optional long timeout = 0, any... arguments); + [CallWith=ScriptState, RuntimeCallStatsCounter=WindowSetTimeout] long setTimeout(Function handler, optional long timeout = 0, any... arguments); [CallWith=ScriptState, RaisesException] long setTimeout(ScriptString handler, optional long timeout = 0, any... arguments); void clearTimeout(optional long handle = 0); - [CallWith=ScriptState] long setInterval(CallbackFunctionTreatedAsScriptValue handler, optional long timeout = 0, any... arguments); + [CallWith=ScriptState] long setInterval(Function handler, optional long timeout = 0, any... arguments); [CallWith=ScriptState, RaisesException] long setInterval(ScriptString handler, optional long timeout = 0, any... arguments); void clearInterval(optional long handle = 0);
diff --git a/third_party/blink/renderer/core/fullscreen/fullscreen.cc b/third_party/blink/renderer/core/fullscreen/fullscreen.cc index d7b294a9..456df69 100644 --- a/third_party/blink/renderer/core/fullscreen/fullscreen.cc +++ b/third_party/blink/renderer/core/fullscreen/fullscreen.cc
@@ -678,7 +678,7 @@ // 10.2. Reject |promise| with a TypeError exception and terminate these // steps. - if (resolver) { + if (resolver && resolver->GetScriptState()->ContextIsValid()) { ScriptState::Scope scope(resolver->GetScriptState()); // TODO(dtapuska): Change error to be something useful instead of just a // boolean and return this to the user.
diff --git a/third_party/blink/renderer/core/html/html_document.cc b/third_party/blink/renderer/core/html/html_document.cc index 17c13f90..46585f1 100644 --- a/third_party/blink/renderer/core/html/html_document.cc +++ b/third_party/blink/renderer/core/html/html_document.cc
@@ -53,6 +53,7 @@ #include "third_party/blink/renderer/core/html/html_document.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/bindings/core/v8/script_controller.h" #include "third_party/blink/renderer/bindings/core/v8/window_proxy.h" #include "third_party/blink/renderer/core/dom/document_init.h" @@ -136,7 +137,7 @@ &kTargetAttr, &kTextAttr, &kTypeAttr, &kValignAttr, &kValuetypeAttr, &kVlinkAttr}; - attr_set->ReserveCapacityForSize(arraysize(case_insensitive_attributes)); + attr_set->ReserveCapacityForSize(base::size(case_insensitive_attributes)); for (const QualifiedName* attr : case_insensitive_attributes) attr_set->insert(attr->LocalName().Impl());
diff --git a/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc b/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc index 235c8222..1ca8589 100644 --- a/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc +++ b/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc
@@ -30,6 +30,7 @@ #include "third_party/blink/renderer/core/html/track/vtt/buffered_line_reader.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/text/character_names.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" @@ -173,12 +174,12 @@ const char* lines[] = {"aaaaaaaaaaaaaaaa", "bbbbbbbbbb", "ccccccccccccc", "", "dddddd", "", "eeeeeeeeee"}; const NewlineType kBreaks[] = {kLf, kLf, kLf, kLf, kLf, kLf, kLf}; - const size_t num_test_lines = arraysize(lines); - static_assert(num_test_lines == arraysize(kBreaks), + const size_t num_test_lines = base::size(lines); + static_assert(num_test_lines == base::size(kBreaks), "number of test lines and breaks should be the same"); String data = MakeTestData(lines, kBreaks, num_test_lines); - for (size_t k = 0; k < arraysize(kBlockSizes); ++k) { + for (size_t k = 0; k < base::size(kBlockSizes); ++k) { size_t line_count = 0; BufferedLineReader reader; wtf_size_t block_size = kBlockSizes[k]; @@ -200,12 +201,12 @@ "aaaaaaaaaaaaaaaa", "bbbbbbbbbb", "ccccccccccccc", "", "dddddd", "eeeeeeeeee", "fffffffffffffffffff"}; const NewlineType kBreaks[] = {kCr, kLf, kCrLf, kCr, kLf, kCrLf, kLf}; - const size_t num_test_lines = arraysize(lines); - static_assert(num_test_lines == arraysize(kBreaks), + const size_t num_test_lines = base::size(lines); + static_assert(num_test_lines == base::size(kBreaks), "number of test lines and breaks should be the same"); String data = MakeTestData(lines, kBreaks, num_test_lines); - for (size_t k = 0; k < arraysize(kBlockSizes); ++k) { + for (size_t k = 0; k < base::size(kBlockSizes); ++k) { size_t line_count = 0; BufferedLineReader reader; wtf_size_t block_size = kBlockSizes[k];
diff --git a/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc b/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc index df6990b..d6abeb1 100644 --- a/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc +++ b/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc
@@ -29,6 +29,7 @@ #include "third_party/blink/renderer/core/html/track/vtt/vtt_cue.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/bindings/core/v8/double_or_auto_keyword.h" #include "third_party/blink/renderer/core/css/css_property_names.h" #include "third_party/blink/renderer/core/css_value_keywords.h" @@ -57,14 +58,14 @@ static const CSSValueID kDisplayWritingModeMap[] = { CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr}; -static_assert(arraysize(kDisplayWritingModeMap) == +static_assert(base::size(kDisplayWritingModeMap) == VTTCue::kNumberOfWritingDirections, "displayWritingModeMap should have the same number of elements " "as VTTCue::NumberOfWritingDirections"); static const CSSValueID kDisplayAlignmentMap[] = { CSSValueStart, CSSValueCenter, CSSValueEnd, CSSValueLeft, CSSValueRight}; -static_assert(arraysize(kDisplayAlignmentMap) == VTTCue::kNumberOfAlignments, +static_assert(base::size(kDisplayAlignmentMap) == VTTCue::kNumberOfAlignments, "displayAlignmentMap should have the same number of elements as " "VTTCue::NumberOfAlignments");
diff --git a/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc b/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc index 0f302c6..c6d1ebe 100644 --- a/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc
@@ -33,6 +33,7 @@ #include <memory> +#include "base/stl_util.h" #include "cc/base/region.h" #include "cc/layers/picture_layer.h" #include "third_party/blink/public/platform/web_float_point.h" @@ -208,7 +209,7 @@ TransformationMatrix::FloatMatrix4 flattened_matrix; transform.ToColumnMajorFloatArray(flattened_matrix); std::unique_ptr<Array<double>> transform_array = Array<double>::create(); - for (size_t i = 0; i < arraysize(flattened_matrix); ++i) + for (size_t i = 0; i < base::size(flattened_matrix); ++i) transform_array->addItem(flattened_matrix[i]); layer_object->setTransform(std::move(transform_array)); const FloatPoint3D& transform_origin = graphics_layer->TransformOrigin();
diff --git a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc index 0e6cb8a..a7237aae 100644 --- a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
@@ -34,6 +34,7 @@ #include "base/auto_reset.h" #include "build/build_config.h" +#include "cc/layers/picture_layer.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_data.h" @@ -69,6 +70,8 @@ #include "third_party/blink/renderer/platform/graphics/color.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h" +#include "third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h" +#include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h" #include "v8/include/v8.h" namespace blink { @@ -142,23 +145,64 @@ } // namespace class InspectorOverlayAgent::InspectorPageOverlayDelegate final - : public FrameOverlay::Delegate { + : public FrameOverlay::Delegate, + public cc::ContentLayerClient { public: explicit InspectorPageOverlayDelegate(InspectorOverlayAgent& overlay) - : overlay_(&overlay) {} + : overlay_(&overlay) { + if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) { + layer_ = cc::PictureLayer::Create(this); + layer_->SetIsDrawable(true); + } + } + ~InspectorPageOverlayDelegate() override { + if (layer_) + layer_->ClearClient(); + } - void PaintFrameOverlay(const FrameOverlay&, + void PaintFrameOverlay(const FrameOverlay& frame_overlay, GraphicsContext& graphics_context, - const IntSize& web_view_size) const override { + const IntSize&) const override { if (overlay_->IsEmpty()) return; + if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) { + layer_->SetBounds(gfx::Size(frame_overlay.Size())); + RecordForeignLayer(graphics_context, + DisplayItem::kForeignLayerDevToolsOverlay, layer_, + PropertyTreeState::Root()); + return; + } + LocalFrameView* view = overlay_->OverlayMainFrame()->View(); view->PaintOutsideOfLifecycle(graphics_context, kGlobalPaintNormalPhase); } + void Invalidate() override { + if (layer_) + layer_->SetNeedsDisplay(); + } + private: + // cc::ContentLayerClient implementation + gfx::Rect PaintableRegion() override { return gfx::Rect(layer_->bounds()); } + bool FillsBoundsCompletely() const override { return false; } + size_t GetApproximateUnsharedMemoryUsage() const override { return 0; } + + scoped_refptr<cc::DisplayItemList> PaintContentsToDisplayList( + PaintingControlSetting) override { + auto display_list = base::MakeRefCounted<cc::DisplayItemList>(); + display_list->StartPaint(); + display_list->push<cc::DrawRecordOp>( + overlay_->OverlayMainFrame()->View()->GetPaintRecord()); + display_list->EndPaintOfUnpaired(PaintableRegion()); + display_list->Finalize(); + return display_list; + } + Persistent<InspectorOverlayAgent> overlay_; + // For CompositeAfterPaint. + scoped_refptr<cc::PictureLayer> layer_; }; class InspectorOverlayAgent::InspectorOverlayChromeClient final @@ -505,10 +549,17 @@ DocumentLifecycle::LifecycleUpdateReason::kOther); } - if (frame_overlay_ && frame_overlay_->GetGraphicsLayer()) + if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled() && frame_overlay_ && + frame_overlay_->GetGraphicsLayer()) frame_overlay_->GetGraphicsLayer()->Paint(nullptr); } +void InspectorOverlayAgent::PaintOverlay(GraphicsContext& context) { + DCHECK(RuntimeEnabledFeatures::CompositeAfterPaintEnabled()); + if (frame_overlay_) + frame_overlay_->Paint(context); +} + bool InspectorOverlayAgent::IsInspectorLayer(GraphicsLayer* layer) { return frame_overlay_ && frame_overlay_->GetGraphicsLayer() == layer; }
diff --git a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h index 0d45f5f..ce1913d 100644 --- a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h +++ b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h
@@ -50,6 +50,7 @@ namespace blink { class Color; +class GraphicsContext; class GraphicsLayer; class InspectedFrames; class InspectorDOMAgent; @@ -127,6 +128,8 @@ // Update the complete lifecycle (e.g., layout, paint) for the overlay. void UpdateAllOverlayLifecyclePhases(); + // For CompositeAfterPaint. + void PaintOverlay(GraphicsContext&); bool IsInspectorLayer(GraphicsLayer*);
diff --git a/third_party/blink/renderer/core/layout/layout_quote.cc b/third_party/blink/renderer/core/layout/layout_quote.cc index 3ab2a8a41..9b12aa15 100644 --- a/third_party/blink/renderer/core/layout/layout_quote.cc +++ b/third_party/blink/renderer/core/layout/layout_quote.cc
@@ -21,14 +21,15 @@ #include "third_party/blink/renderer/core/layout/layout_quote.h" +#include <algorithm> + +#include "base/stl_util.h" #include "third_party/blink/renderer/core/dom/pseudo_element.h" #include "third_party/blink/renderer/core/layout/layout_text_fragment.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" -#include <algorithm> - namespace blink { LayoutQuote::LayoutQuote(PseudoElement& pseudo, QuoteType quote) @@ -233,7 +234,7 @@ return nullptr; // This could be just a hash table, but doing that adds 200k to LayoutQuote.o - Language* languages_end = g_languages + arraysize(g_languages); + Language* languages_end = g_languages + base::size(g_languages); CString lowercase_lang = lang.DeprecatedLower().Utf8(); Language key = {lowercase_lang.data(), 0, 0, 0, 0, nullptr}; Language* match = std::lower_bound(g_languages, languages_end, key);
diff --git a/third_party/blink/renderer/core/layout/layout_table_section.cc b/third_party/blink/renderer/core/layout/layout_table_section.cc index 2071ed1..88d5749 100644 --- a/third_party/blink/renderer/core/layout/layout_table_section.cc +++ b/third_party/blink/renderer/core/layout/layout_table_section.cc
@@ -1469,23 +1469,32 @@ } bool LayoutTableSection::RecalcVisualOverflow() { - if (!ChildNeedsVisualOverflowRecalc()) + if (!NeedsVisualOverflowRecalc()) return false; - ClearChildNeedsVisualOverflowRecalc(); + unsigned total_rows = grid_.size(); - bool children_visual_overflow_changed = false; + bool child_visual_overflow_changed = false; for (unsigned r = 0; r < total_rows; r++) { LayoutTableRow* row_layouter = RowLayoutObjectAt(r); if (!row_layouter || (row_layouter->HasLayer() && row_layouter->Layer()->IsSelfPaintingLayer())) continue; if (row_layouter->RecalcVisualOverflow()) - children_visual_overflow_changed = true; + child_visual_overflow_changed = true; } - if (children_visual_overflow_changed) + + LayoutRect previous_visual_overflow_rect = VisualOverflowRect(); + + if (child_visual_overflow_changed || SelfNeedsVisualOverflowRecalc()) ComputeVisualOverflowFromDescendants(); - AddVisualEffectOverflow(); - return children_visual_overflow_changed; + if (SelfNeedsVisualOverflowRecalc()) + AddVisualEffectOverflow(); + + ClearChildNeedsVisualOverflowRecalc(); + ClearSelfNeedsVisualOverflowRecalc(); + + return child_visual_overflow_changed || + previous_visual_overflow_rect != VisualOverflowRect(); } void LayoutTableSection::MarkAllCellsWidthsDirtyAndOrNeedsLayout( @@ -1737,6 +1746,7 @@ void LayoutTableSection::SetNeedsCellRecalc() { needs_cell_recalc_ = true; + SetNeedsOverflowRecalc(); if (LayoutTable* t = Table()) t->SetNeedsSectionRecalc(); }
diff --git a/third_party/blink/renderer/core/layout/layout_table_section.h b/third_party/blink/renderer/core/layout/layout_table_section.h index d8c2390..1b3e55b 100644 --- a/third_party/blink/renderer/core/layout/layout_table_section.h +++ b/third_party/blink/renderer/core/layout/layout_table_section.h
@@ -291,7 +291,6 @@ void UpdateLogicalWidthForCollapsedCells( const Vector<int>& col_collapsed_width); - void ComputeVisualOverflowFromDescendants(); void ComputeLayoutOverflowFromDescendants(); protected: @@ -302,6 +301,8 @@ HitTestAction) override; private: + void ComputeVisualOverflowFromDescendants(); + bool IsOfType(LayoutObjectType type) const override { return type == kLayoutObjectTableSection || LayoutBox::IsOfType(type); }
diff --git a/third_party/blink/renderer/core/layout/layout_text_combine.cc b/third_party/blink/renderer/core/layout/layout_text_combine.cc index 4056a1f..43fa011a 100644 --- a/third_party/blink/renderer/core/layout/layout_text_combine.cc +++ b/third_party/blink/renderer/core/layout/layout_text_combine.cc
@@ -20,6 +20,7 @@ #include "third_party/blink/renderer/core/layout/layout_text_combine.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" namespace blink { @@ -184,7 +185,7 @@ // Need to try compressed glyphs. static const FontWidthVariant kWidthVariants[] = {kHalfWidth, kThirdWidth, kQuarterWidth}; - for (size_t i = 0; i < arraysize(kWidthVariants); ++i) { + for (size_t i = 0; i < base::size(kWidthVariants); ++i) { description.SetWidthVariant(kWidthVariants[i]); Font compressed_font = Font(description); compressed_font.Update(font_selector);
diff --git a/third_party/blink/renderer/core/layout/layout_text_control.cc b/third_party/blink/renderer/core/layout/layout_text_control.cc index 63a7da56..12a3c45 100644 --- a/third_party/blink/renderer/core/layout/layout_text_control.cc +++ b/third_party/blink/renderer/core/layout/layout_text_control.cc
@@ -22,6 +22,7 @@ #include "third_party/blink/renderer/core/layout/layout_text_control.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/style_change_reason.h" #include "third_party/blink/renderer/core/html/forms/text_control_element.h" #include "third_party/blink/renderer/core/layout/hit_test_result.h" @@ -204,7 +205,7 @@ if (!font_families_with_invalid_char_width_map) { font_families_with_invalid_char_width_map = new HashSet<AtomicString>; - for (size_t i = 0; i < arraysize(kFontFamiliesWithInvalidCharWidth); ++i) + for (size_t i = 0; i < base::size(kFontFamiliesWithInvalidCharWidth); ++i) font_families_with_invalid_char_width_map->insert( AtomicString(kFontFamiliesWithInvalidCharWidth[i])); }
diff --git a/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc b/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc index 8d5b072..aa29d3b 100644 --- a/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc +++ b/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/frame/use_counter.h" namespace blink { @@ -23,7 +24,7 @@ }; static_assert(static_cast<int>(mojom::WebClientHintsType::kMaxValue) + 1 == - arraysize(kWebFeatureMapping), + base::size(kWebFeatureMapping), "unhandled client hint type"); } // namespace
diff --git a/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc b/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc index 599e76ae..2a6b3e22 100644 --- a/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc +++ b/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc
@@ -8,6 +8,7 @@ #include <stdint.h> #include <string.h> +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -49,7 +50,7 @@ {"\rLine", 0, 0}, {"Line\r\nLine", 4, 2}, {"Line\nLine", 4, 1}, {"Line\n\nLine", 4, 1}, {"Line\rLine", 4, 0}, {"Line\r\rLine", 4, 0}, }; - for (size_t i = 0; i < arraysize(line_tests); ++i) { + for (size_t i = 0; i < base::size(line_tests); ++i) { Vector<char> input; input.Append(line_tests[i].input, static_cast<wtf_size_t>(strlen(line_tests[i].input))); @@ -70,7 +71,7 @@ {"foo", "bound", kNotFound}, {"bound", "--boundbound", 0}, }; - for (size_t i = 0; i < arraysize(boundary_tests); ++i) { + for (size_t i = 0; i < base::size(boundary_tests); ++i) { Vector<char> boundary, data; boundary.Append(boundary_tests[i].boundary, static_cast<uint32_t>(strlen(boundary_tests[i].boundary)));
diff --git a/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc b/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc index ecd37132..121dc03 100644 --- a/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc +++ b/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc
@@ -31,6 +31,8 @@ #include "third_party/blink/renderer/core/loader/text_resource_decoder_builder.h" #include <memory> + +#include "base/stl_util.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/dom_implementation.h" #include "third_party/blink/renderer/core/frame/local_frame.h" @@ -78,7 +80,7 @@ url.Host().Split(".", tokens); if (!tokens.IsEmpty()) { auto tld = tokens.back(); - for (size_t i = 0; i < arraysize(kEncodings); i++) { + for (size_t i = 0; i < base::size(kEncodings); i++) { if (tld == kEncodings[i].domain) return WTF::TextEncoding(kEncodings[i].encoding); }
diff --git a/third_party/blink/renderer/core/mojo/tests/js_to_cpp_test.cc b/third_party/blink/renderer/core/mojo/tests/js_to_cpp_test.cc index 9a6b8a5..b14267d 100644 --- a/third_party/blink/renderer/core/mojo/tests/js_to_cpp_test.cc +++ b/third_party/blink/renderer/core/mojo/tests/js_to_cpp_test.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/stl_util.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/system/wait.h" #include "testing/gtest/include/gtest/gtest.h" @@ -401,7 +402,7 @@ global_proxy, scope.GetIsolate())}; V8ScriptRunner::CallFunction(start_fn.As<v8::Function>(), scope.GetExecutionContext(), global_proxy, - arraysize(args), args, scope.GetIsolate()); + base::size(args), args, scope.GetIsolate()); test::EnterRunLoop(); } };
diff --git a/third_party/blink/renderer/core/paint/box_border_painter.cc b/third_party/blink/renderer/core/paint/box_border_painter.cc index 389a970..e3a41fc 100644 --- a/third_party/blink/renderer/core/paint/box_border_painter.cc +++ b/third_party/blink/renderer/core/paint/box_border_painter.cc
@@ -5,6 +5,8 @@ #include "third_party/blink/renderer/core/paint/box_border_painter.h" #include <algorithm> + +#include "base/stl_util.h" #include "third_party/blink/renderer/core/paint/box_painter.h" #include "third_party/blink/renderer/core/paint/object_painter.h" #include "third_party/blink/renderer/core/paint/paint_info.h" @@ -663,7 +665,7 @@ } void BoxBorderPainter::ComputeBorderProperties() { - for (unsigned i = 0; i < arraysize(edges_); ++i) { + for (unsigned i = 0; i < base::size(edges_); ++i) { const BorderEdge& edge = edges_[i]; if (!edge.ShouldRender()) {
diff --git a/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc b/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc index 9bd30e8..55f34d8e 100644 --- a/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc +++ b/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc
@@ -259,6 +259,8 @@ UpdateHitTestableWithoutDrawsContent(true); UpdateOpacity(GetLayoutObject().StyleRef()); UpdateTransform(GetLayoutObject().StyleRef()); + if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) + OwningLayer().UpdateFilterReferenceBox(); UpdateFilters(); UpdateBackdropFilters(); UpdateLayerBlendMode(GetLayoutObject().StyleRef()); @@ -308,18 +310,22 @@ } void CompositedLayerMapping::UpdateFilters() { + // Filters will be handled by property tree + if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) + return; CompositorFilterOperations operations; OwningLayer().UpdateCompositorFilterOperationsForFilter(operations); - graphics_layer_->SetFilters(std::move(operations)); } void CompositedLayerMapping::UpdateBackdropFilters() { - gfx::RectF backdrop_filter_bounds; + // Filters will be handled by property tree + if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) + return; CompositorFilterOperations backdrop_filters = - OwningLayer().CreateCompositorFilterOperationsForBackdropFilter( - &backdrop_filter_bounds); - graphics_layer_->SetBackdropFilters(backdrop_filters, backdrop_filter_bounds); + OwningLayer().CreateCompositorFilterOperationsForBackdropFilter(); + gfx::RectF filter_bounds = OwningLayer().BackdropFilterBounds(); + graphics_layer_->SetBackdropFilters(backdrop_filters, filter_bounds); } void CompositedLayerMapping::UpdateStickyConstraints( @@ -1168,6 +1174,9 @@ if (!GetLayoutObject().StyleRef().IsRunningOpacityAnimationOnCompositor()) UpdateOpacity(GetLayoutObject().StyleRef()); + if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) + OwningLayer().UpdateFilterReferenceBox(); + if (!GetLayoutObject().StyleRef().IsRunningFilterAnimationOnCompositor()) UpdateFilters();
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc b/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc index 2ce4934..aab36ba 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc
@@ -251,16 +251,8 @@ if (settings.GetPreferCompositingToLCDTextEnabled()) ignore_lcd_text = true; - if (!ignore_lcd_text) { - if (!RuntimeEnabledFeatures::CompositeOpaqueFixedPositionEnabled()) - return false; - if (!layer.BackgroundIsKnownToBeOpaqueInRect( - LayoutRect(layer.BoundingBoxForCompositing()), true)) { - return false; - } - if (layer.CompositesWithTransform() || layer.CompositesWithOpacity()) - return false; - } + if (!ignore_lcd_text) + return false; // Don't promote fixed position elements that are descendants of a non-view // container, e.g. transformed elements. They will stay fixed wrt the
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc b/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc index 3dd6e278..263f277 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc
@@ -94,40 +94,6 @@ EXPECT_EQ(kPaintsIntoOwnBacking, paint_layer->GetCompositingState()); } -TEST_F(CompositingReasonFinderTest, PromoteOpaqueFixedPosition) { - ScopedCompositeOpaqueFixedPositionForTest composite_fixed_position(true); - - SetBodyInnerHTML(R"HTML( - <div id='translucent' style='width: 20px; height: 20px; position: - fixed; top: 100px; left: 100px;'></div> - <div id='opaque' style='width: 20px; height: 20px; position: fixed; - top: 100px; left: 200px; background: white;'></div> - <div id='opaque-with-shadow' style='width: 20px; height: 20px; - position: fixed; top: 100px; left: 300px; background: white; - box-shadow: 10px 10px 5px #888888;'></div> - <div id='spacer' style='height: 2000px'></div> - )HTML"); - - // The translucent fixed box should not be promoted. - Element* element = GetDocument().getElementById("translucent"); - PaintLayer* paint_layer = - ToLayoutBoxModelObject(element->GetLayoutObject())->Layer(); - EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState()); - - // The opaque fixed box should be promoted and be opaque so that text will be - // drawn with subpixel anti-aliasing. - element = GetDocument().getElementById("opaque"); - paint_layer = ToLayoutBoxModelObject(element->GetLayoutObject())->Layer(); - EXPECT_EQ(kPaintsIntoOwnBacking, paint_layer->GetCompositingState()); - EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque()); - - // The opaque fixed box with shadow should not be promoted because the layer - // will include the shadow which is not opaque. - element = GetDocument().getElementById("opaque-with-shadow"); - paint_layer = ToLayoutBoxModelObject(element->GetLayoutObject())->Layer(); - EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState()); -} - TEST_F(CompositingReasonFinderTest, OnlyAnchoredStickyPositionPromoted) { SetBodyInnerHTML(R"HTML( <style> @@ -178,103 +144,6 @@ ->GetCompositingState()); } -// Tests that a transform on the fixed or an ancestor will prevent promotion -// TODO(flackr): Allow integer transforms as long as all of the ancestor -// transforms are also integer. -TEST_F(CompositingReasonFinderTest, OnlyNonTransformedFixedLayersPromoted) { - ScopedCompositeOpaqueFixedPositionForTest composite_fixed_position(true); - - SetBodyInnerHTML(R"HTML( - <style> - #fixed { position: fixed; height: 200px; width: 200px; background: - white; top: 0; } - #spacer { height: 3000px; } - </style> - <div id="parent"> - <div id="fixed"></div> - <div id="spacer"></div> - </div> - )HTML"); - - Element* parent = GetDocument().getElementById("parent"); - Element* fixed = GetDocument().getElementById("fixed"); - PaintLayer* paint_layer = - ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer(); - ASSERT_TRUE(paint_layer); - EXPECT_EQ(kPaintsIntoOwnBacking, paint_layer->GetCompositingState()); - EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque()); - - // Change the parent to have a transform. - parent->setAttribute(html_names::kStyleAttr, "transform: translate(1px, 0);"); - UpdateAllLifecyclePhasesForTest(); - paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer(); - ASSERT_TRUE(paint_layer); - EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState()); - - // Change the parent to have no transform again. - parent->removeAttribute(html_names::kStyleAttr); - UpdateAllLifecyclePhasesForTest(); - paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer(); - ASSERT_TRUE(paint_layer); - EXPECT_EQ(kPaintsIntoOwnBacking, paint_layer->GetCompositingState()); - EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque()); - - // Apply a transform to the fixed directly. - fixed->setAttribute(html_names::kStyleAttr, "transform: translate(1px, 0);"); - UpdateAllLifecyclePhasesForTest(); - paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer(); - ASSERT_TRUE(paint_layer); - EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState()); -} - -// Test that opacity applied to the fixed or an ancestor will cause the -// scrolling contents layer to not be promoted. -TEST_F(CompositingReasonFinderTest, OnlyOpaqueFixedLayersPromoted) { - ScopedCompositeOpaqueFixedPositionForTest composite_fixed_position(true); - - SetBodyInnerHTML(R"HTML( - <style> - #fixed { position: fixed; height: 200px; width: 200px; background: - white; top: 0} - #spacer { height: 3000px; } - </style> - <div id="parent"> - <div id="fixed"></div> - <div id="spacer"></div> - </div> - )HTML"); - - Element* parent = GetDocument().getElementById("parent"); - Element* fixed = GetDocument().getElementById("fixed"); - PaintLayer* paint_layer = - ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer(); - ASSERT_TRUE(paint_layer); - EXPECT_EQ(kPaintsIntoOwnBacking, paint_layer->GetCompositingState()); - EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque()); - - // Change the parent to be partially translucent. - parent->setAttribute(html_names::kStyleAttr, "opacity: 0.5;"); - UpdateAllLifecyclePhasesForTest(); - paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer(); - ASSERT_TRUE(paint_layer); - EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState()); - - // Change the parent to be opaque again. - parent->setAttribute(html_names::kStyleAttr, "opacity: 1;"); - UpdateAllLifecyclePhasesForTest(); - paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer(); - ASSERT_TRUE(paint_layer); - EXPECT_EQ(kPaintsIntoOwnBacking, paint_layer->GetCompositingState()); - EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque()); - - // Make the fixed translucent. - fixed->setAttribute(html_names::kStyleAttr, "opacity: 0.5"); - UpdateAllLifecyclePhasesForTest(); - paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer(); - ASSERT_TRUE(paint_layer); - EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState()); -} - TEST_F(CompositingReasonFinderTest, RequiresCompositingForTransformAnimation) { scoped_refptr<ComputedStyle> style = ComputedStyle::Create(); style->SetSubtreeWillChangeContents(false); @@ -362,38 +231,6 @@ CompositingReasonFinder::CompositingReasonsForAnimation(*style)); } -TEST_F(CompositingReasonFinderTest, CompositeNestedSticky) { - ScopedCompositeOpaqueFixedPositionForTest composite_fixed_position(true); - - SetBodyInnerHTML(R"HTML( - <style>.scroller { overflow: scroll; height: 200px; width: 100px; } - .container { height: 500px; } - .opaque { background-color: white; contain: paint; } - #outerSticky { height: 50px; position: sticky; top: 0px; } - #innerSticky { height: 20px; position: sticky; top: 25px; }</style> - <div class='scroller'> - <div class='container'> - <div id='outerSticky' class='opaque'> - <div id='innerSticky' class='opaque'></div> - </div> - </div> - </div> - )HTML"); - - Element* outer_sticky = GetDocument().getElementById("outerSticky"); - PaintLayer* outer_sticky_layer = - ToLayoutBoxModelObject(outer_sticky->GetLayoutObject())->Layer(); - ASSERT_TRUE(outer_sticky_layer); - - Element* inner_sticky = GetDocument().getElementById("innerSticky"); - PaintLayer* inner_sticky_layer = - ToLayoutBoxModelObject(inner_sticky->GetLayoutObject())->Layer(); - ASSERT_TRUE(inner_sticky_layer); - - EXPECT_EQ(kPaintsIntoOwnBacking, outer_sticky_layer->GetCompositingState()); - EXPECT_EQ(kPaintsIntoOwnBacking, inner_sticky_layer->GetCompositingState()); -} - TEST_F(CompositingReasonFinderTest, DontPromoteEmptyIframe) { GetDocument().GetFrame()->GetSettings()->SetPreferCompositingToLCDTextEnabled( true);
diff --git a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc index a21157b..0390581 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc
@@ -148,14 +148,18 @@ } void NGBoxFragmentPainter::Paint(const PaintInfo& paint_info) { + if (PhysicalFragment().IsAtomicInline()) + PaintAtomicInline(paint_info); + else + PaintInternal(paint_info); +} + +void NGBoxFragmentPainter::PaintInternal(const PaintInfo& paint_info) { ScopedPaintState paint_state(box_fragment_, paint_info); if (!ShouldPaint(paint_state)) return; PaintInfo& info = paint_state.MutablePaintInfo(); - if (PhysicalFragment().IsAtomicInline()) - return PaintAtomicInline(info); - LayoutPoint paint_offset = paint_state.PaintOffset(); PaintPhase original_phase = info.phase; @@ -660,53 +664,39 @@ } void NGBoxFragmentPainter::PaintAllPhasesAtomically( - const PaintInfo& paint_info, - bool is_self_painting) { - ScopedPaintState paint_state(box_fragment_, paint_info); - auto paint_offset = paint_state.PaintOffset(); - PaintInfo& local_paint_info = paint_state.MutablePaintInfo(); - + const PaintInfo& paint_info) { // Pass PaintPhaseSelection and PaintPhaseTextClip is handled by the regular // foreground paint implementation. We don't need complete painting for these // phases. PaintPhase phase = paint_info.phase; if (phase == PaintPhase::kSelection || phase == PaintPhase::kTextClip) - return PaintObject(local_paint_info, paint_offset); + return PaintInternal(paint_info); - if (paint_info.phase == PaintPhase::kSelfBlockBackgroundOnly && - is_self_painting) { - PaintObject(local_paint_info, paint_offset); - PaintOverflowControlsIfNeeded(local_paint_info, paint_offset); - return; - } + // Self-painting AtomicInlines must paint their background in background + // phase. + bool is_self_painting_atomic_inline = + PhysicalFragment().IsAtomicInline() && PhysicalFragment().Layer() && + PhysicalFragment().Layer()->IsSelfPaintingLayer(); + if (phase == PaintPhase::kSelfBlockBackgroundOnly && + is_self_painting_atomic_inline) + return PaintInternal(paint_info); if (phase != PaintPhase::kForeground) return; - if (!is_self_painting) { + PaintInfo local_paint_info(paint_info); + if (!is_self_painting_atomic_inline) { local_paint_info.phase = PaintPhase::kBlockBackground; - PaintObject(local_paint_info, paint_offset); + PaintInternal(local_paint_info); } local_paint_info.phase = PaintPhase::kFloat; - PaintObject(local_paint_info, paint_offset); + PaintInternal(local_paint_info); local_paint_info.phase = PaintPhase::kForeground; - if (box_fragment_.GetLayoutObject()->IsBox()) { - ScopedBoxContentsPaintState contents_paint_state( - paint_state, ToLayoutBox(*box_fragment_.GetLayoutObject())); - PaintObject(contents_paint_state.GetPaintInfo(), - contents_paint_state.PaintOffset()); - } else { - PaintObject(local_paint_info, paint_offset); - } + PaintInternal(local_paint_info); local_paint_info.phase = PaintPhase::kOutline; - PaintObject(local_paint_info, paint_offset); - - if (!is_self_painting) { - local_paint_info.phase = PaintPhase::kBlockBackground; - PaintOverflowControlsIfNeeded(local_paint_info, paint_offset); - } + PaintInternal(local_paint_info); } void NGBoxFragmentPainter::PaintLineBoxChildren( @@ -785,7 +775,7 @@ FragmentRequiresLegacyFallback(fragment)) { PaintInlineChildBoxUsingLegacyFallback(fragment, paint_info); } else { - NGBoxFragmentPainter(child).PaintAllPhasesAtomically(paint_info, false); + NGBoxFragmentPainter(child).PaintAllPhasesAtomically(paint_info); } } @@ -841,20 +831,13 @@ rect); } -// Follows BlockPainter::PaintInlineBox void NGBoxFragmentPainter::PaintAtomicInline(const PaintInfo& paint_info) { - if (paint_info.phase != PaintPhase::kForeground && - paint_info.phase != PaintPhase::kSelection && - paint_info.phase != PaintPhase::kSelfBlockBackgroundOnly) - return; - // Text clips are painted only for the direct inline children of the object // that has a text clip style on it, not block children. - DCHECK(paint_info.phase != PaintPhase::kTextClip); + if (paint_info.phase == PaintPhase::kTextClip) + return; - bool is_self_painting = PhysicalFragment().Layer() && - PhysicalFragment().Layer()->IsSelfPaintingLayer(); - PaintAllPhasesAtomically(paint_info, is_self_painting); + PaintAllPhasesAtomically(paint_info); } bool NGBoxFragmentPainter::IsPaintingScrollingBackground(
diff --git a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h index 440d6ad9..d2887ee 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h +++ b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h
@@ -73,8 +73,8 @@ const LayoutRect&); bool BackgroundIsKnownToBeOpaque(const PaintInfo&); - void PaintAllPhasesAtomically(const PaintInfo&, - bool is_self_painting); + void PaintInternal(const PaintInfo&); + void PaintAllPhasesAtomically(const PaintInfo&); void PaintBlockChildren(const PaintInfo&); void PaintLineBoxChildren(NGPaintFragment::ChildList, const PaintInfo&,
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index 7b8260cf..3cefbd35 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -2422,19 +2422,50 @@ return result_layer; } -FloatRect PaintLayer::FilterReferenceBox(const FilterOperations& filter, - float zoom) const { - if (!filter.HasReferenceFilter()) - return FloatRect(); +void PaintLayer::UpdateFilterReferenceBox() { + if (!NeedsFilterReferenceBox()) + return; + FloatRect reference_box = + FloatRect(PhysicalBoundingBoxIncludingStackingChildren( + LayoutPoint(), + PaintLayer::kIncludeTransformsAndCompositedChildLayers)); + float zoom = GetLayoutObject().StyleRef().EffectiveZoom(); + if (zoom != 1) + reference_box.Scale(1 / zoom); + EnsureResourceInfo().SetFilterReferenceBox(reference_box); +} - FloatRect reference_box(PhysicalBoundingBoxIncludingStackingChildren( - LayoutPoint(), PaintLayer::CalculateBoundsOptions:: - kIncludeTransformsAndCompositedChildLayers)); +bool PaintLayer::NeedsFilterReferenceBox() const { + if (GetLayoutObject().HasReflection() && GetLayoutObject().IsBox()) + return true; + FilterOperations operations = GetLayoutObject().StyleRef().Filter(); + if (operations.HasBlurOrReferenceFilter()) + return true; + operations = GetLayoutObject().StyleRef().BackdropFilter(); + return !operations.IsEmpty(); +} + +FloatRect PaintLayer::FilterReferenceBox() const { + DCHECK(IsAllowedToQueryCompositingState()); + if (ResourceInfo()) + return ResourceInfo()->FilterReferenceBox(); + return FloatRect(); +} + +FloatRect PaintLayer::BackdropFilterReferenceBox() const { + FloatRect reference_box(GetLayoutObject().BorderBoundingBox()); + float zoom = GetLayoutObject().StyleRef().EffectiveZoom(); if (zoom != 1) reference_box.Scale(1 / zoom); return reference_box; } +FloatRect PaintLayer::BackdropFilterBounds() const { + FloatRect rect(BackdropFilterReferenceBox()); + rect.Move(-ToFloatSize(FilterReferenceBox().Location())); + return rect; +} + bool PaintLayer::HitTestClippedOutByClipPath( PaintLayer* root_layer, const HitTestLocation& hit_test_location) const { @@ -2733,9 +2764,6 @@ std::make_unique<CompositedLayerMapping>(*this); rare_data_->composited_layer_mapping->SetNeedsGraphicsLayerUpdate( kGraphicsLayerUpdateSubtree); - - if (PaintLayerResourceInfo* resource_info = ResourceInfo()) - resource_info->InvalidateFilterChain(); } void PaintLayer::ClearCompositedLayerMapping(bool layer_being_destroyed) { @@ -2752,12 +2780,6 @@ if (rare_data_) rare_data_->composited_layer_mapping.reset(); - - if (layer_being_destroyed) - return; - - if (PaintLayerResourceInfo* resource_info = ResourceInfo()) - resource_info->InvalidateFilterChain(); } void PaintLayer::SetGroupedMapping(CompositedLayerMapping* grouped_mapping, @@ -2850,8 +2872,7 @@ if (Transform() && GetCompositingState() != kPaintsIntoOwnBacking) return false; - if (!RuntimeEnabledFeatures::CompositeOpaqueFixedPositionEnabled() && - GetLayoutObject().StyleRef().GetPosition() == EPosition::kFixed && + if (GetLayoutObject().StyleRef().GetPosition() == EPosition::kFixed && GetCompositingState() != kPaintsIntoOwnBacking) return false; @@ -2996,8 +3017,6 @@ new_style.Filter().AddClient(EnsureResourceInfo()); if (had_resource_info && old_style) old_style->Filter().RemoveClient(*ResourceInfo()); - if (PaintLayerResourceInfo* resource_info = ResourceInfo()) - resource_info->InvalidateFilterChain(); } void PaintLayer::UpdateClipPath(const ComputedStyle* old_style, @@ -3206,13 +3225,12 @@ void PaintLayer::UpdateCompositorFilterOperationsForFilter( CompositorFilterOperations& operations) const { - const auto& style = GetLayoutObject().StyleRef(); - float zoom = style.EffectiveZoom(); auto filter = FilterOperationsIncludingReflection(); - FloatRect reference_box = FilterReferenceBox(filter, zoom); + FloatRect reference_box = FilterReferenceBox(); if (!operations.IsEmpty() && !filter_on_effect_node_dirty_ && reference_box == operations.ReferenceBox()) return; + float zoom = GetLayoutObject().StyleRef().EffectiveZoom(); operations = FilterEffectBuilder(reference_box, zoom).BuildFilterOperations(filter); } @@ -3221,44 +3239,20 @@ CompositorFilterOperations& operations, gfx::RectF* backdrop_filter_bounds) const { DCHECK(backdrop_filter_bounds); - const auto& style = GetLayoutObject().StyleRef(); - float zoom = style.EffectiveZoom(); - auto filter = FilterOperationsIncludingReflection(); - FloatRect reference_box = FilterReferenceBox(filter, zoom); - if (!operations.IsEmpty() && reference_box == operations.ReferenceBox()) - return; - operations = - CreateCompositorFilterOperationsForBackdropFilter(backdrop_filter_bounds); + *backdrop_filter_bounds = BackdropFilterBounds(); + FloatRect reference_box = BackdropFilterBounds(); + if (operations.IsEmpty() || reference_box != operations.ReferenceBox()) + operations = CreateCompositorFilterOperationsForBackdropFilter(); } CompositorFilterOperations -PaintLayer::CreateCompositorFilterOperationsForBackdropFilter( - gfx::RectF* backdrop_filter_bounds) const { - DCHECK(backdrop_filter_bounds); +PaintLayer::CreateCompositorFilterOperationsForBackdropFilter() const { const auto& style = GetLayoutObject().StyleRef(); float zoom = style.EffectiveZoom(); - FloatRect reference_box = FilterReferenceBox(style.BackdropFilter(), zoom); + FloatRect reference_box = BackdropFilterBounds(); CompositorFilterOperations return_value = FilterEffectBuilder(reference_box, zoom) .BuildFilterOperations(style.BackdropFilter()); - if (!return_value.IsEmpty() && GetLayoutObject().IsBox()) { - const LayoutRect& bounds_rect = - ToLayoutBox(GetLayoutObject()).BorderBoxRect(); - // |bounds_offset| is the location of the element containing - // backdrop_filter, relative to the overall bounding box of the stacking - // context, including stacking children. - const LayoutSize& bounds_offset = - bounds_rect.Location() - - PhysicalBoundingBoxIncludingStackingChildren( - LayoutPoint(), PaintLayer::CalculateBoundsOptions:: - kIncludeTransformsAndCompositedChildLayers) - .Location(); - *backdrop_filter_bounds = - gfx::RectF(bounds_offset.Width(), bounds_offset.Height(), - bounds_rect.Width(), bounds_rect.Height()); - } else { - *backdrop_filter_bounds = gfx::RectF(); - } return return_value; } @@ -3303,32 +3297,9 @@ } } -FilterEffect* PaintLayer::LastFilterEffect() const { - // TODO(chrishtr): ensure (and assert) that compositing is clean here. - if (!PaintsWithFilters()) - return nullptr; - PaintLayerResourceInfo* resource_info = ResourceInfo(); - DCHECK(resource_info); - - if (resource_info->LastEffect()) - return resource_info->LastEffect(); - - const auto& style = GetLayoutObject().StyleRef(); - float zoom = style.EffectiveZoom(); - FilterEffectBuilder builder(FilterReferenceBox(style.Filter(), zoom), zoom); - resource_info->SetLastEffect( - builder.BuildFilterEffect(FilterOperationsIncludingReflection())); - return resource_info->LastEffect(); -} - FloatRect PaintLayer::MapRectForFilter(const FloatRect& rect) const { if (!HasFilterThatMovesPixels()) return rect; - - // Ensure the filter-chain is refreshed wrt reference filters. - // TODO(fs): Avoid having this side-effect inducing call. - LastFilterEffect(); - return FilterOperationsIncludingReflection().MapRect(rect); }
diff --git a/third_party/blink/renderer/core/paint/paint_layer.h b/third_party/blink/renderer/core/paint/paint_layer.h index 64cea82..a385db6 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.h +++ b/third_party/blink/renderer/core/paint/paint_layer.h
@@ -616,8 +616,8 @@ void UpdateCompositorFilterOperationsForBackdropFilter( CompositorFilterOperations& operations, gfx::RectF* backdrop_filter_bounds) const; - CompositorFilterOperations CreateCompositorFilterOperationsForBackdropFilter( - gfx::RectF* backdrop_filter_bounds) const; + CompositorFilterOperations CreateCompositorFilterOperationsForBackdropFilter() + const; void SetIsUnderSVGHiddenContainer(bool value) { is_under_svg_hidden_container_ = value; @@ -625,7 +625,6 @@ bool IsUnderSVGHiddenContainer() { return is_under_svg_hidden_container_; } bool PaintsWithFilters() const; - FilterEffect* LastFilterEffect() const; // Maps "forward" to determine which pixels in a destination rect are // affected by pixels in the source rect. @@ -642,6 +641,14 @@ } PaintLayerResourceInfo& EnsureResourceInfo(); + // Filter reference box is the area over which the filter is computed, in the + // coordinate system of the object with the filter. Filter bounds is the + // reference box, offset by the object's location in the graphics layer. + FloatRect FilterReferenceBox() const; + FloatRect BackdropFilterReferenceBox() const; + FloatRect BackdropFilterBounds() const; + + void UpdateFilterReferenceBox(); void UpdateFilters(const ComputedStyle* old_style, const ComputedStyle& new_style); void UpdateClipPath(const ComputedStyle* old_style, @@ -1225,7 +1232,7 @@ const PaintLayer* stacking_parent, CalculateBoundsOptions) const; - FloatRect FilterReferenceBox(const FilterOperations&, float zoom) const; + bool NeedsFilterReferenceBox() const; LayoutPoint LocationInternal() const;
diff --git a/third_party/blink/renderer/core/paint/paint_layer_resource_info.cc b/third_party/blink/renderer/core/paint/paint_layer_resource_info.cc index 2587cb7..a614901 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_resource_info.cc +++ b/third_party/blink/renderer/core/paint/paint_layer_resource_info.cc
@@ -50,9 +50,6 @@ // to update these properties when filter resources change. layout_object.SetNeedsPaintPropertyUpdate(); layer_->SetFilterOnEffectNodeDirty(); - const ComputedStyle& style = layout_object.StyleRef(); - if (style.HasFilter() && style.Filter().HasReferenceFilter()) - InvalidateFilterChain(); } void PaintLayerResourceInfo::ResourceElementChanged() { @@ -64,26 +61,6 @@ // to update these properties when filter resources change. layout_object.SetNeedsPaintPropertyUpdate(); layer_->SetFilterOnEffectNodeDirty(); - const ComputedStyle& style = layout_object.StyleRef(); - if (style.HasFilter() && style.Filter().HasReferenceFilter()) - InvalidateFilterChain(); -} - -void PaintLayerResourceInfo::SetLastEffect(FilterEffect* last_effect) { - last_effect_ = last_effect; -} - -FilterEffect* PaintLayerResourceInfo::LastEffect() const { - return last_effect_; -} - -void PaintLayerResourceInfo::InvalidateFilterChain() { - last_effect_ = nullptr; -} - -void PaintLayerResourceInfo::Trace(blink::Visitor* visitor) { - visitor->Trace(last_effect_); - SVGResourceClient::Trace(visitor); } } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/paint_layer_resource_info.h b/third_party/blink/renderer/core/paint/paint_layer_resource_info.h index 2b7a0998..9de93ec 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_resource_info.h +++ b/third_party/blink/renderer/core/paint/paint_layer_resource_info.h
@@ -32,6 +32,7 @@ #include "base/macros.h" #include "third_party/blink/renderer/core/svg/svg_resource_client.h" +#include "third_party/blink/renderer/platform/geometry/float_rect.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { @@ -57,21 +58,20 @@ explicit PaintLayerResourceInfo(PaintLayer*); ~PaintLayerResourceInfo() override; - void SetLastEffect(FilterEffect*); - FilterEffect* LastEffect() const; - void InvalidateFilterChain(); + FloatRect FilterReferenceBox() const { return filter_reference_box_; } + void SetFilterReferenceBox(const FloatRect& rect) { + filter_reference_box_ = rect; + } void ClearLayer() { layer_ = nullptr; } void ResourceContentChanged(InvalidationModeMask) override; void ResourceElementChanged() override; - void Trace(blink::Visitor*) override; - private: - // |clearLayer| must be called before *m_layer becomes invalid. + // |ClearLayer| must be called before *layer_ becomes invalid. PaintLayer* layer_; - Member<FilterEffect> last_effect_; + FloatRect filter_reference_box_; DISALLOW_COPY_AND_ASSIGN(PaintLayerResourceInfo); };
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc index 20709f1..82e84a7d 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
@@ -1073,9 +1073,20 @@ if (auto* layer = ToLayoutBoxModelObject(object_).Layer()) { // Try to use the cached filter. - if (properties_->Filter()) + if (properties_->Filter()) { state.filter = properties_->Filter()->Filter(); + state.backdrop_filter = properties_->Filter()->BackdropFilter(); + state.backdrop_filter_bounds = + properties_->Filter()->BackdropFilterBounds(); + } + // With BGPT disabled, UpdateFilterReferenceBox gets called from + // CompositedLayerMapping::UpdateGraphicsLayerGeometry, but only + // for composited layers. + if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() || + layer->GetCompositingState() != kPaintsIntoOwnBacking) { + layer->UpdateFilterReferenceBox(); + } layer->UpdateCompositorFilterOperationsForFilter(state.filter); layer->UpdateCompositorFilterOperationsForBackdropFilter( state.backdrop_filter, &state.backdrop_filter_bounds);
diff --git a/third_party/blink/renderer/core/style/filter_operations.cc b/third_party/blink/renderer/core/style/filter_operations.cc index 37c30fc..ad0ddfe 100644 --- a/third_party/blink/renderer/core/style/filter_operations.cc +++ b/third_party/blink/renderer/core/style/filter_operations.cc
@@ -70,11 +70,12 @@ return true; } -bool FilterOperations::HasReferenceFilter() const { +bool FilterOperations::HasBlurOrReferenceFilter() const { for (const auto& operation : operations_) { - if (operation->GetType() == FilterOperation::REFERENCE || - operation->GetType() == FilterOperation::BOX_REFLECT) + FilterOperation::OperationType type = operation->GetType(); + if (type == FilterOperation::BLUR || type == FilterOperation::REFERENCE) { return true; + } } return false; }
diff --git a/third_party/blink/renderer/core/style/filter_operations.h b/third_party/blink/renderer/core/style/filter_operations.h index 157ab4e..f71b359 100644 --- a/third_party/blink/renderer/core/style/filter_operations.h +++ b/third_party/blink/renderer/core/style/filter_operations.h
@@ -70,7 +70,7 @@ bool HasFilterThatAffectsOpacity() const; bool HasFilterThatMovesPixels() const; - bool HasReferenceFilter() const; + bool HasBlurOrReferenceFilter() const; void AddClient(SVGResourceClient&) const; void RemoveClient(SVGResourceClient&) const;
diff --git a/third_party/blink/renderer/core/svg/svg_element.cc b/third_party/blink/renderer/core/svg/svg_element.cc index 2a888df..2da79ce0 100644 --- a/third_party/blink/renderer/core/svg/svg_element.cc +++ b/third_party/blink/renderer/core/svg/svg_element.cc
@@ -25,6 +25,7 @@ #include "third_party/blink/renderer/core/svg/svg_element.h" #include "base/auto_reset.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h" #include "third_party/blink/renderer/core/animation/document_animations.h" #include "third_party/blink/renderer/core/animation/effect_stack.h" @@ -502,7 +503,7 @@ &kWordSpacingAttr, &kWritingModeAttr, }; - for (size_t i = 0; i < arraysize(attr_names); i++) { + for (size_t i = 0; i < base::size(attr_names); i++) { CSSPropertyID property_id = cssPropertyID(attr_names[i]->LocalName()); DCHECK_GT(property_id, 0); property_name_to_id_map->Set(attr_names[i]->LocalName().Impl(), @@ -786,7 +787,7 @@ {kVisibilityAttr, kAnimatedString}, {kWordSpacingAttr, kAnimatedLength}, }; - for (size_t i = 0; i < arraysize(attr_to_types); i++) + for (size_t i = 0; i < base::size(attr_to_types); i++) css_property_map.Set(attr_to_types[i].attr, attr_to_types[i].prop_type); } return css_property_map.at(attribute_name);
diff --git a/third_party/blink/renderer/core/svg/svg_transform.cc b/third_party/blink/renderer/core/svg/svg_transform.cc index 0c8ca92d..3aea44c 100644 --- a/third_party/blink/renderer/core/svg/svg_transform.cc +++ b/third_party/blink/renderer/core/svg/svg_transform.cc
@@ -20,6 +20,7 @@ #include "third_party/blink/renderer/core/svg/svg_transform.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/geometry/float_size.h" #include "third_party/blink/renderer/platform/wtf/math_extras.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" @@ -202,7 +203,7 @@ arguments[argument_count++] = angle_; break; } - DCHECK_LE(argument_count, arraysize(arguments)); + DCHECK_LE(argument_count, base::size(arguments)); StringBuilder builder; builder.Append(TransformTypePrefixForParsing(transform_type_));
diff --git a/third_party/blink/renderer/core/svg/svg_transform_list.cc b/third_party/blink/renderer/core/svg/svg_transform_list.cc index f00965a..dc48edb 100644 --- a/third_party/blink/renderer/core/svg/svg_transform_list.cc +++ b/third_party/blink/renderer/core/svg/svg_transform_list.cc
@@ -23,6 +23,7 @@ #include "third_party/blink/renderer/core/svg/svg_transform_list.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/css_function_value.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_primitive_value.h" @@ -204,10 +205,10 @@ "index of kSvgTransformSkewx has changed"); static_assert(kSvgTransformSkewy == 6, "index of kSvgTransformSkewy has changed"); -static_assert(arraysize(kRequiredValuesForType) - 1 == kSvgTransformSkewy, +static_assert(base::size(kRequiredValuesForType) - 1 == kSvgTransformSkewy, "the number of transform types have changed"); -static_assert(arraysize(kRequiredValuesForType) == - arraysize(kOptionalValuesForType), +static_assert(base::size(kRequiredValuesForType) == + base::size(kOptionalValuesForType), "the arrays should have the same number of elements"); const unsigned kMaxTransformArguments = 6;
diff --git a/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc b/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc index ea34b93..b55b955 100644 --- a/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc +++ b/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc
@@ -37,6 +37,7 @@ #include <memory> #include "base/auto_reset.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/css/style_engine.h" #include "third_party/blink/renderer/core/dom/cdata_section.h" #include "third_party/blink/renderer/core/dom/comment.h" @@ -1371,7 +1372,7 @@ return nullptr; constexpr size_t kSharedXhtmlEntityResultLength = - arraysize(g_shared_xhtml_entity_result); + base::size(g_shared_xhtml_entity_result); size_t entity_length_in_utf8; // Unlike HTML parser, XML parser parses the content of named // entities. So we need to escape '&' and '<'.
diff --git a/third_party/blink/renderer/core/xml/xpath_functions.cc b/third_party/blink/renderer/core/xml/xpath_functions.cc index b59c7c2..136776dd 100644 --- a/third_party/blink/renderer/core/xml/xpath_functions.cc +++ b/third_party/blink/renderer/core/xml/xpath_functions.cc
@@ -27,6 +27,7 @@ #include "third_party/blink/renderer/core/xml/xpath_functions.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/dom/attr.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/processing_instruction.h" @@ -742,7 +743,7 @@ }; g_function_map = new HashMap<String, FunctionRec>; - for (size_t i = 0; i < arraysize(functions); ++i) + for (size_t i = 0; i < base::size(functions); ++i) g_function_map->Set(functions[i].name, functions[i].function); }
diff --git a/third_party/blink/renderer/modules/animationworklet/animator.cc b/third_party/blink/renderer/modules/animationworklet/animator.cc index a60ce96..10a8d05 100644 --- a/third_party/blink/renderer/modules/animationworklet/animator.cc +++ b/third_party/blink/renderer/modules/animationworklet/animator.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/modules/animationworklet/animator.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/modules/animationworklet/animator_definition.h" @@ -65,7 +66,7 @@ v8::Local<v8::Value> argv[] = {v8_current_time, v8_effect}; V8ScriptRunner::CallFunction(animate, ExecutionContext::From(script_state), - instance, arraysize(argv), argv, isolate); + instance, base::size(argv), argv, isolate); // The animate function may have produced an error! // TODO(majidvp): We should probably just throw here.
diff --git a/third_party/blink/renderer/modules/bluetooth/bluetooth.cc b/third_party/blink/renderer/modules/bluetooth/bluetooth.cc index 1c5e9d1..9cc9b0a 100644 --- a/third_party/blink/renderer/modules/bluetooth/bluetooth.cc +++ b/third_party/blink/renderer/modules/bluetooth/bluetooth.cc
@@ -339,11 +339,11 @@ } void Bluetooth::ContextDestroyed(ExecutionContext*) { - Dispose(); + client_bindings_.CloseAllBindings(); } void Bluetooth::Dispose() { - client_bindings_.CloseAllBindings(); + DCHECK(client_bindings_.empty()); } void Bluetooth::Trace(blink::Visitor* visitor) {
diff --git a/third_party/blink/renderer/modules/crypto/crypto_key.cc b/third_party/blink/renderer/modules/crypto/crypto_key.cc index 8d2319a..39da74d 100644 --- a/third_party/blink/renderer/modules/crypto/crypto_key.cc +++ b/third_party/blink/renderer/modules/crypto/crypto_key.cc
@@ -30,6 +30,7 @@ #include "third_party/blink/renderer/modules/crypto/crypto_key.h" +#include "base/stl_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/public/platform/web_crypto_key_algorithm.h" #include "third_party/blink/public/platform/web_string.h" @@ -80,7 +81,7 @@ "keyUsageMappings needs to be updated"); const char* KeyUsageToString(WebCryptoKeyUsage usage) { - for (size_t i = 0; i < arraysize(kKeyUsageMappings); ++i) { + for (size_t i = 0; i < base::size(kKeyUsageMappings); ++i) { if (kKeyUsageMappings[i].value == usage) return kKeyUsageMappings[i].name; } @@ -89,7 +90,7 @@ } WebCryptoKeyUsageMask KeyUsageStringToMask(const String& usage_string) { - for (size_t i = 0; i < arraysize(kKeyUsageMappings); ++i) { + for (size_t i = 0; i < base::size(kKeyUsageMappings); ++i) { if (kKeyUsageMappings[i].name == usage_string) return kKeyUsageMappings[i].value; } @@ -158,7 +159,7 @@ // different). ScriptValue CryptoKey::usages(ScriptState* script_state) { Vector<String> result; - for (size_t i = 0; i < arraysize(kKeyUsageMappings); ++i) { + for (size_t i = 0; i < base::size(kKeyUsageMappings); ++i) { WebCryptoKeyUsage usage = kKeyUsageMappings[i].value; if (key_.Usages() & usage) result.push_back(KeyUsageToString(usage));
diff --git a/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc b/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc index d2b2e118..69d7a5d 100644 --- a/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc +++ b/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc
@@ -32,6 +32,8 @@ #include <algorithm> #include <memory> + +#include "base/stl_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/renderer/bindings/core/v8/array_buffer_or_array_buffer_view.h" @@ -86,7 +88,7 @@ // Reminder to update the table mapping names to IDs whenever adding a new // algorithm ID. static_assert(kWebCryptoAlgorithmIdLast + 1 == - arraysize(kAlgorithmNameMappings), + base::size(kAlgorithmNameMappings), "algorithmNameMappings needs to be updated"); #if DCHECK_IS_ON() @@ -177,7 +179,7 @@ WebCryptoAlgorithmId& id) { const AlgorithmNameMapping* begin = kAlgorithmNameMappings; const AlgorithmNameMapping* end = - kAlgorithmNameMappings + arraysize(kAlgorithmNameMappings); + kAlgorithmNameMappings + base::size(kAlgorithmNameMappings); #if DCHECK_IS_ON() DCHECK(VerifyAlgorithmNameMappings(begin, end)); @@ -772,7 +774,7 @@ {"P-521", kWebCryptoNamedCurveP521}}; // Reminder to update curveNameMappings when adding a new curve. -static_assert(kWebCryptoNamedCurveLast + 1 == arraysize(kCurveNameMappings), +static_assert(kWebCryptoNamedCurveLast + 1 == base::size(kCurveNameMappings), "curveNameMappings needs to be updated"); bool ParseNamedCurve(const Dictionary& raw, @@ -786,7 +788,7 @@ return false; } - for (size_t i = 0; i < arraysize(kCurveNameMappings); ++i) { + for (size_t i = 0; i < base::size(kCurveNameMappings); ++i) { if (kCurveNameMappings[i].name == named_curve_string) { named_curve = kCurveNameMappings[i].value; return true;
diff --git a/third_party/blink/renderer/modules/crypto/subtle_crypto.cc b/third_party/blink/renderer/modules/crypto/subtle_crypto.cc index 5ea5e94a..5ab2feff 100644 --- a/third_party/blink/renderer/modules/crypto/subtle_crypto.cc +++ b/third_party/blink/renderer/modules/crypto/subtle_crypto.cc
@@ -31,6 +31,7 @@ #include "third_party/blink/renderer/modules/crypto/subtle_crypto.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_crypto.h" @@ -149,7 +150,7 @@ const char* const kPropertyNames[] = {"d", "n", "e", "p", "q", "dp", "dq", "qi", "k", "crv", "x", "y"}; - for (unsigned i = 0; i < arraysize(kPropertyNames); ++i) + for (unsigned i = 0; i < base::size(kPropertyNames); ++i) CopyStringProperty(kPropertyNames[i], dict, json_object.get()); String json = json_object->ToJSONString();
diff --git a/third_party/blink/renderer/modules/eventsource/event_source_parser.cc b/third_party/blink/renderer/modules/eventsource/event_source_parser.cc index 6f1506f..eb65abb 100644 --- a/third_party/blink/renderer/modules/eventsource/event_source_parser.cc +++ b/third_party/blink/renderer/modules/eventsource/event_source_parser.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/modules/eventsource/event_source_parser.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/event_type_names.h" #include "third_party/blink/renderer/modules/eventsource/event_source.h" #include "third_party/blink/renderer/platform/wtf/ascii_ctype.h" @@ -30,10 +31,10 @@ for (uint32_t i = 0; i < size && !is_stopped_; ++i) { // As kBOM contains neither CR nor LF, we can think BOM and the line // break separately. - if (is_recognizing_bom_ && line_.size() + (i - start) == arraysize(kBOM)) { + if (is_recognizing_bom_ && line_.size() + (i - start) == base::size(kBOM)) { Vector<char> line = line_; line.Append(&bytes[start], i - start); - DCHECK_EQ(line.size(), arraysize(kBOM)); + DCHECK_EQ(line.size(), base::size(kBOM)); is_recognizing_bom_ = false; if (memcmp(line.data(), kBOM, sizeof(kBOM)) == 0) { start = i;
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_metrics.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_metrics.cc index fd0ab0a..9073580 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_metrics.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_metrics.cc
@@ -7,7 +7,9 @@ #include <stdint.h> #include <cmath> #include <limits> + #include "base/numerics/safe_conversions.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/keyboard_codes.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -40,7 +42,7 @@ }; // Must match length of UMA MediaTimelinePercent enum. constexpr int32_t kPercentBucketCount = 51; -static_assert(arraysize(kPercentIntervals) * 2 - 1 == kPercentBucketCount, +static_assert(base::size(kPercentIntervals) * 2 - 1 == kPercentBucketCount, "Intervals must match UMA MediaTimelinePercent enum"); // Corresponds to two UMA enums of different sizes! Values are the exclusive @@ -81,16 +83,17 @@ constexpr int32_t kAbsTimeDeltaBucketCount = 25; // Must match length of UMA MediaTimelineTimeDelta enum. constexpr int32_t kTimeDeltaBucketCount = 49; -static_assert(arraysize(kTimeDeltaMSIntervals) == kAbsTimeDeltaBucketCount, +static_assert(base::size(kTimeDeltaMSIntervals) == kAbsTimeDeltaBucketCount, "Intervals must match UMA MediaTimelineAbsTimeDelta enum"); -static_assert(arraysize(kTimeDeltaMSIntervals) * 2 - 1 == kTimeDeltaBucketCount, +static_assert(base::size(kTimeDeltaMSIntervals) * 2 - 1 == + kTimeDeltaBucketCount, "Intervals must match UMA MediaTimelineTimeDelta enum"); // Calculates index of UMA MediaTimelinePercent enum corresponding to |percent|. // Negative values use kPercentIntervals in reverse. int32_t ToPercentSample(double percent) { - constexpr int32_t kNonNegativeBucketCount = arraysize(kPercentIntervals); - constexpr int32_t kNegativeBucketCount = arraysize(kPercentIntervals) - 1; + constexpr int32_t kNonNegativeBucketCount = base::size(kPercentIntervals); + constexpr int32_t kNegativeBucketCount = base::size(kPercentIntervals) - 1; bool negative = percent < 0; double abs_percent = std::abs(percent); if (abs_percent == 0) @@ -121,8 +124,9 @@ // Calculates index of UMA MediaTimelineTimeDelta enum corresponding to // |deltaSeconds|. Negative values use kTimeDeltaMSIntervals in reverse. int32_t ToTimeDeltaSample(double delta_seconds) { - constexpr int32_t kNonNegativeBucketCount = arraysize(kTimeDeltaMSIntervals); - constexpr int32_t kNegativeBucketCount = arraysize(kTimeDeltaMSIntervals) - 1; + constexpr int32_t kNonNegativeBucketCount = base::size(kTimeDeltaMSIntervals); + constexpr int32_t kNegativeBucketCount = + base::size(kTimeDeltaMSIntervals) - 1; bool negative = delta_seconds < 0; double abs_delta_ms = 1000 * std::abs(delta_seconds); if (abs_delta_ms == 0)
diff --git a/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc b/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc index d333b14..15eae4e 100644 --- a/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc +++ b/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc
@@ -26,6 +26,7 @@ #include "third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/use_counter.h" @@ -44,7 +45,7 @@ "mms", "news", "nntp", "openpgp4fpr", "sip", "sms", "smsto", "ssh", "tel", "urn", "webcal", "wtai", "xmpp", }; - for (size_t i = 0; i < arraysize(kSchemes); ++i) + for (size_t i = 0; i < base::size(kSchemes); ++i) g_scheme_whitelist->insert(kSchemes[i]); } @@ -65,7 +66,7 @@ // It is also a SyntaxError if the custom handler URL, as created by removing // the "%s" token and prepending the base url, does not resolve. String new_url = url; - new_url.Remove(index, arraysize(kToken) - 1); + new_url.Remove(index, base::size(kToken) - 1); KURL kurl = document.CompleteURL(new_url); if (kurl.IsEmpty() || !kurl.IsValid()) {
diff --git a/third_party/blink/renderer/modules/notifications/notification_data_test.cc b/third_party/blink/renderer/modules/notifications/notification_data_test.cc index fccc3b1..1a099e28 100644 --- a/third_party/blink/renderer/modules/notifications/notification_data_test.cc +++ b/third_party/blink/renderer/modules/notifications/notification_data_test.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/modules/notifications/notification_data.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/testing/null_execution_context.h" #include "third_party/blink/renderer/modules/notifications/notification.h" @@ -78,7 +79,7 @@ TEST_F(NotificationDataTest, ReflectProperties) { Vector<unsigned> vibration_pattern; - for (size_t i = 0; i < arraysize(kNotificationVibration); ++i) + for (size_t i = 0; i < base::size(kNotificationVibration); ++i) vibration_pattern.push_back(kNotificationVibration[i]); UnsignedLongOrUnsignedLongSequence vibration_sequence; @@ -157,7 +158,7 @@ TEST_F(NotificationDataTest, SilentNotificationWithVibration) { Vector<unsigned> vibration_pattern; - for (size_t i = 0; i < arraysize(kNotificationVibration); ++i) + for (size_t i = 0; i < base::size(kNotificationVibration); ++i) vibration_pattern.push_back(kNotificationVibration[i]); UnsignedLongOrUnsignedLongSequence vibration_sequence; @@ -240,7 +241,7 @@ TEST_F(NotificationDataTest, VibrationNormalization) { Vector<unsigned> unnormalized_pattern; - for (size_t i = 0; i < arraysize(kNotificationVibrationUnnormalized); ++i) + for (size_t i = 0; i < base::size(kNotificationVibrationUnnormalized); ++i) unnormalized_pattern.push_back(kNotificationVibrationUnnormalized[i]); UnsignedLongOrUnsignedLongSequence vibration_sequence; @@ -255,7 +256,7 @@ EXPECT_FALSE(exception_state.HadException()); Vector<int> normalized_pattern; - for (size_t i = 0; i < arraysize(kNotificationVibrationNormalized); ++i) + for (size_t i = 0; i < base::size(kNotificationVibrationNormalized); ++i) normalized_pattern.push_back(kNotificationVibrationNormalized[i]); ASSERT_EQ(normalized_pattern.size(),
diff --git a/third_party/blink/renderer/modules/payments/basic_card_helper.cc b/third_party/blink/renderer/modules/payments/basic_card_helper.cc index c454b57..6f3ca2d6 100644 --- a/third_party/blink/renderer/modules/payments/basic_card_helper.cc +++ b/third_party/blink/renderer/modules/payments/basic_card_helper.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/modules/payments/basic_card_helper.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_basic_card_request.h" #include "third_party/blink/renderer/modules/payments/basic_card_request.h" #include "third_party/blink/renderer/modules/payments/payment_request.h" @@ -57,7 +58,7 @@ } for (const String& network : basic_card->supportedNetworks()) { - for (size_t i = 0; i < arraysize(kBasicCardNetworks); ++i) { + for (size_t i = 0; i < base::size(kBasicCardNetworks); ++i) { if (network == kBasicCardNetworks[i].name) { supported_networks_output.push_back(kBasicCardNetworks[i].code); break; @@ -74,7 +75,7 @@ } for (const String& type : basic_card->supportedTypes()) { - for (size_t i = 0; i < arraysize(kBasicCardTypes); ++i) { + for (size_t i = 0; i < base::size(kBasicCardTypes); ++i) { if (type == kBasicCardTypes[i].name) { supported_types_output.push_back(kBasicCardTypes[i].code); break; @@ -85,7 +86,7 @@ } bool BasicCardHelper::IsNetworkName(const String& input) { - for (size_t i = 0; i < arraysize(kBasicCardNetworks); ++i) { + for (size_t i = 0; i < base::size(kBasicCardNetworks); ++i) { if (input == kBasicCardNetworks[i].name) { return true; }
diff --git a/third_party/blink/renderer/modules/payments/payment_request.cc b/third_party/blink/renderer/modules/payments/payment_request.cc index 14256df..3564c977 100644 --- a/third_party/blink/renderer/modules/payments/payment_request.cc +++ b/third_party/blink/renderer/modules/payments/payment_request.cc
@@ -6,7 +6,9 @@ #include <stddef.h> #include <utility> + #include "base/location.h" +#include "base/stl_util.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h" @@ -414,7 +416,7 @@ for (const String& allowed_card_network : android_pay->allowedCardNetworks()) { - for (size_t i = 0; i < arraysize(kAndroidPayNetwork); ++i) { + for (size_t i = 0; i < base::size(kAndroidPayNetwork); ++i) { if (allowed_card_network == kAndroidPayNetwork[i].name) { output->allowed_card_networks.push_back(kAndroidPayNetwork[i].code); break; @@ -438,7 +440,7 @@ {AndroidPayTokenization::GATEWAY_TOKEN, "GATEWAY_TOKEN"}, {AndroidPayTokenization::NETWORK_TOKEN, "NETWORK_TOKEN"}}; - for (size_t i = 0; i < arraysize(kAndroidPayTokenization); ++i) { + for (size_t i = 0; i < base::size(kAndroidPayTokenization); ++i) { if (tokenization->tokenizationType() == kAndroidPayTokenization[i].name) { output->tokenization_type = kAndroidPayTokenization[i].code;
diff --git a/third_party/blink/renderer/modules/push_messaging/push_subscription_test.cc b/third_party/blink/renderer/modules/push_messaging/push_subscription_test.cc index f547d844..b8c7f895 100644 --- a/third_party/blink/renderer/modules/push_messaging/push_subscription_test.cc +++ b/third_party/blink/renderer/modules/push_messaging/push_subscription_test.cc
@@ -4,7 +4,7 @@ #include "third_party/blink/renderer/modules/push_messaging/push_subscription.h" -#include "base/macros.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/modules/push_messaging/web_push_subscription.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" @@ -35,8 +35,8 @@ WebPushSubscription web_subscription( WebURL() /* endpoint */, true /* user_visible_only */, WebString() /* application_server_key */, - WebVector<unsigned char>(kP256DH, arraysize(kP256DH)), - WebVector<unsigned char>(kAuthSecret, arraysize(kAuthSecret))); + WebVector<unsigned char>(kP256DH, base::size(kP256DH)), + WebVector<unsigned char>(kAuthSecret, base::size(kAuthSecret))); PushSubscription subscription(web_subscription, nullptr /* service_worker_registration */);
diff --git a/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc b/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc index f3bcbac..a046c68 100644 --- a/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc +++ b/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc
@@ -6,6 +6,7 @@ #include <memory> +#include "base/stl_util.h" #include "third_party/blink/public/common/screen_orientation/web_screen_orientation_type.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" @@ -58,7 +59,7 @@ {portrait, kWebScreenOrientationLockPortrait}, {landscape, kWebScreenOrientationLockLandscape}, {natural, kWebScreenOrientationLockNatural}}; - length = arraysize(orientation_map); + length = base::size(orientation_map); return orientation_map; }
diff --git a/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc b/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc index 835af6a..380c708 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc
@@ -7,6 +7,7 @@ #include <memory> #include <utility> +#include "base/stl_util.h" #include "third_party/blink/renderer/bindings/core/v8/idl_types.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" @@ -164,7 +165,7 @@ bool did_construct = V8ScriptRunner::CallAsConstructor( isolate, definition->ConstructorLocal(isolate), - ExecutionContext::From(script_state), arraysize(argv), argv) + ExecutionContext::From(script_state), base::size(argv), argv) .ToLocal(&result); processor_creation_params_.reset(); @@ -327,7 +328,7 @@ v8::Local<v8::Value> local_result; if (!V8ScriptRunner::CallFunction(definition->ProcessLocal(isolate), ExecutionContext::From(script_state), - processor_handle, arraysize(argv), argv, + processor_handle, base::size(argv), argv, isolate) .ToLocal(&local_result) || block.HasCaught()) {
diff --git a/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc b/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc index b2fb0e7..a5ba0fe5 100644 --- a/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc +++ b/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc
@@ -28,6 +28,7 @@ #include "third_party/blink/renderer/modules/webdatabase/sql_transaction.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/modules/webdatabase/database.h" #include "third_party/blink/renderer/modules/webdatabase/database_authorizer.h" @@ -152,7 +153,7 @@ &SQLTransaction::DeliverSuccessCallback // 12. }; - DCHECK(arraysize(kStateFunctions) == + DCHECK(base::size(kStateFunctions) == static_cast<int>(SQLTransactionState::kNumberOfStates)); DCHECK(state < SQLTransactionState::kNumberOfStates);
diff --git a/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc b/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc index 11ef20cc..fbd78bc 100644 --- a/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc +++ b/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc
@@ -29,6 +29,8 @@ #include "third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.h" #include <memory> + +#include "base/stl_util.h" #include "third_party/blink/renderer/modules/webdatabase/database.h" #include "third_party/blink/renderer/modules/webdatabase/database_authorizer.h" #include "third_party/blink/renderer/modules/webdatabase/database_context.h" @@ -491,7 +493,7 @@ &SQLTransactionBackend::SendToFrontendState, }; - DCHECK(arraysize(kStateFunctions) == + DCHECK(base::size(kStateFunctions) == static_cast<int>(SQLTransactionState::kNumberOfStates)); DCHECK_LT(state, SQLTransactionState::kNumberOfStates);
diff --git a/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc index 3bd6dac..25ece46 100644 --- a/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc
@@ -5,8 +5,10 @@ #include "third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h" #include <memory> + #include "base/numerics/checked_math.h" #include "base/numerics/safe_conversions.h" +#include "base/stl_util.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "third_party/blink/public/platform/web_graphics_context_3d_provider.h" #include "third_party/blink/renderer/bindings/modules/v8/webgl_any.h" @@ -149,7 +151,7 @@ supported_internal_formats_storage_.insert( kSupportedInternalFormatsStorage, kSupportedInternalFormatsStorage + - arraysize(kSupportedInternalFormatsStorage)); + base::size(kSupportedInternalFormatsStorage)); } void WebGL2RenderingContextBase::DestroyContext() {
diff --git a/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc b/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc index 22c765f..f74c2967 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc +++ b/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h" namespace blink { @@ -32,7 +33,8 @@ GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR - GL_COMPRESSED_RGBA_ASTC_4x4_KHR; for (size_t i = 0; - i < arraysize(WebGLCompressedTextureASTC::kBlockSizeCompressASTC); i++) { + i < base::size(WebGLCompressedTextureASTC::kBlockSizeCompressASTC); + i++) { /* GL_COMPRESSED_RGBA_ASTC(0x93B0 ~ 0x93BD) */ context->AddCompressedTextureFormat( WebGLCompressedTextureASTC::kBlockSizeCompressASTC[i].compress_type);
diff --git a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc index 2795095..fc97003 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
@@ -28,6 +28,7 @@ #include <memory> #include "base/numerics/checked_math.h" +#include "base/stl_util.h" #include "build/build_config.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "gpu/command_buffer/common/capabilities.h" @@ -1053,9 +1054,9 @@ disabled_extensions_.insert(entry); } -#define ADD_VALUES_TO_SET(set, values) \ - for (size_t i = 0; i < arraysize(values); ++i) { \ - set.insert(values[i]); \ +#define ADD_VALUES_TO_SET(set, values) \ + for (size_t i = 0; i < base::size(values); ++i) { \ + set.insert(values[i]); \ } ADD_VALUES_TO_SET(supported_internal_formats_, kSupportedFormatsES2);
diff --git a/third_party/blink/renderer/platform/bindings/callback_function_base.cc b/third_party/blink/renderer/platform/bindings/callback_function_base.cc index 73d47e3..90fb952 100644 --- a/third_party/blink/renderer/platform/bindings/callback_function_base.cc +++ b/third_party/blink/renderer/platform/bindings/callback_function_base.cc
@@ -43,11 +43,11 @@ return callback_relevant_script_state_; // Report a SecurityError due to a cross origin callback object. + ScriptState::Scope incumbent_scope(incumbent_script_state_); v8::TryCatch try_catch(GetIsolate()); try_catch.SetVerbose(true); ExceptionState exception_state( GetIsolate(), ExceptionState::kExecutionContext, interface, operation); - ScriptState::Scope incumbent_scope(incumbent_script_state_); exception_state.ThrowSecurityError( "An invocation of the provided callback failed due to cross origin " "access."); @@ -61,9 +61,9 @@ return callback_relevant_script_state_; // Throw a SecurityError due to a cross origin callback object. + ScriptState::Scope incumbent_scope(incumbent_script_state_); ExceptionState exception_state( GetIsolate(), ExceptionState::kExecutionContext, interface, operation); - ScriptState::Scope incumbent_scope(incumbent_script_state_); exception_state.ThrowSecurityError( "An invocation of the provided callback failed due to cross origin " "access.");
diff --git a/third_party/blink/renderer/platform/bindings/callback_interface_base.cc b/third_party/blink/renderer/platform/bindings/callback_interface_base.cc index 68b2c8f..f5d336f 100644 --- a/third_party/blink/renderer/platform/bindings/callback_interface_base.cc +++ b/third_party/blink/renderer/platform/bindings/callback_interface_base.cc
@@ -45,11 +45,11 @@ return callback_relevant_script_state_; // Report a SecurityError due to a cross origin callback object. + ScriptState::Scope incumbent_scope(incumbent_script_state_); v8::TryCatch try_catch(GetIsolate()); try_catch.SetVerbose(true); ExceptionState exception_state( GetIsolate(), ExceptionState::kExecutionContext, interface, operation); - ScriptState::Scope incumbent_scope(incumbent_script_state_); exception_state.ThrowSecurityError( "An invocation of the provided callback failed due to cross origin " "access."); @@ -63,9 +63,9 @@ return callback_relevant_script_state_; // Throw a SecurityError due to a cross origin callback object. + ScriptState::Scope incumbent_scope(incumbent_script_state_); ExceptionState exception_state( GetIsolate(), ExceptionState::kExecutionContext, interface, operation); - ScriptState::Scope incumbent_scope(incumbent_script_state_); exception_state.ThrowSecurityError( "An invocation of the provided callback failed due to cross origin " "access.");
diff --git a/third_party/blink/renderer/platform/exported/web_crypto_algorithm.cc b/third_party/blink/renderer/platform/exported/web_crypto_algorithm.cc index 1421bc6..67b793f 100644 --- a/third_party/blink/renderer/platform/exported/web_crypto_algorithm.cc +++ b/third_party/blink/renderer/platform/exported/web_crypto_algorithm.cc
@@ -34,6 +34,7 @@ #include <utility> #include "base/memory/ptr_util.h" +#include "base/stl_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -343,7 +344,7 @@ const WebCryptoAlgorithmInfo* WebCryptoAlgorithm::LookupAlgorithmInfo( WebCryptoAlgorithmId id) { const unsigned id_int = id; - if (id_int >= arraysize(kAlgorithmIdToInfo)) + if (id_int >= base::size(kAlgorithmIdToInfo)) return nullptr; return &kAlgorithmIdToInfo[id]; }
diff --git a/third_party/blink/renderer/platform/fonts/font_description_test.cc b/third_party/blink/renderer/platform/fonts/font_description_test.cc index e573d63..c5935c6b 100644 --- a/third_party/blink/renderer/platform/fonts/font_description_test.cc +++ b/third_party/blink/renderer/platform/fonts/font_description_test.cc
@@ -25,6 +25,7 @@ #include "third_party/blink/renderer/platform/fonts/font_description.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/vector.h" @@ -48,11 +49,11 @@ FontDescription source; WTF::Vector<unsigned> hashes; - for (size_t i = 0; i < arraysize(weights); i++) { + for (size_t i = 0; i < base::size(weights); i++) { source.SetWeight(weights[i]); - for (size_t j = 0; j < arraysize(stretches); j++) { + for (size_t j = 0; j < base::size(stretches); j++) { source.SetStretch(stretches[j]); - for (size_t k = 0; k < arraysize(slopes); k++) { + for (size_t k = 0; k < base::size(slopes); k++) { source.SetStyle(slopes[k]); unsigned hash = source.StyleHashWithoutFamilyList(); ASSERT_FALSE(hashes.Contains(hash));
diff --git a/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm b/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm index 97bebbd..41e4df3 100644 --- a/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm +++ b/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm
@@ -25,6 +25,8 @@ #import <AppKit/NSFont.h> #import <AvailabilityMacros.h> + +#include "base/stl_util.h" #import "third_party/blink/public/platform/mac/web_sandbox_support.h" #import "third_party/blink/public/platform/platform.h" #import "third_party/blink/renderer/platform/fonts/font.h" @@ -59,13 +61,13 @@ const void* descriptors[] = {last_resort.Get()}; RetainPtr<CFArrayRef> values_array( kAdoptCF, CFArrayCreate(kCFAllocatorDefault, descriptors, - arraysize(descriptors), &kCFTypeArrayCallBacks)); + base::size(descriptors), &kCFTypeArrayCallBacks)); const void* keys[] = {kCTFontCascadeListAttribute}; const void* values[] = {values_array.Get()}; RetainPtr<CFDictionaryRef> attributes( kAdoptCF, - CFDictionaryCreate(kCFAllocatorDefault, keys, values, arraysize(keys), + CFDictionaryCreate(kCFAllocatorDefault, keys, values, base::size(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
diff --git a/third_party/blink/renderer/platform/fonts/win/font_cache_skia_win.cc b/third_party/blink/renderer/platform/fonts/win/font_cache_skia_win.cc index b3e09a3..f60e5f3 100644 --- a/third_party/blink/renderer/platform/fonts/win/font_cache_skia_win.cc +++ b/third_party/blink/renderer/platform/fonts/win/font_cache_skia_win.cc
@@ -35,6 +35,7 @@ #include <utility> #include "base/debug/alias.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/fonts/bitmap_glyphs_blacklist.h" #include "third_party/blink/renderer/platform/fonts/font_description.h" #include "third_party/blink/renderer/platform/fonts/font_face_creation_params.h" @@ -215,10 +216,10 @@ int num_fonts = 0; if (script == USCRIPT_HAN) { pan_uni_fonts = kCjkFonts; - num_fonts = arraysize(kCjkFonts); + num_fonts = base::size(kCjkFonts); } else { pan_uni_fonts = kCommonFonts; - num_fonts = arraysize(kCommonFonts); + num_fonts = base::size(kCommonFonts); } // Font returned from getFallbackFamily may not cover |character| // because it's based on script to font mapping. This problem is @@ -294,7 +295,7 @@ {L" ultrabold", 10, FontSelectionValue(800)}, {L" black", 6, FontSelectionValue(900)}, {L" heavy", 6, FontSelectionValue(900)}}; - size_t num_variants = arraysize(kVariantForSuffix); + size_t num_variants = base::size(kVariantForSuffix); for (size_t i = 0; i < num_variants; i++) { const FamilyWeightSuffix& entry = kVariantForSuffix[i]; if (family.EndsWith(entry.suffix, kTextCaseUnicodeInsensitive)) { @@ -331,7 +332,7 @@ {L" expanded", 9, ExpandedWidthValue()}, {L" extraexpanded", 14, ExtraExpandedWidthValue()}, {L" ultraexpanded", 14, UltraExpandedWidthValue()}}; - size_t num_variants = arraysize(kVariantForSuffix); + size_t num_variants = base::size(kVariantForSuffix); for (size_t i = 0; i < num_variants; i++) { const FamilyStretchSuffix& entry = kVariantForSuffix[i]; if (family.EndsWith(entry.suffix, kTextCaseUnicodeInsensitive)) {
diff --git a/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc b/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc index ecb970b..1c4ad7c 100644 --- a/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc +++ b/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc
@@ -34,6 +34,7 @@ #include <unicode/uchar.h> #include <limits> +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/fonts/font_cache.h" #include "third_party/blink/renderer/platform/text/icu_error.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" @@ -376,13 +377,13 @@ static const UChar* math_font = 0; static bool initialized = false; if (!initialized) { - for (size_t i = 0; i < arraysize(kEmojiFonts); i++) { + for (size_t i = 0; i < base::size(kEmojiFonts); i++) { if (IsFontPresent(kEmojiFonts[i], font_manager)) { emoji_font = kEmojiFonts[i]; break; } } - for (size_t i = 0; i < arraysize(kMathFonts); i++) { + for (size_t i = 0; i < base::size(kMathFonts); i++) { if (IsFontPresent(kMathFonts[i], font_manager)) { math_font = kMathFonts[i]; break;
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc index d04b019..48070037 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc
@@ -5,6 +5,7 @@ #include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h" #include "base/metrics/histogram_functions.h" +#include "base/stl_util.h" #include "cc/paint/decode_stashing_image_provider.h" #include "cc/tiles/software_image_decode_cache.h" #include "components/viz/common/resources/resource_format_utils.h" @@ -498,23 +499,23 @@ switch (usage) { case kSoftwareResourceUsage: resource_type_fallback_list = kSoftwareFallbackList; - list_length = arraysize(kSoftwareFallbackList); + list_length = base::size(kSoftwareFallbackList); break; case kSoftwareCompositedResourceUsage: resource_type_fallback_list = kSoftwareCompositedFallbackList; - list_length = arraysize(kSoftwareCompositedFallbackList); + list_length = base::size(kSoftwareCompositedFallbackList); break; case kAcceleratedResourceUsage: resource_type_fallback_list = kAcceleratedFallbackList; - list_length = arraysize(kAcceleratedFallbackList); + list_length = base::size(kAcceleratedFallbackList); break; case kAcceleratedCompositedResourceUsage: resource_type_fallback_list = kAcceleratedCompositedFallbackList; - list_length = arraysize(kAcceleratedCompositedFallbackList); + list_length = base::size(kAcceleratedCompositedFallbackList); break; case kAcceleratedDirectResourceUsage: resource_type_fallback_list = kAcceleratedDirectFallbackList; - list_length = arraysize(kAcceleratedDirectFallbackList); + list_length = base::size(kAcceleratedDirectFallbackList); break; }
diff --git a/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc b/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc index af4e32d..6a33e1f 100644 --- a/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc +++ b/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc
@@ -25,7 +25,10 @@ #include "third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.h" #include <algorithm> + #include "SkTableColorFilter.h" + +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h" #include "third_party/blink/renderer/platform/wtf/math_extras.h" #include "third_party/blink/renderer/platform/wtf/text/text_stream.h" @@ -161,7 +164,7 @@ for (unsigned channel = 0; channel < 4; channel++) { SECURITY_DCHECK(static_cast<size_t>(transfer_function[channel].type) < - arraysize(call_effect)); + base::size(call_effect)); (*call_effect[transfer_function[channel].type])(tables[channel], transfer_function[channel]); }
diff --git a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc index 2fdde1208..655e3765a 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc +++ b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc
@@ -31,7 +31,9 @@ #include "third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.h" #include <memory> + #include "base/memory/scoped_refptr.h" +#include "base/stl_util.h" #include "components/viz/common/resources/single_release_callback.h" #include "components/viz/common/resources/transferable_resource.h" #include "components/viz/test/test_gpu_memory_buffer_manager.h" @@ -635,7 +637,7 @@ DepthStencilTestCase(true, true, 1, "both"), }; - for (size_t i = 0; i < arraysize(cases); i++) { + for (size_t i = 0; i < base::size(cases); i++) { SCOPED_TRACE(cases[i].test_case_name); auto gl = std::make_unique<DepthStencilTrackingGLES2Interface>(); DepthStencilTrackingGLES2Interface* tracking_gl = gl.get();
diff --git a/third_party/blink/renderer/platform/graphics/logging_canvas.cc b/third_party/blink/renderer/platform/graphics/logging_canvas.cc index 07dd685..ea989af 100644 --- a/third_party/blink/renderer/platform/graphics/logging_canvas.cc +++ b/third_party/blink/renderer/platform/graphics/logging_canvas.cc
@@ -31,6 +31,8 @@ #include "third_party/blink/renderer/platform/graphics/logging_canvas.h" #include <unicode/unistr.h> + +#include "base/stl_util.h" #include "base/sys_byteorder.h" #include "build/build_config.h" #include "third_party/blink/renderer/platform/geometry/int_size.h" @@ -234,7 +236,7 @@ std::unique_ptr<JSONObject> path_point_item = JSONObject::Create(); path_point_item->SetString("verb", verb_params.name); DCHECK_LE(verb_params.point_count + verb_params.point_offset, - arraysize(points)); + base::size(points)); path_point_item->SetArray( "points", ArrayForSkPoints(verb_params.point_count, points + verb_params.point_offset));
diff --git a/third_party/blink/renderer/platform/graphics/paint/display_item.cc b/third_party/blink/renderer/platform/graphics/paint/display_item.cc index 2ad3f1f2..9dfd70bb 100644 --- a/third_party/blink/renderer/platform/graphics/paint/display_item.cc +++ b/third_party/blink/renderer/platform/graphics/paint/display_item.cc
@@ -123,6 +123,7 @@ static String ForeignLayerTypeAsDebugString(DisplayItem::Type type) { switch (type) { DEBUG_STRING_CASE(ForeignLayerCanvas); + DEBUG_STRING_CASE(ForeignLayerDevToolsOverlay); DEBUG_STRING_CASE(ForeignLayerPlugin); DEBUG_STRING_CASE(ForeignLayerVideo); DEBUG_STRING_CASE(ForeignLayerWrapper);
diff --git a/third_party/blink/renderer/platform/graphics/paint/display_item.h b/third_party/blink/renderer/platform/graphics/paint/display_item.h index 03f980dc..2c5c6bb 100644 --- a/third_party/blink/renderer/platform/graphics/paint/display_item.h +++ b/third_party/blink/renderer/platform/graphics/paint/display_item.h
@@ -101,6 +101,7 @@ kForeignLayerFirst, kForeignLayerCanvas = kForeignLayerFirst, + kForeignLayerDevToolsOverlay, kForeignLayerPlugin, kForeignLayerVideo, kForeignLayerWrapper,
diff --git a/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc b/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc index 5413eb3..5e57ee5 100644 --- a/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc +++ b/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc
@@ -18,7 +18,9 @@ class ForeignLayerDisplayItemClient final : public DisplayItemClient { public: ForeignLayerDisplayItemClient(scoped_refptr<cc::Layer> layer) - : layer_(std::move(layer)) {} + : layer_(std::move(layer)) { + Invalidate(PaintInvalidationReason::kUncacheable); + } String DebugName() const final { return "ForeignLayer"; } @@ -45,6 +47,7 @@ RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()); DCHECK(IsForeignLayerType(type)); DCHECK(GetLayer()); + DCHECK(!IsCacheable()); } ForeignLayerDisplayItem::~ForeignLayerDisplayItem() { @@ -56,7 +59,7 @@ } bool ForeignLayerDisplayItem::Equals(const DisplayItem& other) const { - return DisplayItem::Equals(other) && + return GetType() == other.GetType() && GetLayer() == static_cast<const ForeignLayerDisplayItem&>(other).GetLayer(); }
diff --git a/third_party/blink/renderer/platform/graphics/placeholder_image.cc b/third_party/blink/renderer/platform/graphics/placeholder_image.cc index f883e79..2d9790e5 100644 --- a/third_party/blink/renderer/platform/graphics/placeholder_image.cc +++ b/third_party/blink/renderer/platform/graphics/placeholder_image.cc
@@ -6,6 +6,7 @@ #include <utility> +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/fonts/font.h" #include "third_party/blink/renderer/platform/fonts/font_description.h" #include "third_party/blink/renderer/platform/fonts/font_family.h" @@ -120,7 +121,7 @@ // Find the smallest unit that can represent |bytes| in 3 digits or less. // Round up to the next higher unit if possible when it would take 4 digits to // display the amount, e.g. 1000 KB will be rounded up to 1 MB. - for (; units < kUnitsNames + (arraysize(kUnitsNames) - 1) && + for (; units < kUnitsNames + (base::size(kUnitsNames) - 1) && bytes >= denomenator * 1000; ++units, denomenator *= 1024) { }
diff --git a/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder_test.cc b/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder_test.cc index f95c8efd..7c402fb 100644 --- a/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder_test.cc +++ b/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder_test.cc
@@ -31,6 +31,8 @@ #include "third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder.h" #include <memory> + +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_data.h" #include "third_party/blink/public/platform/web_size.h" @@ -127,7 +129,7 @@ true}, }; - for (size_t i = 0; i < arraysize(kFrameParameters); ++i) { + for (size_t i = 0; i < base::size(kFrameParameters); ++i) { const ImageFrame* const frame = decoder->DecodeFrameBufferAtIndex(i); EXPECT_EQ(ImageFrame::kFrameComplete, frame->GetStatus()); EXPECT_EQ(kCanvasWidth, frame->Bitmap().width()); @@ -143,7 +145,7 @@ EXPECT_EQ(kFrameParameters[i].has_alpha, frame->HasAlpha()); } - EXPECT_EQ(arraysize(kFrameParameters), decoder->FrameCount()); + EXPECT_EQ(base::size(kFrameParameters), decoder->FrameCount()); EXPECT_EQ(kAnimationLoopInfinite, decoder->RepetitionCount()); } @@ -174,7 +176,7 @@ true}, }; - for (size_t i = 0; i < arraysize(kFrameParameters); ++i) { + for (size_t i = 0; i < base::size(kFrameParameters); ++i) { const ImageFrame* const frame = decoder->DecodeFrameBufferAtIndex(i); EXPECT_EQ(ImageFrame::kFrameComplete, frame->GetStatus()); EXPECT_EQ(kCanvasWidth, frame->Bitmap().width()); @@ -190,7 +192,7 @@ EXPECT_EQ(kFrameParameters[i].has_alpha, frame->HasAlpha()); } - EXPECT_EQ(arraysize(kFrameParameters), decoder->FrameCount()); + EXPECT_EQ(base::size(kFrameParameters), decoder->FrameCount()); EXPECT_EQ(kAnimationLoopInfinite, decoder->RepetitionCount()); } @@ -216,7 +218,7 @@ ImageFrame::kBlendAtopBgcolor, TimeDelta::FromMilliseconds(1000), true}, }; - for (size_t i = 0; i < arraysize(kFrameParameters); ++i) { + for (size_t i = 0; i < base::size(kFrameParameters); ++i) { const ImageFrame* const frame = decoder->DecodeFrameBufferAtIndex(i); EXPECT_EQ(ImageFrame::kFrameComplete, frame->GetStatus()); EXPECT_EQ(kCanvasWidth, frame->Bitmap().width()); @@ -232,7 +234,7 @@ EXPECT_EQ(kFrameParameters[i].has_alpha, frame->HasAlpha()); } - EXPECT_EQ(arraysize(kFrameParameters), decoder->FrameCount()); + EXPECT_EQ(base::size(kFrameParameters), decoder->FrameCount()); EXPECT_EQ(kAnimationLoopInfinite, decoder->RepetitionCount()); }
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource.cc b/third_party/blink/renderer/platform/loader/fetch/resource.cc index ee30703..78b1bf1 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource.cc
@@ -31,6 +31,7 @@ #include <memory> #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "build/build_config.h" #include "services/network/public/mojom/fetch_api.mojom-blink.h" #include "third_party/blink/public/platform/platform.h" @@ -99,12 +100,12 @@ static inline bool ShouldUpdateHeaderAfterRevalidation( const AtomicString& header) { - for (size_t i = 0; i < arraysize(kHeadersToIgnoreAfterRevalidation); i++) { + for (size_t i = 0; i < base::size(kHeadersToIgnoreAfterRevalidation); i++) { if (DeprecatedEqualIgnoringCase(header, kHeadersToIgnoreAfterRevalidation[i])) return false; } - for (size_t i = 0; i < arraysize(kHeaderPrefixesToIgnoreAfterRevalidation); + for (size_t i = 0; i < base::size(kHeaderPrefixesToIgnoreAfterRevalidation); i++) { if (header.StartsWithIgnoringASCIICase( kHeaderPrefixesToIgnoreAfterRevalidation[i]))
diff --git a/third_party/blink/renderer/platform/loader/subresource_integrity.cc b/third_party/blink/renderer/platform/loader/subresource_integrity.cc index d92b21d..9cc09e5 100644 --- a/third_party/blink/renderer/platform/loader/subresource_integrity.cc +++ b/third_party/blink/renderer/platform/loader/subresource_integrity.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/platform/loader/subresource_integrity.h" +#include "base/stl_util.h" #include "third_party/blink/public/platform/web_crypto.h" #include "third_party/blink/public/platform/web_crypto_algorithm.h" #include "third_party/blink/renderer/platform/crypto.h" @@ -321,7 +322,7 @@ // The last algorithm prefix is the ed25519 signature algorithm, which should // only be enabled if kSignatures is requested. We'll implement this by // adjusting the last_prefix index into the array. - size_t last_prefix = arraysize(kPrefixes); + size_t last_prefix = base::size(kPrefixes); if (features != IntegrityFeatures::kSignatures) last_prefix--; @@ -335,7 +336,7 @@ IntegrityAlgorithm& algorithm) { static const AlgorithmPrefixPair kPrefixes[] = { {"ed25519", IntegrityAlgorithm::kEd25519}}; - return ParseAlgorithmPrefix(begin, end, kPrefixes, arraysize(kPrefixes), + return ParseAlgorithmPrefix(begin, end, kPrefixes, base::size(kPrefixes), algorithm); }
diff --git a/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc b/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc index e2ad9b7..65596d4 100644 --- a/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc +++ b/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc
@@ -5,6 +5,7 @@ #include "third_party/blink/renderer/platform/loader/subresource_integrity.h" #include "base/memory/scoped_refptr.h" +#include "base/stl_util.h" #include "services/network/public/mojom/fetch_api.mojom-blink.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/crypto.h" @@ -440,7 +441,7 @@ "sha384-XVVXBGoYw6AJOh9J+Z8pBDMVVPfkBpngexkA7JqZu8d5GENND6TEIup/tA1v5GPr " "sha512-tbUPioKbVBplr0b1ucnWB57SJWt4x9dOE0Vy2mzCXvH3FepqDZ+" "07yMK81ytlg0MPaIrPAjcHqba5csorDWtKg==", - valid_sha384_and_sha512, arraysize(valid_sha384_and_sha512)); + valid_sha384_and_sha512, base::size(valid_sha384_and_sha512)); const IntegrityMetadata valid_sha256_and_sha256[] = { IntegrityMetadata("BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=", @@ -449,7 +450,7 @@ }; ExpectParseMultipleHashes( "sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE= sha256-deadbeef", - valid_sha256_and_sha256, arraysize(valid_sha256_and_sha256)); + valid_sha256_and_sha256, base::size(valid_sha256_and_sha256)); const IntegrityMetadata valid_sha256_and_invalid_sha256[] = { IntegrityMetadata("BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=", @@ -458,7 +459,7 @@ ExpectParseMultipleHashes( "sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE= sha256-!!!!", valid_sha256_and_invalid_sha256, - arraysize(valid_sha256_and_invalid_sha256)); + base::size(valid_sha256_and_invalid_sha256)); const IntegrityMetadata invalid_sha256_and_valid_sha256[] = { IntegrityMetadata("BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=", @@ -467,7 +468,7 @@ ExpectParseMultipleHashes( "sha256-!!! sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=", invalid_sha256_and_valid_sha256, - arraysize(invalid_sha256_and_valid_sha256)); + base::size(invalid_sha256_and_valid_sha256)); ExpectParse("sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=?foo=bar", "BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
diff --git a/third_party/blink/renderer/platform/network/http_parsers_test.cc b/third_party/blink/renderer/platform/network/http_parsers_test.cc index 0b796138..691af02b 100644 --- a/third_party/blink/renderer/platform/network/http_parsers_test.cc +++ b/third_party/blink/renderer/platform/network/http_parsers_test.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/platform/network/http_parsers.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" @@ -304,7 +305,7 @@ {"Foo: bar\r\nBaz:\n", false, 0}, {"\r\n", true, 2}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { ResourceResponse response; wtf_size_t end = 0; bool result = ParseMultipartHeadersFromBody(
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 880f5e4..eca0ba09 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -219,11 +219,6 @@ name: "CompositedSelectionUpdate", }, { - name: "CompositeOpaqueFixedPosition", - settable_from_internals: true, - status: "experimental", - }, - { name: "CompositorTouchAction", status: "test", },
diff --git a/third_party/blink/renderer/platform/text/bidi_resolver_test.cc b/third_party/blink/renderer/platform/text/bidi_resolver_test.cc index a9a0187..fe3e701 100644 --- a/third_party/blink/renderer/platform/text/bidi_resolver_test.cc +++ b/third_party/blink/renderer/platform/text/bidi_resolver_test.cc
@@ -31,6 +31,8 @@ #include "third_party/blink/renderer/platform/text/bidi_resolver.h" #include <fstream> + +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/text/bidi_test_harness.h" #include "third_party/blink/renderer/platform/text/text_run_iterator.h" @@ -106,7 +108,7 @@ // Test broken surrogate: trail appearing before // lead. (U+10858 units reversed) {{0xDC58, 0xD802}, 2, TextDirection::kLtr, false}}; - for (size_t i = 0; i < arraysize(kTestData); ++i) + for (size_t i = 0; i < base::size(kTestData); ++i) TestDirectionality(kTestData[i]); }
diff --git a/third_party/blink/renderer/platform/text/character.cc b/third_party/blink/renderer/platform/text/character.cc index e43dbce..5cf83cd6 100644 --- a/third_party/blink/renderer/platform/text/character.cc +++ b/third_party/blink/renderer/platform/text/character.cc
@@ -33,6 +33,8 @@ #include <unicode/uobject.h> #include <unicode/uscript.h> #include <algorithm> + +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/text/character_property_data.h" #include "third_party/blink/renderer/platform/text/icu_error.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -61,9 +63,9 @@ return unicodeSet; } -#define CREATE_UNICODE_SET(name) \ - createUnicodeSet(name##Array, arraysize(name##Array), name##Ranges, \ - arraysize(name##Ranges)) +#define CREATE_UNICODE_SET(name) \ + createUnicodeSet(name##Array, base::size(name##Array), name##Ranges, \ + base::size(name##Ranges)) #define RETURN_HAS_PROPERTY(c, name) \ static icu::UnicodeSet* unicodeSet = nullptr; \
diff --git a/third_party/blink/renderer/platform/text/locale_icu.cc b/third_party/blink/renderer/platform/text/locale_icu.cc index 13c08e0..fec00ba5 100644 --- a/third_party/blink/renderer/platform/text/locale_icu.cc +++ b/third_party/blink/renderer/platform/text/locale_icu.cc
@@ -37,6 +37,7 @@ #include <memory> #include "base/memory/ptr_util.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/wtf/date_math.h" #include "third_party/blink/renderer/platform/wtf/text/string_buffer.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" @@ -145,7 +146,7 @@ const UChar kGmtTimezone[3] = {'G', 'M', 'T'}; UErrorCode status = U_ZERO_ERROR; return udat_open(time_style, date_style, locale_.data(), kGmtTimezone, - arraysize(kGmtTimezone), nullptr, -1, &status); + base::size(kGmtTimezone), nullptr, -1, &status); } // We cannot use udat_*Symbols API to get standalone month names to use in @@ -259,8 +260,8 @@ static std::unique_ptr<Vector<String>> CreateFallbackMonthLabels() { std::unique_ptr<Vector<String>> labels = std::make_unique<Vector<String>>(); - labels->ReserveCapacity(arraysize(WTF::kMonthFullName)); - for (unsigned i = 0; i < arraysize(WTF::kMonthFullName); ++i) + labels->ReserveCapacity(base::size(WTF::kMonthFullName)); + for (unsigned i = 0; i < base::size(WTF::kMonthFullName); ++i) labels->push_back(WTF::kMonthFullName[i]); return labels; } @@ -416,8 +417,8 @@ return short_month_labels_; } } - short_month_labels_.ReserveCapacity(arraysize(WTF::kMonthName)); - for (unsigned i = 0; i < arraysize(WTF::kMonthName); ++i) + short_month_labels_.ReserveCapacity(base::size(WTF::kMonthName)); + for (unsigned i = 0; i < base::size(WTF::kMonthName); ++i) short_month_labels_.push_back(WTF::kMonthName[i]); return short_month_labels_; }
diff --git a/third_party/blink/renderer/platform/text/locale_mac.mm b/third_party/blink/renderer/platform/text/locale_mac.mm index 490dbff0..ff17c916 100644 --- a/third_party/blink/renderer/platform/text/locale_mac.mm +++ b/third_party/blink/renderer/platform/text/locale_mac.mm
@@ -33,7 +33,9 @@ #import <Foundation/NSDateFormatter.h> #import <Foundation/NSLocale.h> #include <memory> + #include "base/memory/ptr_util.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/language.h" #include "third_party/blink/renderer/platform/web_test_support.h" #include "third_party/blink/renderer/platform/wtf/date_math.h" @@ -127,7 +129,7 @@ month_labels_.push_back(String([array objectAtIndex:i])); return month_labels_; } - for (unsigned i = 0; i < arraysize(WTF::kMonthFullName); ++i) + for (unsigned i = 0; i < base::size(WTF::kMonthFullName); ++i) month_labels_.push_back(WTF::kMonthFullName[i]); return month_labels_; } @@ -142,7 +144,7 @@ week_day_short_labels_.push_back(String([array objectAtIndex:i])); return week_day_short_labels_; } - for (unsigned i = 0; i < arraysize(WTF::kWeekdayName); ++i) { + for (unsigned i = 0; i < base::size(WTF::kWeekdayName); ++i) { // weekdayName starts with Monday. week_day_short_labels_.push_back(WTF::kWeekdayName[(i + 6) % 7]); } @@ -254,7 +256,7 @@ short_month_labels_.push_back([array objectAtIndex:i]); return short_month_labels_; } - for (unsigned i = 0; i < arraysize(WTF::kMonthName); ++i) + for (unsigned i = 0; i < base::size(WTF::kMonthName); ++i) short_month_labels_.push_back(WTF::kMonthName[i]); return short_month_labels_; }
diff --git a/third_party/blink/renderer/platform/text/locale_win.cc b/third_party/blink/renderer/platform/text/locale_win.cc index 80fcf10..adbe562 100644 --- a/third_party/blink/renderer/platform/text/locale_win.cc +++ b/third_party/blink/renderer/platform/text/locale_win.cc
@@ -34,6 +34,7 @@ #include <memory> #include "base/memory/ptr_util.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/date_components.h" #include "third_party/blink/renderer/platform/language.h" #include "third_party/blink/renderer/platform/text/date_time_format.h" @@ -148,13 +149,13 @@ LOCALE_SABBREVMONTHNAME9, LOCALE_SABBREVMONTHNAME10, LOCALE_SABBREVMONTHNAME11, LOCALE_SABBREVMONTHNAME12, }; - short_month_labels_.ReserveCapacity(arraysize(kTypes)); - for (unsigned i = 0; i < arraysize(kTypes); ++i) { + short_month_labels_.ReserveCapacity(base::size(kTypes)); + for (unsigned i = 0; i < base::size(kTypes); ++i) { short_month_labels_.push_back(GetLocaleInfoString(kTypes[i])); if (short_month_labels_.back().IsEmpty()) { short_month_labels_.Shrink(0); - short_month_labels_.ReserveCapacity(arraysize(WTF::kMonthName)); - for (unsigned m = 0; m < arraysize(WTF::kMonthName); ++m) + short_month_labels_.ReserveCapacity(base::size(WTF::kMonthName)); + for (unsigned m = 0; m < base::size(WTF::kMonthName); ++m) short_month_labels_.push_back(WTF::kMonthName[m]); return; } @@ -274,13 +275,13 @@ LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9, LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12, }; - month_labels_.ReserveCapacity(arraysize(kTypes)); - for (unsigned i = 0; i < arraysize(kTypes); ++i) { + month_labels_.ReserveCapacity(base::size(kTypes)); + for (unsigned i = 0; i < base::size(kTypes); ++i) { month_labels_.push_back(GetLocaleInfoString(kTypes[i])); if (month_labels_.back().IsEmpty()) { month_labels_.Shrink(0); - month_labels_.ReserveCapacity(arraysize(WTF::kMonthFullName)); - for (unsigned m = 0; m < arraysize(WTF::kMonthFullName); ++m) + month_labels_.ReserveCapacity(base::size(WTF::kMonthFullName)); + for (unsigned m = 0; m < base::size(WTF::kMonthFullName); ++m) month_labels_.push_back(WTF::kMonthFullName[m]); return; } @@ -295,13 +296,13 @@ LOCALE_SABBREVDAYNAME2, LOCALE_SABBREVDAYNAME3, LOCALE_SABBREVDAYNAME4, LOCALE_SABBREVDAYNAME5, LOCALE_SABBREVDAYNAME6}; - week_day_short_labels_.ReserveCapacity(arraysize(kTypes)); - for (unsigned i = 0; i < arraysize(kTypes); ++i) { + week_day_short_labels_.ReserveCapacity(base::size(kTypes)); + for (unsigned i = 0; i < base::size(kTypes); ++i) { week_day_short_labels_.push_back(GetLocaleInfoString(kTypes[i])); if (week_day_short_labels_.back().IsEmpty()) { week_day_short_labels_.Shrink(0); - week_day_short_labels_.ReserveCapacity(arraysize(WTF::kWeekdayName)); - for (unsigned w = 0; w < arraysize(WTF::kWeekdayName); ++w) { + week_day_short_labels_.ReserveCapacity(base::size(WTF::kWeekdayName)); + for (unsigned w = 0; w < base::size(WTF::kWeekdayName); ++w) { // weekdayName starts with Monday. week_day_short_labels_.push_back(WTF::kWeekdayName[(w + 6) % 7]); }
diff --git a/third_party/blink/renderer/platform/text/text_break_iterator.cc b/third_party/blink/renderer/platform/text/text_break_iterator.cc index 0160d67..731a5256 100644 --- a/third_party/blink/renderer/platform/text/text_break_iterator.cc +++ b/third_party/blink/renderer/platform/text/text_break_iterator.cc
@@ -23,6 +23,7 @@ #include "third_party/blink/renderer/platform/text/text_break_iterator.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/text/character.h" #include "third_party/blink/renderer/platform/wtf/ascii_ctype.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -223,11 +224,11 @@ #undef DI #undef AL -static_assert(arraysize(kAsciiLineBreakTable) == +static_assert(base::size(kAsciiLineBreakTable) == kAsciiLineBreakTableLastChar - kAsciiLineBreakTableFirstChar + 1, "asciiLineBreakTable should be consistent"); -static_assert(arraysize(kBreakAllLineBreakClassTable) == BA_LB_COUNT, +static_assert(base::size(kBreakAllLineBreakClassTable) == BA_LB_COUNT, "breakAllLineBreakClassTable should be consistent"); static inline bool ShouldBreakAfter(UChar last_ch, UChar ch, UChar next_ch) {
diff --git a/third_party/blink/renderer/platform/text/text_break_iterator.h b/third_party/blink/renderer/platform/text/text_break_iterator.h index 8d1f1a5a..f2472e4 100644 --- a/third_party/blink/renderer/platform/text/text_break_iterator.h +++ b/third_party/blink/renderer/platform/text/text_break_iterator.h
@@ -22,14 +22,16 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_TEXT_BREAK_ITERATOR_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_TEXT_BREAK_ITERATOR_H_ +#include <type_traits> + +#include <unicode/brkiter.h> + #include "base/macros.h" #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" #include "third_party/blink/renderer/platform/wtf/text/character_names.h" #include "third_party/blink/renderer/platform/wtf/text/unicode.h" -#include <unicode/brkiter.h> - namespace blink { typedef icu::BreakIterator TextBreakIterator; @@ -143,33 +145,33 @@ const String& GetString() const { return string_; } UChar LastCharacter() const { - static_assert(arraysize(prior_context_) == 2, + static_assert(std::extent<decltype(prior_context_)>() == 2, "TextBreakIterator has unexpected prior context length"); return prior_context_[1]; } UChar SecondToLastCharacter() const { - static_assert(arraysize(prior_context_) == 2, + static_assert(std::extent<decltype(prior_context_)>() == 2, "TextBreakIterator has unexpected prior context length"); return prior_context_[0]; } void SetPriorContext(UChar last, UChar second_to_last) { - static_assert(arraysize(prior_context_) == 2, + static_assert(std::extent<decltype(prior_context_)>() == 2, "TextBreakIterator has unexpected prior context length"); prior_context_[0] = second_to_last; prior_context_[1] = last; } void UpdatePriorContext(UChar last) { - static_assert(arraysize(prior_context_) == 2, + static_assert(std::extent<decltype(prior_context_)>() == 2, "TextBreakIterator has unexpected prior context length"); prior_context_[0] = prior_context_[1]; prior_context_[1] = last; } void ResetPriorContext() { - static_assert(arraysize(prior_context_) == 2, + static_assert(std::extent<decltype(prior_context_)>() == 2, "TextBreakIterator has unexpected prior context length"); prior_context_[0] = 0; prior_context_[1] = 0; @@ -181,7 +183,7 @@ }; PriorContext GetPriorContext() const { - static_assert(arraysize(prior_context_) == 2, + static_assert(std::extent<decltype(prior_context_)>() == 2, "TextBreakIterator has unexpected prior context length"); if (prior_context_[1]) { if (prior_context_[0])
diff --git a/third_party/blink/renderer/platform/text/unicode_utilities_test.cc b/third_party/blink/renderer/platform/text/unicode_utilities_test.cc index 125a2158..17a421e0 100644 --- a/third_party/blink/renderer/platform/text/unicode_utilities_test.cc +++ b/third_party/blink/renderer/platform/text/unicode_utilities_test.cc
@@ -31,6 +31,8 @@ #include "third_party/blink/renderer/platform/text/unicode_utilities.h" #include <unicode/uchar.h> + +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/text/character_names.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -139,13 +141,13 @@ kRightSingleQuotationMarkCharacter, kSoftHyphenCharacter}; - String string_to_fold(kCharactersToFold, arraysize(kCharactersToFold)); + String string_to_fold(kCharactersToFold, base::size(kCharactersToFold)); Vector<UChar> buffer; string_to_fold.AppendTo(buffer); FoldQuoteMarksAndSoftHyphens(string_to_fold); - const String folded_string("\"\"\"\'\'\'\0", arraysize(kCharactersToFold)); + const String folded_string("\"\"\"\'\'\'\0", base::size(kCharactersToFold)); EXPECT_EQ(string_to_fold, folded_string); FoldQuoteMarksAndSoftHyphens(buffer.data(), buffer.size()); @@ -158,37 +160,37 @@ // Check that non-Kana letters will be skipped. EXPECT_TRUE(CheckOnlyKanaLettersInStrings( - kNonKanaString1, arraysize(kNonKanaString1), kNonKanaString2, - arraysize(kNonKanaString2))); + kNonKanaString1, base::size(kNonKanaString1), kNonKanaString2, + base::size(kNonKanaString2))); const UChar kKanaString[] = {'e', 'f', 'g', 0x3041}; EXPECT_FALSE(CheckOnlyKanaLettersInStrings( - kKanaString, arraysize(kKanaString), kNonKanaString2, - arraysize(kNonKanaString2))); + kKanaString, base::size(kKanaString), kNonKanaString2, + base::size(kNonKanaString2))); // Compare with self. - EXPECT_TRUE(CheckOnlyKanaLettersInStrings(kKanaString, arraysize(kKanaString), - kKanaString, - arraysize(kKanaString))); + EXPECT_TRUE( + CheckOnlyKanaLettersInStrings(kKanaString, base::size(kKanaString), + kKanaString, base::size(kKanaString))); UChar voiced_kana_string1[] = {0x3042, 0x3099}; UChar voiced_kana_string2[] = {0x3042, 0x309A}; // Comparing strings with different sound marks should fail. EXPECT_FALSE(CheckOnlyKanaLettersInStrings( - voiced_kana_string1, arraysize(voiced_kana_string1), voiced_kana_string2, - arraysize(voiced_kana_string2))); + voiced_kana_string1, base::size(voiced_kana_string1), voiced_kana_string2, + base::size(voiced_kana_string2))); // Now strings will be the same. voiced_kana_string2[1] = 0x3099; EXPECT_TRUE(CheckOnlyKanaLettersInStrings( - voiced_kana_string1, arraysize(voiced_kana_string1), voiced_kana_string2, - arraysize(voiced_kana_string2))); + voiced_kana_string1, base::size(voiced_kana_string1), voiced_kana_string2, + base::size(voiced_kana_string2))); voiced_kana_string2[0] = 0x3043; EXPECT_FALSE(CheckOnlyKanaLettersInStrings( - voiced_kana_string1, arraysize(voiced_kana_string1), voiced_kana_string2, - arraysize(voiced_kana_string2))); + voiced_kana_string1, base::size(voiced_kana_string1), voiced_kana_string2, + base::size(voiced_kana_string2))); } TEST(UnicodeUtilitiesTest, StringsWithKanaLettersTest) { @@ -196,53 +198,53 @@ const UChar kNonKanaString2[] = {'a', 'b', 'c'}; // Check that non-Kana letters will be compared. - EXPECT_TRUE(CheckKanaStringsEqual(kNonKanaString1, arraysize(kNonKanaString1), - kNonKanaString2, - arraysize(kNonKanaString2))); + EXPECT_TRUE( + CheckKanaStringsEqual(kNonKanaString1, base::size(kNonKanaString1), + kNonKanaString2, base::size(kNonKanaString2))); const UChar kKanaString[] = {'a', 'b', 'c', 0x3041}; - EXPECT_FALSE(CheckKanaStringsEqual(kKanaString, arraysize(kKanaString), + EXPECT_FALSE(CheckKanaStringsEqual(kKanaString, base::size(kKanaString), kNonKanaString2, - arraysize(kNonKanaString2))); + base::size(kNonKanaString2))); // Compare with self. - EXPECT_TRUE(CheckKanaStringsEqual(kKanaString, arraysize(kKanaString), - kKanaString, arraysize(kKanaString))); + EXPECT_TRUE(CheckKanaStringsEqual(kKanaString, base::size(kKanaString), + kKanaString, base::size(kKanaString))); const UChar kKanaString2[] = {'x', 'y', 'z', 0x3041}; // Comparing strings with different non-Kana letters should fail. - EXPECT_FALSE(CheckKanaStringsEqual(kKanaString, arraysize(kKanaString), - kKanaString2, arraysize(kKanaString2))); + EXPECT_FALSE(CheckKanaStringsEqual(kKanaString, base::size(kKanaString), + kKanaString2, base::size(kKanaString2))); const UChar kKanaString3[] = {'a', 'b', 'c', 0x3042, 0x3099, 'm', 'n', 'o'}; // Check that non-Kana letters after Kana letters will be compared. - EXPECT_TRUE(CheckKanaStringsEqual(kKanaString3, arraysize(kKanaString3), - kKanaString3, arraysize(kKanaString3))); + EXPECT_TRUE(CheckKanaStringsEqual(kKanaString3, base::size(kKanaString3), + kKanaString3, base::size(kKanaString3))); const UChar kKanaString4[] = {'a', 'b', 'c', 0x3042, 0x3099, 'm', 'n', 'o', 'p'}; // And now comparing should fail. - EXPECT_FALSE(CheckKanaStringsEqual(kKanaString3, arraysize(kKanaString3), - kKanaString4, arraysize(kKanaString4))); + EXPECT_FALSE(CheckKanaStringsEqual(kKanaString3, base::size(kKanaString3), + kKanaString4, base::size(kKanaString4))); UChar voiced_kana_string1[] = {0x3042, 0x3099}; UChar voiced_kana_string2[] = {0x3042, 0x309A}; // Comparing strings with different sound marks should fail. EXPECT_FALSE(CheckKanaStringsEqual( - voiced_kana_string1, arraysize(voiced_kana_string1), voiced_kana_string2, - arraysize(voiced_kana_string2))); + voiced_kana_string1, base::size(voiced_kana_string1), voiced_kana_string2, + base::size(voiced_kana_string2))); // Now strings will be the same. voiced_kana_string2[1] = 0x3099; EXPECT_TRUE(CheckKanaStringsEqual( - voiced_kana_string1, arraysize(voiced_kana_string1), voiced_kana_string2, - arraysize(voiced_kana_string2))); + voiced_kana_string1, base::size(voiced_kana_string1), voiced_kana_string2, + base::size(voiced_kana_string2))); voiced_kana_string2[0] = 0x3043; EXPECT_FALSE(CheckKanaStringsEqual( - voiced_kana_string1, arraysize(voiced_kana_string1), voiced_kana_string2, - arraysize(voiced_kana_string2))); + voiced_kana_string1, base::size(voiced_kana_string1), voiced_kana_string2, + base::size(voiced_kana_string2))); } } // namespace blink
diff --git a/third_party/blink/renderer/platform/transforms/transform_operations_test.cc b/third_party/blink/renderer/platform/transforms/transform_operations_test.cc index 02db9ce..288d83c1 100644 --- a/third_party/blink/renderer/platform/transforms/transform_operations_test.cc +++ b/third_party/blink/renderer/platform/transforms/transform_operations_test.cc
@@ -24,6 +24,7 @@ #include "third_party/blink/renderer/platform/transforms/transform_operations.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/geometry/float_box.h" #include "third_party/blink/renderer/platform/geometry/float_box_test_helpers.h" @@ -118,8 +119,8 @@ // [0,1]. float progress[][2] = {{0, 1}, {-.25, 1.25}}; - for (size_t i = 0; i < arraysize(test_transforms); ++i) { - for (size_t j = 0; j < arraysize(progress); ++j) { + for (size_t i = 0; i < base::size(test_transforms); ++i) { + for (size_t j = 0; j < base::size(progress); ++j) { TransformOperations from_ops; TransformOperations to_ops; from_ops.Operations().push_back(TranslateTransformOperation::Create( @@ -181,8 +182,8 @@ // [0,1]. float progress[][2] = {{0, 1}, {-.25f, 1.25f}}; - for (size_t i = 0; i < arraysize(test_transforms); ++i) { - for (size_t j = 0; j < arraysize(progress); ++j) { + for (size_t i = 0; i < base::size(test_transforms); ++i) { + for (size_t j = 0; j < base::size(progress); ++j) { TransformOperations from_ops; TransformOperations to_ops; from_ops.Operations().push_back(TranslateTransformOperation::Create( @@ -213,7 +214,7 @@ // 2 * sqrt(2) should give the same result. float sizes[] = {0, 0.1f, sqrt2, 2 * sqrt2}; to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds); - for (size_t i = 0; i < arraysize(sizes); ++i) { + for (size_t i = 0; i < base::size(sizes); ++i) { box.SetSize(FloatPoint3D(sizes[i], sizes[i], 0)); EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds)); @@ -284,9 +285,9 @@ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual, box, bounds); } -// This would have been best as anonymous structs, but |arraysize| +// This would have been best as anonymous structs, but |base::size| // does not get along with anonymous structs once we support C++11 -// arraysize will automatically support anonymous structs. +// base::size will automatically support anonymous structs. struct ProblematicAxisTest { double x; @@ -314,7 +315,7 @@ {0, 1, 1, FloatBox(-1, dim1, dim1, 2, dim2, dim2)}, {1, 0, 1, FloatBox(dim1, -1, dim1, dim2, 2, dim2)}}; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { float x = tests[i].x; float y = tests[i].y; float z = tests[i].z; @@ -346,9 +347,9 @@ float progress[][2] = {{0, 1}, {-0.25f, 1.25f}}; - for (size_t i = 0; i < arraysize(axes); ++i) { - for (size_t j = 0; j < arraysize(angles); ++j) { - for (size_t k = 0; k < arraysize(progress); ++k) { + for (size_t i = 0; i < base::size(axes); ++i) { + for (size_t j = 0; j < base::size(angles); ++j) { + for (size_t k = 0; k < base::size(progress); ++k) { float x = axes[i][0]; float y = axes[i][1]; float z = axes[i][2]; @@ -394,8 +395,8 @@ float progress[][2] = {{0, 1}, {-0.1f, 1.1f}}; - for (size_t i = 0; i < arraysize(depths); ++i) { - for (size_t j = 0; j < arraysize(progress); ++j) { + for (size_t i = 0; i < base::size(depths); ++i) { + for (size_t j = 0; j < base::size(progress); ++j) { TransformOperations from_ops; TransformOperations to_ops;
diff --git a/third_party/blink/renderer/platform/web_vector_test.cc b/third_party/blink/renderer/platform/web_vector_test.cc index a0d8978e..6066cbd5 100644 --- a/third_party/blink/renderer/platform/web_vector_test.cc +++ b/third_party/blink/renderer/platform/web_vector_test.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/public/platform/web_vector.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -60,8 +61,8 @@ TEST(WebVectorTest, Swap) { const int kFirstData[] = {1, 2, 3, 4, 5}; const int kSecondData[] = {6, 5, 8}; - const size_t kFirstDataLength = arraysize(kFirstData); - const size_t kSecondDataLength = arraysize(kSecondData); + const size_t kFirstDataLength = base::size(kFirstData); + const size_t kSecondDataLength = base::size(kSecondData); WebVector<int> first(kFirstData, kFirstDataLength); WebVector<int> second(kSecondData, kSecondDataLength); @@ -136,9 +137,9 @@ WebVector<WebString> vector; vector.reserve(1); WebUChar buffer[] = {'H', 'e', 'l', 'l', 'o', ' ', 'b', 'l', 'i', 'n', 'k'}; - vector.emplace_back(buffer, arraysize(buffer)); + vector.emplace_back(buffer, base::size(buffer)); ASSERT_EQ(1U, vector.size()); - EXPECT_EQ(WebString(buffer, arraysize(buffer)), vector[0]); + EXPECT_EQ(WebString(buffer, base::size(buffer)), vector[0]); } TEST(WebVectorTest, EmplaceBackElementPlacement) {
diff --git a/third_party/blink/renderer/platform/weborigin/kurl_test.cc b/third_party/blink/renderer/platform/weborigin/kurl_test.cc index 1224900..2a047b0 100644 --- a/third_party/blink/renderer/platform/weborigin/kurl_test.cc +++ b/third_party/blink/renderer/platform/weborigin/kurl_test.cc
@@ -35,6 +35,7 @@ #include <stdint.h> +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" @@ -85,7 +86,7 @@ "xn--6qqa088eba", 0, "", nullptr, "/", nullptr, nullptr, nullptr, false}, }; - for (size_t i = 0; i < arraysize(cases); i++) { + for (size_t i = 0; i < base::size(cases); i++) { const GetterCase& c = cases[i]; const String& url = String::FromUTF8(c.url); @@ -176,7 +177,7 @@ nullptr, "http://goo.com:92/#b"}, }; - for (size_t i = 0; i < arraysize(cases); i++) { + for (size_t i = 0; i < base::size(cases); i++) { KURL kurl(cases[i].url); kurl.SetProtocol(cases[i].protocol); @@ -232,7 +233,7 @@ {"%e4%bd%a0%e5%a5%bd", "\xe4\xbd\xa0\xe5\xa5\xbd"}, }; - for (size_t i = 0; i < arraysize(decode_cases); i++) { + for (size_t i = 0; i < base::size(decode_cases); i++) { String input(decode_cases[i].input); String str = DecodeURLEscapeSequences(input, DecodeURLMode::kUTF8OrIsomorphic); @@ -248,7 +249,7 @@ String decoded = DecodeURLEscapeSequences("%e6%bc%a2%e5%ad%97", DecodeURLMode::kUTF8OrIsomorphic); const UChar kDecodedExpected[] = {0x6F22, 0x5b57}; - EXPECT_EQ(String(kDecodedExpected, arraysize(kDecodedExpected)), decoded); + EXPECT_EQ(String(kDecodedExpected, base::size(kDecodedExpected)), decoded); // Test the error behavior for invalid UTF-8 (we differ from WebKit here). // %e4 %a0 are invalid for UTF-8, but %e5%a5%bd is valid. @@ -279,7 +280,7 @@ {"pqrstuvwxyz{|}~\x7f", "pqrstuvwxyz%7B%7C%7D~%7F"}, }; - for (size_t i = 0; i < arraysize(encode_cases); i++) { + for (size_t i = 0; i < base::size(encode_cases); i++) { String input(encode_cases[i].input); String expected_output(encode_cases[i].output); String output = EncodeWithURLEscapeSequences(input); @@ -870,7 +871,7 @@ {"https://www.google.com/#", "https://www.google.com/"}, }; - for (size_t i = 0; i < arraysize(referrer_cases); i++) { + for (size_t i = 0; i < base::size(referrer_cases); i++) { const KURL kurl(referrer_cases[i].input); String referrer = kurl.StrippedForUseAsReferrer(); EXPECT_STREQ(referrer_cases[i].output, referrer.Utf8().data());
diff --git a/third_party/blink/renderer/platform/weborigin/security_origin_test.cc b/third_party/blink/renderer/platform/weborigin/security_origin_test.cc index e77bd92..0e4b717 100644 --- a/third_party/blink/renderer/platform/weborigin/security_origin_test.cc +++ b/third_party/blink/renderer/platform/weborigin/security_origin_test.cc
@@ -32,6 +32,7 @@ #include <stdint.h> +#include "base/stl_util.h" #include "services/network/public/mojom/cors.mojom-shared.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/blob/blob_url.h" @@ -56,7 +57,7 @@ TEST_F(SecurityOriginTest, ValidPortsCreateTupleOrigins) { uint16_t ports[] = {0, 80, 443, 5000, kMaxAllowedPort}; - for (size_t i = 0; i < arraysize(ports); ++i) { + for (size_t i = 0; i < base::size(ports); ++i) { scoped_refptr<const SecurityOrigin> origin = SecurityOrigin::Create("http", "example.com", ports[i]); EXPECT_FALSE(origin->IsOpaque()) @@ -153,7 +154,7 @@ {false, "filesystem:ftp://evil:99/foo"}, }; - for (size_t i = 0; i < arraysize(inputs); ++i) { + for (size_t i = 0; i < base::size(inputs); ++i) { SCOPED_TRACE(inputs[i].url); scoped_refptr<const SecurityOrigin> origin = SecurityOrigin::CreateFromString(inputs[i].url); @@ -237,7 +238,7 @@ {false, "file:///", "file://localhost/"}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { scoped_refptr<const SecurityOrigin> origin1 = SecurityOrigin::CreateFromString(tests[i].origin1); scoped_refptr<const SecurityOrigin> origin2 = @@ -344,7 +345,7 @@ {false, "https://foobar.com", "https://bazbar.com"}, }; - for (size_t i = 0; i < arraysize(tests); ++i) { + for (size_t i = 0; i < base::size(tests); ++i) { scoped_refptr<const SecurityOrigin> origin = SecurityOrigin::CreateFromString(tests[i].origin); blink::KURL url(tests[i].url);
diff --git a/third_party/blink/renderer/platform/wtf/date_math.cc b/third_party/blink/renderer/platform/wtf/date_math.cc index 456098a..87f4972d 100644 --- a/third_party/blink/renderer/platform/wtf/date_math.cc +++ b/third_party/blink/renderer/platform/wtf/date_math.cc
@@ -78,6 +78,8 @@ #include <algorithm> #include <limits> #include <memory> + +#include "base/stl_util.h" #include "build/build_config.h" #include "third_party/blink/renderer/platform/wtf/ascii_ctype.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" @@ -613,7 +615,7 @@ } have_tz = true; } else { - for (size_t i = 0; i < arraysize(known_zones); ++i) { + for (size_t i = 0; i < base::size(known_zones); ++i) { if (0 == strncasecmp(date_string, known_zones[i].tz_name, strlen(known_zones[i].tz_name))) { offset = known_zones[i].tz_offset;
diff --git a/third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h b/third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h index 4933c9b8..b6c9dde 100644 --- a/third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h +++ b/third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h
@@ -24,7 +24,9 @@ #include <limits> #include <type_traits> + #include "base/numerics/safe_conversions.h" +#include "base/stl_util.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/text/unicode.h" @@ -40,7 +42,7 @@ "IntegerType must be a type of integer."); explicit IntegerToStringConverter(IntegerType input) { - LChar* end = buffer_ + arraysize(buffer_); + LChar* end = buffer_ + base::size(buffer_); begin_ = end; // We need to switch to the unsigned type when negating the value since
diff --git a/third_party/blink/renderer/platform/wtf/text/string_builder_test.cc b/third_party/blink/renderer/platform/wtf/text/string_builder_test.cc index bc0d9472..ad83044 100644 --- a/third_party/blink/renderer/platform/wtf/text/string_builder_test.cc +++ b/third_party/blink/renderer/platform/wtf/text/string_builder_test.cc
@@ -31,6 +31,7 @@ #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/text/character_names.h" @@ -121,7 +122,7 @@ EXPECT_EQ(3U, builder_for_u_char32_append.length()); const UChar result_array[] = {U16_LEAD(fraktur_a_char), U16_TRAIL(fraktur_a_char), 'A'}; - ExpectBuilderContent(String(result_array, arraysize(result_array)), + ExpectBuilderContent(String(result_array, base::size(result_array)), builder_for_u_char32_append); }
diff --git a/third_party/blink/renderer/platform/wtf/text/wtf_string_test.cc b/third_party/blink/renderer/platform/wtf/text/wtf_string_test.cc index 01adf9e..ef91f3f 100644 --- a/third_party/blink/renderer/platform/wtf/text/wtf_string_test.cc +++ b/third_party/blink/renderer/platform/wtf/text/wtf_string_test.cc
@@ -26,6 +26,8 @@ #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include <limits> + +#include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/math_extras.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" @@ -494,7 +496,7 @@ 0x30C8}; // "Test" in Japanese. EXPECT_EQ(CString("\"\\u30C6\\u30B9\\u30C8\""), ToCStringThroughPrinter( - String(kUnicodeSample, arraysize(kUnicodeSample)))); + String(kUnicodeSample, base::size(kUnicodeSample)))); } } // namespace WTF
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index 1e88f1b9..de97e4c7 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -403,6 +403,15 @@ ], }, { + 'paths': ['third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc'], + 'allowed': [ + # cc painting types. + 'cc::ContentLayerClient', + 'cc::DisplayItemList', + 'cc::DrawRecordOp', + ], + }, + { 'paths': ['third_party/blink/renderer/core/inspector/inspector_performance_agent.cc'], 'allowed': [ 'base::subtle::TimeTicksNowIgnoringOverride',
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint index efd48d87..61b18bb 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint +++ b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint
@@ -5,7 +5,8 @@ Bug(none) css3/blending [ Pass ] Bug(none) editing/input [ Skip ] Bug(none) external/wpt [ Skip ] -Bug(none) http/tests/devtools [ Skip ] +Bug(none) http/tests/devtools/layers/ [ Skip ] +Bug(none) http/tests/devtools/tracing/ [ Skip ] Bug(none) printing/ [ Skip ] Bug(none) scrollbars/ [ Skip ] Bug(none) scrollingcoordinator/ [ Skip ] @@ -196,7 +197,6 @@ Bug(none) http/tests/misc/slow-loading-mask.html [ Failure ] Bug(none) http/tests/navigation/same-document-scroll-position-restore.html [ Timeout ] Bug(none) ietestcenter/css3/bordersbackgrounds/background-attachment-local-scrolling.htm [ Failure ] -Bug(none) inspector-protocol/dom/dom-setInspectModeEnabled.js [ Crash ] Bug(none) inspector-protocol/layers/paint-profiler.js [ Failure ] Bug(none) inspector-protocol/layers/get-layers.js [ Timeout ] crbug.com/912357 media/video-object-fit.html [ Failure ] @@ -355,7 +355,7 @@ crbug.com/589265 fast/pagination/repeating-thead-tfoot-paged-y.html [ Failure ] # virtual/threaded variants of sub-directories and tests already skipped or marked as failing above. -Bug(none) virtual/threaded/http/tests/devtools/ [ Skip ] +Bug(none) virtual/threaded/http/tests/devtools/tracing/ [ Skip ] Bug(none) virtual/threaded/fast/events/pinch/gesture-pinch-zoom-scroll-bubble.html [ Timeout ] Bug(none) virtual/threaded/fast/events/pinch/pinch-zoom-pan-within-zoomed-viewport.html [ Failure ] Bug(none) virtual/threaded/fast/events/pinch/scroll-visual-viewport-send-boundary-events.html [ Timeout ]
diff --git a/third_party/blink/web_tests/compositing/layer-creation/fixed-position-under-transform-expected.txt b/third_party/blink/web_tests/compositing/layer-creation/fixed-position-under-transform-expected.txt index 9c799d4..2ce4c5abc 100644 --- a/third_party/blink/web_tests/compositing/layer-creation/fixed-position-under-transform-expected.txt +++ b/third_party/blink/web_tests/compositing/layer-creation/fixed-position-under-transform-expected.txt
@@ -21,7 +21,6 @@ { "name": "LayoutBlockFlow DIV id='transform'", "bounds": [256, 256], - "contentsOpaque": true, "transform": 3 }, {
diff --git a/third_party/blink/web_tests/compositing/rtl/rtl-fixed-overflow-expected.txt b/third_party/blink/web_tests/compositing/rtl/rtl-fixed-overflow-expected.txt index a8cf302..b3ce1bd1 100644 --- a/third_party/blink/web_tests/compositing/rtl/rtl-fixed-overflow-expected.txt +++ b/third_party/blink/web_tests/compositing/rtl/rtl-fixed-overflow-expected.txt
@@ -19,14 +19,6 @@ "transform": 1 }, { - "name": "LayoutBlockFlow (positioned) DIV class='positioned indicator'", - "position": [265, 50], - "bounds": [100, 100], - "contentsOpaque": true, - "backgroundColor": "#FF0000", - "transform": 1 - }, - { "name": "LayoutBlockFlow (positioned) DIV class='positioned layer'", "bounds": [100, 100], "contentsOpaque": true,
diff --git a/third_party/blink/web_tests/compositing/rtl/rtl-fixed-overflow-scrolled-expected.txt b/third_party/blink/web_tests/compositing/rtl/rtl-fixed-overflow-scrolled-expected.txt index 3261e35..420542e7 100644 --- a/third_party/blink/web_tests/compositing/rtl/rtl-fixed-overflow-scrolled-expected.txt +++ b/third_party/blink/web_tests/compositing/rtl/rtl-fixed-overflow-scrolled-expected.txt
@@ -19,14 +19,6 @@ "transform": 1 }, { - "name": "LayoutBlockFlow (positioned) DIV class='positioned indicator'", - "position": [51, 50], - "bounds": [100, 100], - "contentsOpaque": true, - "backgroundColor": "#FF0000", - "transform": 1 - }, - { "name": "LayoutBlockFlow (positioned) DIV class='positioned layer'", "bounds": [100, 100], "contentsOpaque": true,
diff --git a/third_party/blink/web_tests/compositing/rtl/rtl-iframe-fixed-overflow-expected.txt b/third_party/blink/web_tests/compositing/rtl/rtl-iframe-fixed-overflow-expected.txt index 2c2c0e57..e6cb740 100644 --- a/third_party/blink/web_tests/compositing/rtl/rtl-iframe-fixed-overflow-expected.txt +++ b/third_party/blink/web_tests/compositing/rtl/rtl-iframe-fixed-overflow-expected.txt
@@ -41,14 +41,6 @@ "transform": 1 }, { - "name": "LayoutBlockFlow (positioned) DIV class='positioned indicator'", - "position": [680, 50], - "bounds": [100, 100], - "contentsOpaque": true, - "backgroundColor": "#FF0000", - "transform": 1 - }, - { "name": "LayoutBlockFlow (positioned) DIV class='positioned layer'", "bounds": [100, 100], "contentsOpaque": true,
diff --git a/third_party/blink/web_tests/compositing/rtl/rtl-iframe-fixed-overflow-scrolled-expected.txt b/third_party/blink/web_tests/compositing/rtl/rtl-iframe-fixed-overflow-scrolled-expected.txt index 2c2c0e57..e6cb740 100644 --- a/third_party/blink/web_tests/compositing/rtl/rtl-iframe-fixed-overflow-scrolled-expected.txt +++ b/third_party/blink/web_tests/compositing/rtl/rtl-iframe-fixed-overflow-scrolled-expected.txt
@@ -41,14 +41,6 @@ "transform": 1 }, { - "name": "LayoutBlockFlow (positioned) DIV class='positioned indicator'", - "position": [680, 50], - "bounds": [100, 100], - "contentsOpaque": true, - "backgroundColor": "#FF0000", - "transform": 1 - }, - { "name": "LayoutBlockFlow (positioned) DIV class='positioned layer'", "bounds": [100, 100], "contentsOpaque": true,
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/resources/url-entry-document-timer-frame.html b/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/resources/url-entry-document-timer-frame.html new file mode 100644 index 0000000..b2c0507 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/resources/url-entry-document-timer-frame.html
@@ -0,0 +1,3 @@ +<script> +setTimeout(parent.timerTest, 10); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/url-entry-document.window.js b/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/url-entry-document.window.js new file mode 100644 index 0000000..c3a1c3a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/url-entry-document.window.js
@@ -0,0 +1,18 @@ +async_test(t => { + const frame = document.body.appendChild(document.createElement("iframe")); + t.add_cleanup(() => frame.remove()); + const frameURL = new URL("resources/url-entry-document-timer-frame.html", document.URL).href; + window.timerTest = t.step_func_done(() => { + assert_equals(frame.contentDocument.URL, frameURL); + assert_equals(frame.contentWindow.location.href, frameURL); + + // In this case, the entry settings object was set when this function is + // executed in the timer task through Web IDL's "invoke a callback + // function" algorithm, to be the relevant settings object of this + // function. Therefore the URL of this document would be inherited. + assert_equals(frame.contentDocument.open(), frame.contentDocument); + assert_equals(frame.contentDocument.URL, document.URL); + assert_equals(frame.contentWindow.location.href, document.URL); + }); + frame.src = frameURL; +}, "document.open() changes document's URL to the entry settings object's responsible document's (through timeouts)");
diff --git a/third_party/blink/web_tests/external/wpt/lint.whitelist b/third_party/blink/web_tests/external/wpt/lint.whitelist index c3ff66b..c9221883 100644 --- a/third_party/blink/web_tests/external/wpt/lint.whitelist +++ b/third_party/blink/web_tests/external/wpt/lint.whitelist
@@ -167,6 +167,7 @@ SET TIMEOUT: html/semantics/scripting-1/the-script-element/* SET TIMEOUT: html/webappapis/dynamic-markup-insertion/opening-the-input-stream/0* SET TIMEOUT: html/webappapis/dynamic-markup-insertion/opening-the-input-stream/resources/history-frame.html +SET TIMEOUT: html/webappapis/dynamic-markup-insertion/opening-the-input-stream/resources/url-entry-document-timer-frame.html SET TIMEOUT: html/webappapis/dynamic-markup-insertion/opening-the-input-stream/tasks.window.js SET TIMEOUT: html/webappapis/scripting/event-loops/* SET TIMEOUT: html/webappapis/scripting/events/event-handler-processing-algorithm-error/*
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt index c6d341b..6303ad5 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt
@@ -15,7 +15,7 @@ { "object": "LayoutBlockFlow DIV id='resize' class='drop-shadow'", "rect": [0, 0, 160, 260], - "reason": "geometry" + "reason": "paint property change" } ], "transform": 1
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/filters/filter-repaint-accelerated-on-accelerated-filter-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/filters/filter-repaint-accelerated-on-accelerated-filter-expected.txt index 6be7d4c4..dfe5c8d 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/filters/filter-repaint-accelerated-on-accelerated-filter-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/filters/filter-repaint-accelerated-on-accelerated-filter-expected.txt
@@ -15,7 +15,7 @@ { "object": "LayoutBlockFlow DIV id='resize' class='drop-shadow accelerated'", "rect": [0, 0, 160, 260], - "reason": "geometry" + "reason": "paint property change" } ], "transform": 1
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/tables/mozilla/bugs/bug5538-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/tables/mozilla/bugs/bug5538-expected.png index 7681d92..83c4c39 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/tables/mozilla/bugs/bug5538-expected.png +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/tables/mozilla/bugs/bug5538-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt b/third_party/blink/web_tests/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt index 695d634..fd0f932 100644 --- a/third_party/blink/web_tests/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt +++ b/third_party/blink/web_tests/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt
@@ -4,6 +4,16 @@ "name": "LayoutView #document", "bounds": [800, 600], "drawsContent": false, + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], "contentsOpaque": true, "backgroundColor": "#FFFFFF" }, @@ -18,8 +28,13 @@ "paintInvalidations": [ { "object": "LayoutBlockFlow DIV id='resize' class='drop-shadow'", - "rect": [-2, -2, 260, 260], - "reason": "geometry" + "rect": [0, 0, 212, 257], + "reason": "paint property change" + }, + { + "object": "LayoutBlockFlow DIV id='resize' class='drop-shadow'", + "rect": [0, 0, 158, 257], + "reason": "paint property change" } ], "transform": 1
diff --git a/third_party/blink/web_tests/platform/linux/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt b/third_party/blink/web_tests/platform/linux/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt deleted file mode 100644 index 19f391b..0000000 --- a/third_party/blink/web_tests/platform/linux/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt +++ /dev/null
@@ -1,50 +0,0 @@ -{ - "layers": [ - { - "name": "LayoutView #document", - "bounds": [800, 600], - "drawsContent": false, - "backgroundColor": "#FFFFFF" - }, - { - "name": "Scrolling Layer", - "bounds": [800, 600], - "drawsContent": false - }, - { - "name": "Scrolling Contents Layer", - "bounds": [800, 600], - "contentsOpaque": true, - "backgroundColor": "#FFFFFF" - }, - { - "name": "LayoutBlockFlow DIV class='blur'", - "position": [8, 8], - "bounds": [200, 200] - }, - { - "name": "LayoutBlockFlow DIV class='accelerated'", - "bounds": [212, 257], - "paintInvalidations": [ - { - "object": "LayoutBlockFlow DIV id='resize' class='drop-shadow'", - "rect": [0, 0, 212, 257], - "reason": "geometry" - } - ], - "transform": 1 - } - ], - "transforms": [ - { - "id": 1, - "transform": [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [-4, -4, 0, 1] - ] - } - ] -} -
diff --git a/third_party/blink/web_tests/platform/mac/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt b/third_party/blink/web_tests/platform/mac/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt deleted file mode 100644 index 19f391b..0000000 --- a/third_party/blink/web_tests/platform/mac/paint/invalidation/filters/filter-repaint-accelerated-child-with-filter-child-expected.txt +++ /dev/null
@@ -1,50 +0,0 @@ -{ - "layers": [ - { - "name": "LayoutView #document", - "bounds": [800, 600], - "drawsContent": false, - "backgroundColor": "#FFFFFF" - }, - { - "name": "Scrolling Layer", - "bounds": [800, 600], - "drawsContent": false - }, - { - "name": "Scrolling Contents Layer", - "bounds": [800, 600], - "contentsOpaque": true, - "backgroundColor": "#FFFFFF" - }, - { - "name": "LayoutBlockFlow DIV class='blur'", - "position": [8, 8], - "bounds": [200, 200] - }, - { - "name": "LayoutBlockFlow DIV class='accelerated'", - "bounds": [212, 257], - "paintInvalidations": [ - { - "object": "LayoutBlockFlow DIV id='resize' class='drop-shadow'", - "rect": [0, 0, 212, 257], - "reason": "geometry" - } - ], - "transform": 1 - } - ], - "transforms": [ - { - "id": 1, - "transform": [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [-4, -4, 0, 1] - ] - } - ] -} -
diff --git a/third_party/blink/web_tests/tables/table-section-visual-overflowing-cell-crash-expected.html b/third_party/blink/web_tests/tables/table-section-visual-overflowing-cell-crash-expected.html new file mode 100644 index 0000000..8dd1c79 --- /dev/null +++ b/third_party/blink/web_tests/tables/table-section-visual-overflowing-cell-crash-expected.html
@@ -0,0 +1,2 @@ +<!doctype HTML> +Passes if it does not crash.
diff --git a/third_party/blink/web_tests/tables/table-section-visual-overflowing-cell-crash.html b/third_party/blink/web_tests/tables/table-section-visual-overflowing-cell-crash.html new file mode 100644 index 0000000..b915da442 --- /dev/null +++ b/third_party/blink/web_tests/tables/table-section-visual-overflowing-cell-crash.html
@@ -0,0 +1,23 @@ +<!doctype HTML> +<style> +.c8 {-webkit-column-width: 1px; } +.c12 { content: no-close-quote; padding-right: 10px; } +.c12 { vertical-align: -10%; padding-bottom: 100%; } +.c18 { display: table-header-group; } +</style> +Passes if it does not crash. +<script> + var cell1 = document.createElement('td'); + cell1.setAttribute('class', 'c8'); + document.documentElement.appendChild(cell1); + + var cell2 = document.createElement('td'); + cell2.setAttribute('rowspan', '65536'); + document.documentElement.appendChild(cell2); + + span = document.createElement('span'); + span.setAttribute('class', 'c12') + + cell2.appendChild(span); + setTimeout(() => cell2.setAttribute('class', 'c18'), 0); +</script>
diff --git a/ui/native_theme/common_theme.cc b/ui/native_theme/common_theme.cc index 66cc659..9c42ce6 100644 --- a/ui/native_theme/common_theme.cc +++ b/ui/native_theme/common_theme.cc
@@ -31,6 +31,7 @@ case NativeTheme::kColorId_ButtonHoverColor: return gfx::kGoogleGrey200; case NativeTheme::kColorId_FocusedMenuItemBackgroundColor: + case NativeTheme::kColorId_FocusedHighlightedMenuItemBackgroundColor: return SkColorSetA(gfx::kGoogleGrey800, 0x99); case NativeTheme::kColorId_MenuBackgroundColor: case NativeTheme::kColorId_BubbleBackground:
diff --git a/ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.html b/ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.html index 133e3e5..8d66c290 100644 --- a/ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.html +++ b/ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.html
@@ -9,14 +9,14 @@ <template> <style> :host dialog { - background-color: white; + background-color: var(--cr-menu-background-color); border: none; border-radius: 4px; - box-shadow: 0 2px 6px var(--paper-grey-500); + box-shadow: var(--cr-menu-shadow); margin: 0; min-width: 128px; outline: none; - padding: 8px 0; + padding: 0; @apply --cr-action-menu-dialog; } @@ -30,7 +30,7 @@ border: none; border-radius: 0; box-sizing: border-box; - color: var(--paper-grey-900); + color: var(--cr-primary-text-color); font: inherit; min-height: 32px; padding: 0 24px; @@ -53,12 +53,14 @@ } :host ::slotted(.dropdown-item:focus) { - background-color: var(--google-grey-200); + background-color: var(--cr-menu-background-focus-color); outline: none; } .item-wrapper { + background: var(--cr-menu-background-sheen); outline: none; + padding: 8px 0; } </style> <dialog id="dialog" tabindex="0" on-close="onNativeDialogClose_" role="menu"
diff --git a/ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html b/ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html index 8fb18010..17d4466 100644 --- a/ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html +++ b/ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html
@@ -18,6 +18,10 @@ height: var(--cr-toolbar-height); } + :host-context([dark]) { + border-bottom: 1px solid var(--cr-separator-color); + } + h1 { flex: 1; font-size: 123%;
diff --git a/ui/webui/resources/cr_elements/shared_vars_css.html b/ui/webui/resources/cr_elements/shared_vars_css.html index f036c300..eac2029 100644 --- a/ui/webui/resources/cr_elements/shared_vars_css.html +++ b/ui/webui/resources/cr_elements/shared_vars_css.html
@@ -6,20 +6,84 @@ <custom-style> <style is="custom-style"> html { + --google-blue-50: #E8F0FE; + --google-blue-600: #1A73E8; + /* -refresh differentiates from google-green-700 in polymer's color.html. */ + --google-green-refresh-700: #188038; + --google-blue-600-opacity-24: rgba(26, 115, 232, 0.24); + /* -refresh differentiates from google-grey-100 in polymer's color.html. */ + --google-grey-refresh-100: #F1F3F4; + --google-grey-200: #E8EAED; + --google-grey-400: #BDC1C6; + --google-grey-600: #80868B; + --google-grey-600-opacity-24: rgba(128, 134, 139, 0.24); + /* -refresh differentiates from google-grey-700 in polymer's color.html. */ + --google-grey-refresh-700: #5F6368; + --google-grey-800: #3C4043; + --google-grey-900: #202124; + --google-red-600: #D93025; + --cr-primary-text-color: var(--google-grey-900); --cr-secondary-text-color: var(--google-grey-refresh-700); + --cr-card-background-color: white; + --cr-card-elevation: { + /* google-grey-800 with opacity */ + box-shadow: rgba(60, 64, 67, .3) 0 1px 2px 0, + rgba(60, 64, 67, .15) 0 1px 3px 1px; + } + + --cr-focused-item-color: var(--google-grey-300); + --cr-form-field-label-color: var(--google-grey-refresh-700); + --cr-link-color: var(--google-blue-700); + --cr-menu-background-color: white; + --cr-menu-background-focus-color: var(--google-grey-200); + --cr-menu-shadow: 0 2px 6px var(--paper-grey-500); + --cr-section-text-color: var(--google-grey-refresh-700); + --cr-separator-color: rgba(0, 0, 0, 0.06); + --cr-title-text-color: rgb(90, 90, 90); + --cr-toggle-color: var(--google-blue-500); + } + + html[dark] { + --dark-primary-color: rgba(255, 255, 255, .87); + --dark-secondary-color: rgba(255, 255, 255, .6); + + --cr-primary-text-color: var(--dark-primary-color); + --cr-secondary-text-color: var(--dark-secondary-color); + + --cr-card-background-color: var(--google-grey-900); + --cr-card-elevation: { + background-color: rgba(255, 255, 255, .04); + box-shadow: rgba(0, 0, 0, .3) 0 1px 2px 0, + rgba(0, 0, 0, .15) 0 4px 8px 3px; + } + + /* TODO(dbeam): form-field-label, {section,title}-text, & toggle colors. */ + + --cr-form-field-label-color: var(--dark-secondary-color); + --cr-link-color: var(--google-blue-300); + --cr-menu-background-color: var(--google-grey-900); + --cr-menu-background-focus-color: rgba(60, 64, 67, .6); + --cr-menu-background-sheen: rgba(255, 255, 255, .06); /* Only dark mode. */ + --cr-menu-shadow: rgba(0, 0, 0, .3) 0 1px 2px 0, + rgba(0, 0, 0, .15) 0 2px 6px 2px; + --cr-separator-color: var(--google-grey-refresh-700); + } + + /* Don't use color values past this point. Instead, create a variable that's + * set for both light and dark modes and use a single variable below. */ + + html { --cr-actionable: { cursor: pointer; - }; + } --cr-button-edge-spacing: 12px; /* Spacing between policy (controlledBy) indicator and control. */ --cr-controlled-by-spacing: 24px; - --cr-focused-item-color: var(--google-grey-300); - /* The inner icon is 20px in size. The button has 8px * 2 padding. */ --cr-icon-ripple-size: 36px; --cr-icon-ripple-padding: 8px; @@ -41,7 +105,7 @@ line-height: 154%; /* Apply 20px default line-height to all text. */ overflow: hidden; /* Prevent double scroll bar bugs. */ user-select: text; - }; + } --cr-paper-icon-button-margin: { /* Shift button so ripple overlaps the end of the row. */ @@ -78,27 +142,25 @@ display: flex; min-height: var(--cr-section-min-height); padding: 0 var(--cr-section-padding); - }; + } --cr-text-elide: { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; - }; + } --cr-title-text: { - color: rgb(90, 90, 90); + color: var(--cr-title-text-color); font-size: 107.6923%; /* Go to 14px from 13px. */ font-weight: 500; - }; + } --cr-section-text: { - color: var(--google-grey-refresh-700); + color: var(--cr-section-text-color); font-size: 100%; /* Likely to be 13px. */ font-weight: 500; - }; - - --cr-toggle-color: var(--google-blue-500); + } --cr-tooltip: { font-size: 92.31%; /* Effectively 12px if the host default is 13px. */ @@ -113,7 +175,8 @@ outline: none; } --cr-separator-height: 1px; - --cr-separator-line: var(--cr-separator-height) solid rgba(0, 0, 0, 0.06); + --cr-separator-line: var(--cr-separator-height) solid + var(--cr-separator-color); --cr-toolbar-overlay-animation-duration: 150ms; @@ -135,18 +198,13 @@ /** MD Refresh Styles */ --cr-card-border-radius: 4px; - --cr-card-elevation: { - /* google-grey-800 with opacity */ - box-shadow: rgba(60, 64, 67, .3) 0 1px 2px 0, - rgba(60, 64, 67, .15) 0 1px 3px 1px; - } --cr-disabled-opacity: 0.38; --cr-form-field-bottom-spacing: 16px; --cr-form-field-label-font-size: 0.625rem; --cr-form-field-label-height: 1em; --cr-form-field-label-line-height: 1em; --cr-form-field-label: { - color: var(--google-grey-refresh-700); + color: var(--cr-form-field-label-color); display: block; font-size: var(--cr-form-field-label-font-size); font-weight: 500; @@ -154,21 +212,6 @@ line-height: var(--cr-form-field-label-line-height); margin-bottom: 8px; } - --google-blue-50: #E8F0FE; - --google-blue-600: #1A73E8; - /* -refresh differentiates from google-green-700 in polymer's color.html. */ - --google-green-refresh-700: #188038; - --google-blue-600-opacity-24: rgba(26, 115, 232, 0.24); - /* -refresh differentiates from google-grey-100 in polymer's color.html. */ - --google-grey-refresh-100: #F1F3F4; - --google-grey-200: #E8EAED; - --google-grey-400: #BDC1C6; - --google-grey-600: #80868B; - --google-grey-600-opacity-24: rgba(128, 134, 139, 0.24); - /* -refresh differentiates from google-grey-700 in polymer's color.html. */ - --google-grey-refresh-700: #5F6368; - --google-grey-900: #202124; - --google-red-600: #D93025; } </style> </custom-style>
diff --git a/ui/webui/resources/html/action_link_css.html b/ui/webui/resources/html/action_link_css.html index dc4a561..43984c19 100644 --- a/ui/webui/resources/html/action_link_css.html +++ b/ui/webui/resources/html/action_link_css.html
@@ -15,11 +15,11 @@ [is='action-link']:active, [is='action-link']:hover, [is='action-link']:visited { - color: var(--google-blue-700); + color: var(--cr-link-color); } [is='action-link'][disabled] { - color: var(--paper-grey-600); + color: var(--paper-grey-600); /* TODO(dbeam): update for dark mode. */ cursor: default; opacity: 0.65; pointer-events: none;
diff --git a/ui/webui/resources/html/i18n_behavior.html b/ui/webui/resources/html/i18n_behavior.html index f7c18edc..4e4b82c 100644 --- a/ui/webui/resources/html/i18n_behavior.html +++ b/ui/webui/resources/html/i18n_behavior.html
@@ -1,2 +1,2 @@ -<link rel="import" href="../html/parse_html_subset.html"> +<link rel="import" href="parse_html_subset.html"> <script src="../js/i18n_behavior.js"></script>
diff --git a/ui/webui/resources/html/icon.html b/ui/webui/resources/html/icon.html index eefa2f10..4168c65 100644 --- a/ui/webui/resources/html/icon.html +++ b/ui/webui/resources/html/icon.html
@@ -1,3 +1,3 @@ -<link rel="import" href="../html/cr.html"> -<link rel="import" href="../html/util.html"> +<link rel="import" href="cr.html"> +<link rel="import" href="util.html"> <script src="../js/icon.js"></script>
diff --git a/ui/webui/resources/html/load_time_data.html b/ui/webui/resources/html/load_time_data.html index 94e11c8..b3f7c5f 100644 --- a/ui/webui/resources/html/load_time_data.html +++ b/ui/webui/resources/html/load_time_data.html
@@ -1,3 +1,3 @@ -<script src="../js/assert.js"></script> +<link rel="import" href="assert.html"> +<link rel="import" href="parse_html_subset.html"> <script src="../js/load_time_data.js"></script> -<script src="../js/parse_html_subset.js"></script>
diff --git a/ui/webui/resources/html/md_select_css.html b/ui/webui/resources/html/md_select_css.html index 115e31b..8e57cc8 100644 --- a/ui/webui/resources/html/md_select_css.html +++ b/ui/webui/resources/html/md_select_css.html
@@ -1,4 +1,4 @@ -<link rel="import" href="../html/polymer.html"> +<link rel="import" href="polymer.html"> <link rel="import" href="../cr_elements/shared_vars_css.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
diff --git a/ui/webui/resources/html/promise_resolver.html b/ui/webui/resources/html/promise_resolver.html index 9dff0709..11f7be9f 100644 --- a/ui/webui/resources/html/promise_resolver.html +++ b/ui/webui/resources/html/promise_resolver.html
@@ -1,2 +1,2 @@ -<link rel="import" href="../html/assert.html"> +<link rel="import" href="assert.html"> <script src="../js/promise_resolver.js"></script>
diff --git a/ui/webui/resources/html/util.html b/ui/webui/resources/html/util.html index 9eaa4c9..07204d0d 100644 --- a/ui/webui/resources/html/util.html +++ b/ui/webui/resources/html/util.html
@@ -1,2 +1,2 @@ -<link rel="import" href="../html/assert.html"> +<link rel="import" href="assert.html"> <script src="../js/util.js"></script>
diff --git a/ui/webui/resources/html/web_ui_listener_behavior.html b/ui/webui/resources/html/web_ui_listener_behavior.html index 9b9f8d08..c3dd68ac 100644 --- a/ui/webui/resources/html/web_ui_listener_behavior.html +++ b/ui/webui/resources/html/web_ui_listener_behavior.html
@@ -1,2 +1,2 @@ -<link rel="import" href="../html/cr.html"> +<link rel="import" href="cr.html"> <script src="../js/web_ui_listener_behavior.js"></script>