diff --git a/AUTHORS b/AUTHORS index 9f4e6ff..68e6c8f 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -667,6 +667,7 @@ Noj Vek <nojvek@gmail.com> Nolan Cao <nolan.robin.cao@gmail.com> Oleksii Kadurin <ovkadurin@gmail.com> +Oliver Dunk <oliver@oliverdunk.com> Olli Raula (Old name Olli Syrjälä) <olli.raula@intel.com> Omar Sandoval <osandov@osandov.com> Pan Deng <pan.deng@intel.com>
diff --git a/DEPS b/DEPS index 5fc7e64..1ee19941 100644 --- a/DEPS +++ b/DEPS
@@ -154,7 +154,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '5c9e165bc4d554840ed32e52876f0fbde45c9a4f', + 'swiftshader_revision': '7e95471ae492b057ae3fa48f9ecb2f12a277ec94', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -257,7 +257,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '08cc49ec59c3ff4d6bd4bb4f2097ede35e802158', + 'spv_tools_revision': '43fb2403a679ede45157aac6ea90f16700560700', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -807,7 +807,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'b933eedeb03d81be108a053619f602b598879dc7', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'e78bec14dbc9b2e3c2b5de18cbe6a7fdf44fdb5b', 'condition': 'checkout_linux', }, @@ -832,7 +832,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '8a37389368143a44c4acd48117be68a4c3214e5b', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '42b03c34539b29f2018295486724904f5549e2a4', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -912,7 +912,7 @@ 'packages': [ { 'package': 'chromium/third_party/google-truth', - 'version': '0VVeotkT0RWtPio6D5NOjDWUwgzDXEbOlqAdmRZ4ku4C', + 'version': 'u8oovXxp24lStqX4d54htRovta-75Sy2w7ijg1TL07gC', }, ], 'condition': 'checkout_android', @@ -1187,7 +1187,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '3515443cb534f2503dffb45e54c384b30598141f', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'a0af62e20b0a6ee8f399da7e4331d22ee3dc1697', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1396,7 +1396,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@c86b527c737088eddef3cd2003b278107812c17e', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@e1929c10f0568a6d8f869ba26fe5f580ce9c06b3', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/browser/aw_browser_main_parts.cc b/android_webview/browser/aw_browser_main_parts.cc index cabe5e41..9464639 100644 --- a/android_webview/browser/aw_browser_main_parts.cc +++ b/android_webview/browser/aw_browser_main_parts.cc
@@ -71,10 +71,12 @@ new AwNetworkChangeNotifierFactory()); } - // Creates a MessageLoop for Android WebView if doesn't yet exist. - DCHECK(!main_message_loop_.get()); - if (!base::MessageLoopCurrent::IsSet()) - main_message_loop_.reset(new base::MessageLoopForUI); + // Creates a SingleThreadTaskExecutor for Android WebView if doesn't exist. + DCHECK(!main_task_executor_.get()); + if (!base::MessageLoopCurrent::IsSet()) { + main_task_executor_ = std::make_unique<base::SingleThreadTaskExecutor>( + base::MessagePump::Type::UI); + } return service_manager::RESULT_CODE_NORMAL_EXIT; }
diff --git a/android_webview/browser/aw_browser_main_parts.h b/android_webview/browser/aw_browser_main_parts.h index d75fee95..37b910f 100644 --- a/android_webview/browser/aw_browser_main_parts.h +++ b/android_webview/browser/aw_browser_main_parts.h
@@ -9,12 +9,9 @@ #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/task/single_thread_task_executor.h" #include "content/public/browser/browser_main_parts.h" -namespace base { -class MessageLoop; -} - namespace android_webview { class AwContentBrowserClient; @@ -33,8 +30,8 @@ content::ServiceManagerConnection* connection) override; private: - // Android specific UI MessageLoop. - std::unique_ptr<base::MessageLoop> main_message_loop_; + // Android specific UI SingleThreadTaskExecutor. + std::unique_ptr<base::SingleThreadTaskExecutor> main_task_executor_; AwContentBrowserClient* browser_client_;
diff --git a/android_webview/browser/gfx/surfaces_instance.cc b/android_webview/browser/gfx/surfaces_instance.cc index 5d348d4d..07a2f296 100644 --- a/android_webview/browser/gfx/surfaces_instance.cc +++ b/android_webview/browser/gfx/surfaces_instance.cc
@@ -177,7 +177,7 @@ const viz::SurfaceId& child_id, float device_scale_factor, const gfx::ColorSpace& color_space) { - DCHECK(base::ContainsValue(child_ids_, child_id)); + DCHECK(base::Contains(child_ids_, child_id)); gfx::ColorSpace display_color_space = color_space.IsValid() ? color_space : gfx::ColorSpace::CreateSRGB(); @@ -240,7 +240,7 @@ } void SurfacesInstance::AddChildId(const viz::SurfaceId& child_id) { - DCHECK(!base::ContainsValue(child_ids_, child_id)); + DCHECK(!base::Contains(child_ids_, child_id)); child_ids_.push_back(child_id); if (root_id_allocation_.IsValid()) SetSolidColorRootFrame();
diff --git a/android_webview/browser/scoped_add_feature_flags.cc b/android_webview/browser/scoped_add_feature_flags.cc index cf2f7d0..bc5b4aa 100644 --- a/android_webview/browser/scoped_add_feature_flags.cc +++ b/android_webview/browser/scoped_add_feature_flags.cc
@@ -40,8 +40,8 @@ void ScopedAddFeatureFlags::AddFeatureIfNotSet(const base::Feature& feature, bool enable) { const char* feature_name = feature.name; - if (base::ContainsValue(enabled_features_, feature_name) || - base::ContainsValue(disabled_features_, feature_name)) { + if (base::Contains(enabled_features_, feature_name) || + base::Contains(disabled_features_, feature_name)) { return; } if (enable) {
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 41e5c9a..b124f7b 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -350,8 +350,8 @@ "keyboard/virtual_keyboard_controller.h", "kiosk_next/kiosk_next_home_controller.cc", "kiosk_next/kiosk_next_home_controller.h", - "kiosk_next/kiosk_next_shell_controller_impl.cc", - "kiosk_next/kiosk_next_shell_controller_impl.h", + "kiosk_next/kiosk_next_shell_controller.cc", + "kiosk_next/kiosk_next_shell_controller.h", "kiosk_next/kiosk_next_shell_observer.h", "laser/laser_pointer_controller.cc", "laser/laser_pointer_controller.h", @@ -688,8 +688,8 @@ "system/locale/locale_detailed_view.h", "system/locale/locale_feature_pod_controller.cc", "system/locale/locale_feature_pod_controller.h", - "system/locale/locale_update_controller.cc", - "system/locale/locale_update_controller.h", + "system/locale/locale_update_controller_impl.cc", + "system/locale/locale_update_controller_impl.h", "system/locale/unified_locale_detailed_view_controller.cc", "system/locale/unified_locale_detailed_view_controller.h", "system/message_center/arc_notification_manager_delegate_impl.cc", @@ -1729,6 +1729,7 @@ "system/accessibility/dictation_button_tray_unittest.cc", "system/accessibility/select_to_speak_tray_unittest.cc", "system/accessibility/tray_accessibility_unittest.cc", + "system/bluetooth/bluetooth_notification_controller_unittest.cc", "system/bluetooth/bluetooth_power_controller_unittest.cc", "system/bluetooth/tray_bluetooth_helper_legacy_unittest.cc", "system/caps_lock_notification_controller_unittest.cc", @@ -1940,6 +1941,7 @@ "//components/user_manager:test_support", "//device/base", "//device/bluetooth", + "//device/bluetooth:mocks", "//extensions/common:common_constants", "//mojo/core/embedder", "//net:net",
diff --git a/ash/accelerators/accelerator_controller_impl.cc b/ash/accelerators/accelerator_controller_impl.cc index 368f3b1..a99d0468 100644 --- a/ash/accelerators/accelerator_controller_impl.cc +++ b/ash/accelerators/accelerator_controller_impl.cc
@@ -25,7 +25,7 @@ #include "ash/ime/ime_controller.h" #include "ash/ime/ime_switch_type.h" #include "ash/keyboard/ui/keyboard_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/magnifier/docked_magnifier_controller_impl.h" #include "ash/magnifier/magnification_controller.h" #include "ash/media/media_controller_impl.h" @@ -1865,7 +1865,7 @@ return RESTRICTION_PREVENT_PROCESSING; } if (Shell::Get()->power_button_controller()->IsMenuOpened() && - !base::ContainsKey(actions_allowed_at_power_menu_, action)) { + !base::Contains(actions_allowed_at_power_menu_, action)) { return RESTRICTION_PREVENT_PROCESSING; } if (Shell::Get()->session_controller()->IsRunningInAppMode() && @@ -1882,7 +1882,7 @@ // cycling through its window elements. return RESTRICTION_PREVENT_PROCESSING_AND_PROPAGATION; } - if (base::ContainsKey(actions_needing_window_, action) && + if (base::Contains(actions_needing_window_, action) && Shell::Get() ->mru_window_tracker() ->BuildMruWindowList(kActiveDesk)
diff --git a/ash/accelerators/pre_target_accelerator_handler.cc b/ash/accelerators/pre_target_accelerator_handler.cc index 49e68fa..4b35dd1 100644 --- a/ash/accelerators/pre_target_accelerator_handler.cc +++ b/ash/accelerators/pre_target_accelerator_handler.cc
@@ -113,7 +113,7 @@ if (accelerator.IsCmdDown()) return true; - if (base::ContainsValue(Shell::GetAllRootWindows(), target)) + if (base::Contains(Shell::GetAllRootWindows(), target)) return true; AcceleratorControllerImpl* accelerator_controller =
diff --git a/ash/app_list/paged_view_structure.cc b/ash/app_list/paged_view_structure.cc index e98096a..56299368 100644 --- a/ash/app_list/paged_view_structure.cc +++ b/ash/app_list/paged_view_structure.cc
@@ -304,7 +304,7 @@ int PagedViewStructure::CalculateTargetSlot(const Page& page) const { size_t target_slot = page.size(); - if (base::ContainsValue(page, apps_grid_view_->drag_view())) + if (base::Contains(page, apps_grid_view_->drag_view())) --target_slot; return static_cast<int>(target_slot); }
diff --git a/ash/ash_prefs.cc b/ash/ash_prefs.cc index ba0d08e..ade78c0e 100644 --- a/ash/ash_prefs.cc +++ b/ash/ash_prefs.cc
@@ -9,7 +9,7 @@ #include "ash/assistant/assistant_controller.h" #include "ash/detachable_base/detachable_base_handler.h" #include "ash/display/display_prefs.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/login/login_screen_controller.h" #include "ash/magnifier/docked_magnifier_controller_impl.h" #include "ash/shelf/shelf_controller.h" @@ -37,7 +37,7 @@ BluetoothPowerController::RegisterProfilePrefs(registry); CapsLockNotificationController::RegisterProfilePrefs(registry, for_test); DockedMagnifierControllerImpl::RegisterProfilePrefs(registry, for_test); - KioskNextShellControllerImpl::RegisterProfilePrefs(registry, for_test); + KioskNextShellController::RegisterProfilePrefs(registry, for_test); LoginScreenController::RegisterProfilePrefs(registry, for_test); LogoutButtonTray::RegisterProfilePrefs(registry); MessageCenterController::RegisterProfilePrefs(registry);
diff --git a/ash/assistant/assistant_screen_context_controller.cc b/ash/assistant/assistant_screen_context_controller.cc index 7d889e65..5c9e796 100644 --- a/ash/assistant/assistant_screen_context_controller.cc +++ b/ash/assistant/assistant_screen_context_controller.cc
@@ -133,10 +133,10 @@ // Parent layer is excluded meaning that it's pointless to clone // current child and all its descendants. This reduces the number // of layers to create. - if (base::ContainsKey(blocked_layers, owner->layer()->parent())) + if (base::Contains(blocked_layers, owner->layer()->parent())) return nullptr; - if (base::ContainsKey(blocked_layers, owner->layer())) { + if (base::Contains(blocked_layers, owner->layer())) { // Blocked layers are replaced with solid black layers so that // they won't be included in the screenshot but still preserve // the window stacking.
diff --git a/ash/assistant/model/assistant_alarm_timer_model.cc b/ash/assistant/model/assistant_alarm_timer_model.cc index 00efbd92..0816a7dd 100644 --- a/ash/assistant/model/assistant_alarm_timer_model.cc +++ b/ash/assistant/model/assistant_alarm_timer_model.cc
@@ -24,7 +24,7 @@ } void AssistantAlarmTimerModel::AddAlarmTimer(const AlarmTimer& alarm_timer) { - DCHECK(!base::ContainsKey(alarms_timers_, alarm_timer.id)); + DCHECK(!base::Contains(alarms_timers_, alarm_timer.id)); alarms_timers_[alarm_timer.id] = alarm_timer; NotifyAlarmTimerAdded(alarm_timer, /*time_remaining=*/base::TimeTicks::Now() - alarm_timer.end_time);
diff --git a/ash/assistant/model/assistant_notification_model.cc b/ash/assistant/model/assistant_notification_model.cc index c804c3c..875396f 100644 --- a/ash/assistant/model/assistant_notification_model.cc +++ b/ash/assistant/model/assistant_notification_model.cc
@@ -91,7 +91,7 @@ bool AssistantNotificationModel::HasNotificationForId( const std::string& id) const { - return base::ContainsKey(notifications_, id); + return base::Contains(notifications_, id); } void AssistantNotificationModel::NotifyNotificationAdded(
diff --git a/ash/assistant/util/deep_link_util.cc b/ash/assistant/util/deep_link_util.cc index a1a401e..01022635 100644 --- a/ash/assistant/util/deep_link_util.cc +++ b/ash/assistant/util/deep_link_util.cc
@@ -364,7 +364,7 @@ DeepLinkType::kLists, DeepLinkType::kNotes, DeepLinkType::kReminders, DeepLinkType::kSettings}; - return base::ContainsKey(kWebDeepLinks, type); + return base::Contains(kWebDeepLinks, type); } } // namespace util
diff --git a/ash/display/cros_display_config.cc b/ash/display/cros_display_config.cc index 88962686..4217404 100644 --- a/ash/display/cros_display_config.cc +++ b/ash/display/cros_display_config.cc
@@ -557,7 +557,7 @@ if (root_id == display::kInvalidDisplayId) { // Look for a display with no layout info to use as the root. for (int64_t id : display_ids) { - if (!base::ContainsKey(layout_ids, id)) { + if (!base::Contains(layout_ids, id)) { root_id = id; break; }
diff --git a/ash/display/cros_display_config_unittest.cc b/ash/display/cros_display_config_unittest.cc index 5cd27e0f..1ba95df6c 100644 --- a/ash/display/cros_display_config_unittest.cc +++ b/ash/display/cros_display_config_unittest.cc
@@ -315,8 +315,8 @@ display::DisplayIdList id_list = display_manager()->GetMirroringDestinationDisplayIdList(); ASSERT_EQ(2u, id_list.size()); - EXPECT_TRUE(base::ContainsValue(id_list, displays[1].id())); - EXPECT_TRUE(base::ContainsValue(id_list, displays[3].id())); + EXPECT_TRUE(base::Contains(id_list, displays[1].id())); + EXPECT_TRUE(base::Contains(id_list, displays[3].id())); } TEST_F(CrosDisplayConfigTest, GetDisplayUnitInfoListBasic) {
diff --git a/ash/display/display_color_manager.cc b/ash/display/display_color_manager.cc index 1128b1f..b892ba78 100644 --- a/ash/display/display_color_manager.cc +++ b/ash/display/display_color_manager.cc
@@ -232,8 +232,7 @@ const display::DisplaySnapshot* display_snapshot, const SkMatrix44& color_matrix) { DCHECK(display_snapshot); - DCHECK( - base::ContainsValue(configurator_->cached_displays(), display_snapshot)); + DCHECK(base::Contains(configurator_->cached_displays(), display_snapshot)); if (!display_snapshot->has_color_correction_matrix()) { // This display doesn't support setting a CRTC matrix.
diff --git a/ash/display/display_move_window_util.cc b/ash/display/display_move_window_util.cc index 0318b61..ebeded81 100644 --- a/ash/display/display_move_window_util.cc +++ b/ash/display/display_move_window_util.cc
@@ -56,7 +56,7 @@ return false; // The movement target window must be in window cycle list. - return base::ContainsValue( + return base::Contains( Shell::Get()->mru_window_tracker()->BuildWindowForCycleList(kActiveDesk), GetTargetWindow()); }
diff --git a/ash/display/display_prefs.cc b/ash/display/display_prefs.cc index 868890a..e9c540a 100644 --- a/ash/display/display_prefs.cc +++ b/ash/display/display_prefs.cc
@@ -352,7 +352,7 @@ calibration_data_to_set = &calibration_data; if (calibration_data_to_set) { - if (!base::ContainsKey(touch_associations, fallback_identifier)) { + if (!base::Contains(touch_associations, fallback_identifier)) { touch_associations.emplace( fallback_identifier, display::TouchDeviceManager::AssociationInfoMap()); @@ -514,7 +514,7 @@ const display::TouchDeviceIdentifier& fallback_identifier = display::TouchDeviceIdentifier::GetFallbackTouchDeviceIdentifier(); display::TouchDeviceManager::AssociationInfoMap legacy_data_map; - if (base::ContainsKey( + if (base::Contains( display_manager->touch_device_manager()->touch_associations(), fallback_identifier)) { legacy_data_map = @@ -563,7 +563,7 @@ // Store the legacy format touch calibration data. This can be removed after // a couple of milestones when every device has migrated to the new format. - if (legacy_data_map.size() && base::ContainsKey(legacy_data_map, id)) { + if (legacy_data_map.size() && base::Contains(legacy_data_map, id)) { TouchDataToValue(legacy_data_map.at(id).calibration_data, property_value.get()); }
diff --git a/ash/display/screen_orientation_controller.cc b/ash/display/screen_orientation_controller.cc index 0a9d42ec..0431dd1 100644 --- a/ash/display/screen_orientation_controller.cc +++ b/ash/display/screen_orientation_controller.cc
@@ -342,7 +342,7 @@ void ScreenOrientationController::OnWindowVisibilityChanged( aura::Window* window, bool visible) { - if (base::ContainsKey(lock_info_map_, window)) + if (base::Contains(lock_info_map_, window)) ApplyLockForActiveWindow(); }
diff --git a/ash/display/screen_orientation_controller_unittest.cc b/ash/display/screen_orientation_controller_unittest.cc index 844ce6f..f5c4c21 100644 --- a/ash/display/screen_orientation_controller_unittest.cc +++ b/ash/display/screen_orientation_controller_unittest.cc
@@ -745,11 +745,10 @@ set_start_session(false); AshTestBase::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); + client_ = BindMockKioskNextShellClient(); } void TearDown() override { - client_.reset(); home_screen_window_.reset(); AshTestBase::TearDown(); }
diff --git a/ash/display/touch_calibrator_controller_unittest.cc b/ash/display/touch_calibrator_controller_unittest.cc index d0f2e53f..46cb8325 100644 --- a/ash/display/touch_calibrator_controller_unittest.cc +++ b/ash/display/touch_calibrator_controller_unittest.cc
@@ -196,7 +196,7 @@ ui::EventTargetTestApi test_api(Shell::Get()); ui::EventHandlerList handlers = test_api.GetPreTargetHandlers(); - EXPECT_TRUE(base::ContainsValue(handlers, &touch_calibrator_controller)); + EXPECT_TRUE(base::Contains(handlers, &touch_calibrator_controller)); } TEST_F(TouchCalibratorControllerTest, KeyEventIntercept) {
diff --git a/ash/home_screen/home_launcher_gesture_handler.cc b/ash/home_screen/home_launcher_gesture_handler.cc index e334f2b..7da5ae7 100644 --- a/ash/home_screen/home_launcher_gesture_handler.cc +++ b/ash/home_screen/home_launcher_gesture_handler.cc
@@ -472,7 +472,7 @@ return; } - DCHECK(base::ContainsValue(hidden_windows_, window)); + DCHECK(base::Contains(hidden_windows_, window)); window->RemoveObserver(this); hidden_windows_.erase( std::find(hidden_windows_.begin(), hidden_windows_.end(), window)); @@ -809,7 +809,7 @@ return false; } - DCHECK(base::ContainsValue(windows, first_window)); + DCHECK(base::Contains(windows, first_window)); DCHECK_NE(Mode::kNone, mode); base::RecordAction(base::UserMetricsAction( mode == Mode::kSlideDownToHide @@ -831,7 +831,7 @@ SplitViewController::LEFT ? split_view_controller->right_window() : split_view_controller->left_window(); - DCHECK(base::ContainsValue(windows, second_window)); + DCHECK(base::Contains(windows, second_window)); secondary_window_ = std::make_unique<ScopedWindowModifier>(second_window); GetSecondaryWindow()->AddObserver(this); base::EraseIf(windows, [this](aura::Window* elem) {
diff --git a/ash/home_screen/home_screen_presenter.cc b/ash/home_screen/home_screen_presenter.cc index ff2b478..2011c9f 100644 --- a/ash/home_screen/home_screen_presenter.cc +++ b/ash/home_screen/home_screen_presenter.cc
@@ -8,7 +8,7 @@ #include "ash/home_screen/home_screen_controller.h" #include "ash/home_screen/home_screen_delegate.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/shell.h" #include "base/bind.h" #include "base/bind_helpers.h"
diff --git a/ash/host/ash_window_tree_host_unified.cc b/ash/host/ash_window_tree_host_unified.cc index e602cb98..fe31c6c8a 100644 --- a/ash/host/ash_window_tree_host_unified.cc +++ b/ash/host/ash_window_tree_host_unified.cc
@@ -87,7 +87,7 @@ aura::Window* src_root = mirroring_ash_host->AsWindowTreeHost()->window(); src_root->SetEventTargeter( std::make_unique<UnifiedEventTargeter>(src_root, window(), delegate_)); - DCHECK(!base::ContainsValue(mirroring_hosts_, mirroring_ash_host)); + DCHECK(!base::Contains(mirroring_hosts_, mirroring_ash_host)); mirroring_hosts_.push_back(mirroring_ash_host); mirroring_ash_host->AsWindowTreeHost()->window()->AddObserver(this); }
diff --git a/ash/ime/ime_controller.cc b/ash/ime/ime_controller.cc index bff6107..bb41780 100644 --- a/ash/ime/ime_controller.cc +++ b/ash/ime/ime_controller.cc
@@ -274,7 +274,7 @@ // Obtain the intersection of input_method_ids_to_switch and available_imes_. for (const mojom::ImeInfo& ime : available_imes_) { - if (base::ContainsValue(input_method_ids_to_switch, ime.id)) + if (base::Contains(input_method_ids_to_switch, ime.id)) candidate_ids.push_back(ime.id); } return candidate_ids;
diff --git a/ash/keyboard/ash_keyboard_controller_unittest.cc b/ash/keyboard/ash_keyboard_controller_unittest.cc index 7ed54ac..70d8a12 100644 --- a/ash/keyboard/ash_keyboard_controller_unittest.cc +++ b/ash/keyboard/ash_keyboard_controller_unittest.cc
@@ -318,7 +318,7 @@ std::vector<keyboard::mojom::KeyboardEnableFlag> enable_flags = test_client()->GetEnableFlags(); EXPECT_TRUE( - base::ContainsValue(enable_flags, KeyboardEnableFlag::kExtensionEnabled)); + base::Contains(enable_flags, KeyboardEnableFlag::kExtensionEnabled)); EXPECT_EQ(enable_flags, test_observer()->enable_flags()); EXPECT_TRUE(test_client()->IsKeyboardEnabled()); @@ -326,9 +326,9 @@ test_client()->SetEnableFlag(KeyboardEnableFlag::kPolicyDisabled); enable_flags = test_client()->GetEnableFlags(); EXPECT_TRUE( - base::ContainsValue(enable_flags, KeyboardEnableFlag::kExtensionEnabled)); + base::Contains(enable_flags, KeyboardEnableFlag::kExtensionEnabled)); EXPECT_TRUE( - base::ContainsValue(enable_flags, KeyboardEnableFlag::kPolicyDisabled)); + base::Contains(enable_flags, KeyboardEnableFlag::kPolicyDisabled)); EXPECT_EQ(enable_flags, test_observer()->enable_flags()); EXPECT_FALSE(test_client()->IsKeyboardEnabled()); @@ -336,9 +336,9 @@ test_client()->ClearEnableFlag(KeyboardEnableFlag::kPolicyDisabled); enable_flags = test_client()->GetEnableFlags(); EXPECT_TRUE( - base::ContainsValue(enable_flags, KeyboardEnableFlag::kExtensionEnabled)); + base::Contains(enable_flags, KeyboardEnableFlag::kExtensionEnabled)); EXPECT_FALSE( - base::ContainsValue(enable_flags, KeyboardEnableFlag::kPolicyDisabled)); + base::Contains(enable_flags, KeyboardEnableFlag::kPolicyDisabled)); EXPECT_EQ(enable_flags, test_observer()->enable_flags()); EXPECT_TRUE(test_client()->IsKeyboardEnabled()); }
diff --git a/ash/keyboard/ui/keyboard_controller.cc b/ash/keyboard/ui/keyboard_controller.cc index baefcce..c116fb3 100644 --- a/ash/keyboard/ui/keyboard_controller.cc +++ b/ash/keyboard/ui/keyboard_controller.cc
@@ -416,7 +416,7 @@ } void KeyboardController::SetEnableFlag(mojom::KeyboardEnableFlag flag) { - if (!base::ContainsKey(keyboard_enable_flags_, flag)) + if (!base::Contains(keyboard_enable_flags_, flag)) keyboard_enable_flags_.insert(flag); // If there is a flag that is mutually exclusive with |flag|, clear it. @@ -455,7 +455,7 @@ } bool KeyboardController::IsEnableFlagSet(mojom::KeyboardEnableFlag flag) const { - return base::ContainsKey(keyboard_enable_flags_, flag); + return base::Contains(keyboard_enable_flags_, flag); } bool KeyboardController::IsKeyboardEnableRequested() const {
diff --git a/ash/kiosk_next/kiosk_next_home_controller_unittest.cc b/ash/kiosk_next/kiosk_next_home_controller_unittest.cc index 10ec17c..2cd7c988 100644 --- a/ash/kiosk_next/kiosk_next_home_controller_unittest.cc +++ b/ash/kiosk_next/kiosk_next_home_controller_unittest.cc
@@ -32,15 +32,15 @@ scoped_feature_list_.InitAndEnableFeature(features::kKioskNextShell); set_start_session(false); AshTestBase::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); + client_ = BindMockKioskNextShellClient(); LogInKioskNextUser(GetSessionControllerClient()); SetUpHomeWindow(); } void TearDown() override { home_screen_window_.reset(); - client_.reset(); AshTestBase::TearDown(); + client_.reset(); } void SetUpHomeWindow() {
diff --git a/ash/kiosk_next/kiosk_next_shell_controller_impl.cc b/ash/kiosk_next/kiosk_next_shell_controller.cc similarity index 78% rename from ash/kiosk_next/kiosk_next_shell_controller_impl.cc rename to ash/kiosk_next/kiosk_next_shell_controller.cc index 51ca121..d4623aad 100644 --- a/ash/kiosk_next/kiosk_next_shell_controller_impl.cc +++ b/ash/kiosk_next/kiosk_next_shell_controller.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include <memory> #include <utility> @@ -52,12 +52,12 @@ } // namespace -KioskNextShellControllerImpl::KioskNextShellControllerImpl() = default; +KioskNextShellController::KioskNextShellController() = default; -KioskNextShellControllerImpl::~KioskNextShellControllerImpl() = default; +KioskNextShellController::~KioskNextShellController() = default; // static -void KioskNextShellControllerImpl::RegisterProfilePrefs( +void KioskNextShellController::RegisterProfilePrefs( PrefRegistrySimple* registry, bool for_test) { if (for_test) { @@ -67,40 +67,43 @@ } } -void KioskNextShellControllerImpl::SetClientAndLaunchSession( - KioskNextShellClient* client) { - DCHECK_NE(!!client, !!client_); - client_ = client; - LaunchKioskNextShellIfEnabled(); +void KioskNextShellController::BindRequest( + mojom::KioskNextShellControllerRequest request) { + bindings_.AddBinding(this, std::move(request)); } -bool KioskNextShellControllerImpl::IsEnabled() { +bool KioskNextShellController::IsEnabled() { return kiosk_next_enabled_; } -void KioskNextShellControllerImpl::AddObserver( - KioskNextShellObserver* observer) { +void KioskNextShellController::AddObserver(KioskNextShellObserver* observer) { observer_list_.AddObserver(observer); } -void KioskNextShellControllerImpl::RemoveObserver( +void KioskNextShellController::RemoveObserver( KioskNextShellObserver* observer) { observer_list_.RemoveObserver(observer); } -void KioskNextShellControllerImpl::OnActiveUserPrefServiceChanged( +void KioskNextShellController::SetClient( + mojom::KioskNextShellClientPtr client) { + kiosk_next_shell_client_ = std::move(client); + LaunchKioskNextShellIfEnabled(); +} + +void KioskNextShellController::OnActiveUserPrefServiceChanged( PrefService* pref_service) { LaunchKioskNextShellIfEnabled(); } -void KioskNextShellControllerImpl::LaunchKioskNextShellIfEnabled() { +void KioskNextShellController::LaunchKioskNextShellIfEnabled() { SessionControllerImpl* session_controller = Shell::Get()->session_controller(); PrefService* pref_service = session_controller->GetPrimaryUserPrefService(); if (!pref_service) return; - if (!client_) + if (!kiosk_next_shell_client_.is_bound()) return; bool prev_kiosk_next_enabled = kiosk_next_enabled_; @@ -116,7 +119,7 @@ kiosk_next_home_controller_.get()); Shell::Get()->RemoveAppListController(); - client_->LaunchKioskNextShell( + kiosk_next_shell_client_->LaunchKioskNextShell( session_controller->GetPrimaryUserSession()->user_info.account_id); UMA_HISTOGRAM_BOOLEAN("KioskNextShell.Launched", true);
diff --git a/ash/kiosk_next/kiosk_next_shell_controller_impl.h b/ash/kiosk_next/kiosk_next_shell_controller.h similarity index 61% rename from ash/kiosk_next/kiosk_next_shell_controller_impl.h rename to ash/kiosk_next/kiosk_next_shell_controller.h index acb5c9b2..6de77c06 100644 --- a/ash/kiosk_next/kiosk_next_shell_controller_impl.h +++ b/ash/kiosk_next/kiosk_next_shell_controller.h
@@ -2,17 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_KIOSK_NEXT_KIOSK_NEXT_SHELL_CONTROLLER_IMPL_H_ -#define ASH_KIOSK_NEXT_KIOSK_NEXT_SHELL_CONTROLLER_IMPL_H_ +#ifndef ASH_KIOSK_NEXT_KIOSK_NEXT_SHELL_CONTROLLER_H_ +#define ASH_KIOSK_NEXT_KIOSK_NEXT_SHELL_CONTROLLER_H_ #include <memory> #include "ash/ash_export.h" #include "ash/kiosk_next/kiosk_next_shell_observer.h" -#include "ash/public/cpp/kiosk_next_shell.h" +#include "ash/public/interfaces/kiosk_next_shell.mojom.h" #include "ash/session/session_observer.h" #include "base/macros.h" #include "base/observer_list.h" +#include "mojo/public/cpp/bindings/binding_set.h" class PrefRegistrySimple; @@ -21,20 +22,21 @@ class KioskNextHomeController; class ShelfModel; -// KioskNextShellControllerImpl allows an ash consumer to manage a Kiosk Next +// KioskNextShellController allows an ash consumer to manage a Kiosk Next // session. During this session most system functions are disabled and we launch // a specific app (Kiosk Next Home) that takes the whole screen. -class ASH_EXPORT KioskNextShellControllerImpl : public KioskNextShellController, - public SessionObserver { +class ASH_EXPORT KioskNextShellController + : public mojom::KioskNextShellController, + public SessionObserver { public: - KioskNextShellControllerImpl(); - ~KioskNextShellControllerImpl() override; + KioskNextShellController(); + ~KioskNextShellController() override; // Register prefs related to the Kiosk Next Shell. static void RegisterProfilePrefs(PrefRegistrySimple* registry, bool for_test); - // KioskNextShellController: - void SetClientAndLaunchSession(KioskNextShellClient* client) override; + // Binds the mojom::KioskNextShellController interface to this object. + void BindRequest(mojom::KioskNextShellControllerRequest request); // Returns if the Kiosk Next Shell is enabled for the current user. If there's // no signed-in user, this returns false. @@ -43,6 +45,9 @@ void AddObserver(KioskNextShellObserver* observer); void RemoveObserver(KioskNextShellObserver* observer); + // mojom::KioskNextShellController: + void SetClient(mojom::KioskNextShellClientPtr client) override; + // SessionObserver: void OnActiveUserPrefServiceChanged(PrefService* pref_service) override; @@ -53,8 +58,8 @@ // available. void LaunchKioskNextShellIfEnabled(); - KioskNextShellClient* client_ = nullptr; - + mojom::KioskNextShellClientPtr kiosk_next_shell_client_; + mojo::BindingSet<mojom::KioskNextShellController> bindings_; base::ObserverList<KioskNextShellObserver> observer_list_; ScopedSessionObserver session_observer_{this}; bool kiosk_next_enabled_ = false; @@ -63,13 +68,13 @@ std::unique_ptr<KioskNextHomeController> kiosk_next_home_controller_; // When KioskNextShell is enabled, only the home button and back button are - // made visible on the Shelf. KioskNextShellControllerImpl therefore hosts its - // own ShelfModel to control the entries visible on the shelf. + // made visible on the Shelf. KioskNextShellController therefore hosts its own + // ShelfModel to control the entries visible on the shelf. std::unique_ptr<ShelfModel> shelf_model_; - DISALLOW_COPY_AND_ASSIGN(KioskNextShellControllerImpl); + DISALLOW_COPY_AND_ASSIGN(KioskNextShellController); }; } // namespace ash -#endif // ASH_KIOSK_NEXT_KIOSK_NEXT_SHELL_CONTROLLER_IMPL_H_ +#endif // ASH_KIOSK_NEXT_KIOSK_NEXT_SHELL_CONTROLLER_H_
diff --git a/ash/kiosk_next/kiosk_next_shell_controller_unittest.cc b/ash/kiosk_next/kiosk_next_shell_controller_unittest.cc index bfb966a..df5d740 100644 --- a/ash/kiosk_next/kiosk_next_shell_controller_unittest.cc +++ b/ash/kiosk_next/kiosk_next_shell_controller_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include <memory> @@ -18,7 +18,7 @@ namespace ash { namespace { -KioskNextShellControllerImpl* GetKioskNextShellController() { +KioskNextShellController* GetKioskNextShellController() { return Shell::Get()->kiosk_next_shell_controller(); } @@ -42,13 +42,13 @@ void SetUp() override { set_start_session(false); AshTestBase::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); + client_ = BindMockKioskNextShellClient(); scoped_feature_list_.InitAndEnableFeature(features::kKioskNextShell); } void TearDown() override { - client_.reset(); AshTestBase::TearDown(); + client_.reset(); } protected:
diff --git a/ash/kiosk_next/mock_kiosk_next_shell_client.cc b/ash/kiosk_next/mock_kiosk_next_shell_client.cc index f9f78b7..405e707 100644 --- a/ash/kiosk_next/mock_kiosk_next_shell_client.cc +++ b/ash/kiosk_next/mock_kiosk_next_shell_client.cc
@@ -4,14 +4,27 @@ #include "ash/kiosk_next/mock_kiosk_next_shell_client.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" +#include "ash/shell.h" + namespace ash { -MockKioskNextShellClient::MockKioskNextShellClient() { - KioskNextShellController::Get()->SetClientAndLaunchSession(this); +MockKioskNextShellClient::MockKioskNextShellClient() = default; + +MockKioskNextShellClient::~MockKioskNextShellClient() = default; + +mojom::KioskNextShellClientPtr +MockKioskNextShellClient::CreateInterfacePtrAndBind() { + mojom::KioskNextShellClientPtr ptr; + binding_.Bind(mojo::MakeRequest(&ptr)); + return ptr; } -MockKioskNextShellClient::~MockKioskNextShellClient() { - KioskNextShellController::Get()->SetClientAndLaunchSession(nullptr); +std::unique_ptr<MockKioskNextShellClient> BindMockKioskNextShellClient() { + auto client = std::make_unique<MockKioskNextShellClient>(); + Shell::Get()->kiosk_next_shell_controller()->SetClient( + client->CreateInterfacePtrAndBind()); + return client; } } // namespace ash
diff --git a/ash/kiosk_next/mock_kiosk_next_shell_client.h b/ash/kiosk_next/mock_kiosk_next_shell_client.h index 9830ac0..6e3b5a56 100644 --- a/ash/kiosk_next/mock_kiosk_next_shell_client.h +++ b/ash/kiosk_next/mock_kiosk_next_shell_client.h
@@ -5,25 +5,36 @@ #ifndef ASH_KIOSK_NEXT_MOCK_KIOSK_NEXT_SHELL_CLIENT_H_ #define ASH_KIOSK_NEXT_MOCK_KIOSK_NEXT_SHELL_CLIENT_H_ -#include "ash/public/cpp/kiosk_next_shell.h" +#include <memory> + +#include "ash/public/interfaces/kiosk_next_shell.mojom.h" #include "base/macros.h" #include "components/account_id/account_id.h" +#include "mojo/public/cpp/bindings/binding.h" #include "testing/gmock/include/gmock/gmock.h" namespace ash { -class MockKioskNextShellClient : public KioskNextShellClient { +class MockKioskNextShellClient : public mojom::KioskNextShellClient { public: MockKioskNextShellClient(); ~MockKioskNextShellClient() override; - // KioskNextShellClient: + mojom::KioskNextShellClientPtr CreateInterfacePtrAndBind(); + + // mojom::KioskNextShellClient: MOCK_METHOD1(LaunchKioskNextShell, void(const AccountId& account_id)); private: + mojo::Binding<mojom::KioskNextShellClient> binding_{this}; + DISALLOW_COPY_AND_ASSIGN(MockKioskNextShellClient); }; +// Helper function to bind a KioskNextShellClient so that it receives mojo +// calls. +std::unique_ptr<MockKioskNextShellClient> BindMockKioskNextShellClient(); + } // namespace ash #endif // ASH_KIOSK_NEXT_MOCK_KIOSK_NEXT_SHELL_CLIENT_H_
diff --git a/ash/main.cc b/ash/main.cc index 8aedc9f..79a08b1 100644 --- a/ash/main.cc +++ b/ash/main.cc
@@ -6,9 +6,9 @@ #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "ui/base/material_design/material_design_controller.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_features.h" @@ -59,6 +59,7 @@ ui::MaterialDesignController::Initialize(); - base::MessageLoop message_loop(base::MessageLoop::TYPE_UI); + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); ash::AshService(std::move(request)).RunUntilTermination(); }
diff --git a/ash/media/media_notification_controller_impl.cc b/ash/media/media_notification_controller_impl.cc index a15dc77a..f03f701 100644 --- a/ash/media/media_notification_controller_impl.cc +++ b/ash/media/media_notification_controller_impl.cc
@@ -138,7 +138,7 @@ media_session::mojom::AudioFocusRequestStatePtr session) { const std::string id = session->request_id->ToString(); - if (base::ContainsKey(notifications_, id)) + if (base::Contains(notifications_, id)) return; media_session::mojom::MediaControllerPtr controller;
diff --git a/ash/media/media_notification_view.cc b/ash/media/media_notification_view.cc index 7661d2f..53d72ae3 100644 --- a/ash/media/media_notification_view.cc +++ b/ash/media/media_notification_view.cc
@@ -359,9 +359,9 @@ for (auto* view : button_row_->children()) { views::Button* action_button = views::Button::AsButton(view); - action_button->SetVisible(base::ContainsKey( - visible_actions, - static_cast<MediaSessionAction>(action_button->tag()))); + action_button->SetVisible( + base::Contains(visible_actions, + static_cast<MediaSessionAction>(action_button->tag()))); } } @@ -452,7 +452,7 @@ continue; } - if (!base::ContainsKey(enabled_actions_, action)) + if (!base::Contains(enabled_actions_, action)) continue; visible_actions.insert(action);
diff --git a/ash/mojo_interface_factory.cc b/ash/mojo_interface_factory.cc index 508da08..ce9103597 100644 --- a/ash/mojo_interface_factory.cc +++ b/ash/mojo_interface_factory.cc
@@ -19,6 +19,7 @@ #include "ash/ime/ime_controller.h" #include "ash/keyboard/ash_keyboard_controller.h" #include "ash/keyboard/ui/keyboard_controller.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/login/login_screen_controller.h" #include "ash/media/media_controller_impl.h" #include "ash/public/cpp/ash_features.h" @@ -26,7 +27,6 @@ #include "ash/public/cpp/voice_interaction_controller.h" #include "ash/shell.h" #include "ash/shell_delegate.h" -#include "ash/system/locale/locale_update_controller.h" #include "ash/system/message_center/message_center_controller.h" #include "ash/system/network/vpn_list.h" #include "ash/system/night_light/night_light_controller.h" @@ -104,9 +104,9 @@ Shell::Get()->ash_keyboard_controller()->BindRequest(std::move(request)); } -void BindLocaleUpdateControllerOnMainThread( - mojom::LocaleUpdateControllerRequest request) { - Shell::Get()->locale_update_controller()->BindRequest(std::move(request)); +void BindKioskNextShellControllerRequestOnMainThread( + mojom::KioskNextShellControllerRequest request) { + Shell::Get()->kiosk_next_shell_controller()->BindRequest(std::move(request)); } void BindLockScreenRequestOnMainThread(mojom::LoginScreenRequest request) { @@ -174,6 +174,11 @@ registry->AddInterface( base::BindRepeating(&BindAshMessageCenterControllerRequestOnMainThread), main_thread_task_runner); + if (base::FeatureList::IsEnabled(features::kKioskNextShell)) { + registry->AddInterface( + base::BindRepeating(&BindKioskNextShellControllerRequestOnMainThread), + main_thread_task_runner); + } registry->AddInterface( base::BindRepeating(&BindImeControllerRequestOnMainThread), main_thread_task_runner); @@ -181,9 +186,6 @@ base::BindRepeating(&BindKeyboardControllerRequestOnMainThread), main_thread_task_runner); registry->AddInterface( - base::BindRepeating(&BindLocaleUpdateControllerOnMainThread), - main_thread_task_runner); - registry->AddInterface( base::BindRepeating(&BindLockScreenRequestOnMainThread), main_thread_task_runner); registry->AddInterface(
diff --git a/ash/policy/policy_recommendation_restorer.cc b/ash/policy/policy_recommendation_restorer.cc index 475b1581..3258cb06 100644 --- a/ash/policy/policy_recommendation_restorer.cc +++ b/ash/policy/policy_recommendation_restorer.cc
@@ -36,7 +36,7 @@ PrefService* prefs = Shell::Get()->session_controller()->GetSigninScreenPrefService(); DCHECK(prefs); - DCHECK(!base::ContainsKey(pref_names_, pref_name)); + DCHECK(!base::Contains(pref_names_, pref_name)); if (!pref_change_registrar_) { pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>();
diff --git a/ash/public/cpp/BUILD.gn b/ash/public/cpp/BUILD.gn index 539d386..8473d9f 100644 --- a/ash/public/cpp/BUILD.gn +++ b/ash/public/cpp/BUILD.gn
@@ -92,8 +92,8 @@ "keyboard_shortcut_viewer.h", "kiosk_app_menu.cc", "kiosk_app_menu.h", - "kiosk_next_shell.cc", - "kiosk_next_shell.h", + "locale_update_controller.cc", + "locale_update_controller.h", "lock_screen_widget_factory.cc", "lock_screen_widget_factory.h", "login_constants.h",
diff --git a/ash/public/cpp/kiosk_next_shell.cc b/ash/public/cpp/kiosk_next_shell.cc deleted file mode 100644 index cb9d503f..0000000 --- a/ash/public/cpp/kiosk_next_shell.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/public/cpp/kiosk_next_shell.h" - -#include "base/logging.h" - -namespace ash { - -namespace { -KioskNextShellController* g_instance = nullptr; -} - -// static -KioskNextShellController* KioskNextShellController::Get() { - return g_instance; -} - -KioskNextShellController::KioskNextShellController() { - DCHECK_EQ(nullptr, g_instance); - g_instance = this; -} - -KioskNextShellController::~KioskNextShellController() { - DCHECK_EQ(this, g_instance); - g_instance = nullptr; -} - -} // namespace ash
diff --git a/ash/public/cpp/kiosk_next_shell.h b/ash/public/cpp/kiosk_next_shell.h deleted file mode 100644 index 7011e6c..0000000 --- a/ash/public/cpp/kiosk_next_shell.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_PUBLIC_CPP_KIOSK_NEXT_SHELL_H_ -#define ASH_PUBLIC_CPP_KIOSK_NEXT_SHELL_H_ - -#include "ash/public/cpp/ash_public_export.h" - -class AccountId; - -namespace ash { - -// Performs browser-side functionality for Kiosk Next, e.g. launching the -// KioskNextShell. -class ASH_PUBLIC_EXPORT KioskNextShellClient { - public: - // Launch the Kiosk Next Shell for the user identified by |account_id|. - virtual void LaunchKioskNextShell(const AccountId& account_id) = 0; - - protected: - virtual ~KioskNextShellClient() = default; -}; - -// Interface that allows Chrome to notify Ash when the KioskNextShellClient is -// ready. -class ASH_PUBLIC_EXPORT KioskNextShellController { - public: - static KioskNextShellController* Get(); - - // Registers the client, and if non-null, launches the Kiosk Next Shell - // session. - virtual void SetClientAndLaunchSession(KioskNextShellClient* client) = 0; - - protected: - KioskNextShellController(); - virtual ~KioskNextShellController(); -}; - -} // namespace ash - -#endif // ASH_PUBLIC_CPP_KIOSK_NEXT_SHELL_H_
diff --git a/ash/public/cpp/locale_update_controller.cc b/ash/public/cpp/locale_update_controller.cc new file mode 100644 index 0000000..adafbbf4 --- /dev/null +++ b/ash/public/cpp/locale_update_controller.cc
@@ -0,0 +1,40 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/public/cpp/locale_update_controller.h" + +#include "base/logging.h" + +namespace ash { + +namespace { + +LocaleUpdateController* g_instance = nullptr; + +} // namespace + +LocaleInfo::LocaleInfo() = default; +LocaleInfo::LocaleInfo(const std::string& iso_code, + const base::string16& display_name) + : iso_code(iso_code), display_name(display_name) {} +LocaleInfo::LocaleInfo(const LocaleInfo& rhs) = default; +LocaleInfo::LocaleInfo(LocaleInfo&& rhs) = default; +LocaleInfo::~LocaleInfo() = default; + +// static +LocaleUpdateController* LocaleUpdateController::Get() { + return g_instance; +} + +LocaleUpdateController::LocaleUpdateController() { + DCHECK(!g_instance); + g_instance = this; +} + +LocaleUpdateController::~LocaleUpdateController() { + DCHECK_EQ(this, g_instance); + g_instance = nullptr; +} + +} // namespace ash
diff --git a/ash/public/cpp/locale_update_controller.h b/ash/public/cpp/locale_update_controller.h new file mode 100644 index 0000000..76a628f --- /dev/null +++ b/ash/public/cpp/locale_update_controller.h
@@ -0,0 +1,63 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_PUBLIC_CPP_LOCALE_UPDATE_CONTROLLER_H_ +#define ASH_PUBLIC_CPP_LOCALE_UPDATE_CONTROLLER_H_ + +#include <string> + +#include "ash/public/cpp/ash_public_export.h" +#include "base/callback_forward.h" +#include "base/strings/string16.h" + +namespace ash { + +// The locale info to show in the system tray locale detailed view. +struct ASH_PUBLIC_EXPORT LocaleInfo { + LocaleInfo(); + LocaleInfo(const std::string& iso_code, const base::string16& display_name); + LocaleInfo(const LocaleInfo& rhs); + LocaleInfo(LocaleInfo&& rhs); + ~LocaleInfo(); + + // This ISO code of the locale. + std::string iso_code; + + // The display name of the locale. + base::string16 display_name; +}; + +// Sent as the response to LocaleUpdateController.OnLocaleChanged(). +enum class LocaleNotificationResult { + kAccept, + kRevert, +}; + +// Used by Chrome to notify locale change events. +class ASH_PUBLIC_EXPORT LocaleUpdateController { + public: + // Get the singleton instance of LocaleUpdateController. + static LocaleUpdateController* Get(); + + // When this is called in OOBE, it returns kAccept immediately after invoking + // observer callbacks. |current|, |from|, and |to| are ignored in this case. + // Otherwise it displays a notification in ash prompting the user whether to + // accept a change in the locale. If the user clicks the accept button (or + // closes the notification), OnLocaleChange() returns kAccept. If the user + // clicks the revert button, returns kRevert. + using OnLocaleChangedCallback = + base::OnceCallback<void(LocaleNotificationResult)>; + virtual void OnLocaleChanged(const std::string& current, + const std::string& from, + const std::string& to, + OnLocaleChangedCallback callback) = 0; + + protected: + LocaleUpdateController(); + virtual ~LocaleUpdateController(); +}; + +} // namespace ash + +#endif // ASH_PUBLIC_CPP_LOCALE_UPDATE_CONTROLLER_H_
diff --git a/ash/public/cpp/manifest.cc b/ash/public/cpp/manifest.cc index 9d7ab1b..6a9a773 100644 --- a/ash/public/cpp/manifest.cc +++ b/ash/public/cpp/manifest.cc
@@ -14,7 +14,6 @@ #include "ash/public/interfaces/ime_controller.mojom.h" #include "ash/public/interfaces/keyboard_controller.mojom.h" #include "ash/public/interfaces/kiosk_next_shell.mojom.h" -#include "ash/public/interfaces/locale.mojom.h" #include "ash/public/interfaces/login_screen.mojom.h" #include "ash/public/interfaces/night_light_controller.mojom.h" #include "ash/public/interfaces/shelf_integration_test_api.mojom.h" @@ -60,11 +59,11 @@ mojom::AssistantNotificationController, mojom::AssistantScreenContextController, mojom::AssistantVolumeControl, + mojom::KioskNextShellController, mojom::CrosDisplayConfigController, mojom::ImeController, - mojom::KeyboardController, mojom::LocaleUpdateController, - mojom::LoginScreen, mojom::NightLightController, - mojom::TrayAction, mojom::VoiceInteractionController, - mojom::VpnList>()) + mojom::KeyboardController, mojom::LoginScreen, + mojom::NightLightController, mojom::TrayAction, + mojom::VoiceInteractionController, mojom::VpnList>()) .ExposeCapability("test", service_manager::Manifest::InterfaceList< mojom::ShelfIntegrationTestApi>()) .RequireCapability("*", "accessibility")
diff --git a/ash/public/cpp/shell_window_ids.cc b/ash/public/cpp/shell_window_ids.cc index c7d3fd2..27c3d71 100644 --- a/ash/public/cpp/shell_window_ids.cc +++ b/ash/public/cpp/shell_window_ids.cc
@@ -65,7 +65,7 @@ } bool IsActivatableShellWindowId(int id) { - return base::ContainsValue(GetActivatableShellWindowIds(), id); + return base::Contains(GetActivatableShellWindowIds(), id); } } // namespace ash
diff --git a/ash/public/cpp/system_tray.h b/ash/public/cpp/system_tray.h index d9cc7742..2bc25e5 100644 --- a/ash/public/cpp/system_tray.h +++ b/ash/public/cpp/system_tray.h
@@ -8,11 +8,11 @@ #include <string> #include "ash/public/cpp/ash_public_export.h" -#include "ash/public/interfaces/locale.mojom-forward.h" #include "base/strings/string16.h" namespace ash { +struct LocaleInfo; class SystemTrayClient; enum class NotificationStyle; enum class UpdateSeverity; @@ -50,7 +50,7 @@ // Sets the list of supported UI locales. |current_locale_iso_code| refers to // the locale currently used by the UI. - virtual void SetLocaleList(std::vector<mojom::LocaleInfoPtr> locale_list, + virtual void SetLocaleList(std::vector<LocaleInfo> locale_list, const std::string& current_locale_iso_code) = 0; // Shows an icon in the system tray or a notification on the unified system
diff --git a/ash/public/interfaces/BUILD.gn b/ash/public/interfaces/BUILD.gn index 8db2301..d273c8af 100644 --- a/ash/public/interfaces/BUILD.gn +++ b/ash/public/interfaces/BUILD.gn
@@ -29,7 +29,7 @@ "keyboard_config.mojom", "keyboard_controller.mojom", "keyboard_controller_types.mojom", - "locale.mojom", + "kiosk_next_shell.mojom", "login_screen.mojom", "night_light_controller.mojom", "shelf_integration_test_api.mojom",
diff --git a/ash/public/interfaces/kiosk_next_shell.mojom b/ash/public/interfaces/kiosk_next_shell.mojom new file mode 100644 index 0000000..a9ec5d2 --- /dev/null +++ b/ash/public/interfaces/kiosk_next_shell.mojom
@@ -0,0 +1,21 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module ash.mojom; + +import "components/account_id/interfaces/account_id.mojom"; + +// Performs browser-side functionality for Kiosk Next, e.g. launching the +// KioskNextShell. +interface KioskNextShellClient { + // Launch the Kiosk Next Shell for the user identified by |account_id|. + LaunchKioskNextShell(signin.mojom.AccountId account_id); +}; + +// Allows Ash and its consumers to interact with Kiosk Next. +// These requests are forwarded to the KioskNextShellClient when necessary. +interface KioskNextShellController { + // Provides a client for dispatching requests. + SetClient(KioskNextShellClient client); +};
diff --git a/ash/public/interfaces/locale.mojom b/ash/public/interfaces/locale.mojom deleted file mode 100644 index a92a518..0000000 --- a/ash/public/interfaces/locale.mojom +++ /dev/null
@@ -1,34 +0,0 @@ -// 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. - -module ash.mojom; - -import "mojo/public/mojom/base/string16.mojom"; - -// The locale info to show in the system tray locale detailed view. -struct LocaleInfo { - // This ISO code of the locale. - string iso_code; - - // The display name of the locale. - mojo_base.mojom.String16 display_name; -}; - -// Sent as the response to LocaleUpdateController.OnLocaleChanged(). -enum LocaleNotificationResult { - ACCEPT, - REVERT -}; - -// Used by Chrome to notify locale change events. -interface LocaleUpdateController { - // When this is called in OOBE, it returnes ACCEPT immediately after invoking - // observer callbacks. |current|, |from|, and |to| are ignored in this case. - // Otherwise it displays a notification in ash prompting the user whether to - // accept a change in the locale. If the user clicks the accept button (or - // closes the notification), OnLocaleChange() returns ACCEPT. If the user - // clicks the revert button, returns REVERT. - OnLocaleChanged(string current, string from, string to) - => (LocaleNotificationResult result); -};
diff --git a/ash/shelf/app_list_button_unittest.cc b/ash/shelf/app_list_button_unittest.cc index 5939d49..1ecad65 100644 --- a/ash/shelf/app_list_button_unittest.cc +++ b/ash/shelf/app_list_button_unittest.cc
@@ -285,12 +285,7 @@ void SetUp() override { set_start_session(false); AppListButtonTest::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - AppListButtonTest::TearDown(); + client_ = BindMockKioskNextShellClient(); } private:
diff --git a/ash/shelf/back_button_unittest.cc b/ash/shelf/back_button_unittest.cc index 1322bab..0dc6d41 100644 --- a/ash/shelf/back_button_unittest.cc +++ b/ash/shelf/back_button_unittest.cc
@@ -133,12 +133,7 @@ void SetUp() override { set_start_session(false); BackButtonTest::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - BackButtonTest::TearDown(); + client_ = BindMockKioskNextShellClient(); } void SimulateKioskNextSession() {
diff --git a/ash/shelf/home_button_delegate.cc b/ash/shelf/home_button_delegate.cc index f65b4199..739049f 100644 --- a/ash/shelf/home_button_delegate.cc +++ b/ash/shelf/home_button_delegate.cc
@@ -8,7 +8,7 @@ #include "ash/app_list/app_list_controller_impl.h" #include "ash/home_screen/home_screen_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/shelf_model.h" #include "ash/shell.h" #include "base/logging.h"
diff --git a/ash/shelf/login_shelf_view.h b/ash/shelf/login_shelf_view.h index 83f4fcc7..7bd2ef4 100644 --- a/ash/shelf/login_shelf_view.h +++ b/ash/shelf/login_shelf_view.h
@@ -16,7 +16,7 @@ #include "ash/public/cpp/login_types.h" #include "ash/public/interfaces/login_screen.mojom.h" #include "ash/shutdown_controller_impl.h" -#include "ash/system/locale/locale_update_controller.h" +#include "ash/system/locale/locale_update_controller_impl.h" #include "ash/tray_action/tray_action_observer.h" #include "base/scoped_observer.h" #include "ui/views/controls/button/button.h" @@ -178,7 +178,7 @@ ScopedObserver<ShutdownControllerImpl, ShutdownControllerImpl::Observer> shutdown_controller_observer_{this}; - ScopedObserver<LocaleUpdateController, LocaleChangeObserver> + ScopedObserver<LocaleUpdateControllerImpl, LocaleChangeObserver> locale_change_observer_{this}; ScopedObserver<LoginDataDispatcher, LoginDataDispatcher::Observer>
diff --git a/ash/shelf/shelf_layout_manager.cc b/ash/shelf/shelf_layout_manager.cc index 2ffd79c..860234e 100644 --- a/ash/shelf/shelf_layout_manager.cc +++ b/ash/shelf/shelf_layout_manager.cc
@@ -28,7 +28,7 @@ #include "ash/shelf/shelf_layout_manager_observer.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" -#include "ash/system/locale/locale_update_controller.h" +#include "ash/system/locale/locale_update_controller_impl.h" #include "ash/system/status_area_widget.h" #include "ash/wallpaper/wallpaper_controller_impl.h" #include "ash/wm/fullscreen_window_finder.h"
diff --git a/ash/shelf/shelf_layout_manager.h b/ash/shelf/shelf_layout_manager.h index 9f9b64c..721f63354 100644 --- a/ash/shelf/shelf_layout_manager.h +++ b/ash/shelf/shelf_layout_manager.h
@@ -16,7 +16,7 @@ #include "ash/session/session_observer.h" #include "ash/shelf/shelf.h" #include "ash/shell_observer.h" -#include "ash/system/locale/locale_update_controller.h" +#include "ash/system/locale/locale_update_controller_impl.h" #include "ash/wm/lock_state_observer.h" #include "ash/wm/overview/overview_observer.h" #include "ash/wm/wm_snap_to_pixel_layout_manager.h"
diff --git a/ash/shelf/shelf_layout_manager_unittest.cc b/ash/shelf/shelf_layout_manager_unittest.cc index 12739c3..6121aed 100644 --- a/ash/shelf/shelf_layout_manager_unittest.cc +++ b/ash/shelf/shelf_layout_manager_unittest.cc
@@ -2343,7 +2343,7 @@ auto* shelf_window = shelf->GetWindow(); aura::Window* container = shelf_window->GetRootWindow()->GetChildById( kShellWindowId_AlwaysOnTopContainer); - EXPECT_TRUE(base::ContainsValue(container->children(), window_two)); + EXPECT_TRUE(base::Contains(container->children(), window_two)); widget_two->Maximize(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState());
diff --git a/ash/shelf/shelf_view_unittest.cc b/ash/shelf/shelf_view_unittest.cc index bf32e17..e9cb7e7 100644 --- a/ash/shelf/shelf_view_unittest.cc +++ b/ash/shelf/shelf_view_unittest.cc
@@ -15,7 +15,7 @@ #include "ash/display/screen_orientation_controller_test_api.h" #include "ash/focus_cycler.h" #include "ash/ime/ime_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/kiosk_next/kiosk_next_shell_test_util.h" #include "ash/kiosk_next/mock_kiosk_next_shell_client.h" #include "ash/public/cpp/ash_features.h" @@ -3944,12 +3944,7 @@ void SetUp() override { set_start_session(false); ShelfViewTest::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - ShelfViewTest::TearDown(); + client_ = BindMockKioskNextShellClient(); } protected:
diff --git a/ash/shelf/shelf_widget.cc b/ash/shelf/shelf_widget.cc index 851c7e5..4612824 100644 --- a/ash/shelf/shelf_widget.cc +++ b/ash/shelf/shelf_widget.cc
@@ -9,7 +9,7 @@ #include "ash/animation/animation_change_type.h" #include "ash/focus_cycler.h" #include "ash/keyboard/ui/keyboard_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_switches.h" #include "ash/public/cpp/shelf_model.h"
diff --git a/ash/shell.cc b/ash/shell.cc index ffd57a21..1525f83 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -55,7 +55,7 @@ #include "ash/ime/ime_controller.h" #include "ash/keyboard/ash_keyboard_controller.h" #include "ash/keyboard/ui/keyboard_ui_factory.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/laser/laser_pointer_controller.h" #include "ash/login/login_screen_controller.h" #include "ash/login_status.h" @@ -95,7 +95,7 @@ #include "ash/system/caps_lock_notification_controller.h" #include "ash/system/keyboard_brightness/keyboard_brightness_controller.h" #include "ash/system/keyboard_brightness_control_delegate.h" -#include "ash/system/locale/locale_update_controller.h" +#include "ash/system/locale/locale_update_controller_impl.h" #include "ash/system/message_center/message_center_controller.h" #include "ash/system/model/system_tray_model.h" #include "ash/system/model/virtual_keyboard_model.h" @@ -552,7 +552,7 @@ immersive_context_(std::make_unique<ImmersiveContextAsh>()), keyboard_brightness_control_delegate_( std::make_unique<KeyboardBrightnessController>()), - locale_update_controller_(std::make_unique<LocaleUpdateController>()), + locale_update_controller_(std::make_unique<LocaleUpdateControllerImpl>()), media_controller_(std::make_unique<MediaControllerImpl>(connector)), session_controller_(std::make_unique<SessionControllerImpl>()), shell_delegate_(std::move(shell_delegate)), @@ -893,8 +893,7 @@ std::make_unique<MultiDeviceNotificationPresenter>( message_center::MessageCenter::Get(), connector_); } - kiosk_next_shell_controller_ = - std::make_unique<KioskNextShellControllerImpl>(); + kiosk_next_shell_controller_ = std::make_unique<KioskNextShellController>(); tablet_mode_controller_ = std::make_unique<TabletModeController>(); accessibility_focus_ring_controller_ = @@ -1126,7 +1125,9 @@ user_activity_detector_.get(), connector_); video_activity_notifier_.reset( new VideoActivityNotifier(video_detector_.get())); - bluetooth_notification_controller_.reset(new BluetoothNotificationController); + bluetooth_notification_controller_ = + std::make_unique<BluetoothNotificationController>( + message_center::MessageCenter::Get()); screen_orientation_controller_ = std::make_unique<ScreenOrientationController>(); screen_layout_observer_.reset(new ScreenLayoutObserver());
diff --git a/ash/shell.h b/ash/shell.h index 5f363fe..f9358ea 100644 --- a/ash/shell.h +++ b/ash/shell.h
@@ -127,10 +127,10 @@ class ImmersiveContext; class KeyAccessibilityEnabler; class KeyboardBrightnessControlDelegate; -class KioskNextShellControllerImpl; +class KioskNextShellController; class AshKeyboardController; class LaserPointerController; -class LocaleUpdateController; +class LocaleUpdateControllerImpl; class LockStateController; class LogoutConfirmationController; class LoginScreenController; @@ -378,7 +378,7 @@ KeyboardBrightnessControlDelegate* keyboard_brightness_control_delegate() { return keyboard_brightness_control_delegate_.get(); } - KioskNextShellControllerImpl* kiosk_next_shell_controller() { + KioskNextShellController* kiosk_next_shell_controller() { return kiosk_next_shell_controller_.get(); } AshKeyboardController* ash_keyboard_controller() { @@ -387,7 +387,7 @@ LaserPointerController* laser_pointer_controller() { return laser_pointer_controller_.get(); } - LocaleUpdateController* locale_update_controller() { + LocaleUpdateControllerImpl* locale_update_controller() { return locale_update_controller_.get(); } LoginScreenController* login_screen_controller() { @@ -661,8 +661,8 @@ std::unique_ptr<ImmersiveContext> immersive_context_; std::unique_ptr<KeyboardBrightnessControlDelegate> keyboard_brightness_control_delegate_; - std::unique_ptr<KioskNextShellControllerImpl> kiosk_next_shell_controller_; - std::unique_ptr<LocaleUpdateController> locale_update_controller_; + std::unique_ptr<KioskNextShellController> kiosk_next_shell_controller_; + std::unique_ptr<LocaleUpdateControllerImpl> locale_update_controller_; std::unique_ptr<LoginScreenController> login_screen_controller_; std::unique_ptr<LogoutConfirmationController> logout_confirmation_controller_; std::unique_ptr<TabletModeController> tablet_mode_controller_;
diff --git a/ash/system/accessibility/autoclick_menu_bubble_controller.h b/ash/system/accessibility/autoclick_menu_bubble_controller.h index 9c99179..bab525f5 100644 --- a/ash/system/accessibility/autoclick_menu_bubble_controller.h +++ b/ash/system/accessibility/autoclick_menu_bubble_controller.h
@@ -7,7 +7,7 @@ #include "ash/public/cpp/ash_constants.h" #include "ash/system/accessibility/autoclick_menu_view.h" -#include "ash/system/locale/locale_update_controller.h" +#include "ash/system/locale/locale_update_controller_impl.h" #include "ash/system/tray/tray_bubble_view.h" namespace ash {
diff --git a/ash/system/bluetooth/bluetooth_notification_controller.cc b/ash/system/bluetooth/bluetooth_notification_controller.cc index 1996722..f753723 100644 --- a/ash/system/bluetooth/bluetooth_notification_controller.cc +++ b/ash/system/bluetooth/bluetooth_notification_controller.cc
@@ -8,8 +8,12 @@ #include <utility> #include "ash/public/cpp/notification_utils.h" +#include "ash/public/cpp/system_tray_client.h" #include "ash/resources/vector_icons/vector_icons.h" +#include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" +#include "ash/system/model/system_tray_model.h" +#include "ash/system/tray/tray_popup_utils.h" #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" @@ -21,7 +25,6 @@ #include "ui/message_center/message_center.h" #include "ui/message_center/public/cpp/notification.h" #include "ui/message_center/public/cpp/notification_delegate.h" -#include "ui/message_center/public/cpp/notification_types.h" using device::BluetoothAdapter; using device::BluetoothAdapterFactory; @@ -29,26 +32,11 @@ using message_center::MessageCenter; using message_center::Notification; +namespace ash { namespace { const char kNotifierBluetooth[] = "ash.bluetooth"; -// Identifier for the discoverable notification. -const char kBluetoothDeviceDiscoverableNotificationId[] = - "chrome://settings/bluetooth/discoverable"; - -// Identifier for the pairing notification; the Bluetooth code ensures we -// only receive one pairing request at a time, so a single id is sufficient and -// means we "update" one notification if not handled rather than continually -// bugging the user. -const char kBluetoothDevicePairingNotificationId[] = - "chrome://settings/bluetooth/pairing"; - -// Identifier for the notification that a device has been paired with the -// system. -const char kBluetoothDevicePairedNotificationId[] = - "chrome://settings/bluetooth/paired"; - // The BluetoothPairingNotificationDelegate handles user interaction with the // pairing notification and sending the confirmation, rejection or cancellation // back to the underlying device. @@ -56,7 +44,8 @@ : public message_center::NotificationDelegate { public: BluetoothPairingNotificationDelegate(scoped_refptr<BluetoothAdapter> adapter, - const std::string& address); + const std::string& address, + const std::string& notification_id); protected: ~BluetoothPairingNotificationDelegate() override; @@ -77,14 +66,16 @@ // Address of the device being paired. const std::string address_; + const std::string notification_id_; DISALLOW_COPY_AND_ASSIGN(BluetoothPairingNotificationDelegate); }; BluetoothPairingNotificationDelegate::BluetoothPairingNotificationDelegate( scoped_refptr<BluetoothAdapter> adapter, - const std::string& address) - : adapter_(adapter), address_(address) {} + const std::string& address, + const std::string& notification_id) + : adapter_(adapter), address_(address), notification_id_(notification_id) {} BluetoothPairingNotificationDelegate::~BluetoothPairingNotificationDelegate() = default; @@ -123,16 +114,59 @@ } // In any case, remove this pairing notification. - MessageCenter::Get()->RemoveNotification( - kBluetoothDevicePairingNotificationId, false /* by_user */); + MessageCenter::Get()->RemoveNotification(notification_id_, + false /* by_user */); } } // namespace -namespace ash { +const char BluetoothNotificationController:: + kBluetoothDeviceDiscoverableNotificationId[] = + "cros_bluetooth_device_discoverable_notification_id"; -BluetoothNotificationController::BluetoothNotificationController() - : weak_ptr_factory_(this) { +const char + BluetoothNotificationController::kBluetoothDevicePairingNotificationId[] = + "cros_bluetooth_device_pairing_notification_id"; + +const char + BluetoothNotificationController::kBluetoothDevicePairedNotificationId[] = + "cros_bluetooth_device_paired_notification_id"; + +// This class handles opening the Bluetooth Settings UI when the user clicks +// on the Paired Notification. +class BluetoothNotificationController::BluetoothPairedNotificationDelegate + : public message_center::NotificationDelegate { + public: + explicit BluetoothPairedNotificationDelegate(OpenUiDelegate* open_delegate) + : open_delegate_(open_delegate) {} + + protected: + ~BluetoothPairedNotificationDelegate() override = default; + + void Click(const base::Optional<int>& button_index, + const base::Optional<base::string16>& reply) override; + + private: + OpenUiDelegate* open_delegate_; + DISALLOW_COPY_AND_ASSIGN(BluetoothPairedNotificationDelegate); +}; + +void BluetoothNotificationController::BluetoothPairedNotificationDelegate:: + Click(const base::Optional<int>& button_index, + const base::Optional<base::string16>& reply) { + if (TrayPopupUtils::CanOpenWebUISettings()) + open_delegate_->OpenBluetoothSettings(); +} + +void BluetoothNotificationController::OpenUiDelegate::OpenBluetoothSettings() { + Shell::Get()->system_tray_model()->client()->ShowBluetoothSettings(); +} + +BluetoothNotificationController::BluetoothNotificationController( + message_center::MessageCenter* message_center) + : open_delegate_(std::make_unique<OpenUiDelegate>()), + message_center_(message_center), + weak_ptr_factory_(this) { BluetoothAdapterFactory::GetAdapter( base::BindOnce(&BluetoothNotificationController::OnGetAdapter, weak_ptr_factory_.GetWeakPtr())); @@ -153,7 +187,7 @@ NotifyAdapterDiscoverable(); } else { // Clear any previous discoverable notification. - MessageCenter::Get()->RemoveNotification( + message_center_->RemoveNotification( kBluetoothDeviceDiscoverableNotificationId, false /* by_user */); } } @@ -281,7 +315,7 @@ kNotifierBluetooth), optional, nullptr, kNotificationBluetoothIcon, message_center::SystemNotificationWarningLevel::NORMAL); - MessageCenter::Get()->AddNotification(std::move(notification)); + message_center_->AddNotification(std::move(notification)); } void BluetoothNotificationController::NotifyPairing( @@ -303,10 +337,12 @@ message_center::NotifierId(message_center::NotifierType::SYSTEM_COMPONENT, kNotifierBluetooth), optional, - new BluetoothPairingNotificationDelegate(adapter_, device->GetAddress()), + base::MakeRefCounted<BluetoothPairingNotificationDelegate>( + adapter_, device->GetAddress(), + kBluetoothDevicePairingNotificationId), kNotificationBluetoothIcon, message_center::SystemNotificationWarningLevel::NORMAL); - MessageCenter::Get()->AddNotification(std::move(notification)); + message_center_->AddNotification(std::move(notification)); } void BluetoothNotificationController::NotifyPairedDevice( @@ -314,10 +350,11 @@ // Remove the currently presented pairing notification; since only one // pairing request is queued at a time, this is guaranteed to be the device // that just became paired. - MessageCenter::Get()->RemoveNotification( - kBluetoothDevicePairingNotificationId, false /* by_user */); - - message_center::RichNotificationData optional; + if (message_center_->FindVisibleNotificationById( + kBluetoothDevicePairingNotificationId)) { + message_center_->RemoveNotification(kBluetoothDevicePairingNotificationId, + false /* by_user */); + } std::unique_ptr<Notification> notification = ash::CreateSystemNotification( message_center::NOTIFICATION_TYPE_SIMPLE, @@ -327,9 +364,12 @@ base::string16() /* display source */, GURL(), message_center::NotifierId(message_center::NotifierType::SYSTEM_COMPONENT, kNotifierBluetooth), - optional, nullptr, kNotificationBluetoothIcon, + message_center::RichNotificationData(), + base::MakeRefCounted<BluetoothPairedNotificationDelegate>( + open_delegate_.get()), + kNotificationBluetoothIcon, message_center::SystemNotificationWarningLevel::NORMAL); - MessageCenter::Get()->AddNotification(std::move(notification)); + message_center_->AddNotification(std::move(notification)); } } // namespace ash
diff --git a/ash/system/bluetooth/bluetooth_notification_controller.h b/ash/system/bluetooth/bluetooth_notification_controller.h index 63f7ef5..9a1aac9f 100644 --- a/ash/system/bluetooth/bluetooth_notification_controller.h +++ b/ash/system/bluetooth/bluetooth_notification_controller.h
@@ -18,6 +18,10 @@ #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_device.h" +namespace message_center { +class MessageCenter; +} // namespace message_center + namespace ash { // The BluetoothNotificationController receives incoming pairing requests from @@ -28,7 +32,8 @@ : public device::BluetoothAdapter::Observer, public device::BluetoothDevice::PairingDelegate { public: - BluetoothNotificationController(); + explicit BluetoothNotificationController( + message_center::MessageCenter* message_center); ~BluetoothNotificationController() override; // device::BluetoothAdapter::Observer override. @@ -54,6 +59,25 @@ void AuthorizePairing(device::BluetoothDevice* device) override; private: + friend class BluetoothNotificationControllerTest; + class BluetoothPairedNotificationDelegate; + + // Wraps calls to settings code which are mocked out for tests. + class OpenUiDelegate { + public: + OpenUiDelegate() = default; + virtual ~OpenUiDelegate() = default; + virtual void OpenBluetoothSettings(); + }; + + static const char kBluetoothDeviceDiscoverableNotificationId[]; + // Identifier for the pairing notification; the Bluetooth code ensures we + // only receive one pairing request at a time, so a single id is sufficient + // and means we "update" one notification if not handled rather than + // continually bugging the user. + static const char kBluetoothDevicePairingNotificationId[]; + static const char kBluetoothDevicePairedNotificationId[]; + // Internal method called by BluetoothAdapterFactory to provide the adapter // object. void OnGetAdapter(scoped_refptr<device::BluetoothAdapter> adapter); @@ -74,6 +98,10 @@ // Clears any shown pairing notification now that the device has been paired. void NotifyPairedDevice(device::BluetoothDevice* device); + std::unique_ptr<OpenUiDelegate> open_delegate_; + + message_center::MessageCenter* const message_center_; + // Reference to the underlying BluetoothAdapter object, holding this reference // ensures we stay around as the pairing delegate for that adapter. scoped_refptr<device::BluetoothAdapter> adapter_;
diff --git a/ash/system/bluetooth/bluetooth_notification_controller_unittest.cc b/ash/system/bluetooth/bluetooth_notification_controller_unittest.cc new file mode 100644 index 0000000..180c7f2 --- /dev/null +++ b/ash/system/bluetooth/bluetooth_notification_controller_unittest.cc
@@ -0,0 +1,179 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/system/bluetooth/bluetooth_notification_controller.h" + +#include <memory> +#include <utility> + +#include "ash/session/test_session_controller_client.h" +#include "ash/strings/grit/ash_strings.h" +#include "ash/system/tray/tray_popup_utils.h" +#include "ash/test/ash_test_base.h" +#include "ash/test/ash_test_helper.h" +#include "base/containers/flat_map.h" +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/strings/utf_string_conversions.h" +#include "device/bluetooth/test/mock_bluetooth_adapter.h" +#include "device/bluetooth/test/mock_bluetooth_device.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/message_center/fake_message_center.h" + +using testing::Return; + +namespace ash { +namespace { + +class TestMessageCenter : public message_center::FakeMessageCenter { + public: + TestMessageCenter() = default; + ~TestMessageCenter() override = default; + + void ClickOnNotification(const std::string& id) override { + message_center::Notification* notification = + FindVisibleNotificationById(id); + DCHECK(notification); + notification->delegate()->Click(base::nullopt, base::nullopt); + } + + private: + DISALLOW_COPY_AND_ASSIGN(TestMessageCenter); +}; + +} // namespace + +class BluetoothNotificationControllerTest : public AshTestBase { + public: + class TestOpenUiDelegate + : public BluetoothNotificationController::OpenUiDelegate { + public: + TestOpenUiDelegate() = default; + ~TestOpenUiDelegate() override = default; + + size_t open_bluetooth_settings_ui_count() const { + return open_bluetooth_settings_ui_count_; + } + + void OpenBluetoothSettings() override { + ++open_bluetooth_settings_ui_count_; + } + + private: + size_t open_bluetooth_settings_ui_count_ = 0u; + + DISALLOW_COPY_AND_ASSIGN(TestOpenUiDelegate); + }; + + protected: + BluetoothNotificationControllerTest() = default; + + void SetUp() override { + AshTestBase::SetUp(); + notification_controller_ = + std::make_unique<BluetoothNotificationController>( + &test_message_center_); + auto open_delegate = std::make_unique<TestOpenUiDelegate>(); + open_ui_delegate_ = open_delegate.get(); + notification_controller_->open_delegate_ = std::move(open_delegate); + bluetooth_device_ = + std::make_unique<testing::NiceMock<device::MockBluetoothDevice>>( + nullptr /* adapter */, 0 /* bluetooth_class */, "name", "address", + false /* paired */, false /* connected */); + + // Mock the device is paired. + ON_CALL(*bluetooth_device_, IsPaired()).WillByDefault(Return(true)); + } + + void ClickPairedNotification() { + test_message_center_.ClickOnNotification( + BluetoothNotificationController::kBluetoothDevicePairedNotificationId); + } + + void DismissPairedNotification(bool by_user) { + test_message_center_.RemoveNotification( + BluetoothNotificationController::kBluetoothDevicePairedNotificationId, + by_user); + } + + void VerifyPairedNotificationIsNotVisible() { + EXPECT_FALSE(test_message_center_.FindVisibleNotificationById( + BluetoothNotificationController::kBluetoothDevicePairedNotificationId)); + } + + void VerifyPairedNotificationIsVisible( + const device::BluetoothDevice* device) { + message_center::Notification* visible_notification = + test_message_center_.FindVisibleNotificationById( + BluetoothNotificationController:: + kBluetoothDevicePairedNotificationId); + EXPECT_TRUE(visible_notification); + EXPECT_EQ(base::string16(), visible_notification->title()); + EXPECT_EQ(l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_BLUETOOTH_PAIRED, + device->GetNameForDisplay()), + visible_notification->message()); + } + + // Run the notification controller to simulate showing a notification by + // adding it to the TestMessageCenter. + void ShowPairedNotification( + BluetoothNotificationController* notification_controller, + device::MockBluetoothDevice* bluetooth_device) { + notification_controller->NotifyPairedDevice(bluetooth_device); + } + + TestMessageCenter test_message_center_; + std::unique_ptr<BluetoothNotificationController> notification_controller_; + TestOpenUiDelegate* open_ui_delegate_; + std::unique_ptr<device::MockBluetoothDevice> bluetooth_device_; + + DISALLOW_COPY_AND_ASSIGN(BluetoothNotificationControllerTest); +}; + +TEST_F(BluetoothNotificationControllerTest, + PairedDeviceNotification_TapNotification) { + // Show the notification to the user. + ShowPairedNotification(notification_controller_.get(), + bluetooth_device_.get()); + + VerifyPairedNotificationIsVisible(bluetooth_device_.get()); + + ClickPairedNotification(); + + // The notification shouldn't dismiss after a click. + VerifyPairedNotificationIsVisible(bluetooth_device_.get()); + + // Check the notification controller tried to open the UI. + EXPECT_EQ(1u, open_ui_delegate_->open_bluetooth_settings_ui_count()); +} + +TEST_F(BluetoothNotificationControllerTest, + PairedDeviceNotification_UserDismissesNotification) { + ShowPairedNotification(notification_controller_.get(), + bluetooth_device_.get()); + + VerifyPairedNotificationIsVisible(bluetooth_device_.get()); + + DismissPairedNotification(true /* by_user */); + + VerifyPairedNotificationIsNotVisible(); + // The settings UI should not open when closing the notification. + EXPECT_EQ(0u, open_ui_delegate_->open_bluetooth_settings_ui_count()); +} + +TEST_F(BluetoothNotificationControllerTest, + PairedDeviceNotification_SystemDismissesNotification) { + ShowPairedNotification(notification_controller_.get(), + bluetooth_device_.get()); + + VerifyPairedNotificationIsVisible(bluetooth_device_.get()); + + DismissPairedNotification(false /* by_user */); + + VerifyPairedNotificationIsNotVisible(); + EXPECT_EQ(0u, open_ui_delegate_->open_bluetooth_settings_ui_count()); +} + +} // namespace ash
diff --git a/ash/system/bluetooth/unified_bluetooth_detailed_view_controller.cc b/ash/system/bluetooth/unified_bluetooth_detailed_view_controller.cc index 0c3b480..4e70b84f 100644 --- a/ash/system/bluetooth/unified_bluetooth_detailed_view_controller.cc +++ b/ash/system/bluetooth/unified_bluetooth_detailed_view_controller.cc
@@ -46,7 +46,7 @@ const std::set<BluetoothAddress>& new_device_address_list) { base::EraseIf(*device_list, [&new_device_address_list]( const BluetoothDeviceInfoPtr& info) { - return !base::ContainsKey(new_device_address_list, info->address); + return !base::Contains(new_device_address_list, info->address); }); }
diff --git a/ash/system/ime_menu/ime_menu_tray.cc b/ash/system/ime_menu/ime_menu_tray.cc index 2323d44..0fbd3e6 100644 --- a/ash/system/ime_menu/ime_menu_tray.cc +++ b/ash/system/ime_menu/ime_menu_tray.cc
@@ -9,7 +9,7 @@ #include "ash/keyboard/ash_keyboard_controller.h" #include "ash/keyboard/ui/keyboard_controller.h" #include "ash/keyboard/virtual_keyboard_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/ash_constants.h" #include "ash/public/cpp/system_tray_client.h" #include "ash/resources/vector_icons/vector_icons.h"
diff --git a/ash/system/ime_menu/ime_menu_tray_unittest.cc b/ash/system/ime_menu/ime_menu_tray_unittest.cc index 59d91fb..9f4db4a0 100644 --- a/ash/system/ime_menu/ime_menu_tray_unittest.cc +++ b/ash/system/ime_menu/ime_menu_tray_unittest.cc
@@ -96,7 +96,7 @@ } for (const auto& ime : ime_map) { // Tests that all the IMEs on the view is in the list of selected IMEs. - EXPECT_TRUE(base::ContainsValue(expected_ime_ids, ime.second)); + EXPECT_TRUE(base::Contains(expected_ime_ids, ime.second)); // Tests that the checked IME is the current IME. ui::AXNodeData node_data; @@ -368,12 +368,7 @@ void SetUp() override { set_start_session(false); ImeMenuTrayTest::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - ImeMenuTrayTest::TearDown(); + client_ = BindMockKioskNextShellClient(); } private:
diff --git a/ash/system/locale/locale_detailed_view.cc b/ash/system/locale/locale_detailed_view.cc index 27f6a3b..a375ca5 100644 --- a/ash/system/locale/locale_detailed_view.cc +++ b/ash/system/locale/locale_detailed_view.cc
@@ -123,18 +123,18 @@ CreateTitleRow(IDS_ASH_STATUS_TRAY_LOCALE_TITLE); CreateScrollableList(); - const std::vector<mojom::LocaleInfoPtr>& locales = + const std::vector<LocaleInfo>& locales = Shell::Get()->system_tray_model()->locale()->locale_list(); int id = 0; for (auto& entry : locales) { const bool checked = - entry->iso_code == + entry.iso_code == Shell::Get()->system_tray_model()->locale()->current_locale_iso_code(); LocaleItem* item = - new LocaleItem(this, entry->iso_code, entry->display_name, checked); + new LocaleItem(this, entry.iso_code, entry.display_name, checked); scroll_content()->AddChildView(item); item->SetID(id); - id_to_locale_[id] = entry->iso_code; + id_to_locale_[id] = entry.iso_code; ++id; } Layout();
diff --git a/ash/system/locale/locale_feature_pod_controller_unittest.cc b/ash/system/locale/locale_feature_pod_controller_unittest.cc index 13e939be..c8ba155 100644 --- a/ash/system/locale/locale_feature_pod_controller_unittest.cc +++ b/ash/system/locale/locale_feature_pod_controller_unittest.cc
@@ -7,7 +7,7 @@ #include <memory> #include <vector> -#include "ash/public/interfaces/locale.mojom.h" +#include "ash/public/cpp/locale_update_controller.h" #include "ash/shell.h" #include "ash/system/model/system_tray_model.h" #include "ash/system/unified/feature_pod_button.h" @@ -60,16 +60,14 @@ EXPECT_FALSE(button->GetVisible()); // The button is invisible if the locale list is empty. - Shell::Get()->system_tray_model()->SetLocaleList( - std::vector<mojom::LocaleInfoPtr>(), kDefaultLocaleIsoCode); + Shell::Get()->system_tray_model()->SetLocaleList({}, kDefaultLocaleIsoCode); button.reset(controller_->CreateButton()); EXPECT_FALSE(button->GetVisible()); // The button is visible if the locale list is non-empty. - std::vector<mojom::LocaleInfoPtr> locale_list; - mojom::LocaleInfoPtr locale = mojom::LocaleInfo::New( - kDefaultLocaleIsoCode, base::UTF8ToUTF16("English (United States)")); - locale_list.push_back(std::move(locale)); + std::vector<LocaleInfo> locale_list; + locale_list.emplace_back(kDefaultLocaleIsoCode, + base::UTF8ToUTF16("English (United States)")); Shell::Get()->system_tray_model()->SetLocaleList(std::move(locale_list), kDefaultLocaleIsoCode); button.reset(controller_->CreateButton()); @@ -77,4 +75,4 @@ } } // namespace -} // namespace ash \ No newline at end of file +} // namespace ash
diff --git a/ash/system/locale/locale_update_controller.h b/ash/system/locale/locale_update_controller.h deleted file mode 100644 index dd7d090..0000000 --- a/ash/system/locale/locale_update_controller.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_SYSTEM_LOCALE_LOCALE_UPDATE_CONTROLLER_H_ -#define ASH_SYSTEM_LOCALE_LOCALE_UPDATE_CONTROLLER_H_ - -#include <string> - -#include "ash/public/interfaces/locale.mojom.h" -#include "base/macros.h" -#include "mojo/public/cpp/bindings/binding_set.h" - -namespace ash { - -class LocaleChangeObserver { - public: - virtual ~LocaleChangeObserver() = default; - - // Called when locale is changed. - virtual void OnLocaleChanged() = 0; -}; - -// Observes and handles locale change events. -class LocaleUpdateController : public mojom::LocaleUpdateController { - public: - LocaleUpdateController(); - ~LocaleUpdateController() override; - - // Binds the mojom::LocaleUpdateController interface request to this - // object. - void BindRequest(mojom::LocaleUpdateControllerRequest request); - - void AddObserver(LocaleChangeObserver* observer); - void RemoveObserver(LocaleChangeObserver* observer); - - private: - // Overridden from mojom::LocaleUpdateController: - void OnLocaleChanged(const std::string& cur_locale, - const std::string& from_locale, - const std::string& to_locale, - OnLocaleChangedCallback callback) override; - - std::string cur_locale_; - std::string from_locale_; - std::string to_locale_; - base::ObserverList<LocaleChangeObserver>::Unchecked observers_; - - // Bindings for the LocaleUpdateController interface. - mojo::BindingSet<mojom::LocaleUpdateController> bindings_; - - DISALLOW_COPY_AND_ASSIGN(LocaleUpdateController); -}; - -} // namespace ash - -#endif // ASH_SYSTEM_LOCALE_LOCALE_UPDATE_CONTROLLER_H_
diff --git a/ash/system/locale/locale_update_controller.cc b/ash/system/locale/locale_update_controller_impl.cc similarity index 69% rename from ash/system/locale/locale_update_controller.cc rename to ash/system/locale/locale_update_controller_impl.cc index 2d6b0e0c..5e2e5f18 100644 --- a/ash/system/locale/locale_update_controller.cc +++ b/ash/system/locale/locale_update_controller_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/system/locale/locale_update_controller.h" +#include "ash/system/locale/locale_update_controller_impl.h" #include <memory> #include <utility> @@ -33,7 +33,7 @@ class LocaleNotificationDelegate : public message_center::NotificationDelegate { public: explicit LocaleNotificationDelegate( - base::OnceCallback<void(ash::mojom::LocaleNotificationResult)> callback); + base::OnceCallback<void(LocaleNotificationResult)> callback); protected: ~LocaleNotificationDelegate() override; @@ -44,26 +44,26 @@ const base::Optional<base::string16>& reply) override; private: - base::OnceCallback<void(ash::mojom::LocaleNotificationResult)> callback_; + base::OnceCallback<void(LocaleNotificationResult)> callback_; DISALLOW_COPY_AND_ASSIGN(LocaleNotificationDelegate); }; LocaleNotificationDelegate::LocaleNotificationDelegate( - base::OnceCallback<void(ash::mojom::LocaleNotificationResult)> callback) + base::OnceCallback<void(LocaleNotificationResult)> callback) : callback_(std::move(callback)) {} LocaleNotificationDelegate::~LocaleNotificationDelegate() { if (callback_) { // We're being destroyed but the user didn't click on anything. Run the // callback so that we don't crash. - std::move(callback_).Run(ash::mojom::LocaleNotificationResult::ACCEPT); + std::move(callback_).Run(LocaleNotificationResult::kAccept); } } void LocaleNotificationDelegate::Close(bool by_user) { if (callback_) { - std::move(callback_).Run(ash::mojom::LocaleNotificationResult::ACCEPT); + std::move(callback_).Run(LocaleNotificationResult::kAccept); } } @@ -73,26 +73,21 @@ if (!callback_) return; - std::move(callback_).Run(button_index - ? ash::mojom::LocaleNotificationResult::REVERT - : ash::mojom::LocaleNotificationResult::ACCEPT); + std::move(callback_).Run(button_index ? LocaleNotificationResult::kRevert + : LocaleNotificationResult::kAccept); } } // namespace -LocaleUpdateController::LocaleUpdateController() = default; +LocaleUpdateControllerImpl::LocaleUpdateControllerImpl() = default; -LocaleUpdateController::~LocaleUpdateController() = default; +LocaleUpdateControllerImpl::~LocaleUpdateControllerImpl() = default; -void LocaleUpdateController::BindRequest( - mojom::LocaleUpdateControllerRequest request) { - bindings_.AddBinding(this, std::move(request)); -} - -void LocaleUpdateController::OnLocaleChanged(const std::string& cur_locale, - const std::string& from_locale, - const std::string& to_locale, - OnLocaleChangedCallback callback) { +void LocaleUpdateControllerImpl::OnLocaleChanged( + const std::string& cur_locale, + const std::string& from_locale, + const std::string& to_locale, + OnLocaleChangedCallback callback) { base::string16 from = l10n_util::GetDisplayNameForLocale(from_locale, cur_locale, true); base::string16 to = @@ -109,11 +104,11 @@ if (Shell::Get()->session_controller()->GetSessionState() == SessionState::OOBE) { - std::move(callback).Run(ash::mojom::LocaleNotificationResult::ACCEPT); + std::move(callback).Run(LocaleNotificationResult::kAccept); return; } - std::unique_ptr<Notification> notification = ash::CreateSystemNotification( + std::unique_ptr<Notification> notification = CreateSystemNotification( message_center::NOTIFICATION_TYPE_SIMPLE, kLocaleChangeNotificationId, l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_LOCALE_CHANGE_TITLE), l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_LOCALE_CHANGE_MESSAGE, @@ -128,11 +123,12 @@ std::move(notification)); } -void LocaleUpdateController::AddObserver(LocaleChangeObserver* observer) { +void LocaleUpdateControllerImpl::AddObserver(LocaleChangeObserver* observer) { observers_.AddObserver(observer); } -void LocaleUpdateController::RemoveObserver(LocaleChangeObserver* observer) { +void LocaleUpdateControllerImpl::RemoveObserver( + LocaleChangeObserver* observer) { observers_.RemoveObserver(observer); }
diff --git a/ash/system/locale/locale_update_controller_impl.h b/ash/system/locale/locale_update_controller_impl.h new file mode 100644 index 0000000..206d3f5 --- /dev/null +++ b/ash/system/locale/locale_update_controller_impl.h
@@ -0,0 +1,50 @@ +// 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 ASH_SYSTEM_LOCALE_LOCALE_UPDATE_CONTROLLER_IMPL_H_ +#define ASH_SYSTEM_LOCALE_LOCALE_UPDATE_CONTROLLER_IMPL_H_ + +#include <string> + +#include "ash/public/cpp/locale_update_controller.h" +#include "base/macros.h" +#include "base/observer_list.h" + +namespace ash { + +class LocaleChangeObserver { + public: + virtual ~LocaleChangeObserver() = default; + + // Called when locale is changed. + virtual void OnLocaleChanged() = 0; +}; + +// Observes and handles locale change events. +class LocaleUpdateControllerImpl : public LocaleUpdateController { + public: + LocaleUpdateControllerImpl(); + ~LocaleUpdateControllerImpl() override; + + void AddObserver(LocaleChangeObserver* observer); + void RemoveObserver(LocaleChangeObserver* observer); + + private: + // LocaleUpdateController: + void OnLocaleChanged(const std::string& cur_locale, + const std::string& from_locale, + const std::string& to_locale, + OnLocaleChangedCallback callback) override; + + std::string cur_locale_; + std::string from_locale_; + std::string to_locale_; + base::ObserverList<LocaleChangeObserver>::Unchecked observers_; + + DISALLOW_COPY_AND_ASSIGN(LocaleUpdateControllerImpl); +}; + +} // namespace ash + +#endif // ASH_SYSTEM_LOCALE_LOCALE_UPDATE_CONTROLLER_IMPL_H_
diff --git a/ash/system/message_center/arc/arc_notification_manager.cc b/ash/system/message_center/arc/arc_notification_manager.cc index 72c15f5..5192552 100644 --- a/ash/system/message_center/arc/arc_notification_manager.cc +++ b/ash/system/message_center/arc/arc_notification_manager.cc
@@ -422,7 +422,7 @@ void ArcNotificationManager::OpenNotificationSnoozeSettings( const std::string& key) { - if (!base::ContainsKey(items_, key)) { + if (!base::Contains(items_, key)) { DVLOG(3) << "Chrome requests to show a snooze setting gut on the" << "notification (key: " << key << "), but it is gone."; return;
diff --git a/ash/system/model/locale_model.cc b/ash/system/model/locale_model.cc index dbb6394..8d82f11b 100644 --- a/ash/system/model/locale_model.cc +++ b/ash/system/model/locale_model.cc
@@ -20,7 +20,7 @@ observers_.RemoveObserver(observer); } -void LocaleModel::SetLocaleList(std::vector<mojom::LocaleInfoPtr> locale_list, +void LocaleModel::SetLocaleList(std::vector<LocaleInfo> locale_list, const std::string& current_locale_iso_code) { locale_list_ = std::move(locale_list); current_locale_iso_code_ = current_locale_iso_code;
diff --git a/ash/system/model/locale_model.h b/ash/system/model/locale_model.h index 3a87c97b..ff070d61 100644 --- a/ash/system/model/locale_model.h +++ b/ash/system/model/locale_model.h
@@ -5,10 +5,11 @@ #ifndef ASH_SYSTEM_MODEL_LOCALE_MODEL_H_ #define ASH_SYSTEM_MODEL_LOCALE_MODEL_H_ +#include <memory> #include <string> #include <vector> -#include "ash/public/interfaces/locale.mojom.h" +#include "ash/public/cpp/locale_update_controller.h" #include "base/macros.h" #include "base/observer_list.h" @@ -32,21 +33,19 @@ void RemoveObserver(Observer* observer); - void SetLocaleList(std::vector<mojom::LocaleInfoPtr> locale_list, + void SetLocaleList(std::vector<LocaleInfo> locale_list, const std::string& current_locale_iso_code); bool ShouldShowCurrentLocaleInStatusArea() const; - const std::vector<mojom::LocaleInfoPtr>& locale_list() { - return locale_list_; - } + const std::vector<LocaleInfo>& locale_list() { return locale_list_; } std::string current_locale_iso_code() const { return current_locale_iso_code_; } private: - std::vector<mojom::LocaleInfoPtr> locale_list_; + std::vector<LocaleInfo> locale_list_; std::string current_locale_iso_code_;
diff --git a/ash/system/model/system_tray_model.cc b/ash/system/model/system_tray_model.cc index f96b8b1a..4de1cb3 100644 --- a/ash/system/model/system_tray_model.cc +++ b/ash/system/model/system_tray_model.cc
@@ -4,7 +4,6 @@ #include "ash/system/model/system_tray_model.h" -#include "ash/public/interfaces/locale.mojom.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/system/model/clock_model.h" @@ -73,7 +72,7 @@ } void SystemTrayModel::SetLocaleList( - std::vector<mojom::LocaleInfoPtr> locale_list, + std::vector<LocaleInfo> locale_list, const std::string& current_locale_iso_code) { locale()->SetLocaleList(std::move(locale_list), current_locale_iso_code); }
diff --git a/ash/system/model/system_tray_model.h b/ash/system/model/system_tray_model.h index b99cd79..9bb8af1 100644 --- a/ash/system/model/system_tray_model.h +++ b/ash/system/model/system_tray_model.h
@@ -41,7 +41,7 @@ void SetEnterpriseDisplayDomain(const std::string& enterprise_display_domain, bool active_directory_managed) override; void SetPerformanceTracingIconVisible(bool visible) override; - void SetLocaleList(std::vector<mojom::LocaleInfoPtr> locale_list, + void SetLocaleList(std::vector<LocaleInfo> locale_list, const std::string& current_locale_iso_code) override; void ShowUpdateIcon(UpdateSeverity severity, bool factory_reset_required,
diff --git a/ash/system/network/tray_network_state_model.cc b/ash/system/network/tray_network_state_model.cc index 737029e2..09003b00a 100644 --- a/ash/system/network/tray_network_state_model.cc +++ b/ash/system/network/tray_network_state_model.cc
@@ -134,7 +134,7 @@ devices_.clear(); for (auto& device : devices) { NetworkType type = device->type; - if (base::ContainsKey(devices_, type)) + if (base::Contains(devices_, type)) continue; // Ignore multiple entries with the same type. devices_.emplace(std::make_pair(type, std::move(device))); }
diff --git a/ash/system/overview/overview_button_tray.cc b/ash/system/overview/overview_button_tray.cc index 4572bdf..da5f478 100644 --- a/ash/system/overview/overview_button_tray.cc +++ b/ash/system/overview/overview_button_tray.cc
@@ -4,7 +4,7 @@ #include "ash/system/overview/overview_button_tray.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/metrics/user_metrics_recorder.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h"
diff --git a/ash/system/overview/overview_button_tray_unittest.cc b/ash/system/overview/overview_button_tray_unittest.cc index ceb1cf5..d619967 100644 --- a/ash/system/overview/overview_button_tray_unittest.cc +++ b/ash/system/overview/overview_button_tray_unittest.cc
@@ -400,12 +400,7 @@ void SetUp() override { set_start_session(false); OverviewButtonTrayTest::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - OverviewButtonTrayTest::TearDown(); + client_ = BindMockKioskNextShellClient(); } private:
diff --git a/ash/system/palette/palette_tray.cc b/ash/system/palette/palette_tray.cc index f1998614b..7da1b778 100644 --- a/ash/system/palette/palette_tray.cc +++ b/ash/system/palette/palette_tray.cc
@@ -7,7 +7,7 @@ #include <memory> #include "ash/accessibility/accessibility_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/stylus_utils.h" #include "ash/public/cpp/system_tray_client.h"
diff --git a/ash/system/palette/palette_tray_unittest.cc b/ash/system/palette/palette_tray_unittest.cc index 89d000aec..a98387f 100644 --- a/ash/system/palette/palette_tray_unittest.cc +++ b/ash/system/palette/palette_tray_unittest.cc
@@ -775,12 +775,7 @@ void SetUp() override { set_start_session(false); PaletteTrayTest::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - PaletteTrayTest::TearDown(); + client_ = BindMockKioskNextShellClient(); } private:
diff --git a/ash/system/palette/palette_welcome_bubble.cc b/ash/system/palette/palette_welcome_bubble.cc index b21770d37..3e171c30 100644 --- a/ash/system/palette/palette_welcome_bubble.cc +++ b/ash/system/palette/palette_welcome_bubble.cc
@@ -6,7 +6,7 @@ #include <memory> -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/session/session_controller_impl.h"
diff --git a/ash/system/screen_layout_observer.cc b/ash/system/screen_layout_observer.cc index efb78ee..808141e2 100644 --- a/ash/system/screen_layout_observer.cc +++ b/ash/system/screen_layout_observer.cc
@@ -57,8 +57,8 @@ // to empty string if this happens on release build. const display::DisplayIdList id_list = display_manager->GetMirroringDestinationDisplayIdList(); - const bool mirroring = display_manager->IsInMirrorMode() && - base::ContainsValue(id_list, display_id); + const bool mirroring = + display_manager->IsInMirrorMode() && base::Contains(id_list, display_id); DCHECK(!mirroring); if (mirroring) return base::string16();
diff --git a/ash/system/session/logout_button_tray.cc b/ash/system/session/logout_button_tray.cc index 2808a1b..c13275a9 100644 --- a/ash/system/session/logout_button_tray.cc +++ b/ash/system/session/logout_button_tray.cc
@@ -6,7 +6,7 @@ #include <memory> -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/ash_typography.h" #include "ash/resources/vector_icons/vector_icons.h"
diff --git a/ash/system/session/logout_button_tray_unittest.cc b/ash/system/session/logout_button_tray_unittest.cc index e100b20..f4e6550 100644 --- a/ash/system/session/logout_button_tray_unittest.cc +++ b/ash/system/session/logout_button_tray_unittest.cc
@@ -150,12 +150,7 @@ void SetUp() override { LogoutButtonTrayTest::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - LogoutButtonTrayTest::TearDown(); + client_ = BindMockKioskNextShellClient(); } private:
diff --git a/ash/system/status_area_widget.cc b/ash/system/status_area_widget.cc index 6f938c6..f1d61d6 100644 --- a/ash/system/status_area_widget.cc +++ b/ash/system/status_area_widget.cc
@@ -4,7 +4,7 @@ #include "ash/system/status_area_widget.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/session/session_controller_impl.h" #include "ash/shelf/shelf.h" #include "ash/shell.h"
diff --git a/ash/system/unified/current_locale_view.cc b/ash/system/unified/current_locale_view.cc index 79cece38..c80b4dec 100644 --- a/ash/system/unified/current_locale_view.cc +++ b/ash/system/unified/current_locale_view.cc
@@ -37,12 +37,11 @@ label()->SetEnabledColor( TrayIconColor(Shell::Get()->session_controller()->GetSessionState())); - const std::vector<mojom::LocaleInfoPtr>& locales = - locale_model->locale_list(); + const std::vector<LocaleInfo>& locales = locale_model->locale_list(); for (auto& entry : locales) { - if (entry->iso_code == locale_model->current_locale_iso_code()) { + if (entry.iso_code == locale_model->current_locale_iso_code()) { const base::string16 description = l10n_util::GetStringFUTF16( - IDS_ASH_STATUS_TRAY_INDICATOR_LOCALE_TOOLTIP, entry->display_name); + IDS_ASH_STATUS_TRAY_INDICATOR_LOCALE_TOOLTIP, entry.display_name); label()->SetTooltipText(description); label()->SetCustomAccessibleName(description); break;
diff --git a/ash/system/unified/top_shortcuts_view.cc b/ash/system/unified/top_shortcuts_view.cc index 155c5ec..0b5ff81 100644 --- a/ash/system/unified/top_shortcuts_view.cc +++ b/ash/system/unified/top_shortcuts_view.cc
@@ -7,7 +7,7 @@ #include <numeric> #include "ash/accessibility/accessibility_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/ash_view_ids.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h"
diff --git a/ash/system/unified/top_shortcuts_view_unittest.cc b/ash/system/unified/top_shortcuts_view_unittest.cc index 8f72a2af..a105e62 100644 --- a/ash/system/unified/top_shortcuts_view_unittest.cc +++ b/ash/system/unified/top_shortcuts_view_unittest.cc
@@ -35,7 +35,6 @@ } void TearDown() override { - kiosk_next_shell_client_.reset(); controller_.reset(); top_shortcuts_view_.reset(); model_.reset(); @@ -48,7 +47,7 @@ } void CreateKioskNextSession() { - kiosk_next_shell_client_ = std::make_unique<MockKioskNextShellClient>(); + kiosk_next_shell_client_ = BindMockKioskNextShellClient(); LogInKioskNextUser(GetSessionControllerClient()); }
diff --git a/ash/system/unified/unified_system_tray_controller.cc b/ash/system/unified/unified_system_tray_controller.cc index 2a8bd67..d4e0d712 100644 --- a/ash/system/unified/unified_system_tray_controller.cc +++ b/ash/system/unified/unified_system_tray_controller.cc
@@ -4,7 +4,7 @@ #include "ash/system/unified/unified_system_tray_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/metrics/user_metrics_action.h" #include "ash/metrics/user_metrics_recorder.h" #include "ash/public/cpp/system_tray_client.h"
diff --git a/ash/system/virtual_keyboard/virtual_keyboard_tray.cc b/ash/system/virtual_keyboard/virtual_keyboard_tray.cc index 3266ad0..56c3628 100644 --- a/ash/system/virtual_keyboard/virtual_keyboard_tray.cc +++ b/ash/system/virtual_keyboard/virtual_keyboard_tray.cc
@@ -8,7 +8,7 @@ #include "ash/accessibility/accessibility_controller.h" #include "ash/keyboard/ui/keyboard_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h" #include "ash/shelf/shelf.h"
diff --git a/ash/system/virtual_keyboard/virtual_keyboard_tray_unittest.cc b/ash/system/virtual_keyboard/virtual_keyboard_tray_unittest.cc index 6425d5a..22fd00ba 100644 --- a/ash/system/virtual_keyboard/virtual_keyboard_tray_unittest.cc +++ b/ash/system/virtual_keyboard/virtual_keyboard_tray_unittest.cc
@@ -76,12 +76,7 @@ void SetUp() override { set_start_session(false); AshTestBase::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - AshTestBase::TearDown(); + client_ = BindMockKioskNextShellClient(); } void EnableVirtualKeyboardForActiveUser() {
diff --git a/ash/wm/ash_focus_rules.cc b/ash/wm/ash_focus_rules.cc index 5d274825..434655f2 100644 --- a/ash/wm/ash_focus_rules.cc +++ b/ash/wm/ash_focus_rules.cc
@@ -64,12 +64,11 @@ // The window must exist within a container that supports activation. // The window cannot be blocked by a modal transient. - return base::ContainsValue(activatable_container_ids_, - window->parent()->id()); + return base::Contains(activatable_container_ids_, window->parent()->id()); } bool AshFocusRules::SupportsChildActivation(const aura::Window* window) const { - return base::ContainsValue(activatable_container_ids_, window->id()); + return base::Contains(activatable_container_ids_, window->id()); } bool AshFocusRules::IsWindowConsideredVisibleForActivation(
diff --git a/ash/wm/desks/desk_mini_view_animations.cc b/ash/wm/desks/desk_mini_view_animations.cc index c9cd7c61..462af939 100644 --- a/ash/wm/desks/desk_mini_view_animations.cc +++ b/ash/wm/desks/desk_mini_view_animations.cc
@@ -109,7 +109,7 @@ begin_transform.Translate(shift_x, 0); for (const auto& mini_view : bar_view->mini_views()) { - const bool is_new = base::ContainsValue(new_mini_views, mini_view.get()); + const bool is_new = base::Contains(new_mini_views, mini_view.get()); ui::Layer* layer = mini_view->layer(); if (is_new)
diff --git a/ash/wm/mru_window_tracker.cc b/ash/wm/mru_window_tracker.cc index 7be9e7f..25a4733 100644 --- a/ash/wm/mru_window_tracker.cc +++ b/ash/wm/mru_window_tracker.cc
@@ -156,7 +156,7 @@ // Only add windows that have not been added previously from // |mru_windows| (if available). - if (mru_windows && base::ContainsValue(*mru_windows, child)) + if (mru_windows && base::Contains(*mru_windows, child)) continue; windows.emplace_back(child);
diff --git a/ash/wm/overview/caption_container_view.cc b/ash/wm/overview/caption_container_view.cc index 1f0a0a7..b80dca8d 100644 --- a/ash/wm/overview/caption_container_view.cc +++ b/ash/wm/overview/caption_container_view.cc
@@ -345,8 +345,7 @@ // Do not process or accept press down events that are on the border. static ui::EventType press_types[] = {ui::ET_GESTURE_TAP_DOWN, ui::ET_MOUSE_PRESSED}; - if (event.IsLocatedEvent() && - base::ContainsValue(press_types, event.type())) { + if (event.IsLocatedEvent() && base::Contains(press_types, event.type())) { gfx::Rect inset_bounds = GetLocalBounds(); inset_bounds.Inset(gfx::Insets(kMarginDp)); if (!inset_bounds.Contains(event.AsLocatedEvent()->location()))
diff --git a/ash/wm/overview/overview_grid.cc b/ash/wm/overview/overview_grid.cc index 40c73b5..1a9042b 100644 --- a/ash/wm/overview/overview_grid.cc +++ b/ash/wm/overview/overview_grid.cc
@@ -8,7 +8,7 @@ #include <functional> #include <utility> -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/metrics/histogram_macros.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/fps_counter.h" @@ -636,6 +636,8 @@ overview_session_->AddItem(drop_target_widget_->GetNativeWindow(), /*reposition=*/true, /*animate=*/false, /*ignored_items=*/{dragged_item}, position); + if (selection_widget_ && selected_index_ >= position) + ++selected_index_; // This part is necessary because |OverviewItem::OnSelectorItemDragStarted| is // called on all overview items before the drop target exists among them. That // is because |AddDropTargetForDraggingFromOverview| is only called for drag @@ -646,7 +648,10 @@ void OverviewGrid::RemoveDropTarget() { DCHECK(drop_target_widget_); - overview_session_->RemoveItem(GetDropTarget()); + OverviewItem* drop_target = GetDropTarget(); + if (selection_widget_ && selected_index_ >= GetOverviewItemIndex(drop_target)) + --selected_index_; + overview_session_->RemoveItem(drop_target); drop_target_widget_.reset(); } @@ -734,6 +739,8 @@ drop_target_widget_ = CreateDropTargetWidget(dragged_window, animate); overview_session_->AddItem(drop_target_widget_->GetNativeWindow(), /*reposition=*/true, animate); + if (selection_widget_) + ++selected_index_; // Stack the |dragged_window| at top during drag. dragged_window->parent()->StackChildAtTop(dragged_window);
diff --git a/ash/wm/overview/overview_session.cc b/ash/wm/overview/overview_session.cc index 994d331..980ddd6 100644 --- a/ash/wm/overview/overview_session.cc +++ b/ash/wm/overview/overview_session.cc
@@ -819,7 +819,6 @@ // we let the app list to handle the key event. // TODO(crbug.com/952315): Explore better ways to handle this splitview + // overview + applist case. - // TODO(crbug.com/969899): Fix for tablet mode. Shell* shell = Shell::Get(); if (shell->app_list_controller() && shell->app_list_controller()->IsVisible() &&
diff --git a/ash/wm/overview/overview_session_unittest.cc b/ash/wm/overview/overview_session_unittest.cc index 7126dcb..51551e65 100644 --- a/ash/wm/overview/overview_session_unittest.cc +++ b/ash/wm/overview/overview_session_unittest.cc
@@ -29,6 +29,7 @@ #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/wm/desks/desks_util.h" +#include "ash/wm/drag_window_resizer.h" #include "ash/wm/overview/caption_container_view.h" #include "ash/wm/overview/overview_constants.h" #include "ash/wm/overview/overview_controller.h" @@ -42,6 +43,7 @@ #include "ash/wm/resize_shadow_controller.h" #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/splitview/split_view_divider.h" +#include "ash/wm/splitview/split_view_drag_indicators.h" #include "ash/wm/splitview/split_view_utils.h" #include "ash/wm/tablet_mode/tablet_mode_browser_window_drag_delegate.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" @@ -347,7 +349,7 @@ void CheckOverviewEnterExitHistogram(const char* trace, std::vector<int>&& enter_counts, std::vector<int>&& exit_counts) { - DCHECK(!base::ContainsValue(trace_names_, trace)) << trace; + DCHECK(!base::Contains(trace_names_, trace)) << trace; trace_names_.push_back(trace); { SCOPED_TRACE(trace + std::string(".Enter")); @@ -1421,6 +1423,52 @@ EXPECT_FALSE(GetDropTarget(1)); } +// Test that |OverviewGrid::selected_index_| is updated with the drop target for +// dragging from overview. +TEST_F(OverviewSessionTest, + SelectionUpdatedWithDropTargetForDraggingFromOverview) { + EnterTabletMode(); + std::unique_ptr<aura::Window> window4(CreateTestWindow()); + std::unique_ptr<aura::Window> window3(CreateTestWindow()); + std::unique_ptr<aura::Window> window2(CreateTestWindow()); + std::unique_ptr<aura::Window> window1(CreateTestWindow()); + ToggleOverview(); + OverviewItem* item2 = GetWindowItemForWindow(0, window2.get()); + const gfx::PointF drag_start_point = item2->target_bounds().CenterPoint(); + const gfx::PointF drag_end_point = + drag_start_point + gfx::Vector2dF(5.f, 0.f); + const auto drag_item_and_check_selection = + [this, &drag_start_point, &drag_end_point](aura::Window* selected_window, + OverviewItem* dragged_item) { + EXPECT_TRUE(SelectWindow(selected_window)); + overview_session()->InitiateDrag(dragged_item, drag_start_point); + overview_session()->Drag(dragged_item, drag_end_point); + EXPECT_EQ(selected_window, GetSelectedWindow()); + overview_session()->CompleteDrag(dragged_item, drag_end_point); + EXPECT_EQ(selected_window, GetSelectedWindow()); + }; + // Test the case where |OverviewGrid::selected_index_| is strictly less than + // the index of the dragged item. + drag_item_and_check_selection(window1.get(), item2); + // Test the case where |OverviewGrid::selected_index_| is equal to the index + // of the dragged item. + drag_item_and_check_selection(window2.get(), item2); + // Test the case where |OverviewGrid::selected_index_| is equal to the index + // where the drop target is to be inserted. + drag_item_and_check_selection(window3.get(), item2); + // Test the case where |OverviewGrid::selected_index_| is strictly greater + // than the index where the drop target is to be inserted. + drag_item_and_check_selection(window4.get(), item2); + + // Test the case where the drop target becomes selected during the drag. + EXPECT_TRUE(SelectWindow(window4.get())); + overview_session()->InitiateDrag(item2, drag_start_point); + overview_session()->Drag(item2, drag_end_point); + EXPECT_TRUE(SelectWindow(GetDropTarget(0)->GetWindow())); + overview_session()->CompleteDrag(item2, drag_end_point); + EXPECT_EQ(window2.get(), GetSelectedWindow()); +} + namespace { // A simple window delegate that returns the specified hit-test code when @@ -1628,8 +1676,18 @@ SendKey(ui::VKEY_BROWSER_BACK); EXPECT_FALSE(overview_controller()->InOverviewSession()); - // TODO(crbug.com/969899): Test in tablet mode, and ensure escape/back does - // not exit single spitview mode with no other windows in overview. + // Tests that in tablet mode, if we snap the only overview window, we cannot + // exit overview mode. + EnterTabletMode(); + ToggleOverview(); + ASSERT_TRUE(overview_controller()->InOverviewSession()); + Shell::Get()->split_view_controller()->SnapWindow(window.get(), + SplitViewController::LEFT); + ASSERT_TRUE(overview_controller()->InOverviewSession()); + SendKey(ui::VKEY_ESCAPE); + EXPECT_TRUE(overview_controller()->InOverviewSession()); + SendKey(ui::VKEY_BROWSER_BACK); + EXPECT_TRUE(overview_controller()->InOverviewSession()); } // Regression test for clusterfuzz crash. https://crbug.com/920568 @@ -4137,7 +4195,7 @@ std::vector<aura::Window*> window_list = overview_controller()->GetWindowsListInOverviewGridsForTest(); EXPECT_EQ(2u, window_list.size()); - EXPECT_FALSE(base::ContainsValue(window_list, window1.get())); + EXPECT_FALSE(base::Contains(window_list, window1.get())); EXPECT_TRUE(wm::IsActiveWindow(window1.get())); // Drag the divider to the left edge. @@ -4154,7 +4212,7 @@ EXPECT_FALSE(split_view_controller()->InSplitViewMode()); window_list = overview_controller()->GetWindowsListInOverviewGridsForTest(); EXPECT_EQ(3u, window_list.size()); - EXPECT_TRUE(base::ContainsValue(window_list, window1.get())); + EXPECT_TRUE(base::Contains(window_list, window1.get())); EXPECT_FALSE(wm::IsActiveWindow(window1.get())); } @@ -4415,6 +4473,40 @@ EXPECT_TRUE(InOverviewSession()); } +// Test that |OverviewGrid::selected_index_| is updated with the drop target for +// dragging a snapped window from the top. +TEST_F(SplitViewOverviewSessionTest, + SelectionUpdatedWithDropTargetForDraggingSnappedWindowFromTop) { + std::unique_ptr<aura::Window> window2(CreateTestWindow()); + window2->SetProperty(aura::client::kAppType, + static_cast<int>(AppType::BROWSER)); + ASSERT_TRUE(CanSnapInSplitview(window2.get())); + std::unique_ptr<aura::Window> window1(CreateTestWindow()); + ToggleOverview(); + split_view_controller()->SnapWindow(window2.get(), SplitViewController::LEFT); + EXPECT_TRUE(SelectWindow(window1.get())); + std::unique_ptr<WindowResizer> resizer = + CreateWindowResizer(window2.get(), gfx::Point(300, 0), HTCAPTION, + ::wm::WINDOW_MOVE_SOURCE_TOUCH); + ASSERT_TRUE(resizer); + TabletModeWindowDragDelegate* drag_delegate = + static_cast<TabletModeWindowDragController*>( + static_cast<DragWindowResizer*>(resizer.get()) + ->next_window_resizer_for_testing()) + ->drag_delegate_for_testing(); + drag_delegate->set_drag_start_deadline_for_testing(base::Time::Now()); + SplitViewDragIndicators* drag_indicators = + drag_delegate->split_view_drag_indicators_for_testing(); + EXPECT_EQ(IndicatorState::kNone, drag_indicators->current_indicator_state()); + EXPECT_EQ(window1.get(), GetSelectedWindow()); + resizer->Drag(gfx::Point(300, 400), ui::EF_NONE); + EXPECT_EQ(IndicatorState::kDragArea, + drag_indicators->current_indicator_state()); + EXPECT_TRUE(InOverviewSession()); + EXPECT_EQ(nullptr, GetSelectedWindow()); + resizer->CompleteDrag(); +} + // Test the split view and overview functionalities in clamshell mode. Split // view is only active when overview is active in clamshell mode. class SplitViewOverviewSessionInClamshellTest
diff --git a/ash/wm/overview/overview_window_drag_controller_unittest.cc b/ash/wm/overview/overview_window_drag_controller_unittest.cc index 7930d1e5..bae7edb 100644 --- a/ash/wm/overview/overview_window_drag_controller_unittest.cc +++ b/ash/wm/overview/overview_window_drag_controller_unittest.cc
@@ -150,7 +150,7 @@ event_generator->ReleaseLeftButton(); waiter.Wait(); EXPECT_FALSE(overview_controller->InOverviewSession()); - EXPECT_FALSE(base::ContainsValue( + EXPECT_FALSE(base::Contains( Shell::Get()->mru_window_tracker()->BuildMruWindowList(kAllDesks), window_ptr)); }
diff --git a/ash/wm/splitview/split_view_controller.cc b/ash/wm/splitview/split_view_controller.cc index c4c6ec47..3db41ca 100644 --- a/ash/wm/splitview/split_view_controller.cc +++ b/ash/wm/splitview/split_view_controller.cc
@@ -934,7 +934,7 @@ } // Only windows in MRU list can be snapped. - if (!base::ContainsValue( + if (!base::Contains( Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk), gained_active)) { return;
diff --git a/ash/wm/splitview/split_view_controller_unittest.cc b/ash/wm/splitview/split_view_controller_unittest.cc index 0d08de5..6106051 100644 --- a/ash/wm/splitview/split_view_controller_unittest.cc +++ b/ash/wm/splitview/split_view_controller_unittest.cc
@@ -222,7 +222,7 @@ void CheckOverviewEnterExitHistogram(const char* trace, std::vector<int>&& enter_counts, std::vector<int>&& exit_counts) { - DCHECK(!base::ContainsValue(trace_names_, trace)) << trace; + DCHECK(!base::Contains(trace_names_, trace)) << trace; trace_names_.push_back(trace); { SCOPED_TRACE(trace + std::string(".Enter")); @@ -580,8 +580,8 @@ CheckOverviewEnterExitHistogram("EnterInSplitView", {0, 1}, {0, 0}); EXPECT_EQ(split_view_controller()->state(), SplitViewState::kLeftSnapped); EXPECT_FALSE( - base::ContainsValue(GetWindowsInOverviewGrids(), - split_view_controller()->GetDefaultSnappedWindow())); + base::Contains(GetWindowsInOverviewGrids(), + split_view_controller()->GetDefaultSnappedWindow())); ToggleOverview(); CheckOverviewEnterExitHistogram("ExitInSplitView", {0, 1}, {0, 1}); @@ -4615,15 +4615,10 @@ SplitViewAppDraggingTest::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); + client_ = BindMockKioskNextShellClient(); LogInKioskNextUser(GetSessionControllerClient()); } - void TearDown() override { - client_.reset(); - SplitViewAppDraggingTest::TearDown(); - } - private: base::test::ScopedFeatureList scoped_feature_list_; std::unique_ptr<MockKioskNextShellClient> client_;
diff --git a/ash/wm/splitview/split_view_divider.cc b/ash/wm/splitview/split_view_divider.cc index b2fe1fca..bedb6a2b 100644 --- a/ash/wm/splitview/split_view_divider.cc +++ b/ash/wm/splitview/split_view_divider.cc
@@ -336,7 +336,7 @@ } void SplitViewDivider::AddObservedWindow(aura::Window* window) { - if (!base::ContainsValue(observed_windows_, window)) { + if (!base::Contains(observed_windows_, window)) { window->AddObserver(this); ::wm::TransientWindowManager::GetOrCreate(window)->AddObserver(this); observed_windows_.push_back(window); @@ -401,8 +401,7 @@ aura::Window* gained_active, aura::Window* lost_active) { if (!is_dragging_window_ && - (!gained_active || - base::ContainsValue(observed_windows_, gained_active))) { + (!gained_active || base::Contains(observed_windows_, gained_active))) { SetAlwaysOnTop(true); } else { // If |gained_active| is not one of the observed windows, or there is one
diff --git a/ash/wm/splitview/split_view_utils.cc b/ash/wm/splitview/split_view_utils.cc index 0a63faf2..b9fb0d5c 100644 --- a/ash/wm/splitview/split_view_utils.cc +++ b/ash/wm/splitview/split_view_utils.cc
@@ -6,7 +6,7 @@ #include "ash/accessibility/accessibility_controller.h" #include "ash/display/screen_orientation_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_switches.h" #include "ash/screen_util.h"
diff --git a/ash/wm/switchable_windows.cc b/ash/wm/switchable_windows.cc index 149e2fc..1c7c31f 100644 --- a/ash/wm/switchable_windows.cc +++ b/ash/wm/switchable_windows.cc
@@ -76,7 +76,7 @@ return false; const int shell_window_id = window->id(); - return base::ContainsValue(GetSwitchableContainersIds(), shell_window_id); + return base::Contains(GetSwitchableContainersIds(), shell_window_id); } } // namespace wm
diff --git a/ash/wm/system_modal_container_layout_manager.cc b/ash/wm/system_modal_container_layout_manager.cc index a980e2c..897223be 100644 --- a/ash/wm/system_modal_container_layout_manager.cc +++ b/ash/wm/system_modal_container_layout_manager.cc
@@ -63,7 +63,7 @@ return; if (window->IsVisible()) { - DCHECK(!base::ContainsValue(modal_windows_, window)); + DCHECK(!base::Contains(modal_windows_, window)); AddModalWindow(window); } else { if (RemoveModalWindow(window)) @@ -121,7 +121,7 @@ return; if (window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM) { - if (base::ContainsValue(modal_windows_, window)) + if (base::Contains(modal_windows_, window)) return; AddModalWindow(window); } else { @@ -201,7 +201,7 @@ capture_window->ReleaseCapture(); } DCHECK(window->IsVisible()); - DCHECK(!base::ContainsValue(modal_windows_, window)); + DCHECK(!base::Contains(modal_windows_, window)); modal_windows_.push_back(window); // Create the modal background on all displays for |window|.
diff --git a/ash/wm/tablet_mode/tablet_mode_controller.cc b/ash/wm/tablet_mode/tablet_mode_controller.cc index f02a8a8..cb2e6298 100644 --- a/ash/wm/tablet_mode/tablet_mode_controller.cc +++ b/ash/wm/tablet_mode/tablet_mode_controller.cc
@@ -8,7 +8,7 @@ #include <string> #include <utility> -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" +#include "ash/kiosk_next/kiosk_next_shell_controller.h" #include "ash/public/cpp/ash_switches.h" #include "ash/public/cpp/fps_counter.h" #include "ash/public/cpp/tablet_mode.h"
diff --git a/ash/wm/tablet_mode/tablet_mode_window_manager.cc b/ash/wm/tablet_mode/tablet_mode_window_manager.cc index 987aa873..41d2adf 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_manager.cc +++ b/ash/wm/tablet_mode/tablet_mode_window_manager.cc
@@ -161,7 +161,7 @@ } bool TabletModeWindowManager::IsTrackingWindow(aura::Window* window) { - return base::ContainsKey(window_state_map_, window); + return base::Contains(window_state_map_, window); } void TabletModeWindowManager::AddWindow(aura::Window* window) { @@ -246,7 +246,7 @@ // container window can be removed on display destruction. window->RemoveObserver(this); observed_container_windows_.erase(window); - } else if (base::ContainsKey(added_windows_, window)) { + } else if (base::Contains(added_windows_, window)) { // Added window was destroyed before being shown. added_windows_.erase(window); window->RemoveObserver(this); @@ -261,12 +261,12 @@ const HierarchyChangeParams& params) { // A window can get removed and then re-added by a drag and drop operation. if (params.new_parent && IsContainerWindow(params.new_parent) && - !base::ContainsKey(window_state_map_, params.target)) { + !base::Contains(window_state_map_, params.target)) { // Don't register the window if the window is invisible. Instead, // wait until it becomes visible because the client may update the // flag to control if the window should be added. if (!params.target->IsVisible()) { - if (!base::ContainsKey(added_windows_, params.target)) { + if (!base::Contains(added_windows_, params.target)) { added_windows_.insert(params.target); params.target->AddObserver(this); } @@ -275,7 +275,7 @@ TrackWindow(params.target); // When the state got added, the "WM_EVENT_ADDED_TO_WORKSPACE" event got // already sent and we have to notify our state again. - if (base::ContainsKey(window_state_map_, params.target)) { + if (base::Contains(window_state_map_, params.target)) { wm::WMEvent event(wm::WM_EVENT_ADDED_TO_WORKSPACE); wm::GetWindowState(params.target)->OnWMEvent(&event); } @@ -320,7 +320,7 @@ return; if (IsContainerWindow(window->parent()) && - base::ContainsKey(added_windows_, window) && visible) { + base::Contains(added_windows_, window) && visible) { added_windows_.erase(window); window->RemoveObserver(this); TrackWindow(window); @@ -582,7 +582,7 @@ // windows. for (aura::Window* root : Shell::GetAllRootWindows()) { for (auto* desk_container : desks_util::GetDesksContainers(root)) { - DCHECK(!base::ContainsKey(observed_container_windows_, desk_container)); + DCHECK(!base::Contains(observed_container_windows_, desk_container)); desk_container->AddObserver(this); observed_container_windows_.insert(desk_container); } @@ -603,7 +603,7 @@ } bool TabletModeWindowManager::IsContainerWindow(aura::Window* window) { - return base::ContainsKey(observed_container_windows_, window); + return base::Contains(observed_container_windows_, window); } void TabletModeWindowManager::EnableBackdropBehindTopWindowOnEachDisplay(
diff --git a/ash/wm/window_cycle_controller_unittest.cc b/ash/wm/window_cycle_controller_unittest.cc index fd52d84..8512f8b 100644 --- a/ash/wm/window_cycle_controller_unittest.cc +++ b/ash/wm/window_cycle_controller_unittest.cc
@@ -711,10 +711,10 @@ // All desks' windows are included in the cycle list. auto cycle_windows = GetWindows(cycle_controller); EXPECT_EQ(4u, cycle_windows.size()); - EXPECT_TRUE(base::ContainsValue(cycle_windows, win0.get())); - EXPECT_TRUE(base::ContainsValue(cycle_windows, win1.get())); - EXPECT_TRUE(base::ContainsValue(cycle_windows, win2.get())); - EXPECT_TRUE(base::ContainsValue(cycle_windows, win3.get())); + EXPECT_TRUE(base::Contains(cycle_windows, win0.get())); + EXPECT_TRUE(base::Contains(cycle_windows, win1.get())); + EXPECT_TRUE(base::Contains(cycle_windows, win2.get())); + EXPECT_TRUE(base::Contains(cycle_windows, win3.get())); // The MRU order is {win3, win2, win1, win0}. We're now at win2. Cycling one // more time and completing the cycle, will activate win1 which exists on a
diff --git a/ash/wm/window_util.cc b/ash/wm/window_util.cc index 86b9c2e..ecaef7cc 100644 --- a/ash/wm/window_util.cc +++ b/ash/wm/window_util.cc
@@ -296,7 +296,7 @@ for (auto it = out_window_list->begin(); it != out_window_list->end();) { aura::Window* transient_root = ::wm::GetTransientRoot(*it); if (*it != transient_root && - base::ContainsValue(*out_window_list, transient_root)) { + base::Contains(*out_window_list, transient_root)) { it = out_window_list->erase(it); } else { ++it;
diff --git a/ash/wm/window_util_unittest.cc b/ash/wm/window_util_unittest.cc index ef71b48c..f51ef57 100644 --- a/ash/wm/window_util_unittest.cc +++ b/ash/wm/window_util_unittest.cc
@@ -188,8 +188,8 @@ window_list.push_back(descendant2.get()); RemoveTransientDescendants(&window_list); ASSERT_EQ(2u, window_list.size()); - ASSERT_TRUE(base::ContainsValue(window_list, window1.get())); - ASSERT_TRUE(base::ContainsValue(window_list, window2.get())); + ASSERT_TRUE(base::Contains(window_list, window1.get())); + ASSERT_TRUE(base::Contains(window_list, window2.get())); // Create a window which has a transient parent that is not in |window_list|. // Test that the window is not removed when calling
diff --git a/ash/wm/workspace/multi_window_resize_controller_unittest.cc b/ash/wm/workspace/multi_window_resize_controller_unittest.cc index 5b6fd5c7..6cf7c08 100644 --- a/ash/wm/workspace/multi_window_resize_controller_unittest.cc +++ b/ash/wm/workspace/multi_window_resize_controller_unittest.cc
@@ -83,8 +83,7 @@ resize_controller_->windows_.window2 == window) { return true; } - return base::ContainsValue(resize_controller_->windows_.other_windows, - window); + return base::Contains(resize_controller_->windows_.other_windows, window); } bool IsOverWindows(const gfx::Point& loc) {
diff --git a/ash/wm/workspace/workspace_event_handler_unittest.cc b/ash/wm/workspace/workspace_event_handler_unittest.cc index 8f534cb..0297833 100644 --- a/ash/wm/workspace/workspace_event_handler_unittest.cc +++ b/ash/wm/workspace/workspace_event_handler_unittest.cc
@@ -79,7 +79,7 @@ ~WindowPropertyObserver() override { window_->RemoveObserver(this); } bool DidPropertyChange(const void* property) const { - return base::ContainsValue(properties_changed_, property); + return base::Contains(properties_changed_, property); } private:
diff --git a/ash/wm/workspace/workspace_window_resizer.cc b/ash/wm/workspace/workspace_window_resizer.cc index b3def8d..c45d7f9 100644 --- a/ash/wm/workspace/workspace_window_resizer.cc +++ b/ash/wm/workspace/workspace_window_resizer.cc
@@ -902,7 +902,7 @@ for (auto i = children.rbegin(); i != children.rend() && !matcher.AreEdgesObscured(); ++i) { // Ignore already attached windows. - if (base::ContainsValue(attached_windows_, *i)) + if (base::Contains(attached_windows_, *i)) continue; wm::WindowState* other_state = wm::GetWindowState(*i);
diff --git a/base/BUILD.gn b/base/BUILD.gn index 702655d..b6e9a1a 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -2425,6 +2425,7 @@ "android/application_status_listener_unittest.cc", "android/child_process_unittest.cc", "android/content_uri_utils_unittest.cc", + "android/java_handler_thread_unittest.cc", "android/jni_android_unittest.cc", "android/jni_array_unittest.cc", "android/jni_string_unittest.cc",
diff --git a/base/allocator/allocator_interception_mac.mm b/base/allocator/allocator_interception_mac.mm index 0f5f8608..9db4dc5 100644 --- a/base/allocator/allocator_interception_mac.mm +++ b/base/allocator/allocator_interception_mac.mm
@@ -211,7 +211,7 @@ // === Core Foundation CFAllocators === bool CanGetContextForCFAllocator() { - return !base::mac::IsOSLaterThan10_14_DontCallThis(); + return !base::mac::IsOSLaterThan10_15_DontCallThis(); } CFAllocatorContext* ContextForCFAllocator(CFAllocatorRef allocator) {
diff --git a/base/android/java_handler_thread.cc b/base/android/java_handler_thread.cc index 19f6995..9248ef04 100644 --- a/base/android/java_handler_thread.cc +++ b/base/android/java_handler_thread.cc
@@ -9,8 +9,10 @@ #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/bind.h" +#include "base/message_loop/message_pump.h" #include "base/run_loop.h" #include "base/synchronization/waitable_event.h" +#include "base/task/sequence_manager/sequence_manager_impl.h" #include "base/threading/platform_thread_internal_posix.h" #include "base/threading/thread_id_name_manager.h" #include "base/threading/thread_restrictions.h" @@ -39,22 +41,22 @@ JavaHandlerThread::~JavaHandlerThread() { JNIEnv* env = base::android::AttachCurrentThread(); DCHECK(!Java_JavaHandlerThread_isAlive(env, java_thread_)); - DCHECK(!message_loop_ || message_loop_->IsAborted()); + DCHECK(!task_environment_ || task_environment_->pump->IsAborted()); // TODO(mthiesse): We shouldn't leak the MessageLoop as this could affect // future tests. - if (message_loop_ && message_loop_->IsAborted()) { - // When the message loop has been aborted due to a crash, we intentionally - // leak the message loop because the message loop hasn't been shut down + if (task_environment_ && task_environment_->pump->IsAborted()) { + // When the Pump has been aborted due to a crash, we intentionally leak the + // SequenceManager because the SequenceManager hasn't been shut down // properly and would trigger DCHECKS. This should only happen in tests, // where we handle the exception instead of letting it take down the // process. - message_loop_.release(); + task_environment_.release(); } } void JavaHandlerThread::Start() { // Check the thread has not already been started. - DCHECK(!message_loop_); + DCHECK(!task_environment_); JNIEnv* env = base::android::AttachCurrentThread(); base::WaitableEvent initialize_event( @@ -88,9 +90,7 @@ if (name_) PlatformThread::SetName(name_); - // TYPE_JAVA to get the Android java style message loop. - message_loop_ = - std::make_unique<MessageLoopForUI>(base::MessageLoop::TYPE_JAVA); + task_environment_ = std::make_unique<TaskEnvironment>(); Init(); reinterpret_cast<base::WaitableEvent*>(event)->Signal(); } @@ -98,7 +98,7 @@ void JavaHandlerThread::OnLooperStopped(JNIEnv* env, const JavaParamRef<jobject>& obj) { DCHECK(task_runner()->BelongsToCurrentThread()); - message_loop_.reset(); + task_environment_.reset(); CleanUp(); @@ -107,7 +107,7 @@ base::PlatformThread::CurrentId()); } -void JavaHandlerThread::StopMessageLoopForTesting() { +void JavaHandlerThread::StopSequenceManagerForTesting() { DCHECK(task_runner()->BelongsToCurrentThread()); StopOnThread(); } @@ -133,7 +133,8 @@ void JavaHandlerThread::StopOnThread() { DCHECK(task_runner()->BelongsToCurrentThread()); - message_loop_->QuitWhenIdle(base::BindOnce( + DCHECK(task_environment_); + task_environment_->pump->QuitWhenIdle(base::BindOnce( &JavaHandlerThread::QuitThreadSafely, base::Unretained(this))); } @@ -144,5 +145,27 @@ reinterpret_cast<intptr_t>(this)); } +JavaHandlerThread::TaskEnvironment::TaskEnvironment() + : sequence_manager(sequence_manager::CreateUnboundSequenceManager( + sequence_manager::SequenceManager::Settings::Builder() + .SetMessagePumpType(base::MessagePump::Type::JAVA) + .Build())), + default_task_queue(sequence_manager->CreateTaskQueue( + sequence_manager::TaskQueue::Spec("default_tq"))) { + // TYPE_JAVA to get the Android java style message loop. + std::unique_ptr<MessagePump> message_pump = + MessagePump::Create(base::MessagePump::Type::JAVA); + pump = static_cast<MessagePumpForUI*>(message_pump.get()); + + // We must set SetTaskRunner before binding because the Android UI pump + // creates a RunLoop which samples ThreadTaskRunnerHandle::Get. + static_cast<sequence_manager::internal::SequenceManagerImpl*>( + sequence_manager.get()) + ->SetTaskRunner(default_task_queue->task_runner()); + sequence_manager->BindToMessagePump(std::move(message_pump)); +} + +JavaHandlerThread::TaskEnvironment::~TaskEnvironment() = default; + } // namespace android } // namespace base
diff --git a/base/android/java_handler_thread.h b/base/android/java_handler_thread.h index d1dcf2e..a21ff27 100644 --- a/base/android/java_handler_thread.h +++ b/base/android/java_handler_thread.h
@@ -10,12 +10,14 @@ #include <memory> #include "base/android/scoped_java_ref.h" -#include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" +#include "base/task/sequence_manager/sequence_manager.h" +#include "base/task/sequence_manager/task_queue.h" +#include "base/threading/thread_task_runner_handle.h" namespace base { -class MessageLoop; +class MessagePumpForUI; namespace android { @@ -37,13 +39,12 @@ const base::android::ScopedJavaLocalRef<jobject>& obj); virtual ~JavaHandlerThread(); - // Called from any thread. - base::MessageLoop* message_loop() const { return message_loop_.get(); } - // Gets the TaskRunner associated with the message loop. // Called from any thread. scoped_refptr<SingleThreadTaskRunner> task_runner() const { - return message_loop_ ? message_loop_->task_runner() : nullptr; + return task_environment_ + ? task_environment_->default_task_queue->task_runner() + : nullptr; } // Called from the parent thread. @@ -59,7 +60,7 @@ void OnLooperStopped(JNIEnv* env, const JavaParamRef<jobject>& obj); // Called from this thread. - void StopMessageLoopForTesting(); + void StopSequenceManagerForTesting(); // Called from this thread. void JoinForTesting(); @@ -70,6 +71,19 @@ ScopedJavaLocalRef<jthrowable> GetUncaughtExceptionIfAny(); protected: + // Struct exists so JavaHandlerThread destructor can intentionally leak in an + // abort scenario. + struct TaskEnvironment { + TaskEnvironment(); + ~TaskEnvironment(); + + std::unique_ptr<sequence_manager::SequenceManager> sequence_manager; + scoped_refptr<sequence_manager::TaskQueue> default_task_queue; + MessagePumpForUI* pump = nullptr; + }; + + TaskEnvironment* task_environment() const { return task_environment_.get(); } + // Semantically the same as base::Thread#Init(), but unlike base::Thread the // Android Looper will already be running. This Init() call will still run // before other tasks are posted to the thread. @@ -79,7 +93,7 @@ // loop ends. The Android Looper will also have been quit by this point. virtual void CleanUp() {} - std::unique_ptr<base::MessageLoopForUI> message_loop_; + std::unique_ptr<TaskEnvironment> task_environment_; private: void StartMessageLoop();
diff --git a/base/android/java_handler_thread_unittest.cc b/base/android/java_handler_thread_unittest.cc new file mode 100644 index 0000000..66ab184 --- /dev/null +++ b/base/android/java_handler_thread_unittest.cc
@@ -0,0 +1,150 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/android/java_handler_thread.h" + +#include "base/synchronization/waitable_event.h" +#include "base/task/sequence_manager/sequence_manager_impl.h" +#include "base/test/android/java_handler_thread_helpers.h" +#include "base/test/bind_test_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { +namespace { + +class JavaHandlerThreadForTest : public android::JavaHandlerThread { + public: + explicit JavaHandlerThreadForTest( + const char* name, + base::ThreadPriority priority = base::ThreadPriority::NORMAL) + : android::JavaHandlerThread(name, priority) {} + + using android::JavaHandlerThread::task_environment; + using android::JavaHandlerThread::TaskEnvironment; +}; + +class DummyTaskObserver : public MessageLoop::TaskObserver { + public: + explicit DummyTaskObserver(int num_tasks) + : num_tasks_started_(0), num_tasks_processed_(0), num_tasks_(num_tasks) {} + + DummyTaskObserver(int num_tasks, int num_tasks_started) + : num_tasks_started_(num_tasks_started), + num_tasks_processed_(0), + num_tasks_(num_tasks) {} + + ~DummyTaskObserver() override = default; + + void WillProcessTask(const PendingTask& pending_task) override { + num_tasks_started_++; + EXPECT_LE(num_tasks_started_, num_tasks_); + EXPECT_EQ(num_tasks_started_, num_tasks_processed_ + 1); + } + + void DidProcessTask(const PendingTask& pending_task) override { + num_tasks_processed_++; + EXPECT_LE(num_tasks_started_, num_tasks_); + EXPECT_EQ(num_tasks_started_, num_tasks_processed_); + } + + int num_tasks_started() const { return num_tasks_started_; } + int num_tasks_processed() const { return num_tasks_processed_; } + + private: + int num_tasks_started_; + int num_tasks_processed_; + const int num_tasks_; + + DISALLOW_COPY_AND_ASSIGN(DummyTaskObserver); +}; + +void PostNTasks(int posts_remaining) { + if (posts_remaining > 1) { + ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, BindOnce(&PostNTasks, posts_remaining - 1)); + } +} + +} // namespace + +class JavaHandlerThreadTest : public ::testing::Test {}; + +void RunTest_AbortDontRunMoreTasks(bool delayed, bool init_java_first) { + WaitableEvent test_done_event; + std::unique_ptr<android::JavaHandlerThread> java_thread; + if (init_java_first) { + java_thread = android::JavaHandlerThreadHelpers::CreateJavaFirst(); + } else { + java_thread = std::make_unique<android::JavaHandlerThread>( + "JavaHandlerThreadForTesting from AbortDontRunMoreTasks"); + } + java_thread->Start(); + java_thread->ListenForUncaughtExceptionsForTesting(); + + auto target = + BindOnce(&android::JavaHandlerThreadHelpers::ThrowExceptionAndAbort, + &test_done_event); + if (delayed) { + java_thread->task_runner()->PostDelayedTask( + FROM_HERE, std::move(target), TimeDelta::FromMilliseconds(10)); + } else { + java_thread->task_runner()->PostTask(FROM_HERE, std::move(target)); + java_thread->task_runner()->PostTask(FROM_HERE, + MakeExpectedNotRunClosure(FROM_HERE)); + } + test_done_event.Wait(); + java_thread->Stop(); + android::ScopedJavaLocalRef<jthrowable> exception = + java_thread->GetUncaughtExceptionIfAny(); + ASSERT_TRUE( + android::JavaHandlerThreadHelpers::IsExceptionTestException(exception)); +} + +TEST_F(JavaHandlerThreadTest, JavaExceptionAbort) { + constexpr bool delayed = false; + constexpr bool init_java_first = false; + RunTest_AbortDontRunMoreTasks(delayed, init_java_first); +} + +TEST_F(JavaHandlerThreadTest, DelayedJavaExceptionAbort) { + constexpr bool delayed = true; + constexpr bool init_java_first = false; + RunTest_AbortDontRunMoreTasks(delayed, init_java_first); +} + +TEST_F(JavaHandlerThreadTest, JavaExceptionAbortInitJavaFirst) { + constexpr bool delayed = false; + constexpr bool init_java_first = true; + RunTest_AbortDontRunMoreTasks(delayed, init_java_first); +} + +TEST_F(JavaHandlerThreadTest, RunTasksWhileShuttingDownJavaThread) { + const int kNumPosts = 6; + DummyTaskObserver observer(kNumPosts, 1); + + auto java_thread = std::make_unique<JavaHandlerThreadForTest>("test"); + java_thread->Start(); + + sequence_manager::internal::SequenceManagerImpl* sequence_manager = + static_cast<sequence_manager::internal::SequenceManagerImpl*>( + java_thread->task_environment()->sequence_manager.get()); + + java_thread->task_runner()->PostTask( + FROM_HERE, BindLambdaForTesting([&]() { + sequence_manager->AddTaskObserver(&observer); + ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), + TimeDelta::FromDays(1)); + java_thread->StopSequenceManagerForTesting(); + PostNTasks(kNumPosts); + })); + + java_thread->JoinForTesting(); + java_thread.reset(); + + EXPECT_EQ(kNumPosts, observer.num_tasks_started()); + EXPECT_EQ(kNumPosts, observer.num_tasks_processed()); +} + +} // namespace base
diff --git a/base/logging.cc b/base/logging.cc index 23b8a99..36b8bfc 100644 --- a/base/logging.cc +++ b/base/logging.cc
@@ -480,21 +480,13 @@ if (severity < g_min_log_level) return false; - // Return true here unless we know ~LogMessage won't do anything. + // Return true here unless we know ~LogMessage won't do anything. Note that + // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even + // when g_logging_destination is LOG_NONE. return g_logging_destination != LOG_NONE || log_message_handler || severity >= kAlwaysPrintErrorLevel; } -// Returns true when logging destination LOG_TO_STDERR flag is set. Also when -// configured to only LOG_TO_FILE, continue to log higher-severity messages to -// stderr as well to better detect and diagnose problems with unit tests, -// especially on the buildbots. -bool ShouldLogToStderr(int severity) { - return ((g_logging_destination & LOG_TO_STDERR) != 0) || - (severity >= kAlwaysPrintErrorLevel && - g_logging_destination == LOG_TO_FILE); -} - int GetVlogVerbosity() { return std::max(-1, LOG_INFO - GetMinLogLevel()); } @@ -856,7 +848,11 @@ #endif // OS_FUCHSIA } - if (ShouldLogToStderr(severity_)) { + if ((g_logging_destination & LOG_TO_STDERR) != 0 || + severity_ >= kAlwaysPrintErrorLevel) { + // Write logs with destination LOG_TO_STDERR to stderr. Also output to + // stderr for logs above a certain log level to better detect and diagnose + // problems with unit tests, especially on the buildbots. ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr)); fflush(stderr); }
diff --git a/base/logging_unittest.cc b/base/logging_unittest.cc index d5b31b31..b316176 100644 --- a/base/logging_unittest.cc +++ b/base/logging_unittest.cc
@@ -6,8 +6,6 @@ #include "base/bind.h" #include "base/callback.h" #include "base/compiler_specific.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" @@ -236,60 +234,6 @@ LOG(INFO) << mock_log_source_stderr.Log(); } -// Check that when logging to file and message severity is -// kAlwaysPrintErrorLevel or higher that the message is also written to stderr. -// When severity is lower, make sure the message is only written to file. -// Relies on POSIX specific APIs. Though this feature is cross-platform, testing -// on POSIX platforms is sufficient. -#if defined(OS_POSIX) || defined(OS_FUCHSIA) -TEST_F(LoggingTest, LogToFileAndStderr) { - const char kInfoLogMessage[] = "This is an INFO level message"; - const char kErrorLogMessage[] = "Here we have a message of level ERROR"; - base::ScopedTempDir temp_dir; - ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - - // Set up logging to log to a file. - base::FilePath file_logs_path = temp_dir.GetPath().Append("file.log"); - LoggingSettings settings; - settings.logging_dest = LOG_TO_FILE; - settings.log_file = file_logs_path.value().c_str(); - InitLogging(settings); - - // Create a file and change stderr to write to that file, to easily check - // contents. - base::FilePath stderr_logs_path = temp_dir.GetPath().Append("stderr.log"); - base::File stderr_logs = base::File( - stderr_logs_path, - base::File::FLAG_CREATE | base::File::FLAG_WRITE | base::File::FLAG_READ); - base::ScopedFD stderr_backup = base::ScopedFD(dup(STDERR_FILENO)); - int dup_result = dup2(stderr_logs.GetPlatformFile(), STDERR_FILENO); - ASSERT_GE(dup_result, 0); - - LOG(INFO) << kInfoLogMessage; - LOG(ERROR) << kErrorLogMessage; - - // Restore the original stderr logging destination. - dup_result = dup2(stderr_backup.get(), STDERR_FILENO); - ASSERT_EQ(dup_result, STDERR_FILENO); - - // Check that both log messages are written to "file.log". - std::string written_file_logs; - ASSERT_TRUE(base::ReadFileToString(file_logs_path, &written_file_logs)); - std::size_t found_info_log = written_file_logs.find(kInfoLogMessage); - EXPECT_FALSE(found_info_log == std::string::npos); - std::size_t found_error_log = written_file_logs.find(kErrorLogMessage); - EXPECT_FALSE(found_error_log == std::string::npos); - - // Check that the kErrorLogMessage is written to |stderr.log| and - // kInfoLogMessage is not. - ASSERT_TRUE(base::ReadFileToString(stderr_logs_path, &written_file_logs)); - found_info_log = written_file_logs.find(kInfoLogMessage); - EXPECT_TRUE(found_info_log == std::string::npos); - found_error_log = written_file_logs.find(kErrorLogMessage); - EXPECT_FALSE(found_error_log == std::string::npos); -} -#endif - // Official builds have CHECKs directly call BreakDebugger. #if !defined(OFFICIAL_BUILD)
diff --git a/base/mac/mac_util.h b/base/mac/mac_util.h index 2ff62ec5..22d2742 100644 --- a/base/mac/mac_util.h +++ b/base/mac/mac_util.h
@@ -19,7 +19,7 @@ namespace mac { // Full screen modes, in increasing order of priority. More permissive modes -// take predecence. +// take precedence. enum FullScreenMode { kFullScreenModeHideAll = 0, kFullScreenModeHideDock = 1, @@ -112,23 +112,27 @@ } // namespace internal -// Run-time OS version checks. Use these instead of +// Run-time OS version checks. Prefer @available in Objective-C files. If that +// is not possible, use these functions instead of // base::SysInfo::OperatingSystemVersionNumbers. Prefer the "AtLeast" and -// "AtMost" variants to those that check for a specific version, unless you -// know for sure that you need to check for a specific version. +// "AtMost" variants to those that check for a specific version, unless you know +// for sure that you need to check for a specific version. -#define DEFINE_IS_OS_FUNCS(V, TEST_DEPLOYMENT_TARGET) \ - inline bool IsOS10_##V() { \ - TEST_DEPLOYMENT_TARGET(>, V, false) \ - return internal::MacOSXMinorVersion() == V; \ - } \ - inline bool IsAtLeastOS10_##V() { \ - TEST_DEPLOYMENT_TARGET(>=, V, true) \ - return internal::MacOSXMinorVersion() >= V; \ - } \ - inline bool IsAtMostOS10_##V() { \ - TEST_DEPLOYMENT_TARGET(>, V, false) \ - return internal::MacOSXMinorVersion() <= V; \ +#define DEFINE_IS_OS_FUNCS_CR_MIN_REQUIRED(V, TEST_DEPLOYMENT_TARGET) \ + inline bool IsOS10_##V() { \ + TEST_DEPLOYMENT_TARGET(>, V, false) \ + return internal::MacOSXMinorVersion() == V; \ + } \ + inline bool IsAtMostOS10_##V() { \ + TEST_DEPLOYMENT_TARGET(>, V, false) \ + return internal::MacOSXMinorVersion() <= V; \ + } + +#define DEFINE_IS_OS_FUNCS(V, TEST_DEPLOYMENT_TARGET) \ + DEFINE_IS_OS_FUNCS_CR_MIN_REQUIRED(V, TEST_DEPLOYMENT_TARGET) \ + inline bool IsAtLeastOS10_##V() { \ + TEST_DEPLOYMENT_TARGET(>=, V, true) \ + return internal::MacOSXMinorVersion() >= V; \ } #define TEST_DEPLOYMENT_TARGET(OP, V, RET) \ @@ -136,26 +140,19 @@ return RET; #define IGNORE_DEPLOYMENT_TARGET(OP, V, RET) -DEFINE_IS_OS_FUNCS(9, TEST_DEPLOYMENT_TARGET) -DEFINE_IS_OS_FUNCS(10, TEST_DEPLOYMENT_TARGET) +// Notes: +// - When bumping the minimum version of the macOS required by Chromium, remove +// lines from below corresponding to versions of the macOS no longer +// supported. Ensure that the minimum supported version uses the +// DEFINE_IS_OS_FUNCS_CR_MIN_REQUIRED macro. +// - When bumping the minimum version of the macOS SDK required to build +// Chromium, remove the #ifdef that switches between TEST_DEPLOYMENT_TARGET +// and IGNORE_DEPLOYMENT_TARGET. -#ifdef MAC_OS_X_VERSION_10_11 +DEFINE_IS_OS_FUNCS_CR_MIN_REQUIRED(10, TEST_DEPLOYMENT_TARGET) DEFINE_IS_OS_FUNCS(11, TEST_DEPLOYMENT_TARGET) -#else -DEFINE_IS_OS_FUNCS(11, IGNORE_DEPLOYMENT_TARGET) -#endif - -#ifdef MAC_OS_X_VERSION_10_12 DEFINE_IS_OS_FUNCS(12, TEST_DEPLOYMENT_TARGET) -#else -DEFINE_IS_OS_FUNCS(12, IGNORE_DEPLOYMENT_TARGET) -#endif - -#ifdef MAC_OS_X_VERSION_10_13 DEFINE_IS_OS_FUNCS(13, TEST_DEPLOYMENT_TARGET) -#else -DEFINE_IS_OS_FUNCS(13, IGNORE_DEPLOYMENT_TARGET) -#endif #ifdef MAC_OS_X_VERSION_10_14 DEFINE_IS_OS_FUNCS(14, TEST_DEPLOYMENT_TARGET) @@ -163,15 +160,22 @@ DEFINE_IS_OS_FUNCS(14, IGNORE_DEPLOYMENT_TARGET) #endif +#ifdef MAC_OS_X_VERSION_10_15 +DEFINE_IS_OS_FUNCS(15, TEST_DEPLOYMENT_TARGET) +#else +DEFINE_IS_OS_FUNCS(15, IGNORE_DEPLOYMENT_TARGET) +#endif + #undef IGNORE_DEPLOYMENT_TARGET #undef TEST_DEPLOYMENT_TARGET +#undef DEFINE_IS_OS_FUNCS_CR_MIN_REQUIRED #undef DEFINE_IS_OS_FUNCS // This should be infrequently used. It only makes sense to use this to avoid // codepaths that are very likely to break on future (unreleased, untested, // unborn) OS releases, or to log when the OS is newer than any known version. -inline bool IsOSLaterThan10_14_DontCallThis() { - return !IsAtMostOS10_14(); +inline bool IsOSLaterThan10_15_DontCallThis() { + return !IsAtMostOS10_15(); } // Retrieve the system's model identifier string from the IOKit registry:
diff --git a/base/mac/mac_util.mm b/base/mac/mac_util.mm index 9a6b8fd..e624c44 100644 --- a/base/mac/mac_util.mm +++ b/base/mac/mac_util.mm
@@ -420,11 +420,10 @@ // version for Darwin versions beginning with 6, corresponding to Mac OS X // 10.2. Since this correspondence may change in the future, warn when // encountering a version higher than anything seen before. Older Darwin - // versions, or versions that can't be determined, result in - // immediate death. + // versions, or versions that can't be determined, result in immediate death. CHECK(darwin_major_version >= 6); int mac_os_x_minor_version = darwin_major_version - 4; - DLOG_IF(WARNING, darwin_major_version > 18) + DLOG_IF(WARNING, darwin_major_version > 19) << "Assuming Darwin " << base::NumberToString(darwin_major_version) << " is macOS 10." << base::NumberToString(mac_os_x_minor_version);
diff --git a/base/mac/mac_util_unittest.mm b/base/mac/mac_util_unittest.mm index c1585be2..645dc34 100644 --- a/base/mac/mac_util_unittest.mm +++ b/base/mac/mac_util_unittest.mm
@@ -143,168 +143,90 @@ // - FALSE/TRUE/FALSE (it is not the later version, it is "at most" the later // version, it is not "at least" the later version) - // TODO(avi): Is there a better way to test this? Maybe with macros? Are - // macros a better way to test this? +#define TEST_FOR_PAST_OS(V) \ + EXPECT_FALSE(IsOS10_##V()); \ + EXPECT_FALSE(IsAtMostOS10_##V()); \ + EXPECT_TRUE(IsAtLeastOS10_##V()); + +#define TEST_FOR_SAME_OS(V) \ + EXPECT_TRUE(IsOS10_##V()); \ + EXPECT_TRUE(IsAtMostOS10_##V()); \ + EXPECT_TRUE(IsAtLeastOS10_##V()); + +#define TEST_FOR_FUTURE_OS(V) \ + EXPECT_FALSE(IsOS10_##V()); \ + EXPECT_TRUE(IsAtMostOS10_##V()); \ + EXPECT_FALSE(IsAtLeastOS10_##V()); if (major == 10) { - if (minor == 9) { - EXPECT_TRUE(IsOS10_9()); - EXPECT_TRUE(IsAtMostOS10_9()); - EXPECT_TRUE(IsAtLeastOS10_9()); - - EXPECT_FALSE(IsOS10_10()); - EXPECT_TRUE(IsAtMostOS10_10()); - EXPECT_FALSE(IsAtLeastOS10_10()); - - EXPECT_FALSE(IsOS10_11()); - EXPECT_TRUE(IsAtMostOS10_11()); - EXPECT_FALSE(IsAtLeastOS10_11()); - - EXPECT_FALSE(IsOS10_12()); - EXPECT_TRUE(IsAtMostOS10_12()); - EXPECT_FALSE(IsAtLeastOS10_12()); - - EXPECT_FALSE(IsOS10_13()); - EXPECT_TRUE(IsAtMostOS10_13()); - EXPECT_FALSE(IsAtLeastOS10_13()); - - EXPECT_FALSE(IsOS10_14()); - EXPECT_TRUE(IsAtMostOS10_14()); - EXPECT_FALSE(IsAtLeastOS10_14()); - - EXPECT_FALSE(IsOSLaterThan10_14_DontCallThis()); - } else if (minor == 10) { - EXPECT_FALSE(IsOS10_9()); - EXPECT_FALSE(IsAtMostOS10_9()); - EXPECT_TRUE(IsAtLeastOS10_9()); - + if (minor == 10) { EXPECT_TRUE(IsOS10_10()); EXPECT_TRUE(IsAtMostOS10_10()); - EXPECT_TRUE(IsAtLeastOS10_10()); - EXPECT_FALSE(IsOS10_11()); - EXPECT_TRUE(IsAtMostOS10_11()); - EXPECT_FALSE(IsAtLeastOS10_11()); + TEST_FOR_FUTURE_OS(11); + TEST_FOR_FUTURE_OS(12); + TEST_FOR_FUTURE_OS(13); + TEST_FOR_FUTURE_OS(14); + TEST_FOR_FUTURE_OS(15); - EXPECT_FALSE(IsOS10_12()); - EXPECT_TRUE(IsAtMostOS10_12()); - EXPECT_FALSE(IsAtLeastOS10_12()); - - EXPECT_FALSE(IsOS10_13()); - EXPECT_TRUE(IsAtMostOS10_13()); - EXPECT_FALSE(IsAtLeastOS10_13()); - - EXPECT_FALSE(IsOS10_14()); - EXPECT_TRUE(IsAtMostOS10_14()); - EXPECT_FALSE(IsAtLeastOS10_14()); - - EXPECT_FALSE(IsOSLaterThan10_14_DontCallThis()); + EXPECT_FALSE(IsOSLaterThan10_15_DontCallThis()); } else if (minor == 11) { - EXPECT_FALSE(IsOS10_9()); - EXPECT_FALSE(IsAtMostOS10_9()); - EXPECT_TRUE(IsAtLeastOS10_9()); - EXPECT_FALSE(IsOS10_10()); EXPECT_FALSE(IsAtMostOS10_10()); - EXPECT_TRUE(IsAtLeastOS10_10()); - EXPECT_TRUE(IsOS10_11()); - EXPECT_TRUE(IsAtMostOS10_11()); - EXPECT_TRUE(IsAtLeastOS10_11()); + TEST_FOR_SAME_OS(11); + TEST_FOR_FUTURE_OS(12); + TEST_FOR_FUTURE_OS(13); + TEST_FOR_FUTURE_OS(14); + TEST_FOR_FUTURE_OS(15); - EXPECT_FALSE(IsOS10_12()); - EXPECT_TRUE(IsAtMostOS10_12()); - EXPECT_FALSE(IsAtLeastOS10_12()); - - EXPECT_FALSE(IsOS10_13()); - EXPECT_TRUE(IsAtMostOS10_13()); - EXPECT_FALSE(IsAtLeastOS10_13()); - - EXPECT_FALSE(IsOS10_14()); - EXPECT_TRUE(IsAtMostOS10_14()); - EXPECT_FALSE(IsAtLeastOS10_14()); - - EXPECT_FALSE(IsOSLaterThan10_14_DontCallThis()); + EXPECT_FALSE(IsOSLaterThan10_15_DontCallThis()); } else if (minor == 12) { - EXPECT_FALSE(IsOS10_9()); - EXPECT_FALSE(IsAtMostOS10_9()); - EXPECT_TRUE(IsAtLeastOS10_9()); - EXPECT_FALSE(IsOS10_10()); EXPECT_FALSE(IsAtMostOS10_10()); - EXPECT_TRUE(IsAtLeastOS10_10()); - EXPECT_FALSE(IsOS10_11()); - EXPECT_FALSE(IsAtMostOS10_11()); - EXPECT_TRUE(IsAtLeastOS10_11()); + TEST_FOR_PAST_OS(11); + TEST_FOR_SAME_OS(12); + TEST_FOR_FUTURE_OS(13); + TEST_FOR_FUTURE_OS(14); + TEST_FOR_FUTURE_OS(15); - EXPECT_TRUE(IsOS10_12()); - EXPECT_TRUE(IsAtMostOS10_12()); - EXPECT_TRUE(IsAtLeastOS10_12()); - - EXPECT_FALSE(IsOS10_13()); - EXPECT_TRUE(IsAtMostOS10_13()); - EXPECT_FALSE(IsAtLeastOS10_13()); - - EXPECT_FALSE(IsOS10_14()); - EXPECT_TRUE(IsAtMostOS10_14()); - EXPECT_FALSE(IsAtLeastOS10_14()); - - EXPECT_FALSE(IsOSLaterThan10_14_DontCallThis()); + EXPECT_FALSE(IsOSLaterThan10_15_DontCallThis()); } else if (minor == 13) { - EXPECT_FALSE(IsOS10_9()); - EXPECT_FALSE(IsAtMostOS10_9()); - EXPECT_TRUE(IsAtLeastOS10_9()); - EXPECT_FALSE(IsOS10_10()); EXPECT_FALSE(IsAtMostOS10_10()); - EXPECT_TRUE(IsAtLeastOS10_10()); - EXPECT_FALSE(IsOS10_11()); - EXPECT_FALSE(IsAtMostOS10_11()); - EXPECT_TRUE(IsAtLeastOS10_11()); + TEST_FOR_PAST_OS(11); + TEST_FOR_PAST_OS(12); + TEST_FOR_SAME_OS(13); + TEST_FOR_FUTURE_OS(14); + TEST_FOR_FUTURE_OS(15); - EXPECT_FALSE(IsOS10_12()); - EXPECT_FALSE(IsAtMostOS10_12()); - EXPECT_TRUE(IsAtLeastOS10_12()); - - EXPECT_TRUE(IsOS10_13()); - EXPECT_TRUE(IsAtMostOS10_13()); - EXPECT_TRUE(IsAtLeastOS10_13()); - - EXPECT_FALSE(IsOS10_14()); - EXPECT_TRUE(IsAtMostOS10_14()); - EXPECT_FALSE(IsAtLeastOS10_14()); - - EXPECT_FALSE(IsOSLaterThan10_14_DontCallThis()); + EXPECT_FALSE(IsOSLaterThan10_15_DontCallThis()); } else if (minor == 14) { - EXPECT_FALSE(IsOS10_9()); - EXPECT_FALSE(IsAtMostOS10_9()); - EXPECT_TRUE(IsAtLeastOS10_9()); - EXPECT_FALSE(IsOS10_10()); EXPECT_FALSE(IsAtMostOS10_10()); - EXPECT_TRUE(IsAtLeastOS10_10()); - EXPECT_FALSE(IsOS10_11()); - EXPECT_FALSE(IsAtMostOS10_11()); - EXPECT_TRUE(IsAtLeastOS10_11()); + TEST_FOR_PAST_OS(11); + TEST_FOR_PAST_OS(12); + TEST_FOR_PAST_OS(13); + TEST_FOR_SAME_OS(14); + TEST_FOR_FUTURE_OS(15); - EXPECT_FALSE(IsOS10_12()); - EXPECT_FALSE(IsAtMostOS10_12()); - EXPECT_TRUE(IsAtLeastOS10_12()); + EXPECT_FALSE(IsOSLaterThan10_15_DontCallThis()); + } else if (minor == 15) { + EXPECT_FALSE(IsOS10_10()); + EXPECT_FALSE(IsAtMostOS10_10()); - EXPECT_FALSE(IsOS10_13()); - EXPECT_FALSE(IsAtMostOS10_13()); - EXPECT_TRUE(IsAtLeastOS10_13()); + TEST_FOR_PAST_OS(11); + TEST_FOR_PAST_OS(12); + TEST_FOR_PAST_OS(13); + TEST_FOR_PAST_OS(14); + TEST_FOR_SAME_OS(15); - EXPECT_TRUE(IsOS10_14()); - EXPECT_TRUE(IsAtMostOS10_14()); - EXPECT_TRUE(IsAtLeastOS10_14()); - - EXPECT_FALSE(IsOSLaterThan10_14_DontCallThis()); + EXPECT_FALSE(IsOSLaterThan10_15_DontCallThis()); } else { - // Not nine, ten, eleven, twelve, thirteen, or fourteen. Ah, ah, ah. + // Not ten, eleven, twelve, thirteen, fourteen, or fifteen. Ah, ah, ah. EXPECT_TRUE(false); } } else { @@ -313,6 +235,10 @@ } } +#undef TEST_FOR_PAST_OS +#undef TEST_FOR_SAME_OS +#undef TEST_FOR_FUTURE_OS + TEST_F(MacUtilTest, ParseModelIdentifier) { std::string model; int32_t major = 1, minor = 2;
diff --git a/base/message_loop/message_loop_unittest.cc b/base/message_loop/message_loop_unittest.cc index edc72dc..6bbbb5b7 100644 --- a/base/message_loop/message_loop_unittest.cc +++ b/base/message_loop/message_loop_unittest.cc
@@ -267,89 +267,6 @@ class MessageLoopTest : public ::testing::Test {}; -#if defined(OS_ANDROID) -void DoNotRun() { - ASSERT_TRUE(false); -} - -void RunTest_AbortDontRunMoreTasks(bool delayed, bool init_java_first) { - WaitableEvent test_done_event(WaitableEvent::ResetPolicy::MANUAL, - WaitableEvent::InitialState::NOT_SIGNALED); - std::unique_ptr<android::JavaHandlerThread> java_thread; - if (init_java_first) { - java_thread = android::JavaHandlerThreadHelpers::CreateJavaFirst(); - } else { - java_thread = std::make_unique<android::JavaHandlerThread>( - "JavaHandlerThreadForTesting from AbortDontRunMoreTasks"); - } - java_thread->Start(); - java_thread->ListenForUncaughtExceptionsForTesting(); - - auto target = - BindOnce(&android::JavaHandlerThreadHelpers::ThrowExceptionAndAbort, - &test_done_event); - if (delayed) { - java_thread->message_loop()->task_runner()->PostDelayedTask( - FROM_HERE, std::move(target), TimeDelta::FromMilliseconds(10)); - } else { - java_thread->message_loop()->task_runner()->PostTask(FROM_HERE, - std::move(target)); - java_thread->message_loop()->task_runner()->PostTask(FROM_HERE, - BindOnce(&DoNotRun)); - } - test_done_event.Wait(); - java_thread->Stop(); - android::ScopedJavaLocalRef<jthrowable> exception = - java_thread->GetUncaughtExceptionIfAny(); - ASSERT_TRUE( - android::JavaHandlerThreadHelpers::IsExceptionTestException(exception)); -} - -TEST_F(MessageLoopTest, JavaExceptionAbort) { - constexpr bool delayed = false; - constexpr bool init_java_first = false; - RunTest_AbortDontRunMoreTasks(delayed, init_java_first); -} -TEST_F(MessageLoopTest, DelayedJavaExceptionAbort) { - constexpr bool delayed = true; - constexpr bool init_java_first = false; - RunTest_AbortDontRunMoreTasks(delayed, init_java_first); -} -TEST_F(MessageLoopTest, JavaExceptionAbortInitJavaFirst) { - constexpr bool delayed = false; - constexpr bool init_java_first = true; - RunTest_AbortDontRunMoreTasks(delayed, init_java_first); -} - -TEST_F(MessageLoopTest, RunTasksWhileShuttingDownJavaThread) { - const int kNumPosts = 6; - DummyTaskObserver observer(kNumPosts, 1); - - auto java_thread = std::make_unique<android::JavaHandlerThread>("test"); - java_thread->Start(); - - java_thread->message_loop()->task_runner()->PostTask( - FROM_HERE, - BindOnce( - [](android::JavaHandlerThread* java_thread, - DummyTaskObserver* observer, int num_posts) { - java_thread->message_loop()->AddTaskObserver(observer); - ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, BindOnce([]() { ADD_FAILURE(); }), - TimeDelta::FromDays(1)); - java_thread->StopMessageLoopForTesting(); - PostNTasks(num_posts); - }, - Unretained(java_thread.get()), Unretained(&observer), kNumPosts)); - - java_thread->JoinForTesting(); - java_thread.reset(); - - EXPECT_EQ(kNumPosts, observer.num_tasks_started()); - EXPECT_EQ(kNumPosts, observer.num_tasks_processed()); -} -#endif // defined(OS_ANDROID) - #if defined(OS_WIN) void SubPumpFunc(OnceClosure on_done) {
diff --git a/base/message_loop/message_pump_perftest.cc b/base/message_loop/message_pump_perftest.cc index c3e85f6..271e903 100644 --- a/base/message_loop/message_pump_perftest.cc +++ b/base/message_loop/message_pump_perftest.cc
@@ -28,6 +28,20 @@ #endif namespace base { +namespace { + +#if defined(OS_ANDROID) +class JavaHandlerThreadForTest : public android::JavaHandlerThread { + public: + explicit JavaHandlerThreadForTest(const char* name) + : android::JavaHandlerThread(name, base::ThreadPriority::NORMAL) {} + + using android::JavaHandlerThread::task_environment; + using android::JavaHandlerThread::TaskEnvironment; +}; +#endif + +} // namespace class ScheduleWorkTest : public testing::Test { public: @@ -75,7 +89,7 @@ void ScheduleWork(MessageLoop::Type target_type, int num_scheduling_threads) { #if defined(OS_ANDROID) if (target_type == MessageLoop::TYPE_JAVA) { - java_thread_.reset(new android::JavaHandlerThread("target")); + java_thread_.reset(new JavaHandlerThreadForTest("target")); java_thread_->Start(); } else #endif @@ -179,8 +193,10 @@ sequence_manager::internal::SequenceManagerImpl* target_message_loop_base() { #if defined(OS_ANDROID) - if (java_thread_) - return java_thread_->message_loop()->GetSequenceManagerImpl(); + if (java_thread_) { + return static_cast<sequence_manager::internal::SequenceManagerImpl*>( + java_thread_->task_environment()->sequence_manager.get()); + } #endif return MessageLoopCurrent::Get()->GetCurrentSequenceManagerImpl(); } @@ -189,7 +205,7 @@ std::unique_ptr<Thread> target_; MessageLoop* message_loop_; #if defined(OS_ANDROID) - std::unique_ptr<android::JavaHandlerThread> java_thread_; + std::unique_ptr<JavaHandlerThreadForTest> java_thread_; #endif std::unique_ptr<base::TimeDelta[]> scheduling_times_; std::unique_ptr<base::TimeDelta[]> scheduling_thread_times_;
diff --git a/base/task/single_thread_task_executor.cc b/base/task/single_thread_task_executor.cc index c94b0804..2c52470 100644 --- a/base/task/single_thread_task_executor.cc +++ b/base/task/single_thread_task_executor.cc
@@ -6,20 +6,29 @@ #include "base/message_loop/message_pump.h" #include "base/task/sequence_manager/sequence_manager.h" +#include "base/task/sequence_manager/sequence_manager_impl.h" +#include "build/build_config.h" namespace base { SingleThreadTaskExecutor::SingleThreadTaskExecutor(MessagePump::Type type) - : sequence_manager_( - sequence_manager::CreateSequenceManagerOnCurrentThreadWithPump( - MessagePump::Create(type), - sequence_manager::SequenceManager::Settings::Builder() - .SetMessagePumpType(type) - .Build())), + : sequence_manager_(sequence_manager::CreateUnboundSequenceManager( + sequence_manager::SequenceManager::Settings::Builder() + .SetMessagePumpType(type) + .Build())), default_task_queue_(sequence_manager_->CreateTaskQueue( sequence_manager::TaskQueue::Spec("default_tq"))), type_(type) { sequence_manager_->SetDefaultTaskRunner(default_task_queue_->task_runner()); + sequence_manager_->BindToMessagePump(MessagePump::Create(type)); + +#if defined(OS_IOS) + if (type == MessagePump::Type::UI) { + static_cast<sequence_manager::internal::SequenceManagerImpl*>( + sequence_manager_.get()) + ->AttachToMessagePump(); + } +#endif } SingleThreadTaskExecutor::~SingleThreadTaskExecutor() = default;
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index 5c509c02..f1e605a 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h
@@ -115,7 +115,7 @@ } namespace cc { class CompletionEvent; -class SingleThreadTaskGraphRunner; +class TileTaskManagerImpl; } namespace chromeos { class BlockingMethodCaller; @@ -453,6 +453,8 @@ friend class base::MessageLoopImpl; friend class base::ScopedAllowThreadRecallForStackSamplingProfiler; friend class base::StackSamplingProfiler; + friend class cc::TileTaskManagerImpl; + friend class content::CategorizedWorkerPool; friend class content::DesktopCaptureDevice; friend class content::InProcessUtilityThread; friend class content::RTCVideoDecoder; @@ -474,10 +476,8 @@ 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 content:: BrowserGpuChannelHostFactory; // http://crbug.com/125248 - friend class content::CategorizedWorkerPool; // http://crbug.com/902823 friend class dbus::Bus; // http://crbug.com/125222 friend class disk_cache::BackendImpl; // http://crbug.com/74623 friend class disk_cache::InFlightIO; // http://crbug.com/74623
diff --git a/base/trace_event/trace_log.cc b/base/trace_event/trace_log.cc index 0a98759..44ee37c 100644 --- a/base/trace_event/trace_log.cc +++ b/base/trace_event/trace_log.cc
@@ -1191,7 +1191,7 @@ // current thread to avoid locks in most cases. if (thread_id == static_cast<int>(PlatformThread::CurrentId())) { const char* new_name = - ThreadIdNameManager::GetInstance()->GetName(thread_id); + ThreadIdNameManager::GetInstance()->GetNameForCurrentThread(); // Check if the thread name has been set or changed since the previous // call (if any), but don't bother if the new name is empty. Note this will // not detect a thread name change within the same char* buffer address: we
diff --git a/build/config/mac/base_rules.gni b/build/config/mac/base_rules.gni index bcb34a16..88641af 100644 --- a/build/config/mac/base_rules.gni +++ b/build/config/mac/base_rules.gni
@@ -4,8 +4,8 @@ # This file contains rules that are shared between Mac and iOS. -import("//build/toolchain/toolchain.gni") import("//build/config/mac/symbols.gni") +import("//build/toolchain/toolchain.gni") if (is_mac) { import("//build/config/mac/mac_sdk.gni") @@ -38,22 +38,19 @@ "deps", ]) - script = "//build/config/mac/xcrun.py" + script = "//build/gn_run_binary.py" sources = [ invoker.source, ] outputs = [ invoker.output, ] - args = [] - if (!use_system_xcode) { - args += [ - "--developer_dir", - hermetic_xcode_path, - ] - } - args += [ - "plutil", + + # /usr/bin/plutil is present on all images of macOS. If at some point in the + # future we need to ship our own copy [e.g. for cross-compile], we can add a + # layer of indirection. + args = [ + "/usr/bin/plutil", "-convert", invoker.format, "-o",
diff --git a/build/config/mac/xcrun.py b/build/config/mac/xcrun.py deleted file mode 100644 index 1f8dc20..0000000 --- a/build/config/mac/xcrun.py +++ /dev/null
@@ -1,28 +0,0 @@ -# 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. - -import argparse -import os -import subprocess -import sys - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description='A script to execute a command via xcrun.') - parser.add_argument('--stamp', action='store', type=str, - help='Write a stamp file to this path on success.') - parser.add_argument('--developer_dir', required=False, - help='Path to Xcode.') - args, unknown_args = parser.parse_known_args() - - if args.developer_dir: - os.environ['DEVELOPER_DIR'] = args.developer_dir - - rv = subprocess.check_call(['xcrun'] + unknown_args) - if rv == 0 and args.stamp: - if os.path.exists(args.stamp): - os.unlink(args.stamp) - open(args.stamp, 'w+').close() - - sys.exit(rv)
diff --git a/build/fuchsia/layout_test_proxy/layout_test_proxy.cc b/build/fuchsia/layout_test_proxy/layout_test_proxy.cc index 1d14df99..0d2117b2 100644 --- a/build/fuchsia/layout_test_proxy/layout_test_proxy.cc +++ b/build/fuchsia/layout_test_proxy/layout_test_proxy.cc
@@ -3,9 +3,9 @@ // found in the LICENSE file. #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" +#include "base/task/single_thread_task_executor.h" #include "net/base/ip_endpoint.h" #include "net/test/tcp_socket_proxy.h" @@ -55,13 +55,13 @@ return 1; } - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); std::vector<std::unique_ptr<net::TcpSocketProxy>> proxies; for (int port : ports) { auto test_server_proxy = - std::make_unique<net::TcpSocketProxy>(message_loop.task_runner()); + std::make_unique<net::TcpSocketProxy>(io_task_executor.task_runner()); if (!test_server_proxy->Initialize(port)) { LOG(ERROR) << "Can't bind proxy to port " << port; return 1; @@ -71,8 +71,8 @@ proxies.push_back(std::move(test_server_proxy)); } - // Run the message loop indefinitely. + // Run the task executor indefinitely. base::RunLoop().Run(); return 0; -} \ No newline at end of file +}
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index eb2e8d4..1ddfe3f 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8911432991615498112 \ No newline at end of file +8911405404837592016 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 9974916..2139485 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -8911431548849094000 \ No newline at end of file +8911405401977229536 \ No newline at end of file
diff --git a/build/toolchain/mac/BUILD.gn b/build/toolchain/mac/BUILD.gn index 22316c9..efba8b3 100644 --- a/build/toolchain/mac/BUILD.gn +++ b/build/toolchain/mac/BUILD.gn
@@ -440,27 +440,33 @@ description = "COPY_BUNDLE_DATA {{source}} {{output}}" pool = ":bundle_pool($default_toolchain)" } - tool("compile_xcassets") { - _tool = rebase_path("//build/toolchain/mac/compile_xcassets.py", - root_build_dir) - if (is_ios) { - _sdk_name = ios_sdk_name - _min_deployment_target = ios_deployment_target - _compress_pngs = "" - } else { - _sdk_name = mac_sdk_name - _min_deployment_target = mac_deployment_target - _compress_pngs = " -c " - } - command = - "$env_wrapper rm -f \"{{output}}\" && " + - "TOOL_VERSION=${tool_versions.compile_xcassets} " + - "python $_tool$_compress_pngs -p \"$_sdk_name\" " + - "-t \"$_min_deployment_target\" -T \"{{bundle_product_type}}\" " + - "-P \"{{bundle_partial_info_plist}}\" -o {{output}} {{inputs}}" - description = "COMPILE_XCASSETS {{output}}" - pool = ":bundle_pool($default_toolchain)" + # xcassets are only used on iOS, not macOS. We want to minimize the number + # of Xcode-based tools used by the macOS toolchain, so we intentionally + # disallow future uses of xcassets on macOS. https://crbug.com/965663. + if (toolchain_args.current_os == "ios") { + tool("compile_xcassets") { + _tool = rebase_path("//build/toolchain/mac/compile_xcassets.py", + root_build_dir) + if (is_ios) { + _sdk_name = ios_sdk_name + _min_deployment_target = ios_deployment_target + _compress_pngs = "" + } else { + _sdk_name = mac_sdk_name + _min_deployment_target = mac_deployment_target + _compress_pngs = " -c " + } + command = + "$env_wrapper rm -f \"{{output}}\" && " + + "TOOL_VERSION=${tool_versions.compile_xcassets} " + + "python $_tool$_compress_pngs -p \"$_sdk_name\" " + + "-t \"$_min_deployment_target\" -T \"{{bundle_product_type}}\" " + + "-P \"{{bundle_partial_info_plist}}\" -o {{output}} {{inputs}}" + + description = "COMPILE_XCASSETS {{output}}" + pool = ":bundle_pool($default_toolchain)" + } } tool("action") {
diff --git a/cc/layers/picture_layer_impl.cc b/cc/layers/picture_layer_impl.cc index b9cbcd3..30ce00f6 100644 --- a/cc/layers/picture_layer_impl.cc +++ b/cc/layers/picture_layer_impl.cc
@@ -1749,4 +1749,25 @@ controller->UnregisterAnimationDriver(data.paint_image_id, this); } +std::unique_ptr<base::DictionaryValue> PictureLayerImpl::LayerAsJson() const { + auto result = LayerImpl::LayerAsJson(); + auto dictionary = std::make_unique<base::DictionaryValue>(); + if (raster_source_) { + dictionary->SetBoolean("IsSolidColor", raster_source_->IsSolidColor()); + auto list = std::make_unique<base::ListValue>(); + list->AppendInteger(raster_source_->GetSize().width()); + list->AppendInteger(raster_source_->GetSize().height()); + dictionary->Set("Size", std::move(list)); + dictionary->SetBoolean("HasRecordings", raster_source_->HasRecordings()); + + const auto& display_list = raster_source_->GetDisplayItemList(); + size_t op_count = display_list ? display_list->TotalOpCount() : 0; + size_t bytes_used = display_list ? display_list->BytesUsed() : 0; + dictionary->SetInteger("OpCount", op_count); + dictionary->SetInteger("BytesUsed", bytes_used); + } + result->Set("RasterSource", std::move(dictionary)); + return result; +} + } // namespace cc
diff --git a/cc/layers/picture_layer_impl.h b/cc/layers/picture_layer_impl.h index 82309bd..d97e820 100644 --- a/cc/layers/picture_layer_impl.h +++ b/cc/layers/picture_layer_impl.h
@@ -159,6 +159,8 @@ void RegisterAnimatedImages(); void UnregisterAnimatedImages(); + std::unique_ptr<base::DictionaryValue> LayerAsJson() const override; + PictureLayerImpl* twin_layer_; std::unique_ptr<PictureLayerTilingSet> tilings_;
diff --git a/cc/paint/BUILD.gn b/cc/paint/BUILD.gn index 6c428fba..2e6d184e 100644 --- a/cc/paint/BUILD.gn +++ b/cc/paint/BUILD.gn
@@ -60,6 +60,8 @@ "paint_shader.cc", "paint_shader.h", "paint_worklet_input.h", + "paint_worklet_job.cc", + "paint_worklet_job.h", "paint_worklet_layer_painter.h", "raw_memory_transfer_cache_entry.cc", "raw_memory_transfer_cache_entry.h",
diff --git a/cc/paint/paint_worklet_input.h b/cc/paint/paint_worklet_input.h index 94e2cfda..dd80da7 100644 --- a/cc/paint/paint_worklet_input.h +++ b/cc/paint/paint_worklet_input.h
@@ -6,12 +6,12 @@ #define CC_PAINT_PAINT_WORKLET_INPUT_H_ #include "base/memory/ref_counted.h" -#include "cc/cc_export.h" +#include "cc/paint/paint_export.h" #include "ui/gfx/geometry/size_f.h" namespace cc { -class CC_EXPORT PaintWorkletInput +class CC_PAINT_EXPORT PaintWorkletInput : public base::RefCountedThreadSafe<PaintWorkletInput> { public: virtual gfx::SizeF GetSize() const = 0;
diff --git a/cc/paint/paint_worklet_job.cc b/cc/paint/paint_worklet_job.cc new file mode 100644 index 0000000..13f09da --- /dev/null +++ b/cc/paint/paint_worklet_job.cc
@@ -0,0 +1,23 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "cc/paint/paint_worklet_job.h" + +#include "cc/paint/paint_worklet_input.h" + +namespace cc { + +PaintWorkletJob::PaintWorkletJob(scoped_refptr<PaintWorkletInput> input) + : input_(std::move(input)) {} + +PaintWorkletJob::PaintWorkletJob(const PaintWorkletJob& other) = default; +PaintWorkletJob::PaintWorkletJob(PaintWorkletJob&& other) = default; +PaintWorkletJob::~PaintWorkletJob() = default; + +void PaintWorkletJob::SetOutput(sk_sp<PaintRecord> output) { + DCHECK(!output_); + output_ = std::move(output); +} + +} // namespace cc
diff --git a/cc/paint/paint_worklet_job.h b/cc/paint/paint_worklet_job.h new file mode 100644 index 0000000..dc64133 --- /dev/null +++ b/cc/paint/paint_worklet_job.h
@@ -0,0 +1,55 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CC_PAINT_PAINT_WORKLET_JOB_H_ +#define CC_PAINT_PAINT_WORKLET_JOB_H_ + +#include "base/containers/flat_map.h" +#include "base/memory/scoped_refptr.h" +#include "cc/paint/paint_export.h" +#include "cc/paint/paint_record.h" +#include "third_party/skia/include/core/SkRefCnt.h" + +namespace cc { + +class PaintWorkletInput; + +// A PaintWorkletJob instance encapsulates the data that needs to be passed +// around in order to dispatch PaintWorklets to the worklet thread, paint them, +// and return the results to cc-impl. +class CC_PAINT_EXPORT PaintWorkletJob { + public: + explicit PaintWorkletJob(scoped_refptr<PaintWorkletInput> input); + PaintWorkletJob(const PaintWorkletJob& other); + PaintWorkletJob(PaintWorkletJob&& other); + ~PaintWorkletJob(); + + const scoped_refptr<PaintWorkletInput>& input() const { return input_; } + const sk_sp<PaintRecord>& output() const { return output_; } + + void SetOutput(sk_sp<PaintRecord> output); + + private: + // The input for a PaintWorkletJob is encapsulated in a PaintWorkletInput + // instance; see class-level comments on |PaintWorkletInput| for details. + scoped_refptr<PaintWorkletInput> input_; + + // The output for a PaintWorkletJob is a series of paint ops for the painted + // content, that can be passed to raster. + sk_sp<PaintRecord> output_; +}; + +// The PaintWorklet dispatcher logic passes the PaintWorkletJobVector to the +// worklet thread during painting. To keep the structure alive on both the +// compositor and worklet side (as technically the compositor could be town down +// whilst the worklet is still painting), we use base::RefCountedJob for it. +using PaintWorkletJobVector = + base::RefCountedData<std::vector<PaintWorkletJob>>; +using PaintWorkletId = int; +using PaintWorkletJobMap = + base::flat_map<PaintWorkletId, scoped_refptr<PaintWorkletJobVector>>; + +} // namespace cc + +#endif // CC_PAINT_PAINT_WORKLET_JOB_H_
diff --git a/cc/paint/paint_worklet_layer_painter.h b/cc/paint/paint_worklet_layer_painter.h index 6535432b..10e18f2 100644 --- a/cc/paint/paint_worklet_layer_painter.h +++ b/cc/paint/paint_worklet_layer_painter.h
@@ -5,18 +5,34 @@ #ifndef CC_PAINT_PAINT_WORKLET_LAYER_PAINTER_H_ #define CC_PAINT_PAINT_WORKLET_LAYER_PAINTER_H_ -#include "cc/cc_export.h" +#include "base/callback.h" +#include "cc/paint/paint_export.h" #include "cc/paint/paint_record.h" +#include "cc/paint/paint_worklet_job.h" namespace cc { class PaintWorkletInput; -class CC_EXPORT PaintWorkletLayerPainter { +// PaintWorkletLayerPainter bridges between the compositor and the PaintWorklet +// thread, providing hooks for the compositor to paint PaintWorklet content that +// Blink has deferred on. +class CC_PAINT_EXPORT PaintWorkletLayerPainter { public: virtual ~PaintWorkletLayerPainter() {} - virtual sk_sp<PaintRecord> Paint(PaintWorkletInput*) = 0; + // Synchronously paints a PaintWorklet instance (represented by a + // PaintWorkletInput), returning the resultant PaintRecord. + // + // TODO(crbug.com/907897): Once we remove the raster thread path, we will only + // be using |DispatchWorklets| and this can be removed. + virtual sk_sp<PaintRecord> Paint(const PaintWorkletInput*) = 0; + + // Asynchronously paints a set of PaintWorklet instances. The results are + // returned via the provided callback, on the same thread that originally + // called this method. + using DoneCallback = base::OnceCallback<void(PaintWorkletJobMap)>; + virtual void DispatchWorklets(PaintWorkletJobMap, DoneCallback) = 0; }; } // namespace cc
diff --git a/cc/raster/single_thread_task_graph_runner.cc b/cc/raster/single_thread_task_graph_runner.cc index afb47e8..67e4ab3 100644 --- a/cc/raster/single_thread_task_graph_runner.cc +++ b/cc/raster/single_thread_task_graph_runner.cc
@@ -9,7 +9,6 @@ #include <string> #include "base/threading/simple_thread.h" -#include "base/threading/thread_restrictions.h" #include "base/trace_event/trace_event.h" namespace cc { @@ -83,8 +82,6 @@ { base::AutoLock lock(lock_); - // http://crbug.com/902823 - base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; auto* task_namespace = work_queue_.GetNamespaceForToken(token);
diff --git a/cc/raster/synchronous_task_graph_runner.cc b/cc/raster/synchronous_task_graph_runner.cc index 4ee102e..b7e0e94 100644 --- a/cc/raster/synchronous_task_graph_runner.cc +++ b/cc/raster/synchronous_task_graph_runner.cc
@@ -10,7 +10,6 @@ #include <utility> #include "base/threading/simple_thread.h" -#include "base/threading/thread_restrictions.h" #include "base/trace_event/trace_event.h" namespace cc {
diff --git a/cc/test/test_paint_worklet_layer_painter.cc b/cc/test/test_paint_worklet_layer_painter.cc index 35dd5a47..bf2b51a5 100644 --- a/cc/test/test_paint_worklet_layer_painter.cc +++ b/cc/test/test_paint_worklet_layer_painter.cc
@@ -13,7 +13,8 @@ TestPaintWorkletLayerPainter::~TestPaintWorkletLayerPainter() = default; -sk_sp<PaintRecord> TestPaintWorkletLayerPainter::Paint(PaintWorkletInput*) { +sk_sp<PaintRecord> TestPaintWorkletLayerPainter::Paint( + const PaintWorkletInput*) { auto manual_record = sk_make_sp<PaintOpBuffer>(); scoped_refptr<TestPaintWorkletInput> input = base::MakeRefCounted<TestPaintWorkletInput>(gfx::SizeF(100, 100)); @@ -22,4 +23,7 @@ return manual_record; } +void TestPaintWorkletLayerPainter::DispatchWorklets(PaintWorkletJobMap, + DoneCallback) {} + } // namespace cc
diff --git a/cc/test/test_paint_worklet_layer_painter.h b/cc/test/test_paint_worklet_layer_painter.h index 74911ed..b0110ef 100644 --- a/cc/test/test_paint_worklet_layer_painter.h +++ b/cc/test/test_paint_worklet_layer_painter.h
@@ -17,7 +17,8 @@ TestPaintWorkletLayerPainter(); ~TestPaintWorkletLayerPainter() override; - sk_sp<PaintRecord> Paint(PaintWorkletInput*) override; + sk_sp<PaintRecord> Paint(const PaintWorkletInput*) override; + void DispatchWorklets(PaintWorkletJobMap, DoneCallback) override; }; } // namespace cc
diff --git a/cc/tiles/tile_task_manager.cc b/cc/tiles/tile_task_manager.cc index 2bfdd9e..476a7d7 100644 --- a/cc/tiles/tile_task_manager.cc +++ b/cc/tiles/tile_task_manager.cc
@@ -5,6 +5,7 @@ #include "cc/tiles/tile_task_manager.h" #include "base/memory/ptr_util.h" +#include "base/threading/thread_restrictions.h" #include "base/trace_event/trace_event.h" namespace cc { @@ -50,7 +51,10 @@ // Cancel non-scheduled tasks and wait for running tasks to finish. TaskGraph empty; task_graph_runner_->ScheduleTasks(namespace_token_, &empty); - task_graph_runner_->WaitForTasksToFinishRunning(namespace_token_); + { + base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; + task_graph_runner_->WaitForTasksToFinishRunning(namespace_token_); + } } } // namespace cc
diff --git a/cc/trees/layer_tree_host_pixeltest_filters.cc b/cc/trees/layer_tree_host_pixeltest_filters.cc index 2e585f1..c38e7fa 100644 --- a/cc/trees/layer_tree_host_pixeltest_filters.cc +++ b/cc/trees/layer_tree_host_pixeltest_filters.cc
@@ -12,6 +12,54 @@ #include "cc/test/pixel_comparator.h" #include "cc/test/solid_color_content_layer_client.h" +// TODO(crbug.com/971325): Fix memory leaks in tests and re-enable on LSAN. +#ifdef LEAK_SANITIZER +#define MAYBE_CroppedFilter DISABLED_CroppedFilter +#define MAYBE_EnlargedTextureWithAlphaThresholdFilter \ + DISABLED_EnlargedTextureWithAlphaThresholdFilter +#define MAYBE_ImageFilterClipped DISABLED_ImageFilterClipped +#define MAYBE_BlurFilterWithClip DISABLED_BlurFilterWithClip +#define MAYBE_NullFilter DISABLED_NullFilter +#define MAYBE_StandardDpi DISABLED_StandardDpi +#define MAYBE_BackdropFilterBlurOutsets DISABLED_BackdropFilterBlurOutsets +#define MAYBE_FilterWithGiantCropRect DISABLED_FilterWithGiantCropRect +#define MAYBE_HiDpi DISABLED_HiDpi +#define MAYBE_FilterWithGiantCropRectNoClip \ + DISABLED_FilterWithGiantCropRectNoClip +#define MAYBE_ImageRenderSurfaceScaled DISABLED_ImageRenderSurfaceScaled +#define MAYBE_BackdropFilterBlurRect DISABLED_BackdropFilterBlurRect +#define MAYBE_ImageFilterScaled DISABLED_ImageFilterScaled +#define MAYBE_StandardDpi DISABLED_StandardDpi +#define MAYBE_ImageFilterNonZeroOrigin DISABLED_ImageFilterNonZeroOrigin +#define MAYBE_ZoomFilter DISABLED_ZoomFilter +#define MAYBE_HiDpi DISABLED_HiDpi +#define MAYBE_RotatedFilter DISABLED_RotatedFilter +#define MAYBE_EnlargedTextureWithCropOffsetFilter \ + DISABLED_EnlargedTextureWithCropOffsetFilter +#else +#define MAYBE_CroppedFilter CroppedFilter +#define MAYBE_EnlargedTextureWithAlphaThresholdFilter \ + EnlargedTextureWithAlphaThresholdFilter +#define MAYBE_ImageFilterClipped ImageFilterClipped +#define MAYBE_BlurFilterWithClip BlurFilterWithClip +#define MAYBE_NullFilter NullFilter +#define MAYBE_StandardDpi StandardDpi +#define MAYBE_BackdropFilterBlurOutsets BackdropFilterBlurOutsets +#define MAYBE_FilterWithGiantCropRect FilterWithGiantCropRect +#define MAYBE_HiDpi HiDpi +#define MAYBE_FilterWithGiantCropRectNoClip FilterWithGiantCropRectNoClip +#define MAYBE_ImageRenderSurfaceScaled ImageRenderSurfaceScaled +#define MAYBE_BackdropFilterBlurRect BackdropFilterBlurRect +#define MAYBE_ImageFilterScaled ImageFilterScaled +#define MAYBE_StandardDpi StandardDpi +#define MAYBE_ImageFilterNonZeroOrigin ImageFilterNonZeroOrigin +#define MAYBE_ZoomFilter ZoomFilter +#define MAYBE_HiDpi HiDpi +#define MAYBE_RotatedFilter RotatedFilter +#define MAYBE_EnlargedTextureWithCropOffsetFilter \ + EnlargedTextureWithCropOffsetFilter +#endif + #if !defined(OS_ANDROID) namespace cc { @@ -123,7 +171,7 @@ ::testing::Values(LayerTreeTest::RENDERER_GL, LayerTreeTest::RENDERER_SKIA_GL)); -TEST_P(LayerTreeHostFiltersPixelTestGPU, BackdropFilterBlurRect) { +TEST_P(LayerTreeHostFiltersPixelTestGPU, MAYBE_BackdropFilterBlurRect) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer( gfx::Rect(200, 200), SK_ColorWHITE); @@ -205,7 +253,7 @@ base::FilePath(FILE_PATH_LITERAL("backdrop_filter_blur_rounded.png"))); } -TEST_P(LayerTreeHostFiltersPixelTestGPU, BackdropFilterBlurOutsets) { +TEST_P(LayerTreeHostFiltersPixelTestGPU, MAYBE_BackdropFilterBlurOutsets) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer( gfx::Rect(200, 200), SK_ColorWHITE); @@ -407,15 +455,15 @@ #endif )); -TEST_P(LayerTreeHostFiltersScaledPixelTest, StandardDpi) { +TEST_P(LayerTreeHostFiltersScaledPixelTest, MAYBE_StandardDpi) { RunPixelTestType(100, 1.f); } -TEST_P(LayerTreeHostFiltersScaledPixelTest, HiDpi) { +TEST_P(LayerTreeHostFiltersScaledPixelTest, MAYBE_HiDpi) { RunPixelTestType(50, 2.f); } -TEST_P(LayerTreeHostFiltersPixelTest, NullFilter) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_NullFilter) { layer_transforms_should_scale_layer_contents_ = false; scoped_refptr<SolidColorLayer> foreground = @@ -429,7 +477,7 @@ base::FilePath(FILE_PATH_LITERAL("green.png"))); } -TEST_P(LayerTreeHostFiltersPixelTest, CroppedFilter) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_CroppedFilter) { layer_transforms_should_scale_layer_contents_ = false; scoped_refptr<SolidColorLayer> foreground = @@ -448,7 +496,7 @@ base::FilePath(FILE_PATH_LITERAL("white.png"))); } -TEST_P(LayerTreeHostFiltersPixelTest, ImageFilterClipped) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_ImageFilterClipped) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(gfx::Rect(200, 200), SK_ColorYELLOW); @@ -484,7 +532,7 @@ base::FilePath(FILE_PATH_LITERAL("blue_yellow.png"))); } -TEST_P(LayerTreeHostFiltersPixelTest, ImageFilterNonZeroOrigin) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_ImageFilterNonZeroOrigin) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(gfx::Rect(200, 200), SK_ColorYELLOW); @@ -516,7 +564,7 @@ base::FilePath(FILE_PATH_LITERAL("blue_yellow.png"))); } -TEST_P(LayerTreeHostFiltersPixelTest, ImageFilterScaled) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_ImageFilterScaled) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(gfx::Rect(200, 200), SK_ColorWHITE); @@ -643,7 +691,7 @@ .InsertBeforeExtensionASCII(GetRendererSuffix())); } -TEST_P(LayerTreeHostFiltersPixelTest, ImageRenderSurfaceScaled) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_ImageRenderSurfaceScaled) { // A filter will cause a render surface to be used. Here we force the // render surface on, and scale the result to make sure that we rasterize at // the correct resolution. @@ -694,7 +742,7 @@ .InsertBeforeExtensionASCII(GetRendererSuffix())); } -TEST_P(LayerTreeHostFiltersPixelTest, ZoomFilter) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_ZoomFilter) { scoped_refptr<SolidColorLayer> root = CreateSolidColorLayer(gfx::Rect(300, 300), SK_ColorWHITE); @@ -763,7 +811,7 @@ .InsertBeforeExtensionASCII(GetRendererSuffix())); } -TEST_P(LayerTreeHostFiltersPixelTest, RotatedFilter) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_RotatedFilter) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(gfx::Rect(300, 300), SK_ColorWHITE); @@ -896,7 +944,8 @@ base::FilePath(FILE_PATH_LITERAL("translated_blue_green_alpha.png"))); } -TEST_P(LayerTreeHostFiltersPixelTest, EnlargedTextureWithAlphaThresholdFilter) { +TEST_P(LayerTreeHostFiltersPixelTest, + MAYBE_EnlargedTextureWithAlphaThresholdFilter) { // Rectangles chosen so that if flipped, the test will fail. gfx::Rect rect1(10, 10, 10, 15); gfx::Rect rect2(20, 25, 70, 65); @@ -936,7 +985,8 @@ base::FilePath(FILE_PATH_LITERAL("enlarged_texture_on_threshold.png"))); } -TEST_P(LayerTreeHostFiltersPixelTest, EnlargedTextureWithCropOffsetFilter) { +TEST_P(LayerTreeHostFiltersPixelTest, + MAYBE_EnlargedTextureWithCropOffsetFilter) { // Rectangles chosen so that if flipped, the test will fail. gfx::Rect rect1(10, 10, 10, 15); gfx::Rect rect2(20, 25, 70, 65); @@ -974,7 +1024,7 @@ base::FilePath(FILE_PATH_LITERAL("enlarged_texture_on_crop_offset.png"))); } -TEST_P(LayerTreeHostFiltersPixelTest, BlurFilterWithClip) { +TEST_P(LayerTreeHostFiltersPixelTest, MAYBE_BlurFilterWithClip) { scoped_refptr<SolidColorLayer> child1 = CreateSolidColorLayer(gfx::Rect(200, 200), SK_ColorBLUE); scoped_refptr<SolidColorLayer> child2 = @@ -1027,14 +1077,14 @@ .InsertBeforeExtensionASCII(GetRendererSuffix())); } -TEST_P(LayerTreeHostFiltersPixelTestGPU, FilterWithGiantCropRect) { +TEST_P(LayerTreeHostFiltersPixelTestGPU, MAYBE_FilterWithGiantCropRect) { scoped_refptr<SolidColorLayer> tree = BuildFilterWithGiantCropRect(true); RunPixelTest( renderer_type(), tree, base::FilePath(FILE_PATH_LITERAL("filter_with_giant_crop_rect.png"))); } -TEST_P(LayerTreeHostFiltersPixelTestGPU, FilterWithGiantCropRectNoClip) { +TEST_P(LayerTreeHostFiltersPixelTestGPU, MAYBE_FilterWithGiantCropRectNoClip) { scoped_refptr<SolidColorLayer> tree = BuildFilterWithGiantCropRect(false); RunPixelTest( renderer_type(), tree, @@ -1091,12 +1141,12 @@ #endif )); -TEST_P(BackdropFilterWithDeviceScaleFactorTest, StandardDpi) { +TEST_P(BackdropFilterWithDeviceScaleFactorTest, MAYBE_StandardDpi) { RunPixelTestType( 1.f, base::FilePath(FILE_PATH_LITERAL("offset_backdrop_filter_1x.png"))); } -TEST_P(BackdropFilterWithDeviceScaleFactorTest, HiDpi) { +TEST_P(BackdropFilterWithDeviceScaleFactorTest, MAYBE_HiDpi) { RunPixelTestType( 2.f, base::FilePath(FILE_PATH_LITERAL("offset_backdrop_filter_2x.png"))); }
diff --git a/chrome/android/features/keyboard_accessory/BUILD.gn b/chrome/android/features/keyboard_accessory/BUILD.gn index a33f1ff5..5384a03 100644 --- a/chrome/android/features/keyboard_accessory/BUILD.gn +++ b/chrome/android/features/keyboard_accessory/BUILD.gn
@@ -42,6 +42,7 @@ "javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_component/AccessorySheetViewTest.java", "javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessorySheetViewTest.java", "javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessoryIntegrationTest.java", + "javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewTest.java", "javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryIntegrationTest.java", "javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetViewTest.java", "javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewTest.java",
diff --git a/chrome/android/features/keyboard_accessory/internal/BUILD.gn b/chrome/android/features/keyboard_accessory/internal/BUILD.gn index 08ca7def..9f44c1d 100644 --- a/chrome/android/features/keyboard_accessory/internal/BUILD.gn +++ b/chrome/android/features/keyboard_accessory/internal/BUILD.gn
@@ -61,7 +61,10 @@ "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessoryInfoView.java", "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessorySheetCoordinator.java", "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessorySheetViewBinder.java", + "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessoryInfoView.java", "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetCoordinator.java", + "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetMediator.java", + "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewBinder.java", "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryInfoView.java", "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetCoordinator.java", "java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewBinder.java",
diff --git a/chrome/android/features/keyboard_accessory/internal/java/res/layout/credit_card_accessory_sheet.xml b/chrome/android/features/keyboard_accessory/internal/java/res/layout/credit_card_accessory_sheet.xml new file mode 100644 index 0000000..6309f7eb --- /dev/null +++ b/chrome/android/features/keyboard_accessory/internal/java/res/layout/credit_card_accessory_sheet.xml
@@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2019 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> + +<android.support.v7.widget.RecyclerView + xmlns:android="http://schemas.android.com/apk/res/android" + android:fillViewport="true" + android:layout_height="match_parent" + android:layout_width="match_parent" + android:clipToPadding="false" + android:paddingBottom="8dp"/>
diff --git a/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_credit_card_info.xml b/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_credit_card_info.xml new file mode 100644 index 0000000..7da04b9 --- /dev/null +++ b/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_credit_card_info.xml
@@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2019 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> + +<org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.CreditCardAccessoryInfoView + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:gravity="top|start" + android:fillViewport="true" + android:layout_height="wrap_content" + android:layout_width="match_parent" + android:paddingStart="@dimen/keyboard_accessory_suggestion_padding" + android:paddingEnd="@dimen/keyboard_accessory_suggestion_padding" + android:layout_marginTop="@dimen/keyboard_accessory_sheet_top_margin" + android:layout_marginBottom="@dimen/keyboard_accessory_sheet_padding" + android:orientation="horizontal"> + + <LinearLayout + android:gravity="center_vertical|start" + android:fillViewport="true" + android:layout_height="wrap_content" + android:paddingTop="@dimen/keyboard_accessory_sheet_padding" + android:paddingBottom="@dimen/keyboard_accessory_sheet_padding" + android:layout_width="0dp" + android:layout_weight="1" + android:orientation="vertical"> + + <org.chromium.ui.widget.ChipView + android:id="@+id/cc_number" + android:gravity="center_vertical|start" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + style="@style/InputChip" /> + + <LinearLayout + android:gravity="center_vertical|start" + android:fillViewport="true" + android:layout_height="@dimen/keyboard_accessory_suggestion_height" + android:paddingTop="@dimen/keyboard_accessory_sheet_padding" + android:paddingBottom="@dimen/keyboard_accessory_sheet_padding" + android:layout_width="match_parent" + android:orientation="horizontal"> + + <org.chromium.ui.widget.ChipView + android:id="@+id/exp_month" + android:gravity="center_vertical|start" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + style="@style/InputChip" /> + + <TextView + android:text="/" + tools:ignore="HardcodedText" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:paddingStart="@dimen/keyboard_accessory_sheet_padding" + android:paddingEnd="@dimen/keyboard_accessory_sheet_padding" + android:textAppearance="@style/TextAppearance.BlackHint1" + /> + + <org.chromium.ui.widget.ChipView + android:id="@+id/exp_year" + android:gravity="center_vertical|start" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + style="@style/InputChip" /> + + </LinearLayout> + + + <org.chromium.ui.widget.ChipView + android:id="@+id/cardholder" + android:gravity="center_vertical|start" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + style="@style/InputChip" /> + + </LinearLayout> + + <!-- TODO(crbug.com/969708): Replace placeholder dimensions once icon is replaced --> + <ImageView + android:id="@+id/icon" + android:layout_width="@dimen/keyboard_accessory_suggestion_icon_size" + android:layout_height="@dimen/keyboard_accessory_suggestion_icon_size" + android:layout_weight="0" + android:importantForAccessibility="no" + android:layout_gravity="top|end" /> + +</org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.CreditCardAccessoryInfoView>
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabModel.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabModel.java index e37796c..b293d4e 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabModel.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabModel.java
@@ -37,7 +37,7 @@ */ int PASSWORD_INFO = 2; /** - * A section containing a users name, address, etc. + * A section containing a user's name, address, etc. */ int ADDRESS_INFO = 3; /**
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessoryInfoView.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessoryInfoView.java new file mode 100644 index 0000000..bde2085 --- /dev/null +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessoryInfoView.java
@@ -0,0 +1,72 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.keyboard_accessory.sheet_tabs; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.support.annotation.Nullable; +import android.util.AttributeSet; +import android.view.View; +import android.widget.ImageView; +import android.widget.LinearLayout; + +import org.chromium.chrome.browser.keyboard_accessory.R; +import org.chromium.ui.widget.ChipView; + +/** + * This view represents a section of user credit card details in the payment method tab of the + * keyboard accessory (manual fallback) sheet. + */ + +class CreditCardAccessoryInfoView extends LinearLayout { + private ImageView mIcon; + private ChipView mCCNumber; + private ChipView mExpMonth; + private ChipView mExpYear; + private ChipView mCardholder; + + /** + * Constructor for inflating from XML. + */ + public CreditCardAccessoryInfoView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected void onFinishInflate() { + super.onFinishInflate(); + + mIcon = findViewById(R.id.icon); + mCCNumber = findViewById(R.id.cc_number); + mExpMonth = findViewById(R.id.exp_month); + mExpYear = findViewById(R.id.exp_year); + mCardholder = findViewById(R.id.cardholder); + } + + public void setIcon(@Nullable Drawable drawable) { + if (drawable == null) { + mIcon.setVisibility(View.GONE); + return; + } + mIcon.setVisibility(View.VISIBLE); + mIcon.setImageDrawable(drawable); + } + + public ChipView getCCNumber() { + return mCCNumber; + } + + public ChipView getExpMonth() { + return mExpMonth; + } + + public ChipView getExpYear() { + return mExpYear; + } + + public ChipView getCardholder() { + return mCardholder; + } +}
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetCoordinator.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetCoordinator.java index d6f16bde..82a7f162 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetCoordinator.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetCoordinator.java
@@ -8,6 +8,7 @@ import android.support.annotation.Nullable; import android.support.v7.content.res.AppCompatResources; import android.support.v7.widget.RecyclerView; +import android.view.ViewGroup; import org.chromium.chrome.browser.keyboard_accessory.AccessoryTabType; import org.chromium.chrome.browser.keyboard_accessory.R; @@ -30,18 +31,22 @@ */ public CreditCardAccessorySheetCoordinator( Context context, @Nullable RecyclerView.OnScrollListener scrollListener) { - super( // TODO(crbug.com/926365): Add an appropriate title, icon, and restructure this class - // to use an Icon Provider with a static instance of the resource. - context.getString(R.string.autofill_payment_methods), - AppCompatResources.getDrawable(context, R.drawable.ic_info_outline_grey), - // TODO(crbug.com/926365): Add strings and resources properly. - "Open credit card sheet", "Credit card sheet is open", - // TODO(crbug.com/926365): Add a new layout, or generalize the existing one. - R.layout.password_accessory_sheet, AccessoryTabType.CREDIT_CARDS, scrollListener); + super(context.getString(R.string.autofill_payment_methods), + AppCompatResources.getDrawable(context, R.drawable.infobar_autofill_cc), + context.getString(R.string.credit_card_accessory_sheet_toggle), + context.getString(R.string.credit_card_accessory_sheet_opened), + R.layout.credit_card_accessory_sheet, AccessoryTabType.CREDIT_CARDS, + scrollListener); } @Override protected AccessorySheetTabMediator getMediator() { return mMediator; } + + @Override + public void onTabCreated(ViewGroup view) { + super.onTabCreated(view); + CreditCardAccessorySheetViewBinder.initializeView((RecyclerView) view, mModel); + } }
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetMediator.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetMediator.java new file mode 100644 index 0000000..c525ba04 --- /dev/null +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetMediator.java
@@ -0,0 +1,54 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.keyboard_accessory.sheet_tabs; + +import org.chromium.chrome.browser.ChromeFeatureList; +import org.chromium.chrome.browser.keyboard_accessory.AccessoryTabType; +import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData.AccessorySheetData; +import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData.FooterCommand; +import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData.UserInfo; +import org.chromium.chrome.browser.keyboard_accessory.data.Provider; +import org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.AccessorySheetTabModel.AccessorySheetDataPiece; +import org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.AccessorySheetTabModel.AccessorySheetDataPiece.Type; + +import java.util.ArrayList; +import java.util.List; + +class CreditCardAccessorySheetMediator implements Provider.Observer<AccessorySheetData> { + private final AccessorySheetTabModel mModel; + + @Override + public void onItemAvailable(int typeId, AccessorySheetData accessorySheetData) { + List<AccessorySheetDataPiece> items = new ArrayList<>(); + + if (accessorySheetData != null) { + if (shouldShowTitle(accessorySheetData.getUserInfoList())) { + items.add(new AccessorySheetDataPiece(accessorySheetData.getTitle(), Type.TITLE)); + } + for (UserInfo info : accessorySheetData.getUserInfoList()) { + items.add(new AccessorySheetDataPiece(info, Type.CREDIT_CARD_INFO)); + } + for (FooterCommand command : accessorySheetData.getFooterCommands()) { + items.add(new AccessorySheetDataPiece(command, Type.FOOTER_COMMAND)); + } + } + + mModel.set(items.toArray(new AccessorySheetDataPiece[0])); + } + + CreditCardAccessorySheetMediator(AccessorySheetTabModel model) { + mModel = model; + } + + void onTabShown() { + AccessorySheetTabMetricsRecorder.recordSheetSuggestions( + AccessoryTabType.CREDIT_CARDS, mModel); + } + + private boolean shouldShowTitle(List<UserInfo> userInfoList) { + return !ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY) + || userInfoList.isEmpty(); + } +}
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewBinder.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewBinder.java new file mode 100644 index 0000000..205259e --- /dev/null +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewBinder.java
@@ -0,0 +1,77 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.keyboard_accessory.sheet_tabs; + +import android.support.v7.content.res.AppCompatResources; +import android.support.v7.widget.RecyclerView; +import android.view.View; +import android.view.ViewGroup; + +import org.chromium.chrome.browser.keyboard_accessory.R; +import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData; +import org.chromium.chrome.browser.keyboard_accessory.data.UserInfoField; +import org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.AccessorySheetTabModel.AccessorySheetDataPiece; +import org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.AccessorySheetTabViewBinder.ElementViewHolder; +import org.chromium.ui.modelutil.RecyclerViewAdapter; +import org.chromium.ui.modelutil.SimpleRecyclerViewMcp; +import org.chromium.ui.widget.ChipView; + +class CreditCardAccessorySheetViewBinder { + static ElementViewHolder create(ViewGroup parent, @AccessorySheetDataPiece.Type int viewType) { + switch (viewType) { + case AccessorySheetDataPiece.Type.TITLE: + return new AccessorySheetTabViewBinder.TitleViewHolder( + parent, R.layout.keyboard_accessory_sheet_tab_title); + case AccessorySheetDataPiece.Type.CREDIT_CARD_INFO: + return new CreditCardInfoViewHolder(parent); + case AccessorySheetDataPiece.Type.FOOTER_COMMAND: + return AccessorySheetTabViewBinder.create(parent, viewType); + } + assert false : "Unhandled type of data piece: " + viewType; + return null; + } + + /** + * View which represents a single credit card and its selectable fields. + */ + static class CreditCardInfoViewHolder + extends ElementViewHolder<KeyboardAccessoryData.UserInfo, CreditCardAccessoryInfoView> { + CreditCardInfoViewHolder(ViewGroup parent) { + super(parent, R.layout.keyboard_accessory_sheet_tab_credit_card_info); + } + + @Override + protected void bind(KeyboardAccessoryData.UserInfo info, CreditCardAccessoryInfoView view) { + bindChipView(view.getCCNumber(), info.getFields().get(0)); + bindChipView(view.getExpMonth(), info.getFields().get(1)); + bindChipView(view.getExpYear(), info.getFields().get(2)); + bindChipView(view.getCardholder(), info.getFields().get(3)); + + // TODO(crbug.com/969708): Replace placeholder icon with data-specific icon. + view.setIcon(AppCompatResources.getDrawable( + view.getContext(), R.drawable.infobar_autofill_cc)); + } + + void bindChipView(ChipView chip, UserInfoField field) { + chip.getPrimaryTextView().setText(field.getDisplayText()); + chip.getPrimaryTextView().setContentDescription(field.getA11yDescription()); + if (!field.isSelectable() || field.getDisplayText().isEmpty()) { + chip.setVisibility(View.GONE); + return; + } + chip.setVisibility(View.VISIBLE); + chip.setOnClickListener(src -> field.triggerSelection()); + chip.setClickable(true); + chip.setEnabled(true); + } + } + + static void initializeView(RecyclerView view, AccessorySheetTabModel model) { + view.setAdapter(new RecyclerViewAdapter<>( + new SimpleRecyclerViewMcp<>(model, AccessorySheetDataPiece::getType, + AccessorySheetTabViewBinder.ElementViewHolder::bind), + CreditCardAccessorySheetViewBinder::create)); + } +}
diff --git a/chrome/android/features/keyboard_accessory/internal/java/strings/android_keyboard_accessory_strings.grd b/chrome/android/features/keyboard_accessory/internal/java/strings/android_keyboard_accessory_strings.grd index 13c4690f..fd406cf 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/strings/android_keyboard_accessory_strings.grd +++ b/chrome/android/features/keyboard_accessory/internal/java/strings/android_keyboard_accessory_strings.grd
@@ -139,6 +139,12 @@ <message name="IDS_ADDRESS_ACCESSORY_SHEET_OPENED" desc="Accessibility announcement when opening an address bottom sheet containing saved addresses."> Showing saved addresses </message> + <message name="IDS_CREDIT_CARD_ACCESSORY_SHEET_TOGGLE" desc="Description for the icon button used to open and close the payment method accessory sheet, where users' saved payment methods (e.g., credit cards) are shown for use when filling web forms."> + Show payment methods + </message> + <message name="IDS_CREDIT_CARD_ACCESSORY_SHEET_OPENED" desc="Accessibility announcement when opening a sheet containing users' saved payment methods (e.g., credit cards) for use when filling web forms."> + Showing saved payment methods + </message> </messages> </release> </grit>
diff --git a/chrome/android/features/keyboard_accessory/internal/java/strings/android_keyboard_accessory_strings_grd/IDS_CREDIT_CARD_ACCESSORY_SHEET_TOGGLE.png.sha1 b/chrome/android/features/keyboard_accessory/internal/java/strings/android_keyboard_accessory_strings_grd/IDS_CREDIT_CARD_ACCESSORY_SHEET_TOGGLE.png.sha1 new file mode 100644 index 0000000..b97a0a0 --- /dev/null +++ b/chrome/android/features/keyboard_accessory/internal/java/strings/android_keyboard_accessory_strings_grd/IDS_CREDIT_CARD_ACCESSORY_SHEET_TOGGLE.png.sha1
@@ -0,0 +1 @@ +f6e66b2459b9373c0d49a02b75841ec5edcc12b9 \ No newline at end of file
diff --git a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewTest.java b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewTest.java new file mode 100644 index 0000000..e1e28901 --- /dev/null +++ b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewTest.java
@@ -0,0 +1,183 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.keyboard_accessory.sheet_tabs; + +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +import android.support.annotation.IdRes; +import android.support.test.filters.MediumTest; +import android.support.v7.widget.RecyclerView; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.chrome.browser.ChromeSwitches; +import org.chromium.chrome.browser.keyboard_accessory.AccessoryTabType; +import org.chromium.chrome.browser.keyboard_accessory.R; +import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData; +import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData.UserInfo; +import org.chromium.chrome.browser.keyboard_accessory.data.UserInfoField; +import org.chromium.chrome.browser.keyboard_accessory.sheet_component.AccessorySheetCoordinator; +import org.chromium.chrome.browser.keyboard_accessory.sheet_tabs.AccessorySheetTabModel.AccessorySheetDataPiece; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.ChromeTabbedActivityTestRule; +import org.chromium.content_public.browser.test.util.Criteria; +import org.chromium.content_public.browser.test.util.CriteriaHelper; +import org.chromium.content_public.browser.test.util.TestThreadUtils; +import org.chromium.ui.widget.ChipView; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +/** + * View tests for the credit card accessory sheet. + */ +@RunWith(ChromeJUnit4ClassRunner.class) +@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) +public class CreditCardAccessorySheetViewTest { + private final AccessorySheetTabModel mModel = new AccessorySheetTabModel(); + private AtomicReference<RecyclerView> mView = new AtomicReference<>(); + + @Rule + public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); + + @Before + public void setUp() throws InterruptedException { + mActivityTestRule.startMainActivityOnBlankPage(); + TestThreadUtils.runOnUiThreadBlocking(() -> { + AccessorySheetCoordinator accessorySheet = + new AccessorySheetCoordinator(mActivityTestRule.getActivity().findViewById( + R.id.keyboard_accessory_sheet_stub)); + accessorySheet.setTabs(new KeyboardAccessoryData.Tab[] {new KeyboardAccessoryData.Tab( + "Credit Cards", null, null, R.layout.credit_card_accessory_sheet, + AccessoryTabType.CREDIT_CARDS, new KeyboardAccessoryData.Tab.Listener() { + @Override + public void onTabCreated(ViewGroup view) { + mView.set((RecyclerView) view); + AccessorySheetTabViewBinder.initializeView(mView.get(), null); + CreditCardAccessorySheetViewBinder.initializeView(mView.get(), mModel); + } + + @Override + public void onTabShown() {} + })}); + accessorySheet.setHeight( + mActivityTestRule.getActivity().getResources().getDimensionPixelSize( + R.dimen.keyboard_accessory_sheet_height)); + accessorySheet.show(); + }); + CriteriaHelper.pollUiThread(Criteria.equals(true, () -> mView.get() != null)); + } + + @After + public void tearDown() { + mView.set(null); + } + + @Test + @MediumTest + public void testAddingCaptionsToTheModelRendersThem() { + assertThat(mView.get().getChildCount(), is(0)); + + TestThreadUtils.runOnUiThreadBlocking(() -> { + mModel.add(new AccessorySheetDataPiece( + "Credit Cards", AccessorySheetDataPiece.Type.TITLE)); + }); + + CriteriaHelper.pollUiThread(Criteria.equals(1, () -> mView.get().getChildCount())); + View title = mView.get().findViewById(R.id.tab_title); + assertThat(title, is(not(nullValue()))); + assertThat(title, instanceOf(TextView.class)); + assertThat(((TextView) title).getText(), is("Credit Cards")); + } + + @Test + @MediumTest + public void testAddingUserInfoToTheModelRendersClickableActions() throws ExecutionException { + final AtomicBoolean clicked = new AtomicBoolean(); + assertThat(mView.get().getChildCount(), is(0)); + + TestThreadUtils.runOnUiThreadBlocking(() -> { + mModel.add(new AccessorySheetDataPiece( + createInfo("4111111111111111", "04", "2034", "Kirby Puckett", clicked), + AccessorySheetDataPiece.Type.CREDIT_CARD_INFO)); + mModel.add(new AccessorySheetDataPiece( + new KeyboardAccessoryData.FooterCommand("Manage credit cards", null), + AccessorySheetDataPiece.Type.FOOTER_COMMAND)); + }); + + CriteriaHelper.pollUiThread(Criteria.equals(2, () -> mView.get().getChildCount())); + + // Check that the titles are correct: + assertThat(getChipText(R.id.cc_number), is("4111111111111111")); + assertThat(getChipText(R.id.exp_month), is("04")); + assertThat(getChipText(R.id.exp_year), is("2034")); + assertThat(getChipText(R.id.cardholder), is("Kirby Puckett")); + + // Chips are clickable: + TestThreadUtils.runOnUiThreadBlocking(findChipView(R.id.cc_number)::performClick); + assertThat(clicked.get(), is(true)); + clicked.set(false); + TestThreadUtils.runOnUiThreadBlocking(findChipView(R.id.exp_month)::performClick); + assertThat(clicked.get(), is(true)); + } + + @Test + @MediumTest + public void testEmptyChipsAreNotVisible() throws ExecutionException { + final AtomicBoolean clicked = new AtomicBoolean(); + assertThat(mView.get().getChildCount(), is(0)); + + TestThreadUtils.runOnUiThreadBlocking(() -> { + mModel.add(new AccessorySheetDataPiece( + // Cardholder name is empty + createInfo("4111111111111111", "04", "2034", "", clicked), + AccessorySheetDataPiece.Type.CREDIT_CARD_INFO)); + mModel.add(new AccessorySheetDataPiece( + new KeyboardAccessoryData.FooterCommand("Manage credit cards", null), + AccessorySheetDataPiece.Type.FOOTER_COMMAND)); + }); + + CriteriaHelper.pollUiThread(Criteria.equals(2, () -> mView.get().getChildCount())); + + assertThat(findChipView(R.id.cardholder).isShown(), is(false)); + } + + private UserInfo createInfo( + String number, String month, String year, String name, AtomicBoolean clickRecorder) { + UserInfo info = new UserInfo(null); + info.addField(new UserInfoField(number, number, false, item -> clickRecorder.set(true))); + info.addField(new UserInfoField(month, month, false, item -> clickRecorder.set(true))); + info.addField(new UserInfoField(year, year, false, item -> clickRecorder.set(true))); + info.addField(new UserInfoField(name, name, false, item -> clickRecorder.set(true))); + return info; + } + + private ChipView findChipView(@IdRes int id) { + assertThat(mView.get().getChildAt(0), instanceOf(LinearLayout.class)); + LinearLayout layout = (LinearLayout) mView.get().getChildAt(0); + View view = layout.findViewById(id); + assertThat(view, is(not(nullValue()))); + assertThat(view, instanceOf(ChipView.class)); + return ((ChipView) view); + } + + private CharSequence getChipText(@IdRes int id) { + return findChipView(id).getPrimaryTextView().getText(); + } +}
diff --git a/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponent.java b/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponent.java index 0ba19d1..17d65fa 100644 --- a/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponent.java +++ b/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponent.java
@@ -56,7 +56,7 @@ * By registering a provider, an empty tab of the given tab type is created. Call * {@link PropertyProvider#notifyObservers(Object)} to fill or update the sheet. * @param sheetType The type of sheet to instantiate and to provide data for. - * @param sheetDataProvider The {@link PropertyProvider} the tab will get it's data from. + * @param sheetDataProvider The {@link PropertyProvider} the tab will get its data from. */ void registerSheetDataProvider(@AccessoryTabType int sheetType, PropertyProvider<KeyboardAccessoryData.AccessorySheetData> sheetDataProvider);
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGridContainerViewBinderTest.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGridContainerViewBinderTest.java index c4c968fe..2d0e233 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGridContainerViewBinderTest.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGridContainerViewBinderTest.java
@@ -8,8 +8,9 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; +import android.animation.ValueAnimator; import android.graphics.drawable.ColorDrawable; -import android.os.Build; +import android.provider.Settings; import android.support.test.annotation.UiThreadTest; import android.support.test.filters.MediumTest; import android.view.View; @@ -20,6 +21,7 @@ import org.junit.runner.RunWith; import org.chromium.base.ApiCompatibilityUtils; +import org.chromium.base.ContextUtils; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.DisabledTest; import org.chromium.chrome.tab_ui.R; @@ -111,8 +113,7 @@ assertThat(mStartedShowingCallback.getCallCount(), equalTo(1)); assertThat(mRecyclerView.getVisibility(), equalTo(View.VISIBLE)); - // TODO(yusufo): Find a way to test this on KitKat. - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { + if (areAnimatorsEnabled()) { assertThat(mRecyclerView.getAlpha(), equalTo(0.0f)); } assertThat(mIsAnimating, equalTo(true)); @@ -163,8 +164,7 @@ assertThat(mStartedHidingCallback.getCallCount(), equalTo(1)); assertThat(mRecyclerView.getVisibility(), equalTo(View.VISIBLE)); - // TODO(yusufo): Find a way to test this on KitKat. - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { + if (areAnimatorsEnabled()) { assertThat(mRecyclerView.getAlpha(), equalTo(1.0f)); } assertThat(mIsAnimating, equalTo(true)); @@ -172,10 +172,11 @@ CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { - return mRecyclerView.getAlpha() == 0.0f; + // Invisibility signals the end of the animation, not alpha being zero. + return mRecyclerView.getVisibility() == View.INVISIBLE; } }); - assertThat(mRecyclerView.getVisibility(), equalTo(View.INVISIBLE)); + assertThat(mRecyclerView.getAlpha(), equalTo(0.0f)); } @Test @@ -248,4 +249,17 @@ mMCP.destroy(); super.tearDownTest(); } + + /** + * Should be the same as {@link ValueAnimator#areAnimatorsEnabled}, which requires API level 26. + */ + public static boolean areAnimatorsEnabled() { + // We default to assuming that animations are enabled in case ANIMATOR_DURATION_SCALE is not + // defined. + final float defaultScale = 1f; + float durationScale = + Settings.Global.getFloat(ContextUtils.getApplicationContext().getContentResolver(), + Settings.Global.ANIMATOR_DURATION_SCALE, defaultScale); + return !(durationScale == 0.0); + } }
diff --git a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java index 77a6c64a..52ac0e5 100644 --- a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java +++ b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java
@@ -99,8 +99,21 @@ @Override public void show(String message, String action, SnackbarCallbackApi callback) { - // TODO(https://crbug.com/924742): Set action text and correctly invoke callback. - show(message); + mManager.showSnackbar( + Snackbar.make(message, + new SnackbarManager.SnackbarController() { + @Override + public void onAction(Object actionData) { + callback.onDismissedWithAction(); + } + + @Override + public void onDismissNoAction(Object actionData) { + callback.onDismissNoAction(); + } + }, + Snackbar.TYPE_ACTION, Snackbar.UMA_FEED_NTP_STREAM) + .setAction(action, null)); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayoutBase.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayoutBase.java index 95dee59..65f1b77 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayoutBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayoutBase.java
@@ -523,11 +523,13 @@ }; if (mNavigationEnabled && mNavigationHandler == null) { Tab currentTab = mTabModelSelector.getCurrentTab(); - mNavigationHandler = new NavigationHandler(mViewContainer, - new TabSwitcherActionDelegate(currentTab.getActivity()::onBackPressed, - mTabModelSelector::getCurrentTab), - NavigationGlowFactory.forSceneLayer(mViewContainer, mSceneLayer, - currentTab.getActivity().getWindowAndroid())); + if (currentTab != null) { + mNavigationHandler = new NavigationHandler(mViewContainer, + new TabSwitcherActionDelegate(currentTab.getActivity()::onBackPressed, + mTabModelSelector::getCurrentTab), + NavigationGlowFactory.forSceneLayer(mViewContainer, mSceneLayer, + currentTab.getActivity().getWindowAndroid())); + } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java index 27e5636..4d8638d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java
@@ -415,7 +415,7 @@ // (1) if (!initialized) { - tasks.add(() -> { + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> { try (TraceEvent e = TraceEvent.scoped("CustomTabsConnection.initializeBrowser()")) { initializeBrowser(ContextUtils.getApplicationContext()); ChromeBrowserInitializer.getInstance().initNetworkChangeNotifier(); @@ -426,7 +426,7 @@ // (2) if (mayCreateSpareWebContents && !mHiddenTabHolder.hasHiddenTab()) { - tasks.add(() -> { + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> { // Temporary fix for https://crbug.com/797832. // TODO(lizeb): Properly fix instead of papering over the bug, this code should // not be scheduled unless startup is done. See https://crbug.com/797832. @@ -441,7 +441,7 @@ } // (3) - tasks.add(() -> { + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> { try (TraceEvent e = TraceEvent.scoped("InitializeViewHierarchy")) { WarmupManager.getInstance().initializeViewHierarchy( ContextUtils.getApplicationContext(), @@ -450,7 +450,7 @@ }); if (!initialized) { - tasks.add(() -> { + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> { try (TraceEvent e = TraceEvent.scoped("WarmupInternalFinishInitialization")) { // (4) Profile profile = Profile.getLastUsedProfile(); @@ -465,7 +465,7 @@ }); } - tasks.add(() -> notifyWarmupIsDone(uid)); + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> notifyWarmupIsDone(uid)); tasks.start(false); mWarmupTasks = tasks; return true;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ChainedTasks.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ChainedTasks.java index c2614cc..ee157a2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ChainedTasks.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ChainedTasks.java
@@ -4,7 +4,11 @@ package org.chromium.chrome.browser.init; +import android.util.Pair; + import org.chromium.base.ThreadUtils; +import org.chromium.base.task.PostTask; +import org.chromium.base.task.TaskTraits; import java.util.LinkedList; @@ -18,15 +22,16 @@ * - {@link cancel()} must be called from the UI thread. */ public class ChainedTasks { - private LinkedList<Runnable> mTasks = new LinkedList<>(); + private LinkedList<Pair<TaskTraits, Runnable>> mTasks = new LinkedList<>(); private volatile boolean mFinalized; private final Runnable mRunAndPost = new Runnable() { @Override public void run() { if (mTasks.isEmpty()) return; - mTasks.pop().run(); - ThreadUtils.postOnUiThread(this); + Pair<TaskTraits, Runnable> pair = mTasks.pop(); + pair.second.run(); + if (!mTasks.isEmpty()) PostTask.postTask(mTasks.peek().first, this); } }; @@ -34,9 +39,9 @@ * Adds a task to the list of tasks to run. Cannot be called once {@link start()} has been * called. */ - public void add(Runnable task) { + public void add(TaskTraits traits, Runnable task) { if (mFinalized) throw new IllegalStateException("Must not call add() after start()"); - mTasks.add(task); + mTasks.add(new Pair<>(traits, task)); } /** @@ -59,16 +64,17 @@ public void start(final boolean coalesceTasks) { if (mFinalized) throw new IllegalStateException("Cannot call start() several times"); mFinalized = true; + if (mTasks.isEmpty()) return; if (coalesceTasks) { - ThreadUtils.runOnUiThread(new Runnable() { + PostTask.runOrPostTask(mTasks.peek().first, new Runnable() { @Override public void run() { - for (Runnable task : mTasks) task.run(); + for (Pair<TaskTraits, Runnable> pair : mTasks) pair.second.run(); mTasks.clear(); } }); } else { - ThreadUtils.postOnUiThread(mRunAndPost); + PostTask.postTask(mTasks.peek().first, mRunAndPost); } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java index 430c73e..3a7c11ba 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java
@@ -279,14 +279,15 @@ // launch its required components. if (!delegate.startServiceManagerOnly() && !ProcessInitializationHandler.getInstance().postNativeInitializationComplete()) { - tasks.add(() -> ProcessInitializationHandler.getInstance().initializePostNative()); + tasks.add(UiThreadTaskTraits.BOOTSTRAP, + () -> ProcessInitializationHandler.getInstance().initializePostNative()); } if (!mNetworkChangeNotifierInitializationComplete) { - tasks.add(this::initNetworkChangeNotifier); + tasks.add(UiThreadTaskTraits.BOOTSTRAP, this::initNetworkChangeNotifier); } - tasks.add(() -> { + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> { // This is not broken down as a separate task, since this: // 1. Should happen as early as possible // 2. Only submits asynchronous work @@ -299,23 +300,25 @@ onStartNativeInitialization(); }); - tasks.add(() -> { + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> { if (delegate.isActivityFinishingOrDestroyed()) return; delegate.initializeCompositor(); }); - tasks.add(() -> { + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> { if (delegate.isActivityFinishingOrDestroyed()) return; delegate.initializeState(); }); - if (!mNativeInitializationComplete) tasks.add(this::onFinishNativeInitialization); - - tasks.add(() -> { + tasks.add(UiThreadTaskTraits.BOOTSTRAP, () -> { if (delegate.isActivityFinishingOrDestroyed()) return; + // Some tasks posted by this are on the critical path. delegate.startNativeInitialization(); }); + if (!mNativeInitializationComplete) + tasks.add(UiThreadTaskTraits.DEFAULT, this::onFinishNativeInitialization); + if (isAsync) { // We want to start this queue once the C++ startup tasks have run; allow the // C++ startup to run asynchonously, and set it up to start the Java queue once
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java b/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java index 04958d11..db17acb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java
@@ -15,7 +15,6 @@ import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; import org.chromium.base.Log; -import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.task.AsyncTask; @@ -299,7 +298,8 @@ initializeAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // Cancel the initialization if it reaches timeout. - ThreadUtils.postOnUiThreadDelayed(() -> initializeAsyncTask.cancel(true), timeoutMs); + PostTask.postDelayedTask( + UiThreadTaskTraits.DEFAULT, () -> initializeAsyncTask.cancel(true), timeoutMs); } /** @@ -325,7 +325,7 @@ public static void setOnInitializeAsyncFinished(final Runnable callback, long timeoutMs) { sInitializeAsyncCallbacks.add(callback); - ThreadUtils.postOnUiThreadDelayed(() -> { + PostTask.postDelayedTask(UiThreadTaskTraits.DEFAULT, () -> { if (sInitializeAsyncCallbacks.remove(callback)) callback.run(); }, sIsInitialized ? 0 : timeoutMs); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java index 5eeb82f..29af8cce 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.photo_picker; +import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.res.Configuration; @@ -445,6 +446,12 @@ mWorkerTask.cancel(true); } + // TODO(finnur): Remove once we figure out the cause of crbug.com/950024. + if (!mActivity.getWindowAndroid().hasPermission( + Manifest.permission.READ_EXTERNAL_STORAGE)) { + throw new RuntimeException("Bitmap enumeration without storage read permission"); + } + mEnumStartTime = SystemClock.elapsedRealtime(); mWorkerTask = new FileEnumWorkerTask(mActivity.getWindowAndroid(), this, new MimeTypeFilter(mMimeTypes, true), mMimeTypes, mActivity.getContentResolver());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ServicificationBackgroundServiceTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ServicificationBackgroundServiceTest.java index 407fff9..9316cb8 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ServicificationBackgroundServiceTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/ServicificationBackgroundServiceTest.java
@@ -20,7 +20,6 @@ import org.chromium.base.StrictModeContext; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.init.ServiceManagerStartupUtils; @@ -88,10 +87,9 @@ MappedByteBuffer mappedByteBuffer = mMappedSpareFile.getChannel().map( FileChannel.MapMode.READ_WRITE, 0, ALLOC_SIZE); - mappedByteBuffer.load(); - Assert.assertTrue(mappedByteBuffer.isLoaded()); mappedByteBuffer.put(0, (byte) 0); + mappedByteBuffer.force(); Assert.assertTrue(Byte.compare(mappedByteBuffer.get(0), (byte) 0) == 0); } catch (Exception e) { Log.d(TAG, "Fail to create memory-mapped file: %s", SPARE_FILE_NAME); @@ -123,7 +121,6 @@ @Feature({"ServicificationStartup"}) @CommandLineFlags.Add({"enable-features=NetworkService,AllowStartingServiceManagerOnly," + "WriteBasicSystemProfileToPersistentHistogramsFile"}) - @DisabledTest(message = "https://crbug.com/970190") public void testHistogramsPersistedWithServiceManagerOnlyStart() { createBrowserMetricsSpareFile();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/init/ChainedTasksTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/init/ChainedTasksTest.java index 1ab18b2..fc07634d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/init/ChainedTasksTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/init/ChainedTasksTest.java
@@ -50,7 +50,9 @@ Arrays.asList(new String[] {"First", "Second", "Third"}); final List<String> messages = new ArrayList<>(); final ChainedTasks tasks = new ChainedTasks(); - for (String message : expectedMessages) tasks.add(new TestRunnable(messages, message)); + for (String message : expectedMessages) { + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, message)); + } TestThreadUtils.runOnUiThreadBlocking(() -> { tasks.start(true); @@ -65,7 +67,7 @@ final Semaphore finished = new Semaphore(0); final ChainedTasks tasks = new ChainedTasks(); - tasks.add(new Runnable() { + tasks.add(UiThreadTaskTraits.DEFAULT, new Runnable() { @Override public void run() { try { @@ -78,8 +80,10 @@ List<String> expectedMessages = Arrays.asList(new String[] {"First", "Second", "Third"}); final List<String> messages = new ArrayList<>(); - for (String message : expectedMessages) tasks.add(new TestRunnable(messages, message)); - tasks.add(new Runnable() { + for (String message : expectedMessages) { + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, message)); + } + tasks.add(UiThreadTaskTraits.DEFAULT, new Runnable() { @Override public void run() { finished.release(); @@ -102,8 +106,10 @@ final ChainedTasks tasks = new ChainedTasks(); final Semaphore finished = new Semaphore(0); - for (String message : expectedMessages) tasks.add(new TestRunnable(messages, message)); - tasks.add(new Runnable() { + for (String message : expectedMessages) { + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, message)); + } + tasks.add(UiThreadTaskTraits.DEFAULT, new Runnable() { @Override public void run() { finished.release(); @@ -131,9 +137,9 @@ // Posts 2 tasks, waits for a high priority task to be posted from another thread, and // carries on. - tasks.add(new TestRunnable(messages, "First")); - tasks.add(new TestRunnable(messages, "Second")); - tasks.add(new Runnable() { + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, "First")); + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, "Second")); + tasks.add(UiThreadTaskTraits.DEFAULT, new Runnable() { @Override public void run() { try { @@ -144,8 +150,8 @@ } } }); - tasks.add(new TestRunnable(messages, "Third")); - tasks.add(new Runnable() { + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, "Third")); + tasks.add(UiThreadTaskTraits.DEFAULT, new Runnable() { @Override public void run() { finished.release(); @@ -169,16 +175,16 @@ final ChainedTasks tasks = new ChainedTasks(); final Semaphore finished = new Semaphore(0); - tasks.add(new TestRunnable(messages, "First")); - tasks.add(new TestRunnable(messages, "Second")); - tasks.add(new Runnable() { + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, "First")); + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, "Second")); + tasks.add(UiThreadTaskTraits.DEFAULT, new Runnable() { @Override public void run() { tasks.cancel(); } }); - tasks.add(new TestRunnable(messages, "Third")); - tasks.add(new Runnable() { + tasks.add(UiThreadTaskTraits.DEFAULT, new TestRunnable(messages, "Third")); + tasks.add(UiThreadTaskTraits.DEFAULT, new Runnable() { @Override public void run() { finished.release();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/MainIntentBehaviorMetricsIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/MainIntentBehaviorMetricsIntegrationTest.java index beba824..a266180 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/MainIntentBehaviorMetricsIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/MainIntentBehaviorMetricsIntegrationTest.java
@@ -11,6 +11,7 @@ import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Intent; +import android.net.Uri; import android.support.test.InstrumentationRegistry; import android.support.test.filters.MediumTest; @@ -116,7 +117,11 @@ @MediumTest @Test public void testCreateNtp() { - startActivity(true); + // startActivity(true) creates a NTP which is problematical for this test if + // ChromeTabbedActivity.setupCompositorContent runs before that NTP is created because + // that creates a SimpleAnimationLayout which tries to hide the page resulting in a + // MainIntentActionType.SWITCH_TABS. Starting from about:blank avoids this confusion. + startActivityWithAboutBlank(true); assertMainIntentBehavior(null); TestThreadUtils.runOnUiThreadBlocking( () -> mActivityTestRule.getActivity().getTabCreator(false).launchNTP()); @@ -310,6 +315,18 @@ } } + private void startActivityWithAboutBlank(boolean addLauncherCategory) { + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.setData(Uri.parse("about:blank")); + if (addLauncherCategory) intent.addCategory(Intent.CATEGORY_LAUNCHER); + intent.setComponent(new ComponentName( + InstrumentationRegistry.getTargetContext(), ChromeTabbedActivity.class)); + + mActivityTestRule.startActivityCompletely(intent); + mActivityTestRule.waitForActivityNativeInitializationComplete(); + } + private void startActivity(boolean addLauncherCategory) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerDisableBookmarksEditingUnitTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerDisableBookmarksEditingUnitTest.java index 971cf9a..3d341c3 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerDisableBookmarksEditingUnitTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerDisableBookmarksEditingUnitTest.java
@@ -21,6 +21,7 @@ import org.chromium.base.test.util.Feature; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.partnercustomizations.TestPartnerBrowserCustomizationsDelayedProvider; import org.chromium.chrome.test.partnercustomizations.TestPartnerBrowserCustomizationsProvider; import org.chromium.content_public.browser.test.util.TestThreadUtils; @@ -140,13 +141,12 @@ TestThreadUtils.runOnUiThreadBlocking(() -> { PartnerBrowserCustomizations.initializeAsync(mTestRule.getContextWrapper(), 2000); }); - PartnerBrowserCustomizations.setOnInitializeAsyncFinished(mTestRule.getCallback(), 300); - - mTestRule.getCallbackLock().acquire(); + PartnerBrowserCustomizations.setOnInitializeAsyncFinished(mTestRule.getCallback()); Assert.assertFalse(PartnerBrowserCustomizations.isInitialized()); Assert.assertFalse(PartnerBrowserCustomizations.isBookmarksEditingDisabled()); + TestPartnerBrowserCustomizationsDelayedProvider.unblockQuery(); PartnerBrowserCustomizations.setOnInitializeAsyncFinished(mTestRule.getCallback(), 3000); mTestRule.getCallbackLock().acquire();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerDisableIncognitoModeUnitTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerDisableIncognitoModeUnitTest.java index 1cbd880..324cf389 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerDisableIncognitoModeUnitTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerDisableIncognitoModeUnitTest.java
@@ -21,6 +21,7 @@ import org.chromium.base.test.util.Feature; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.partnercustomizations.TestPartnerBrowserCustomizationsDelayedProvider; import org.chromium.chrome.test.partnercustomizations.TestPartnerBrowserCustomizationsProvider; import org.chromium.content_public.browser.test.util.TestThreadUtils; @@ -140,13 +141,12 @@ TestThreadUtils.runOnUiThreadBlocking(() -> { PartnerBrowserCustomizations.initializeAsync(mTestRule.getContextWrapper(), 2000); }); - PartnerBrowserCustomizations.setOnInitializeAsyncFinished(mTestRule.getCallback(), 300); - - mTestRule.getCallbackLock().acquire(); + PartnerBrowserCustomizations.setOnInitializeAsyncFinished(mTestRule.getCallback()); Assert.assertFalse(PartnerBrowserCustomizations.isInitialized()); Assert.assertFalse(PartnerBrowserCustomizations.isIncognitoDisabled()); + TestPartnerBrowserCustomizationsDelayedProvider.unblockQuery(); PartnerBrowserCustomizations.setOnInitializeAsyncFinished(mTestRule.getCallback(), 3000); mTestRule.getCallbackLock().acquire();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTestFramework.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTestFramework.java index 91a28a5c..718f905 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTestFramework.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTestFramework.java
@@ -23,14 +23,6 @@ } } - @Override - public void enterSessionWithUserGesture() { - super.enterSessionWithUserGesture(); - - PermissionUtils.waitForConsentPrompt(getRule().getActivity()); - PermissionUtils.acceptConsentPrompt(getRule().getActivity()); - } - /** * VR-specific implementation of enterSessionWithUserGesture that includes a workaround for * receiving broadcasts late.
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTransitionTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTransitionTest.java index cdd01eb..b1d59c7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTransitionTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrVrTransitionTest.java
@@ -38,6 +38,7 @@ import org.chromium.base.test.params.ParameterSet; import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.UrlUtils; @@ -206,6 +207,7 @@ @LargeTest @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) @XrActivityRestriction({XrActivityRestriction.SupportedActivity.ALL}) + @DisabledTest(message = "https://crbug.com/969024") public void testNfcFiresVrdisplayactivate() throws InterruptedException { mWebVrTestFramework.loadUrlAndAwaitInitialization( WebVrTestFramework.getFileUrlForHtmlTestFile("test_nfc_fires_vrdisplayactivate"), @@ -286,6 +288,7 @@ @MediumTest @Restriction({RESTRICTION_TYPE_DEVICE_DAYDREAM, RESTRICTION_TYPE_VR_SETTINGS_SERVICE}) @VrSettingsFile(VrSettingsServiceUtils.FILE_DDVIEW_DONENABLED) + @DisabledTest(message = "https://crbug.com/969024") @CommandLineFlags .Remove({"enable-webvr"}) @CommandLineFlags.Add({"enable-features=WebXR"})
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/OpenLastTabMediator.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/OpenLastTabMediator.java index c1c96787..94154c5 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/OpenLastTabMediator.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/OpenLastTabMediator.java
@@ -8,8 +8,12 @@ import static android.text.format.DateUtils.getRelativeTimeSpanString; import android.content.Context; +import android.content.Intent; import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; import android.graphics.Bitmap; +import android.net.Uri; import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskTraits; @@ -43,6 +47,8 @@ private static final String FIRST_LAUNCHED_KEY = "TOUCHLESS_WAS_FIRST_LAUNCHED"; private static final String LAST_REMOVED_VISIT_TIMESTAMP_KEY = "TOUCHLESS_LAST_REMOVED_VISIT_TIMESTAMP"; + // Used to match URLs in Chome's history to PWA launches via webapk. + private static final String WEBAPK_CLASS_NAME = "org.chromium.webapk.shell_apk"; private final Context mContext; private final Profile mProfile; @@ -131,12 +137,25 @@ @Override public void onQueryHistoryComplete(List<HistoryItem> items, boolean hasMorePotentialMatches) { - if (items.size() == 0) { - mHistoryItem = null; - } else { - // First item is most recent. - mHistoryItem = items.get(0); + mHistoryItem = null; + if (items.size() > 0) { + for (int i = 0; i < items.size(); i++) { + HistoryItem currentItem = items.get(i); + // Filter for history items that correspond to PWAs launched through webapk. + if (historyItemMatchesWebApkIntent(currentItem)) { + continue; + } else { + mHistoryItem = currentItem; + break; + } + } + + if (mHistoryItem == null && hasMorePotentialMatches) { + mHistoryBridge.queryHistoryContinuation(); + return; + } } + if (mPreferencesRead) { updateModel(); } @@ -243,4 +262,30 @@ }; mModel.set(OpenLastTabProperties.CONTEXT_MENU_DELEGATE, delegate); } + + /** + * @param item The HistoryItem to check. + * @return True if the HistoryItem corresponds to a PWA launched through webapk. + */ + private boolean historyItemMatchesWebApkIntent(HistoryItem item) { + Uri uri = Uri.parse(item.getUrl()); + Intent intent = new Intent(Intent.ACTION_VIEW, uri); + + List<ResolveInfo> resolveInfo = mContext.getPackageManager().queryIntentActivities( + intent, PackageManager.MATCH_ALL); + if (resolveInfo == null || resolveInfo.isEmpty()) { + return false; + } + for (ResolveInfo info : resolveInfo) { + if (info.activityInfo == null) { + continue; + } + + if (info.activityInfo.name.contains(WEBAPK_CLASS_NAME)) { + return true; + } + } + + return false; + } }
diff --git a/chrome/app_shim/chrome_main_app_mode_mac.mm b/chrome/app_shim/chrome_main_app_mode_mac.mm index a5c4d159..53241ed 100644 --- a/chrome/app_shim/chrome_main_app_mode_mac.mm +++ b/chrome/app_shim/chrome_main_app_mode_mac.mm
@@ -20,10 +20,10 @@ #include "base/mac/mac_logging.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread.h" #include "chrome/app/chrome_crash_reporter_client.h" #include "chrome/app_shim/app_shim_controller.h" @@ -136,8 +136,9 @@ [AppShimApplication sharedApplication]; CHECK([NSApp isKindOfClass:[AppShimApplication class]]); - base::MessageLoopForUI main_message_loop; - ui::WindowResizeHelperMac::Get()->Init(main_message_loop.task_runner()); + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); + ui::WindowResizeHelperMac::Get()->Init(main_task_executor.task_runner()); base::PlatformThread::SetName("CrAppShimMain"); // TODO(https://crbug.com/925998): This workaround ensures that there is
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 022da24..5db0e97 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -4132,7 +4132,7 @@ ] } - if (enable_desktop_in_product_help) { + if (enable_legacy_desktop_in_product_help) { sources += [ "feature_engagement/bookmark/bookmark_tracker.cc", "feature_engagement/bookmark/bookmark_tracker.h",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 3848be2..3ebe0d9 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3518,12 +3518,14 @@ FEATURE_VALUE_TYPE(printing::features::kEnableCustomMacPaperSizes)}, #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_CHROMEOS) {"enable-reopen-tab-in-product-help", flag_descriptions::kReopenTabInProductHelpName, flag_descriptions::kReopenTabInProductHelpDescription, kOsDesktop, FEATURE_VALUE_TYPE(feature_engagement::kIPHReopenTabFeature)}, -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_CHROMEOS) {"enable-audio-focus-enforcement", flag_descriptions::kEnableAudioFocusEnforcementName, @@ -3913,6 +3915,11 @@ FEATURE_VALUE_TYPE(chromeos::features::kGesturePropertiesDBusService)}, #endif // defined(OS_CHROMEOS) + {"cookie-deprecation-messages", + flag_descriptions::kCookieDeprecationMessagesName, + flag_descriptions::kCookieDeprecationMessagesDescription, kOsAll, + FEATURE_VALUE_TYPE(features::kCookieDeprecationMessages)}, + // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/android/metrics/ukm_utils_for_test.cc b/chrome/browser/android/metrics/ukm_utils_for_test.cc index ed18f3c..1ae6ea6 100644 --- a/chrome/browser/android/metrics/ukm_utils_for_test.cc +++ b/chrome/browser/android/metrics/ukm_utils_for_test.cc
@@ -27,7 +27,7 @@ auto* service = g_browser_process->GetMetricsServicesManager()->GetUkmService(); DCHECK(service); - return base::ContainsKey(service->sources(), source_id); + return base::Contains(service->sources(), source_id); } // static
diff --git a/chrome/browser/android/preferences/website_preference_bridge.cc b/chrome/browser/android/preferences/website_preference_bridge.cc index 53d08dc..761ab2f 100644 --- a/chrome/browser/android/preferences/website_preference_bridge.cc +++ b/chrome/browser/android/preferences/website_preference_bridge.cc
@@ -187,7 +187,7 @@ for (const auto& settings_it : embargo_settings) { const std::string origin = settings_it.primary_pattern.ToString(); - if (base::ContainsValue(seen_origins, origin)) { + if (base::Contains(seen_origins, origin)) { // This origin has already been added to the list, so don't add it again. continue; }
diff --git a/chrome/browser/android/signin/signin_manager_android_unittest.cc b/chrome/browser/android/signin/signin_manager_android_unittest.cc index e9bd83e..14c90f3 100644 --- a/chrome/browser/android/signin/signin_manager_android_unittest.cc +++ b/chrome/browser/android/signin/signin_manager_android_unittest.cc
@@ -156,10 +156,9 @@ // TODO(crbug.com/929456): If deleted, the key should not be present. for (const TestCase& test_case : kTestCases) { - EXPECT_EQ( - test_case.should_be_deleted, - base::ContainsKey(remaining_cache_storages, - url::Origin::Create(GURL(test_case.worker_url)))) + EXPECT_EQ(test_case.should_be_deleted, + base::Contains(remaining_cache_storages, + url::Origin::Create(GURL(test_case.worker_url)))) << test_case.worker_url << " should " << (test_case.should_be_deleted ? "" : "NOT ") << "be deleted, but it was"
diff --git a/chrome/browser/android/thumbnail/thumbnail_cache.cc b/chrome/browser/android/thumbnail/thumbnail_cache.cc index 48061fd7..0594fa3 100644 --- a/chrome/browser/android/thumbnail/thumbnail_cache.cc +++ b/chrome/browser/android/thumbnail/thumbnail_cache.cc
@@ -225,8 +225,8 @@ } if (force_disk_read && primary_tab_id_ != tab_id && - base::ContainsValue(visible_ids_, tab_id) && - !base::ContainsValue(read_queue_, tab_id)) { + base::Contains(visible_ids_, tab_id) && + !base::Contains(read_queue_, tab_id)) { read_queue_.push_back(tab_id); ReadNextThumbnail(); } @@ -321,7 +321,7 @@ TabId tab_id = *iter; visible_ids_.push_back(tab_id); if (!cache_.Get(tab_id) && primary_tab_id_ != tab_id && - !base::ContainsValue(read_queue_, tab_id)) + !base::Contains(read_queue_, tab_id)) read_queue_.push_back(tab_id); iter++; count++; @@ -420,7 +420,7 @@ } void ThumbnailCache::MakeSpaceForNewItemIfNecessary(TabId tab_id) { - if (cache_.Get(tab_id) || !base::ContainsValue(visible_ids_, tab_id) || + if (cache_.Get(tab_id) || !base::Contains(visible_ids_, tab_id) || cache_.size() < cache_.MaximumCacheSize()) { return; } @@ -432,7 +432,7 @@ for (ExpiringThumbnailCache::iterator iter = cache_.begin(); iter != cache_.end(); iter++) { - if (!base::ContainsValue(visible_ids_, iter->first)) { + if (!base::Contains(visible_ids_, iter->first)) { key_to_remove = iter->first; found_key_to_remove = true; break;
diff --git a/chrome/browser/app_controller_mac.mm b/chrome/browser/app_controller_mac.mm index 73b214e..fae9ad4 100644 --- a/chrome/browser/app_controller_mac.mm +++ b/chrome/browser/app_controller_mac.mm
@@ -232,9 +232,6 @@ // NTP after all the |urls| have been opened. - (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls; -// Whether instances of this class should use the Handoff feature. -- (BOOL)shouldUseHandoff; - // This method passes |handoffURL| to |handoffManager_|. - (void)passURLToHandoffManager:(const GURL&)handoffURL; @@ -1678,18 +1675,11 @@ #pragma mark - Handoff Manager -- (BOOL)shouldUseHandoff { - return base::mac::IsAtLeastOS10_10(); -} - - (void)passURLToHandoffManager:(const GURL&)handoffURL { [handoffManager_ updateActiveURL:handoffURL]; } - (void)updateHandoffManager:(content::WebContents*)webContents { - if (![self shouldUseHandoff]) - return; - if (!handoffManager_) handoffManager_.reset([[HandoffManager alloc] init]);
diff --git a/chrome/browser/app_controller_mac_browsertest.mm b/chrome/browser/app_controller_mac_browsertest.mm index 13f1b9a..fcbe58d1 100644 --- a/chrome/browser/app_controller_mac_browsertest.mm +++ b/chrome/browser/app_controller_mac_browsertest.mm
@@ -751,15 +751,10 @@ static GURL g_handoff_url; @interface AppController (BrowserTest) -- (BOOL)new_shouldUseHandoff; - (void)new_passURLToHandoffManager:(const GURL&)handoffURL; @end @implementation AppController (BrowserTest) -- (BOOL)new_shouldUseHandoff { - return YES; -} - - (void)new_passURLToHandoffManager:(const GURL&)handoffURL { g_handoff_url = handoffURL; } @@ -790,16 +785,10 @@ // Swizzle Handoff related implementations. void SetUpInProcessBrowserTestFixture() override { - // Handoff is only available on OSX 10.10+. This swizzle makes the logic - // run on all OSX versions. - SEL originalMethod = @selector(shouldUseHandoff); - SEL newMethod = @selector(new_shouldUseHandoff); - ExchangeSelectors(originalMethod, newMethod); - // This swizzle intercepts the URL that would be sent to the Handoff // Manager, and instead puts it into a variable accessible to this test. - originalMethod = @selector(passURLToHandoffManager:); - newMethod = @selector(new_passURLToHandoffManager:); + SEL originalMethod = @selector(passURLToHandoffManager:); + SEL newMethod = @selector(new_passURLToHandoffManager:); ExchangeSelectors(originalMethod, newMethod); }
diff --git a/chrome/browser/apps/app_service/extension_apps.cc b/chrome/browser/apps/app_service/extension_apps.cc index c1115cbb..f4765638 100644 --- a/chrome/browser/apps/app_service/extension_apps.cc +++ b/chrome/browser/apps/app_service/extension_apps.cc
@@ -207,7 +207,7 @@ ContentSettingsType permission_type = static_cast<ContentSettingsType>(permission->permission_id); - if (!base::ContainsValue(kSupportedPermissionTypes, permission_type)) { + if (!base::Contains(kSupportedPermissionTypes, permission_type)) { return; } @@ -278,7 +278,7 @@ ContentSettingsType content_type, const std::string& resource_identifier) { // If content_type is not one of the supported permissions, do nothing. - if (!base::ContainsValue(kSupportedPermissionTypes, content_type)) { + if (!base::Contains(kSupportedPermissionTypes, content_type)) { return; }
diff --git a/chrome/browser/apps/guest_view/web_view_browsertest.cc b/chrome/browser/apps/guest_view/web_view_browsertest.cc index fb1a56c8..3d71e67d09 100644 --- a/chrome/browser/apps/guest_view/web_view_browsertest.cc +++ b/chrome/browser/apps/guest_view/web_view_browsertest.cc
@@ -1915,10 +1915,10 @@ if (AreCommittedInterstitialsEnabled()) { // With committed interstitials, interstitials are no longer a special case // so we can just use the main frame from the WebContents. - EXPECT_TRUE(base::ContainsValue( - hosts, outer_web_contents->GetMainFrame()->GetView())); + EXPECT_TRUE( + base::Contains(hosts, outer_web_contents->GetMainFrame()->GetView())); } else { - EXPECT_TRUE(base::ContainsValue( + EXPECT_TRUE(base::Contains( hosts, guest_web_contents->GetInterstitialPage()->GetMainFrame()->GetView())); }
diff --git a/chrome/browser/apps/platform_apps/app_browsertest.cc b/chrome/browser/apps/platform_apps/app_browsertest.cc index 6d9e4b0..d2c92413e 100644 --- a/chrome/browser/apps/platform_apps/app_browsertest.cc +++ b/chrome/browser/apps/platform_apps/app_browsertest.cc
@@ -1219,7 +1219,7 @@ incognito_profile, file_manager, WindowOpenDisposition::NEW_FOREGROUND_TAB, extensions::SOURCE_TEST)); - while (!base::ContainsKey(opener_app_ids_, file_manager->id())) { + while (!base::Contains(opener_app_ids_, file_manager->id())) { content::RunAllPendingInMessageLoop(); } }
diff --git a/chrome/browser/apps/platform_apps/app_window_registry_util.cc b/chrome/browser/apps/platform_apps/app_window_registry_util.cc index be26f35..261035a 100644 --- a/chrome/browser/apps/platform_apps/app_window_registry_util.cc +++ b/chrome/browser/apps/platform_apps/app_window_registry_util.cc
@@ -82,7 +82,7 @@ AppWindowList window_list_copy(registry->app_windows()); for (auto* window : window_list_copy) { // Ensure window is still valid. - if (base::ContainsValue(registry->app_windows(), window)) + if (base::Contains(registry->app_windows(), window)) window->GetBaseWindow()->Close(); } }
diff --git a/chrome/browser/autofill/automated_tests/cache_replayer.cc b/chrome/browser/autofill/automated_tests/cache_replayer.cc index e48e8029..e165fa6a 100644 --- a/chrome/browser/autofill/automated_tests/cache_replayer.cc +++ b/chrome/browser/autofill/automated_tests/cache_replayer.cc
@@ -308,7 +308,7 @@ return false; } std::string key = GetKeyFromQueryRequest(query); - if (!base::ContainsKey(const_cache_, key)) { + if (!base::Contains(const_cache_, key)) { VLOG(1) << "Did not match any response for " << key; return false; }
diff --git a/chrome/browser/autofill/credit_card_accessory_controller_impl.cc b/chrome/browser/autofill/credit_card_accessory_controller_impl.cc index 45a204a..c9ff538 100644 --- a/chrome/browser/autofill/credit_card_accessory_controller_impl.cc +++ b/chrome/browser/autofill/credit_card_accessory_controller_impl.cc
@@ -43,13 +43,17 @@ AddField(data->ObfuscatedLastFourDigits(), &user_info); if (data->HasValidExpirationDate()) { - // TOOD(crbug.com/902425): Pass expiration date as grouped values AddField(data->ExpirationMonthAsString(), &user_info); AddField(data->Expiration4DigitYearAsString(), &user_info); + } else { + AddField(base::string16(), &user_info); + AddField(base::string16(), &user_info); } if (data->HasNameOnCard()) { AddField(data->GetRawInfo(autofill::CREDIT_CARD_NAME_FULL), &user_info); + } else { + AddField(base::string16(), &user_info); } return user_info;
diff --git a/chrome/browser/autofill/form_structure_browsertest.cc b/chrome/browser/autofill/form_structure_browsertest.cc index 0247eb0..786664aa 100644 --- a/chrome/browser/autofill/form_structure_browsertest.cc +++ b/chrome/browser/autofill/form_structure_browsertest.cc
@@ -223,7 +223,7 @@ // Prints the path of the test to be executed. LOG(INFO) << GetParam().MaybeAsASCII(); bool is_expected_to_pass = - !base::ContainsKey(GetFailingTestNames(), GetParam().BaseName().value()); + !base::Contains(GetFailingTestNames(), GetParam().BaseName().value()); RunOneDataDrivenTest(GetParam(), GetOutputDirectory(kTestName), is_expected_to_pass); }
diff --git a/chrome/browser/background/background_mode_manager.cc b/chrome/browser/background/background_mode_manager.cc index 90e5e3b..72db2b3 100644 --- a/chrome/browser/background/background_mode_manager.cc +++ b/chrome/browser/background/background_mode_manager.cc
@@ -308,7 +308,7 @@ void BackgroundModeManager::RegisterProfile(Profile* profile) { // We don't want to register multiple times for one profile. - DCHECK(!base::ContainsKey(background_mode_data_, profile)); + DCHECK(!base::Contains(background_mode_data_, profile)); auto bmd = std::make_unique<BackgroundModeData>(profile, &command_id_handler_vector_); BackgroundModeData* bmd_ptr = bmd.get();
diff --git a/chrome/browser/background_sync/background_sync_controller_impl.cc b/chrome/browser/background_sync/background_sync_controller_impl.cc index 0c4807f8..d37407c6 100644 --- a/chrome/browser/background_sync/background_sync_controller_impl.cc +++ b/chrome/browser/background_sync/background_sync_controller_impl.cc
@@ -78,8 +78,8 @@ parameters->disable = true; } - if (base::ContainsKey(field_params, - kMaxAttemptsWithNotificationPermissionParameterName)) { + if (base::Contains(field_params, + kMaxAttemptsWithNotificationPermissionParameterName)) { int max_attempts; if (base::StringToInt( field_params[kMaxAttemptsWithNotificationPermissionParameterName], @@ -88,7 +88,7 @@ } } - if (base::ContainsKey(field_params, kMaxAttemptsParameterName)) { + if (base::Contains(field_params, kMaxAttemptsParameterName)) { int max_attempts; if (base::StringToInt(field_params[kMaxAttemptsParameterName], &max_attempts)) { @@ -96,7 +96,7 @@ } } - if (base::ContainsKey(field_params, kInitialRetryParameterName)) { + if (base::Contains(field_params, kInitialRetryParameterName)) { int initial_retry_delay_sec; if (base::StringToInt(field_params[kInitialRetryParameterName], &initial_retry_delay_sec)) { @@ -105,7 +105,7 @@ } } - if (base::ContainsKey(field_params, kRetryDelayFactorParameterName)) { + if (base::Contains(field_params, kRetryDelayFactorParameterName)) { int retry_delay_factor; if (base::StringToInt(field_params[kRetryDelayFactorParameterName], &retry_delay_factor)) { @@ -113,7 +113,7 @@ } } - if (base::ContainsKey(field_params, kMinSyncRecoveryTimeName)) { + if (base::Contains(field_params, kMinSyncRecoveryTimeName)) { int min_sync_recovery_time_sec; if (base::StringToInt(field_params[kMinSyncRecoveryTimeName], &min_sync_recovery_time_sec)) { @@ -122,7 +122,7 @@ } } - if (base::ContainsKey(field_params, kMaxSyncEventDurationName)) { + if (base::Contains(field_params, kMaxSyncEventDurationName)) { int max_sync_event_duration_sec; if (base::StringToInt(field_params[kMaxSyncEventDurationName], &max_sync_event_duration_sec)) {
diff --git a/chrome/browser/browser_process.h b/chrome/browser/browser_process.h index c2f0bc6..e6442ab0 100644 --- a/chrome/browser/browser_process.h +++ b/chrome/browser/browser_process.h
@@ -78,10 +78,6 @@ class MetricsServicesManager; } -namespace net { -class URLRequestContextGetter; -} - namespace net_log { class ChromeNetLog; } @@ -149,7 +145,6 @@ virtual rappor::RapporServiceImpl* rappor_service() = 0; virtual ProfileManager* profile_manager() = 0; virtual PrefService* local_state() = 0; - virtual net::URLRequestContextGetter* system_request_context() = 0; virtual scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory() = 0; virtual variations::VariationsService* variations_service() = 0;
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 5c707ec..81d12bb7 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -715,11 +715,6 @@ return local_state_.get(); } -net::URLRequestContextGetter* BrowserProcessImpl::system_request_context() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return io_thread()->system_url_request_context_getter(); -} - variations::VariationsService* BrowserProcessImpl::variations_service() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return GetMetricsServicesManager()->GetVariationsService(); @@ -1178,7 +1173,6 @@ SystemNetworkContextManager::CreateInstance(local_state()); io_thread_ = std::make_unique<IOThread>( local_state(), policy_service(), net_log_.get(), - extension_event_router_forwarder(), SystemNetworkContextManager::GetInstance()); }
diff --git a/chrome/browser/browser_process_impl.h b/chrome/browser/browser_process_impl.h index 206ede7..fccea77a 100644 --- a/chrome/browser/browser_process_impl.h +++ b/chrome/browser/browser_process_impl.h
@@ -151,7 +151,6 @@ WatchDogThread* watchdog_thread() override; ProfileManager* profile_manager() override; PrefService* local_state() override; - net::URLRequestContextGetter* system_request_context() override; variations::VariationsService* variations_service() override; BrowserProcessPlatformPart* platform_part() override; extensions::EventRouterForwarder* extension_event_router_forwarder() override;
diff --git a/chrome/browser/browsing_data/browsing_data_appcache_helper_unittest.cc b/chrome/browser/browsing_data/browsing_data_appcache_helper_unittest.cc index f8d6760..65f9c22 100644 --- a/chrome/browser/browsing_data/browsing_data_appcache_helper_unittest.cc +++ b/chrome/browser/browsing_data/browsing_data_appcache_helper_unittest.cc
@@ -129,7 +129,7 @@ helper->DeleteAppCaches(url::Origin::Create(manifest2)); EXPECT_EQ(2u, helper->GetCount()); EXPECT_FALSE( - base::ContainsKey(helper->GetOrigins(), url::Origin::Create(manifest2))); + base::Contains(helper->GetOrigins(), url::Origin::Create(manifest2))); } TEST_F(CannedBrowsingDataAppCacheHelperTest, IgnoreExtensionsAndDevTools) {
diff --git a/chrome/browser/browsing_data/browsing_data_file_system_helper_unittest.cc b/chrome/browser/browsing_data/browsing_data_file_system_helper_unittest.cc index 734107f8..4801b08 100644 --- a/chrome/browser/browsing_data/browsing_data_file_system_helper_unittest.cc +++ b/chrome/browser/browsing_data/browsing_data_file_system_helper_unittest.cc
@@ -219,21 +219,21 @@ if (info.origin == kOrigin1) { EXPECT_FALSE(test_hosts_found[0]); test_hosts_found[0] = true; - EXPECT_FALSE(base::ContainsKey(info.usage_map, kPersistent)); - EXPECT_TRUE(base::ContainsKey(info.usage_map, kTemporary)); + EXPECT_FALSE(base::Contains(info.usage_map, kPersistent)); + EXPECT_TRUE(base::Contains(info.usage_map, kTemporary)); EXPECT_EQ(kEmptyFileSystemSize, info.usage_map.at(storage::kFileSystemTypeTemporary)); } else if (info.origin == kOrigin2) { EXPECT_FALSE(test_hosts_found[1]); test_hosts_found[1] = true; - EXPECT_TRUE(base::ContainsKey(info.usage_map, kPersistent)); - EXPECT_FALSE(base::ContainsKey(info.usage_map, kTemporary)); + EXPECT_TRUE(base::Contains(info.usage_map, kPersistent)); + EXPECT_FALSE(base::Contains(info.usage_map, kTemporary)); EXPECT_EQ(kEmptyFileSystemSize, info.usage_map.at(kPersistent)); } else if (info.origin == kOrigin3) { EXPECT_FALSE(test_hosts_found[2]); test_hosts_found[2] = true; - EXPECT_TRUE(base::ContainsKey(info.usage_map, kPersistent)); - EXPECT_TRUE(base::ContainsKey(info.usage_map, kTemporary)); + EXPECT_TRUE(base::Contains(info.usage_map, kPersistent)); + EXPECT_TRUE(base::Contains(info.usage_map, kTemporary)); EXPECT_EQ(kEmptyFileSystemSize, info.usage_map.at(kPersistent)); EXPECT_EQ(kEmptyFileSystemSize, info.usage_map.at(kTemporary)); } else { @@ -259,8 +259,8 @@ BrowsingDataFileSystemHelper::FileSystemInfo info = *(file_system_info_list_->begin()); EXPECT_EQ(kOrigin3, info.origin); - EXPECT_TRUE(base::ContainsKey(info.usage_map, kPersistent)); - EXPECT_TRUE(base::ContainsKey(info.usage_map, kTemporary)); + EXPECT_TRUE(base::Contains(info.usage_map, kPersistent)); + EXPECT_TRUE(base::Contains(info.usage_map, kTemporary)); EXPECT_EQ(kEmptyFileSystemSize, info.usage_map[kPersistent]); EXPECT_EQ(kEmptyFileSystemSize, info.usage_map[kTemporary]); } @@ -286,13 +286,13 @@ EXPECT_EQ(2U, file_system_info_list_->size()); auto info = file_system_info_list_->begin(); EXPECT_EQ(kOrigin1, info->origin); - EXPECT_FALSE(base::ContainsKey(info->usage_map, kPersistent)); - EXPECT_FALSE(base::ContainsKey(info->usage_map, kTemporary)); + EXPECT_FALSE(base::Contains(info->usage_map, kPersistent)); + EXPECT_FALSE(base::Contains(info->usage_map, kTemporary)); info++; EXPECT_EQ(kOrigin2, info->origin); - EXPECT_FALSE(base::ContainsKey(info->usage_map, kPersistent)); - EXPECT_FALSE(base::ContainsKey(info->usage_map, kTemporary)); + EXPECT_FALSE(base::Contains(info->usage_map, kPersistent)); + EXPECT_FALSE(base::Contains(info->usage_map, kTemporary)); } // Verifies that the CannedBrowsingDataFileSystemHelper correctly ignores
diff --git a/chrome/browser/browsing_data/browsing_data_helper.cc b/chrome/browser/browsing_data/browsing_data_helper.cc index c7c2eca8..64ce45f 100644 --- a/chrome/browser/browsing_data/browsing_data_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_helper.cc
@@ -15,7 +15,7 @@ // Static bool BrowsingDataHelper::IsWebScheme(const std::string& scheme) { const std::vector<std::string>& schemes = url::GetWebStorageSchemes(); - return base::ContainsValue(schemes, scheme); + return base::Contains(schemes, scheme); } // Static
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc index 27d45da..1f957e34 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc
@@ -311,12 +311,6 @@ public: RemoveSafeBrowsingCookieTester() : browser_process_(TestingBrowserProcess::GetGlobal()) { - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - browser_process_->SetSystemRequestContext( - system_request_context_getter_.get()); // TODO(crbug/925153): Port consumers of the |sb_service| to use the // interface in components/safe_browsing, and remove this cast. scoped_refptr<safe_browsing::SafeBrowsingService> sb_service = @@ -349,7 +343,6 @@ private: TestingBrowserProcess* browser_process_; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; DISALLOW_COPY_AND_ASSIGN(RemoveSafeBrowsingCookieTester); }; @@ -2883,7 +2876,7 @@ // Set a value for every WebsiteSetting. for (const content_settings::WebsiteSettingsInfo* info : *registry) { - if (base::ContainsValue(whitelisted_types, info->type())) + if (base::Contains(whitelisted_types, info->type())) continue; base::Value some_value; auto* content_setting = content_setting_registry->Get(info->type()); @@ -2928,7 +2921,7 @@ // All settings should be deleted now. for (const content_settings::WebsiteSettingsInfo* info : *registry) { - if (base::ContainsValue(whitelisted_types, info->type())) + if (base::Contains(whitelisted_types, info->type())) continue; std::unique_ptr<base::Value> value = map->GetWebsiteSetting(url, url, info->type(), std::string(), nullptr);
diff --git a/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc b/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc index 9dcdc56..54d3099 100644 --- a/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/run_loop.h" +#include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" @@ -118,7 +119,13 @@ }; // Tests that for the empty cache, the result is zero. -IN_PROC_BROWSER_TEST_F(CacheCounterTest, Empty) { +// Flaky. See crbug.com/971650. +#if defined(OS_LINUX) +#define MAYBE_Empty DISABLED_Empty +#else +#define MAYBE_Empty Empty +#endif +IN_PROC_BROWSER_TEST_F(CacheCounterTest, MAYBE_Empty) { Profile* profile = browser()->profile(); CacheCounter counter(profile);
diff --git a/chrome/browser/browsing_data/mock_browsing_data_cookie_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_cookie_helper.cc index 03a09ce9..44e618b 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_cookie_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_cookie_helper.cc
@@ -30,7 +30,7 @@ void MockBrowsingDataCookieHelper::DeleteCookie( const net::CanonicalCookie& cookie) { std::string key = cookie.Name() + "=" + cookie.Value(); - ASSERT_TRUE(base::ContainsKey(cookies_, key)); + ASSERT_TRUE(base::Contains(cookies_, key)); cookies_[key] = false; }
diff --git a/chrome/browser/browsing_data/mock_browsing_data_database_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_database_helper.cc index a3d3fd51..12326bd 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_database_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_database_helper.cc
@@ -24,7 +24,7 @@ void MockBrowsingDataDatabaseHelper::DeleteDatabase(const url::Origin& origin) { const std::string identifier = storage::GetIdentifierFromOrigin(origin); - ASSERT_TRUE(base::ContainsKey(databases_, identifier)); + ASSERT_TRUE(base::Contains(databases_, identifier)); last_deleted_origin_ = identifier; databases_[identifier] = false; }
diff --git a/chrome/browser/browsing_data/mock_browsing_data_file_system_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_file_system_helper.cc index 60d4aad..367f1224 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_file_system_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_file_system_helper.cc
@@ -30,7 +30,7 @@ void MockBrowsingDataFileSystemHelper::DeleteFileSystemOrigin( const url::Origin& origin) { std::string key = origin.Serialize(); - ASSERT_TRUE(base::ContainsKey(file_systems_, key)); + ASSERT_TRUE(base::Contains(file_systems_, key)); last_deleted_origin_ = origin; file_systems_[key] = false; }
diff --git a/chrome/browser/browsing_data/mock_browsing_data_indexed_db_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_indexed_db_helper.cc index ef59333..d3109413 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_indexed_db_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_indexed_db_helper.cc
@@ -31,7 +31,7 @@ void MockBrowsingDataIndexedDBHelper::DeleteIndexedDB( const GURL& origin) { - ASSERT_TRUE(base::ContainsKey(origins_, origin)); + ASSERT_TRUE(base::Contains(origins_, origin)); origins_[origin] = false; }
diff --git a/chrome/browser/browsing_data/mock_browsing_data_local_storage_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_local_storage_helper.cc index fa4558b9a..3fa6511 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_local_storage_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_local_storage_helper.cc
@@ -29,7 +29,7 @@ void MockBrowsingDataLocalStorageHelper::DeleteOrigin( const url::Origin& origin, base::OnceClosure callback) { - ASSERT_TRUE(base::ContainsKey(origins_, origin)); + ASSERT_TRUE(base::Contains(origins_, origin)); last_deleted_origin_ = origin; origins_[origin] = false; std::move(callback).Run();
diff --git a/chrome/browser/browsing_data/mock_browsing_data_service_worker_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_service_worker_helper.cc index b5fcdda..3262d1f2 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_service_worker_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_service_worker_helper.cc
@@ -34,7 +34,7 @@ void MockBrowsingDataServiceWorkerHelper::DeleteServiceWorkers( const GURL& origin) { - ASSERT_TRUE(base::ContainsKey(origins_, origin)); + ASSERT_TRUE(base::Contains(origins_, origin)); origins_[origin] = false; }
diff --git a/chrome/browser/browsing_data/mock_browsing_data_shared_worker_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_shared_worker_helper.cc index ab39ef6..708d0ef 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_shared_worker_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_shared_worker_helper.cc
@@ -31,7 +31,7 @@ const std::string& name, const url::Origin& constructor_origin) { SharedWorkerInfo key(worker, name, constructor_origin); - ASSERT_TRUE(base::ContainsKey(workers_, key)); + ASSERT_TRUE(base::Contains(workers_, key)); workers_[key] = false; }
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 9ae816ff..be51276 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -1983,7 +1983,7 @@ prefs::kUserTriggeredIsolatedOrigins); base::ListValue* list = update.Get(); base::Value value(origin.Serialize()); - if (!base::ContainsValue(list->GetList(), value)) + if (!base::Contains(list->GetList(), value)) list->GetList().push_back(std::move(value)); }
diff --git a/chrome/browser/chrome_worker_browsertest.cc b/chrome/browser/chrome_worker_browsertest.cc index bffad52..2ee917b 100644 --- a/chrome/browser/chrome_worker_browsertest.cc +++ b/chrome/browser/chrome_worker_browsertest.cc
@@ -68,7 +68,7 @@ ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL(test_url)); run_loop.Run(); - EXPECT_FALSE(base::ContainsKey(header_map_, "Cookie")); + EXPECT_FALSE(base::Contains(header_map_, "Cookie")); } // Set a cookie. @@ -83,7 +83,7 @@ ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL(test_url)); run_loop.Run(); - EXPECT_TRUE(base::ContainsKey(header_map_, "Cookie")); + EXPECT_TRUE(base::Contains(header_map_, "Cookie")); EXPECT_EQ(kCookie, header_map_["Cookie"]); } }
diff --git a/chrome/browser/chromeos/base/locale_util.cc b/chrome/browser/chromeos/base/locale_util.cc index 36873de..0b565fc1 100644 --- a/chrome/browser/chromeos/base/locale_util.cc +++ b/chrome/browser/chromeos/base/locale_util.cc
@@ -18,6 +18,7 @@ #include "components/prefs/pref_service.h" #include "components/translate/core/browser/translate_prefs.h" #include "content/public/browser/browser_thread.h" +#include "extensions/common/extension_l10n_util.h" #include "ui/base/ime/chromeos/input_method_manager.h" #include "ui/base/ime/chromeos/input_method_util.h" #include "ui/base/l10n/l10n_util.h" @@ -66,6 +67,11 @@ if (data->result.success) { g_browser_process->SetApplicationLocale(data->result.loaded_locale); + // Ensure chrome app names are localized. Note that the user might prefer + // a different locale than was actually loaded (e.g. "en-CA" vs. "en-US"). + extension_l10n_util::SetProcessLocale(data->result.loaded_locale); + extension_l10n_util::SetPreferredLocale(data->result.requested_locale); + if (data->enable_locale_keyboard_layouts) { input_method::InputMethodManager* manager = input_method::InputMethodManager::Get(); @@ -155,7 +161,7 @@ return true; // Check if locale is in list of allowed UI locales. - return base::ContainsValue(allowed_languages, base::Value(language)); + return base::Contains(allowed_languages, base::Value(language)); } bool IsAllowedUILanguage(const std::string& language, @@ -228,7 +234,7 @@ std::vector<std::string> preferred_languages = base::SplitString(preferred_languages_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - if (!base::ContainsValue(preferred_languages, locale)) { + if (!base::Contains(preferred_languages, locale)) { preferred_languages.push_back(locale); prefs->SetString(language::prefs::kPreferredLanguages, base::JoinString(preferred_languages, ","));
diff --git a/chrome/browser/chromeos/base/locale_util_browsertest.cc b/chrome/browser/chromeos/base/locale_util_browsertest.cc new file mode 100644 index 0000000..4150b2c --- /dev/null +++ b/chrome/browser/chromeos/base/locale_util_browsertest.cc
@@ -0,0 +1,46 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/base/locale_util.h" + +#include <string> + +#include "base/bind.h" +#include "base/run_loop.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "extensions/common/extension_l10n_util.h" + +namespace chromeos { +namespace { + +void OnLocaleSwitched(base::RunLoop* run_loop, + const locale_util::LanguageSwitchResult& result) { + run_loop->Quit(); +} + +using LocaleUtilTest = InProcessBrowserTest; + +IN_PROC_BROWSER_TEST_F(LocaleUtilTest, SwitchLanguage) { + // Tests default to English. + EXPECT_EQ("en-US", g_browser_process->GetApplicationLocale()); + + // Attempt switch to Belgian French. + base::RunLoop run_loop; + locale_util::SwitchLanguage("fr-BE", true, false, + base::BindRepeating(&OnLocaleSwitched, &run_loop), + ProfileManager::GetActiveUserProfile()); + run_loop.Run(); + + // Locale was remapped to generic French. + EXPECT_EQ("fr", g_browser_process->GetApplicationLocale()); + + // Extension subsystem has both actual locale and preferred locale. + EXPECT_EQ("fr", extension_l10n_util::CurrentLocaleOrDefault()); + EXPECT_EQ("fr-BE", extension_l10n_util::GetPreferredLocaleForTest()); +} + +} // namespace +} // namespace chromeos
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc index 6ef1af8..a1311a72 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc
@@ -11,6 +11,7 @@ #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/login_screen.h" #include "ash/public/cpp/shelf_item.h" +#include "ash/public/cpp/shelf_prefs.h" #include "ash/public/cpp/tablet_mode.h" #include "ash/public/interfaces/ash_message_center_controller.mojom.h" #include "ash/public/interfaces/constants.mojom.h" @@ -1605,10 +1606,6 @@ *args_)); EXTENSION_FUNCTION_VALIDATE(params); - service_manager::Connector* connector = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); - connector->BindInterface(ash::mojom::kServiceName, &shelf_test_api_); - int64_t display_id; if (!base::StringToInt64(params->display_id, &display_id)) { return RespondNow(Error(base::StrCat( @@ -1616,16 +1613,9 @@ params->display_id}))); } - shelf_test_api_->GetAutoHideBehavior( - display_id, - base::BindOnce(&AutotestPrivateGetShelfAutoHideBehaviorFunction:: - OnGetShelfAutoHideBehaviorCompleted, - this)); - return RespondLater(); -} - -void AutotestPrivateGetShelfAutoHideBehaviorFunction:: - OnGetShelfAutoHideBehaviorCompleted(ash::ShelfAutoHideBehavior behavior) { + Profile* const profile = Profile::FromBrowserContext(browser_context()); + ash::ShelfAutoHideBehavior behavior = + ash::GetShelfAutoHideBehaviorPref(profile->GetPrefs(), display_id); std::string str_behavior; switch (behavior) { case ash::ShelfAutoHideBehavior::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS: @@ -1635,10 +1625,10 @@ str_behavior = "never"; break; case ash::ShelfAutoHideBehavior::SHELF_AUTO_HIDE_ALWAYS_HIDDEN: - str_behavior = "hidden"; - break; + // SHELF_AUTO_HIDE_ALWAYS_HIDDEN not supported by shelf_prefs.cc + return RespondNow(Error("SHELF_AUTO_HIDE_ALWAYS_HIDDEN not supported")); } - Respond(OneArgument(std::make_unique<base::Value>(str_behavior))); + return RespondNow(OneArgument(std::make_unique<base::Value>(str_behavior))); } /////////////////////////////////////////////////////////////////////////////// @@ -1660,21 +1650,15 @@ *args_)); EXTENSION_FUNCTION_VALIDATE(params); - service_manager::Connector* connector = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); - connector->BindInterface(ash::mojom::kServiceName, &shelf_test_api_); - ash::ShelfAutoHideBehavior behavior; if (params->behavior == "always") { behavior = ash::ShelfAutoHideBehavior::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS; } else if (params->behavior == "never") { behavior = ash::ShelfAutoHideBehavior::SHELF_AUTO_HIDE_BEHAVIOR_NEVER; - } else if (params->behavior == "hidden") { - behavior = ash::ShelfAutoHideBehavior::SHELF_AUTO_HIDE_ALWAYS_HIDDEN; } else { - return RespondNow(Error(base::StrCat( - {"Invalid behavior; expected 'always', 'never' or 'hidden', got ", - params->behavior}))); + return RespondNow(Error( + base::StrCat({"Invalid behavior; expected 'always', 'never', got ", + params->behavior}))); } int64_t display_id; if (!base::StringToInt64(params->display_id, &display_id)) { @@ -1683,17 +1667,9 @@ params->display_id}))); } - shelf_test_api_->SetAutoHideBehavior( - display_id, behavior, - base::BindOnce(&AutotestPrivateSetShelfAutoHideBehaviorFunction:: - OnSetShelfAutoHideBehaviorCompleted, - this)); - return RespondLater(); -} - -void AutotestPrivateSetShelfAutoHideBehaviorFunction:: - OnSetShelfAutoHideBehaviorCompleted() { - Respond(NoArguments()); + Profile* const profile = Profile::FromBrowserContext(browser_context()); + ash::SetShelfAutoHideBehaviorPref(profile->GetPrefs(), display_id, behavior); + return RespondNow(NoArguments()); } /////////////////////////////////////////////////////////////////////////////// @@ -1714,10 +1690,6 @@ api::autotest_private::GetShelfAlignment::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - service_manager::Connector* connector = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); - connector->BindInterface(ash::mojom::kServiceName, &shelf_test_api_); - int64_t display_id; if (!base::StringToInt64(params->display_id, &display_id)) { return RespondNow(Error(base::StrCat( @@ -1725,15 +1697,9 @@ params->display_id}))); } - shelf_test_api_->GetAlignment( - display_id, base::BindOnce(&AutotestPrivateGetShelfAlignmentFunction:: - OnGetShelfAlignmentCompleted, - this)); - return RespondLater(); -} - -void AutotestPrivateGetShelfAlignmentFunction::OnGetShelfAlignmentCompleted( - ash::ShelfAlignment alignment) { + Profile* const profile = Profile::FromBrowserContext(browser_context()); + ash::ShelfAlignment alignment = + ash::GetShelfAlignmentPref(profile->GetPrefs(), display_id); api::autotest_private::ShelfAlignmentType alignment_type; switch (alignment) { case ash::ShelfAlignment::SHELF_ALIGNMENT_BOTTOM: @@ -1749,11 +1715,10 @@ api::autotest_private::ShelfAlignmentType::SHELF_ALIGNMENT_TYPE_RIGHT; break; case ash::ShelfAlignment::SHELF_ALIGNMENT_BOTTOM_LOCKED: - alignment_type = api::autotest_private::ShelfAlignmentType:: - SHELF_ALIGNMENT_TYPE_BOTTOMLOCKED; - break; + // SHELF_ALIGNMENT_BOTTOM_LOCKED not supported by shelf_prefs.cc + return RespondNow(Error("SHELF_ALIGNMENT_BOTTOM_LOCKED not supported")); } - Respond(OneArgument(std::make_unique<base::Value>( + return RespondNow(OneArgument(std::make_unique<base::Value>( api::autotest_private::ToString(alignment_type)))); } @@ -1775,10 +1740,6 @@ api::autotest_private::SetShelfAlignment::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - service_manager::Connector* connector = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); - connector->BindInterface(ash::mojom::kServiceName, &shelf_test_api_); - ash::ShelfAlignment alignment; switch (params->alignment) { case api::autotest_private::ShelfAlignmentType::SHELF_ALIGNMENT_TYPE_BOTTOM: @@ -1790,14 +1751,10 @@ case api::autotest_private::ShelfAlignmentType::SHELF_ALIGNMENT_TYPE_RIGHT: alignment = ash::ShelfAlignment::SHELF_ALIGNMENT_RIGHT; break; - case api::autotest_private::ShelfAlignmentType:: - SHELF_ALIGNMENT_TYPE_BOTTOMLOCKED: - alignment = ash::ShelfAlignment::SHELF_ALIGNMENT_BOTTOM_LOCKED; - break; case api::autotest_private::ShelfAlignmentType::SHELF_ALIGNMENT_TYPE_NONE: return RespondNow( - Error("Unsupported None alignment; expected 'Bottom', 'Left', " - "'Right' or 'BottomLocked'")); + Error("Invalid None alignment; expected 'Bottom', 'Left', or " + "'Right'")); } int64_t display_id; if (!base::StringToInt64(params->display_id, &display_id)) { @@ -1806,16 +1763,9 @@ params->display_id}))); } - shelf_test_api_->SetAlignment( - display_id, alignment, - base::BindOnce(&AutotestPrivateSetShelfAlignmentFunction:: - OnSetShelfAlignmentCompleted, - this)); - return RespondLater(); -} - -void AutotestPrivateSetShelfAlignmentFunction::OnSetShelfAlignmentCompleted() { - Respond(NoArguments()); + Profile* const profile = Profile::FromBrowserContext(browser_context()); + ash::SetShelfAlignmentPref(profile->GetPrefs(), display_id, alignment); + return RespondNow(NoArguments()); } ///////////////////////////////////////////////////////////////////////////////
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h index 518a4df..72b03db4 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h
@@ -11,9 +11,7 @@ #include "ash/public/cpp/assistant/assistant_state_proxy.h" #include "ash/public/cpp/assistant/default_voice_interaction_observer.h" -#include "ash/public/cpp/shelf_types.h" #include "ash/public/interfaces/ash_message_center_controller.mojom.h" -#include "ash/public/interfaces/shelf_integration_test_api.mojom.h" #include "base/compiler_specific.h" #include "base/timer/timer.h" #include "chrome/browser/chromeos/printing/cups_printers_manager.h" @@ -631,11 +629,8 @@ AUTOTESTPRIVATE_GETSHELFAUTOHIDEBEHAVIOR) private: - void OnGetShelfAutoHideBehaviorCompleted(ash::ShelfAutoHideBehavior behavior); ~AutotestPrivateGetShelfAutoHideBehaviorFunction() override; ResponseAction Run() override; - - ash::mojom::ShelfIntegrationTestApiPtr shelf_test_api_; }; // Sets shelf autohide behavior. @@ -647,11 +642,8 @@ AUTOTESTPRIVATE_SETSHELFAUTOHIDEBEHAVIOR) private: - void OnSetShelfAutoHideBehaviorCompleted(); ~AutotestPrivateSetShelfAutoHideBehaviorFunction() override; ResponseAction Run() override; - - ash::mojom::ShelfIntegrationTestApiPtr shelf_test_api_; }; // Returns the shelf alignment. @@ -663,11 +655,8 @@ AUTOTESTPRIVATE_GETSHELFALIGNMENT) private: - void OnGetShelfAlignmentCompleted(ash::ShelfAlignment alignment); ~AutotestPrivateGetShelfAlignmentFunction() override; ResponseAction Run() override; - - ash::mojom::ShelfIntegrationTestApiPtr shelf_test_api_; }; // Sets shelf alignment. @@ -679,11 +668,8 @@ AUTOTESTPRIVATE_SETSHELFALIGNMENT) private: - void OnSetShelfAlignmentCompleted(); ~AutotestPrivateSetShelfAlignmentFunction() override; ResponseAction Run() override; - - ash::mojom::ShelfIntegrationTestApiPtr shelf_test_api_; }; class AutotestPrivateShowVirtualKeyboardIfEnabledFunction
diff --git a/chrome/browser/chromeos/launcher_search_provider/launcher_search_provider_service.cc b/chrome/browser/chromeos/launcher_search_provider/launcher_search_provider_service.cc index 619c77cb..d2b89ea 100644 --- a/chrome/browser/chromeos/launcher_search_provider/launcher_search_provider_service.cc +++ b/chrome/browser/chromeos/launcher_search_provider/launcher_search_provider_service.cc
@@ -91,7 +91,7 @@ void Service::OnOpenResult(const ExtensionId& extension_id, const std::string& item_id) { CacheListenerExtensionIds(); - CHECK(base::ContainsKey(*cached_listener_extension_ids_.get(), extension_id)); + CHECK(base::Contains(*cached_listener_extension_ids_.get(), extension_id)); extensions::EventRouter* event_router = extensions::EventRouter::Get(profile_); @@ -116,8 +116,7 @@ // If |extension| is not in the listener extensions list, ignore it. CacheListenerExtensionIds(); - if (!base::ContainsKey(*cached_listener_extension_ids_.get(), - extension->id())) { + if (!base::Contains(*cached_listener_extension_ids_.get(), extension->id())) { return; }
diff --git a/chrome/browser/chromeos/locale_change_guard.cc b/chrome/browser/chromeos/locale_change_guard.cc index 94fe383c..619d64f 100644 --- a/chrome/browser/chromeos/locale_change_guard.cc +++ b/chrome/browser/chromeos/locale_change_guard.cc
@@ -6,7 +6,6 @@ #include <algorithm> -#include "ash/public/interfaces/constants.mojom.h" #include "base/bind.h" #include "base/metrics/user_metrics.h" #include "base/stl_util.h" @@ -26,8 +25,6 @@ #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/service_manager_connection.h" -#include "services/service_manager/public/cpp/connector.h" #include "ui/base/l10n/l10n_util.h" using base::UserMetricsAction; @@ -67,18 +64,6 @@ content::NotificationService::AllBrowserContextsAndSources()); } -void LocaleChangeGuard::ConnectToLocaleUpdateController() { - content::ServiceManagerConnection* connection = - content::ServiceManagerConnection::GetForProcess(); - service_manager::Connector* connector = - connection ? connection->GetConnector() : nullptr; - // Unit tests may not have a connector. - if (!connector) - return; - - connector->BindInterface(ash::mojom::kServiceName, ¬ification_controller_); -} - void LocaleChangeGuard::RevertLocaleChange() { if (profile_ == NULL || from_locale_.empty() || @@ -191,20 +176,17 @@ PrepareChangingLocale(from_locale, to_locale); } - if (!notification_controller_) - ConnectToLocaleUpdateController(); - - notification_controller_->OnLocaleChanged( + ash::LocaleUpdateController::Get()->OnLocaleChanged( cur_locale, from_locale_, to_locale_, base::Bind(&LocaleChangeGuard::OnResult, AsWeakPtr())); } -void LocaleChangeGuard::OnResult(ash::mojom::LocaleNotificationResult result) { +void LocaleChangeGuard::OnResult(ash::LocaleNotificationResult result) { switch (result) { - case ash::mojom::LocaleNotificationResult::ACCEPT: + case ash::LocaleNotificationResult::kAccept: AcceptLocaleChange(); break; - case ash::mojom::LocaleNotificationResult::REVERT: + case ash::LocaleNotificationResult::kRevert: RevertLocaleChange(); break; } @@ -256,7 +238,7 @@ if (from_lang != to_lang) return true; - return !base::ContainsValue(kSkipShowNotificationLanguages, from_lang); + return !base::Contains(kSkipShowNotificationLanguages, from_lang); } // static
diff --git a/chrome/browser/chromeos/locale_change_guard.h b/chrome/browser/chromeos/locale_change_guard.h index b622d7d1..c5f90584c 100644 --- a/chrome/browser/chromeos/locale_change_guard.h +++ b/chrome/browser/chromeos/locale_change_guard.h
@@ -10,7 +10,7 @@ #include <memory> #include <string> -#include "ash/public/interfaces/locale.mojom.h" +#include "ash/public/cpp/locale_update_controller.h" #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/lazy_instance.h" @@ -48,11 +48,9 @@ FRIEND_TEST_ALL_PREFIXES(LocaleChangeGuardTest, ShowNotificationLocaleChangedList); - void ConnectToLocaleUpdateController(); - void Check(); - void OnResult(ash::mojom::LocaleNotificationResult result); + void OnResult(ash::LocaleNotificationResult result); void AcceptLocaleChange(); void RevertLocaleChange(); @@ -71,9 +69,6 @@ static const char* const* GetSkipShowNotificationLanguagesForTesting(); static size_t GetSkipShowNotificationLanguagesSizeForTesting(); - // Ash's mojom::LocaleUpdateController used to display notifications. - ash::mojom::LocaleUpdateControllerPtr notification_controller_; - std::string from_locale_; std::string to_locale_; Profile* profile_;
diff --git a/chrome/browser/chromeos/locale_change_guard_unittest.cc b/chrome/browser/chromeos/locale_change_guard_unittest.cc index f98ca85..64e168b 100644 --- a/chrome/browser/chromeos/locale_change_guard_unittest.cc +++ b/chrome/browser/chromeos/locale_change_guard_unittest.cc
@@ -211,7 +211,7 @@ (dash ? std::string(locale, dash - locale) : std::string(locale)); const bool notification_allowed = - base::ContainsValue(kShowNotificationLanguages, language); + base::Contains(kShowNotificationLanguages, language); const char* const* skipped_begin = LocaleChangeGuard::GetSkipShowNotificationLanguagesForTesting();
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_session.cc b/chrome/browser/chromeos/login/demo_mode/demo_session.cc index 3e8acd93..937dc210 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_session.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_session.cc
@@ -7,7 +7,7 @@ #include <algorithm> #include <utility> -#include "ash/public/interfaces/locale.mojom.h" +#include "ash/public/cpp/locale_update_controller.h" #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" @@ -170,7 +170,7 @@ } // Returns the list of locales (and related info) supported by demo mode. -std::vector<ash::mojom::LocaleInfoPtr> GetSupportedLocales() { +std::vector<ash::LocaleInfo> GetSupportedLocales() { const base::flat_set<std::string> kSupportedLocales( {"da", "en-GB", "en-US", "fi", "fr", "fr-CA", "nb", "nl", "sv"}); @@ -179,19 +179,19 @@ const std::string current_locale_iso_code = ProfileManager::GetActiveUserProfile()->GetPrefs()->GetString( language::prefs::kApplicationLocale); - std::vector<ash::mojom::LocaleInfoPtr> supported_locales; + std::vector<ash::LocaleInfo> supported_locales; for (const std::string& locale : available_locales) { if (!kSupportedLocales.contains(locale)) continue; - ash::mojom::LocaleInfoPtr locale_info = ash::mojom::LocaleInfo::New(); - locale_info->iso_code = locale; - locale_info->display_name = l10n_util::GetDisplayNameForLocale( + ash::LocaleInfo locale_info; + locale_info.iso_code = locale; + locale_info.display_name = l10n_util::GetDisplayNameForLocale( locale, current_locale_iso_code, true /* is_for_ui */); const base::string16 native_display_name = l10n_util::GetDisplayNameForLocale(locale, locale, true /* is_for_ui */); - if (locale_info->display_name != native_display_name) { - locale_info->display_name += + if (locale_info.display_name != native_display_name) { + locale_info.display_name += base::UTF8ToUTF16(" - ") + native_display_name; } supported_locales.push_back(std::move(locale_info));
diff --git a/chrome/browser/chromeos/login/enrollment/enrollment_local_policy_server_browsertest.cc b/chrome/browser/chromeos/login/enrollment/enrollment_local_policy_server_browsertest.cc index b99e696..565ff4e 100644 --- a/chrome/browser/chromeos/login/enrollment/enrollment_local_policy_server_browsertest.cc +++ b/chrome/browser/chromeos/login/enrollment/enrollment_local_policy_server_browsertest.cc
@@ -483,15 +483,8 @@ OobeScreenWaiter(GaiaView::kScreenId).Wait(); } -// https://crbug.com/965367 -#if defined(OS_CHROMEOS) -#define MAYBE_ReenrollmentNone DISABLED_ReenrollmentNone -#else -#define MAYBE_ReenrollmentNone ReenrollmentNone -#endif // State keys are present but restore mode is not requested. -IN_PROC_BROWSER_TEST_F(AutoEnrollmentLocalPolicyServer, - MAYBE_ReenrollmentNone) { +IN_PROC_BROWSER_TEST_F(AutoEnrollmentLocalPolicyServer, ReenrollmentNone) { EXPECT_TRUE(policy_server_.SetDeviceStateRetrievalResponse( state_keys_broker(), enterprise_management::DeviceStateRetrievalResponse::RESTORE_MODE_NONE,
diff --git a/chrome/browser/chromeos/login/screens/welcome_screen.cc b/chrome/browser/chromeos/login/screens/welcome_screen.cc index 5732faa7..15485fc 100644 --- a/chrome/browser/chromeos/login/screens/welcome_screen.cc +++ b/chrome/browser/chromeos/login/screens/welcome_screen.cc
@@ -7,7 +7,6 @@ #include <utility> #include <vector> -#include "ash/public/interfaces/constants.mojom.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/logging.h" @@ -30,8 +29,6 @@ #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" -#include "content/public/common/service_manager_connection.h" -#include "services/service_manager/public/cpp/connector.h" namespace { @@ -270,27 +267,10 @@ observer.OnLanguageListReloaded(); } -void WelcomeScreen::ConnectToLocaleUpdateController() { - content::ServiceManagerConnection* connection = - content::ServiceManagerConnection::GetForProcess(); - service_manager::Connector* connector = - connection ? connection->GetConnector() : nullptr; - // Unit tests may not have a connector. - if (!connector) - return; - - connector->BindInterface(ash::mojom::kServiceName, - &locale_update_controller_); -} - void WelcomeScreen::NotifyLocaleChange() { - if (!locale_update_controller_) - ConnectToLocaleUpdateController(); - - DCHECK(locale_update_controller_); - locale_update_controller_->OnLocaleChanged( + ash::LocaleUpdateController::Get()->OnLocaleChanged( std::string(), std::string(), std::string(), - base::DoNothing::Once<ash::mojom::LocaleNotificationResult>()); + base::DoNothing::Once<ash::LocaleNotificationResult>()); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/screens/welcome_screen.h b/chrome/browser/chromeos/login/screens/welcome_screen.h index bec3e72..f064cb5a 100644 --- a/chrome/browser/chromeos/login/screens/welcome_screen.h +++ b/chrome/browser/chromeos/login/screens/welcome_screen.h
@@ -8,7 +8,7 @@ #include <memory> #include <string> -#include "ash/public/interfaces/locale.mojom.h" +#include "ash/public/cpp/locale_update_controller.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -109,10 +109,9 @@ // Callback when the system timezone settings is changed. void OnSystemTimezoneChanged(); - // Notifies locale change via mojom. - void ConnectToLocaleUpdateController(); + // Notifies locale change via ash::LocaleUpdateController. void NotifyLocaleChange(); - void OnLocaleChangeResult(ash::mojom::LocaleNotificationResult result); + void OnLocaleChangeResult(ash::LocaleNotificationResult result); WelcomeView* view_ = nullptr; base::RepeatingClosure exit_callback_; @@ -130,9 +129,6 @@ base::ObserverList<Observer>::Unchecked observers_; - // Ash's mojom::LocaleUpdateController - ash::mojom::LocaleUpdateControllerPtr locale_update_controller_ = nullptr; - base::WeakPtrFactory<WelcomeScreen> weak_factory_; DISALLOW_COPY_AND_ASSIGN(WelcomeScreen);
diff --git a/chrome/browser/chromeos/note_taking_helper.cc b/chrome/browser/chromeos/note_taking_helper.cc index 246ced2..bd50f68 100644 --- a/chrome/browser/chromeos/note_taking_helper.cc +++ b/chrome/browser/chromeos/note_taking_helper.cc
@@ -415,7 +415,7 @@ bool NoteTakingHelper::IsWhitelistedChromeApp( const extensions::Extension* extension) const { DCHECK(extension); - return base::ContainsValue(whitelisted_chrome_app_ids_, extension->id()); + return base::Contains(whitelisted_chrome_app_ids_, extension->id()); } std::vector<const extensions::Extension*> NoteTakingHelper::GetChromeApps( @@ -437,7 +437,7 @@ // Add any extensions which have a "note" action in their manifest // "action_handler" entry. for (const auto& extension : enabled_extensions) { - if (base::ContainsValue(extensions, extension.get())) + if (base::Contains(extensions, extension.get())) continue; if (extensions::ActionHandlersInfo::HasActionHandler(
diff --git a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc index d761753..0243816 100644 --- a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc +++ b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc
@@ -446,7 +446,7 @@ settings->mutable_allow_new_users()->set_allow_new_users(true); em::UserWhitelistProto* whitelist_proto = settings->mutable_user_whitelist(); - if (!base::ContainsValue(whitelist_proto->user_whitelist(), user_id)) + if (!base::Contains(whitelist_proto->user_whitelist(), user_id)) whitelist_proto->add_user_whitelist(user_id); }
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_metrics_util.cc b/chrome/browser/chromeos/plugin_vm/plugin_vm_metrics_util.cc index cee62cef..4571cc4 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_metrics_util.cc +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_metrics_util.cc
@@ -10,6 +10,7 @@ "PluginVm.Image.DownloadedSize"; const char kPluginVmLaunchResultHistogram[] = "PluginVm.LaunchResult"; const char kPluginVmSetupResultHistogram[] = "PluginVm.SetupResult"; +const char kPluginVmSetupTimeHistogram[] = "PluginVm.SetupTime"; void RecordPluginVmImageDownloadedSizeHistogram(uint64_t bytes_downloaded) { uint64_t megabytes_downloaded = bytes_downloaded / (1024 * 1024); @@ -25,4 +26,8 @@ base::UmaHistogramEnumeration(kPluginVmSetupResultHistogram, setup_result); } +void RecordPluginVmSetupTimeHistogram(base::TimeDelta setup_time) { + base::UmaHistogramLongTimes(kPluginVmSetupTimeHistogram, setup_time); +} + } // namespace plugin_vm
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_metrics_util.h b/chrome/browser/chromeos/plugin_vm/plugin_vm_metrics_util.h index e220f20..078987b 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_metrics_util.h +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_metrics_util.h
@@ -12,6 +12,10 @@ extern const char kPluginVmImageDownloadedSizeHistogram[]; extern const char kPluginVmLaunchResultHistogram[]; extern const char kPluginVmSetupResultHistogram[]; +// Histogram for recording successful setup time. +// When error occurs and user hits retry button in setup dialog - time between +// pressing retry button and setup being finished is recorded. +extern const char kPluginVmSetupTimeHistogram[]; // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. @@ -40,6 +44,7 @@ void RecordPluginVmImageDownloadedSizeHistogram(uint64_t bytes_downloaded); void RecordPluginVmLaunchResultHistogram(PluginVmLaunchResult launch_result); void RecordPluginVmSetupResultHistogram(PluginVmSetupResult setup_result); +void RecordPluginVmSetupTimeHistogram(base::TimeDelta setup_time); } // namespace plugin_vm
diff --git a/chrome/browser/chromeos/policy/lock_to_single_user_manager.cc b/chrome/browser/chromeos/policy/lock_to_single_user_manager.cc index d38f4a8..a5c3f56e 100644 --- a/chrome/browser/chromeos/policy/lock_to_single_user_manager.cc +++ b/chrome/browser/chromeos/policy/lock_to_single_user_manager.cc
@@ -7,6 +7,8 @@ #include "base/bind.h" #include "base/logging.h" #include "base/metrics/histogram_functions.h" +#include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chromeos/cryptohome/cryptohome_parameters.h" @@ -14,7 +16,7 @@ #include "chromeos/login/session/session_termination_manager.h" #include "chromeos/settings/cros_settings_names.h" #include "components/policy/proto/chrome_device_policy.pb.h" -#include "components/user_manager/user_manager.h" +#include "content/public/browser/notification_service.h" using RebootOnSignOutPolicy = enterprise_management::DeviceRebootOnUserSignoutProto; @@ -49,15 +51,22 @@ } // namespace LockToSingleUserManager::LockToSingleUserManager() { - CHECK(chromeos::LoginState::IsInitialized()); - login_state_observer_.Add(chromeos::LoginState::Get()); + notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED, + content::NotificationService::AllSources()); } -LockToSingleUserManager::~LockToSingleUserManager() {} +LockToSingleUserManager::~LockToSingleUserManager() = default; -void LockToSingleUserManager::LoggedInStateChanged() { - if (!chromeos::LoginState::Get()->IsUserLoggedIn() || - !user_manager::UserManager::Get()->GetPrimaryUser()) { +void LockToSingleUserManager::Observe( + int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_EQ(chrome::NOTIFICATION_PROFILE_CREATED, type); + const user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile( + content::Source<Profile>(source).ptr()); + if (!user || user->IsAffiliated()) { return; } int policy_value = -1; @@ -65,7 +74,7 @@ chromeos::kDeviceRebootOnUserSignout, &policy_value)) { return; } - login_state_observer_.RemoveAll(); + notification_registrar_.RemoveAll(); switch (policy_value) { case RebootOnSignOutPolicy::ALWAYS: LockToSingleUser();
diff --git a/chrome/browser/chromeos/policy/lock_to_single_user_manager.h b/chrome/browser/chromeos/policy/lock_to_single_user_manager.h index 779765e..7bf3903d 100644 --- a/chrome/browser/chromeos/policy/lock_to_single_user_manager.h +++ b/chrome/browser/chromeos/policy/lock_to_single_user_manager.h
@@ -11,25 +11,29 @@ #include "base/scoped_observer.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/login/login_state/login_state.h" +#include "components/user_manager/user_manager.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" namespace policy { // This class observes the LoginState and ArcSessionManager and checks if the // device must be locked to a single user mount, if the policy forces it. -class LockToSingleUserManager final : public chromeos::LoginState::Observer, - public arc::ArcSessionManager::Observer { +class LockToSingleUserManager final : public arc::ArcSessionManager::Observer, + public content::NotificationObserver { public: LockToSingleUserManager(); ~LockToSingleUserManager() override; - // chromeos::LoginState::Observer overrides - void LoggedInStateChanged() override; - + private: // arc::ArcSessionManager::Observer overrides void OnArcStarted() override; - private: + // content::NotificationObserver overrides + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override; + // Sends D-Bus request to lock device to single user mount. void LockToSingleUser(); @@ -39,8 +43,7 @@ ScopedObserver<arc::ArcSessionManager, arc::ArcSessionManager::Observer> arc_session_observer_{this}; - ScopedObserver<chromeos::LoginState, chromeos::LoginState::Observer> - login_state_observer_{this}; + content::NotificationRegistrar notification_registrar_; base::WeakPtrFactory<LockToSingleUserManager> weak_factory_{this};
diff --git a/chrome/browser/chromeos/policy/lock_to_single_user_manager_unittest.cc b/chrome/browser/chromeos/policy/lock_to_single_user_manager_unittest.cc index 4e8d23b8..32555dd7 100644 --- a/chrome/browser/chromeos/policy/lock_to_single_user_manager_unittest.cc +++ b/chrome/browser/chromeos/policy/lock_to_single_user_manager_unittest.cc
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" @@ -24,6 +25,7 @@ #include "components/arc/test/fake_arc_session.h" #include "components/policy/proto/chrome_device_policy.pb.h" #include "components/user_manager/scoped_user_manager.h" +#include "content/public/browser/notification_service.h" namespace policy { @@ -64,11 +66,15 @@ chromeos::LoginState::Shutdown(); } - void LogInUser() { + void LogInUser(bool is_affiliated) { const AccountId account_id(AccountId::FromUserEmailGaiaId( profile()->GetProfileUserName(), "1234567890")); - fake_user_manager_->AddUser(account_id); + fake_user_manager_->AddUserWithAffiliation(account_id, is_affiliated); fake_user_manager_->LoginUser(account_id); + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_PROFILE_CREATED, + content::Source<Profile>(profile()), + content::NotificationService::NoDetails()); chromeos::LoginState::Get()->SetLoggedInState( chromeos::LoginState::LOGGED_IN_ACTIVE, chromeos::LoginState::LOGGED_IN_USER_REGULAR); @@ -107,7 +113,7 @@ TEST_F(LockToSingleUserManagerTest, ArcSessionLockTest) { SetPolicyValue( enterprise_management::DeviceRebootOnUserSignoutProto::ARC_SESSION); - LogInUser(); + LogInUser(false /* is_affiliated */); EXPECT_FALSE(is_device_locked()); StartArc(); EXPECT_TRUE(is_device_locked()); @@ -115,13 +121,13 @@ TEST_F(LockToSingleUserManagerTest, AlwaysLockTest) { SetPolicyValue(enterprise_management::DeviceRebootOnUserSignoutProto::ALWAYS); - LogInUser(); + LogInUser(false /* is_affiliated */); EXPECT_TRUE(is_device_locked()); } TEST_F(LockToSingleUserManagerTest, NeverLockTest) { SetPolicyValue(enterprise_management::DeviceRebootOnUserSignoutProto::NEVER); - LogInUser(); + LogInUser(false /* is_affiliated */); EXPECT_FALSE(is_device_locked()); } @@ -129,7 +135,13 @@ chromeos::FakeCryptohomeClient::Get()->set_cryptohome_error( cryptohome::CRYPTOHOME_ERROR_KEY_NOT_FOUND); SetPolicyValue(enterprise_management::DeviceRebootOnUserSignoutProto::ALWAYS); - LogInUser(); + LogInUser(false /* is_affiliated */); + EXPECT_FALSE(is_device_locked()); +} + +TEST_F(LockToSingleUserManagerTest, DoesNotAffectAffiliatedUsersTest) { + SetPolicyValue(enterprise_management::DeviceRebootOnUserSignoutProto::ALWAYS); + LogInUser(true /* is_affiliated */); EXPECT_FALSE(is_device_locked()); }
diff --git a/chrome/browser/client_hints/client_hints_browsertest.cc b/chrome/browser/client_hints/client_hints_browsertest.cc index bda5769..a7435dc 100644 --- a/chrome/browser/client_hints/client_hints_browsertest.cc +++ b/chrome/browser/client_hints/client_hints_browsertest.cc
@@ -567,8 +567,8 @@ } for (size_t i = 0; i < blink::kClientHintsMappingsCount; ++i) { - if (base::ContainsKey(request.headers, - blink::kClientHintsHeaderMapping[i])) { + if (base::Contains(request.headers, + blink::kClientHintsHeaderMapping[i])) { // The user agent hint is special: if (std::string(blink::kClientHintsHeaderMapping[i]) == "sec-ch-ua") { count_user_agent_hint_headers_seen_++; @@ -594,9 +594,9 @@ continue; } - EXPECT_EQ(expect_client_hints, - base::ContainsKey(request.headers, - blink::kClientHintsHeaderMapping[i])); + EXPECT_EQ( + expect_client_hints, + base::Contains(request.headers, blink::kClientHintsHeaderMapping[i])); } }
diff --git a/chrome/browser/component_updater/cros_component_installer_chromeos_unittest.cc b/chrome/browser/component_updater/cros_component_installer_chromeos_unittest.cc index af7964ae..523630b 100644 --- a/chrome/browser/component_updater/cros_component_installer_chromeos_unittest.cc +++ b/chrome/browser/component_updater/cros_component_installer_chromeos_unittest.cc
@@ -75,8 +75,8 @@ // Whether has a pending update request (either foreground or background). bool HasPendingUpdate(const std::string& name) { - return base::ContainsKey(background_updates_, name) || - base::ContainsKey(foreground_updates_, name); + return base::Contains(background_updates_, name) || + base::Contains(foreground_updates_, name); } // Finishes a foreground update request. Returns false if there is no pending
diff --git a/chrome/browser/component_updater/supervised_user_whitelist_installer.cc b/chrome/browser/component_updater/supervised_user_whitelist_installer.cc index d4703e66..a65d7c7 100644 --- a/chrome/browser/component_updater/supervised_user_whitelist_installer.cc +++ b/chrome/browser/component_updater/supervised_user_whitelist_installer.cc
@@ -204,7 +204,7 @@ continue; // Ignore folders that correspond to registered whitelists. - if (base::ContainsKey(registered_whitelists, crx_id)) + if (base::Contains(registered_whitelists, crx_id)) continue; RecordUncleanUninstall(); @@ -235,7 +235,7 @@ continue; // Ignore files that correspond to registered whitelists. - if (base::ContainsKey(registered_whitelists, crx_id)) + if (base::Contains(registered_whitelists, crx_id)) continue; RecordUncleanUninstall(); @@ -520,7 +520,7 @@ // previously registered on the command line but isn't anymore. const base::ListValue* clients = nullptr; if ((!dict->GetList(kClients, &clients) || clients->empty()) && - !base::ContainsKey(command_line_whitelists, id)) { + !base::Contains(command_line_whitelists, id)) { stale_whitelists.insert(id); continue; } @@ -573,7 +573,7 @@ } base::Value client(client_id); - DCHECK(!base::ContainsValue(clients->GetList(), client)); + DCHECK(!base::Contains(clients->GetList(), client)); clients->GetList().push_back(std::move(client)); }
diff --git a/chrome/browser/custom_handlers/protocol_handler_registry.cc b/chrome/browser/custom_handlers/protocol_handler_registry.cc index d310587..801be3a 100644 --- a/chrome/browser/custom_handlers/protocol_handler_registry.cc +++ b/chrome/browser/custom_handlers/protocol_handler_registry.cc
@@ -427,7 +427,7 @@ ProtocolHandlerRegistry::ProtocolHandlerList result; for (const auto& entry : user_protocol_handlers_) { for (const ProtocolHandler& handler : entry.second) { - if (base::ContainsValue(predefined_protocol_handlers_, handler)) + if (base::Contains(predefined_protocol_handlers_, handler)) continue; if (begin <= handler.last_modified() && handler.last_modified() < end) result.push_back(handler); @@ -489,7 +489,7 @@ if (!handlers) { return false; } - return base::ContainsValue(*handlers, handler); + return base::Contains(*handlers, handler); } bool ProtocolHandlerRegistry::IsRegisteredByUser( @@ -874,7 +874,7 @@ bool ProtocolHandlerRegistry::HandlerExists(const ProtocolHandler& handler, const ProtocolHandlerList& list) { - return base::ContainsValue(list, handler); + return base::Contains(list, handler); } void ProtocolHandlerRegistry::EraseHandler(const ProtocolHandler& handler,
diff --git a/chrome/browser/data_use_measurement/chrome_data_use_measurement.cc b/chrome/browser/data_use_measurement/chrome_data_use_measurement.cc index 941dfcd0..97144396 100644 --- a/chrome/browser/data_use_measurement/chrome_data_use_measurement.cc +++ b/chrome/browser/data_use_measurement/chrome_data_use_measurement.cc
@@ -86,6 +86,14 @@ return g_chrome_data_use_measurement; } +// static +void ChromeDataUseMeasurement::DeleteInstance() { + if (g_chrome_data_use_measurement) { + delete g_chrome_data_use_measurement; + g_chrome_data_use_measurement = nullptr; + } +} + ChromeDataUseMeasurement::ChromeDataUseMeasurement( std::unique_ptr<URLRequestClassifier> url_request_classifier, DataUseAscriber* ascriber,
diff --git a/chrome/browser/data_use_measurement/chrome_data_use_measurement.h b/chrome/browser/data_use_measurement/chrome_data_use_measurement.h index de8c0a2..ba1fee85 100644 --- a/chrome/browser/data_use_measurement/chrome_data_use_measurement.h +++ b/chrome/browser/data_use_measurement/chrome_data_use_measurement.h
@@ -21,6 +21,7 @@ public: static void CreateInstance(PrefService* local_state); static ChromeDataUseMeasurement* GetInstance(); + static void DeleteInstance(); ChromeDataUseMeasurement( std::unique_ptr<URLRequestClassifier> url_request_classifier,
diff --git a/chrome/browser/devtools/chrome_devtools_manager_delegate.cc b/chrome/browser/devtools/chrome_devtools_manager_delegate.cc index 0ef34b4..d34abfa 100644 --- a/chrome/browser/devtools/chrome_devtools_manager_delegate.cc +++ b/chrome/browser/devtools/chrome_devtools_manager_delegate.cc
@@ -117,7 +117,7 @@ std::string ChromeDevToolsManagerDelegate::GetTargetType( content::WebContents* web_contents) { - if (base::ContainsValue(AllTabContentses(), web_contents)) + if (base::Contains(AllTabContentses(), web_contents)) return DevToolsAgentHost::kTypePage; std::string extension_name;
diff --git a/chrome/browser/devtools/device/tcp_device_provider.cc b/chrome/browser/devtools/device/tcp_device_provider.cc index c949036f..48a1ca31 100644 --- a/chrome/browser/devtools/device/tcp_device_provider.cc +++ b/chrome/browser/devtools/device/tcp_device_provider.cc
@@ -97,7 +97,7 @@ std::vector<std::string> result; for (const net::HostPortPair& target : targets_) { const std::string& host = target.host(); - if (base::ContainsValue(result, host)) + if (base::Contains(result, host)) continue; result.push_back(host); }
diff --git a/chrome/browser/devtools/device/usb/android_usb_browsertest.cc b/chrome/browser/devtools/device/usb/android_usb_browsertest.cc index b664a3b..8da28af 100644 --- a/chrome/browser/devtools/device/usb/android_usb_browsertest.cc +++ b/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
@@ -423,7 +423,7 @@ void GetDevice(const std::string& guid, device::mojom::UsbDeviceRequest device_request, device::mojom::UsbDeviceClientPtr device_client) override { - DCHECK(base::ContainsKey(devices(), guid)); + DCHECK(base::Contains(devices(), guid)); FakeAndroidUsbDevice::Create(devices()[guid], std::move(device_request), std::move(device_client)); }
diff --git a/chrome/browser/devtools/device/usb/android_usb_device.cc b/chrome/browser/devtools/device/usb/android_usb_device.cc index 7d2d59f..b38049dd 100644 --- a/chrome/browser/devtools/device/usb/android_usb_device.cc +++ b/chrome/browser/devtools/device/usb/android_usb_device.cc
@@ -166,7 +166,7 @@ base::BindOnce(&OnProbeFinished, callback, devices)); for (const auto& device_info : device_info_list) { - if (base::ContainsValue(g_open_devices.Get(), device_info.guid)) { + if (base::Contains(g_open_devices.Get(), device_info.guid)) { // This device is already open, do not make parallel attempts to connect // to it. barrier.Run();
diff --git a/chrome/browser/download/download_request_limiter.cc b/chrome/browser/download/download_request_limiter.cc index 379d7d2..05a181e 100644 --- a/chrome/browser/download/download_request_limiter.cc +++ b/chrome/browser/download/download_request_limiter.cc
@@ -611,7 +611,7 @@ void DownloadRequestLimiter::Remove(TabDownloadState* state, content::WebContents* contents) { - DCHECK(base::ContainsKey(state_map_, contents)); + DCHECK(base::Contains(state_map_, contents)); state_map_.erase(contents); delete state; }
diff --git a/chrome/browser/engagement/important_sites_util.cc b/chrome/browser/engagement/important_sites_util.cc index 900f794..cf0876f 100644 --- a/chrome/browser/engagement/important_sites_util.cc +++ b/chrome/browser/engagement/important_sites_util.cc
@@ -213,8 +213,7 @@ std::unordered_set<std::string> ignoring_domains; for (const ContentSettingPatternSource& site : content_settings_list) { GURL origin(site.primary_pattern.ToString()); - if (!origin.is_valid() || - base::ContainsKey(ignoring_domains, origin.host())) { + if (!origin.is_valid() || base::Contains(ignoring_domains, origin.host())) { continue; }
diff --git a/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc b/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc index 9cff1e3..ce87607 100644 --- a/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc +++ b/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc
@@ -9,11 +9,14 @@ #include <utility> #include <vector> +#include "base/feature_list.h" #include "base/task/post_task.h" +#include "base/test/scoped_feature_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service_test_base.h" #include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/safe_browsing/test_safe_browsing_service.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" @@ -27,6 +30,7 @@ #include "content/public/test/web_contents_tester.h" #include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_request_test_util.h" +#include "services/network/public/cpp/features.h" namespace extensions { @@ -78,12 +82,16 @@ std::unique_ptr<TestBrowserWindow> browser_window_; std::unique_ptr<Browser> browser_; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; + base::test::ScopedFeatureList feature_list_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateApiUnitTest); }; void SafeBrowsingPrivateApiUnitTest::SetUp() { + // Need to use the network service path because we've removed the + // URLRequestContext path in src/chrome and unit_tests currently are running + // with network service disabled. https://crbug.com/966633 + feature_list_.InitAndEnableFeature(network::features::kNetworkService); ExtensionServiceTestBase::SetUp(); InitializeEmptyExtensionService(); content::BrowserSideNavigationSetUp(); @@ -97,12 +105,6 @@ // Initialize Safe Browsing service. safe_browsing::TestSafeBrowsingServiceFactory sb_service_factory; auto* safe_browsing_service = sb_service_factory.CreateSafeBrowsingService(); - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext( - system_request_context_getter_.get()); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService( safe_browsing_service); g_browser_process->safe_browsing_service()->Initialize(); @@ -120,6 +122,10 @@ TestingBrowserProcess::GetGlobal()->safe_browsing_service()->ShutDown(); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr); + // Depends on LocalState from ChromeRenderViewHostTestHarness. + if (SystemNetworkContextManager::GetInstance()) + SystemNetworkContextManager::DeleteInstance(); + ExtensionServiceTestBase::TearDown(); }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 4272a99..6d63a28 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -456,6 +456,11 @@ "expiry_milestone": 76 }, { + "name": "cookie-deprecation-messages", + "owners": [ "chlily", "aarontag" ], + "expiry_milestone": 82 + }, + { "name": "cookies-without-same-site-must-be-secure", "owners": [ "chlily", "morlovich" ], "expiry_milestone": 80
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 041dfc1b..0b820d2 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -289,9 +289,14 @@ "Renders a border around composited Render Layers to help debug and study " "layer compositing."; -extern const char kCookiesWithoutSameSiteMustBeSecureName[] = +const char kCookieDeprecationMessagesName[] = "Cookie deprecation messages"; +const char kCookieDeprecationMessagesDescription[] = + "Show messages in the DevTools console about upcoming deprecations that " + "would affect sent/received cookies."; + +const char kCookiesWithoutSameSiteMustBeSecureName[] = "Cookies without SameSite must be secure"; -extern const char kCookiesWithoutSameSiteMustBeSecureDescription[] = +const char kCookiesWithoutSameSiteMustBeSecureDescription[] = "If enabled, cookies without SameSite restrictions must also be Secure. If " "a cookie without SameSite restrictions is set without the Secure " "attribute, it will be rejected. This flag only has an effect if " @@ -3255,6 +3260,11 @@ "InstallableInkDrop is part of an InkDrop refactoring effort. This enables " "the pilot implementation where available."; +const char kReopenTabInProductHelpName[] = "Reopen tab in-product help"; +const char kReopenTabInProductHelpDescription[] = + "Enable in-product help that guides a user to reopen a tab if it looks " + "like they accidentally closed it."; + #endif // defined(TOOLKIT_VIEWS) // Random platform combinations ----------------------------------------------- @@ -3372,15 +3382,6 @@ #endif // defined(TOOLKIT_VIEWS) || defined(OS_ANDROID) -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - -const char kReopenTabInProductHelpName[] = "Reopen tab in-product help"; -const char kReopenTabInProductHelpDescription[] = - "Enable in-product help that guides a user to reopen a tab if it looks " - "like they accidentally closed it."; - -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - #if defined(WEBRTC_USE_PIPEWIRE) extern const char kWebrtcPipeWireCapturerName[] = "WebRTC PipeWire support";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 76aef53..311fcd43 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -10,7 +10,6 @@ #include "build/build_config.h" #include "build/buildflag.h" #include "chrome/common/buildflags.h" -#include "components/feature_engagement/buildflags.h" #include "components/nacl/common/buildflags.h" #include "device/vr/buildflags/buildflags.h" #include "media/media_buildflags.h" @@ -203,6 +202,9 @@ extern const char kCompositedLayerBordersName[]; extern const char kCompositedLayerBordersDescription[]; +extern const char kCookieDeprecationMessagesName[]; +extern const char kCookieDeprecationMessagesDescription[]; + extern const char kCookiesWithoutSameSiteMustBeSecureName[]; extern const char kCookiesWithoutSameSiteMustBeSecureDescription[]; @@ -1958,6 +1960,9 @@ extern const char kInstallableInkDropName[]; extern const char kInstallableInkDropDescription[]; +extern const char kReopenTabInProductHelpName[]; +extern const char kReopenTabInProductHelpDescription[]; + #endif // defined(TOOLKIT_VIEWS) // Random platform combinations ----------------------------------------------- @@ -2053,12 +2058,6 @@ #endif // defined(TOOLKIT_VIEWS) || defined(OS_ANDROID) -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - -extern const char kReopenTabInProductHelpName[]; -extern const char kReopenTabInProductHelpDescription[]; - -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) extern const char kAvoidFlashBetweenNavigationName[]; extern const char kAvoidFlahsBetweenNavigationDescription[];
diff --git a/chrome/browser/google/google_brand.cc b/chrome/browser/google/google_brand.cc index 336b7913..a25ed2b 100644 --- a/chrome/browser/google/google_brand.cc +++ b/chrome/browser/google/google_brand.cc
@@ -146,7 +146,7 @@ "CHIQ", "CHSG", "HLJY", "NTMO", "OOBA", "OOBB", "OOBC", "OOBD", "OOBE", "OOBF", "OOBG", "OOBH", "OOBI", "OOBJ", "IDCM", }; - return base::ContainsValue(kBrands, brand); + return base::Contains(kBrands, brand); } // BrandForTesting ------------------------------------------------------------
diff --git a/chrome/browser/installable/installable_manager.cc b/chrome/browser/installable/installable_manager.cc index e53ba98..09089d4b 100644 --- a/chrome/browser/installable/installable_manager.cc +++ b/chrome/browser/installable/installable_manager.cc
@@ -109,8 +109,8 @@ base::CompareCase::INSENSITIVE_ASCII))) continue; - if (!base::ContainsValue(icon.purpose, - blink::Manifest::ImageResource::Purpose::ANY)) { + if (!base::Contains(icon.purpose, + blink::Manifest::ImageResource::Purpose::ANY)) { continue; }
diff --git a/chrome/browser/internal_auth.cc b/chrome/browser/internal_auth.cc index 74d9c74..45b2727 100644 --- a/chrome/browser/internal_auth.cc +++ b/chrome/browser/internal_auth.cc
@@ -110,8 +110,8 @@ sizeof(kAllowedChars) == 26 + 26 + 10 + 1 + 1, "some mess with chars"); // We must not allow kItemSeparator in anything used as an input to construct // message to sign. - DCHECK(!base::ContainsValue(kAllowedChars, kItemSeparator)); - DCHECK(!base::ContainsValue(kAllowedChars, kVarValueSeparator)); + DCHECK(!base::Contains(kAllowedChars, kItemSeparator)); + DCHECK(!base::Contains(kAllowedChars, kVarValueSeparator)); return !var.empty() && var.size() <= kStringLengthLimit && base::IsStringASCII(var) && @@ -381,7 +381,7 @@ int idx = static_cast<int>(used_ticks_.size()) - static_cast<int>(current_tick - tick + 1); if (idx < 0 || used_ticks_[idx] != tick) { - DCHECK(!base::ContainsValue(used_ticks_, tick)); + DCHECK(!base::Contains(used_ticks_, tick)); return tick; } }
diff --git a/chrome/browser/io_thread.cc b/chrome/browser/io_thread.cc index 25cb133..5c2dacb 100644 --- a/chrome/browser/io_thread.cc +++ b/chrome/browser/io_thread.cc
@@ -10,7 +10,6 @@ #include "base/base64.h" #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/command_line.h" #include "base/compiler_specific.h" #include "base/debug/leak_tracker.h" #include "base/files/file_path.h" @@ -35,7 +34,6 @@ #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" -#include "components/certificate_transparency/ct_known_logs.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h" #include "components/data_use_measurement/core/data_use_ascriber.h" #include "components/metrics/metrics_service.h" @@ -54,41 +52,14 @@ #include "content/public/common/content_switches.h" #include "content/public/common/user_agent.h" #include "extensions/buildflags/buildflags.h" -#include "net/cert/caching_cert_verifier.h" -#include "net/cert/cert_verifier.h" -#include "net/cert/cert_verify_proc.h" -#include "net/cert/ct_log_verifier.h" -#include "net/cert/multi_threaded_cert_verifier.h" -#include "net/cert_net/cert_net_fetcher_impl.h" -#include "net/http/http_network_session.h" -#include "net/http/http_server_properties_impl.h" -#include "net/http/http_transaction_factory.h" -#include "net/net_buildflags.h" +#include "net/cert/cert_database.h" #include "net/nqe/network_quality_estimator.h" #include "net/nqe/network_quality_estimator_params.h" -#include "net/proxy_resolution/pac_file_fetcher_impl.h" -#include "net/proxy_resolution/proxy_config_service.h" -#include "net/proxy_resolution/proxy_resolution_service.h" -#include "net/quic/quic_utils_chromium.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_context_builder.h" -#include "net/url_request/url_request_context_getter.h" -#include "services/network/ignore_errors_cert_verifier.h" #include "services/network/network_service.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/network_switches.h" -#include "services/network/url_request_context_builder_mojo.h" #include "url/url_constants.h" -#if BUILDFLAG(ENABLE_EXTENSIONS) -#include "chrome/browser/extensions/event_router_forwarder.h" -#endif - -#if defined(OS_ANDROID) -#include "net/cert/cert_verify_proc_android.h" -#endif // defined(OS_ANDROID) - #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chromeos/network/dhcp_pac_file_fetcher_factory_chromeos.h" @@ -104,36 +75,6 @@ namespace { -net::CertVerifier* g_cert_verifier_for_io_thread_testing = nullptr; - -// A CertVerifier that forwards all requests to -// |g_cert_verifier_for_io_thread_testing|. This is used to allow IOThread to -// have its own std::unique_ptr<net::CertVerifier> while forwarding calls to the -// static verifier. -class WrappedCertVerifierForIOThreadTesting : public net::CertVerifier { - public: - ~WrappedCertVerifierForIOThreadTesting() override = default; - - // CertVerifier implementation - int Verify(const RequestParams& params, - net::CertVerifyResult* verify_result, - net::CompletionOnceCallback callback, - std::unique_ptr<Request>* out_req, - const net::NetLogWithSource& net_log) override { - verify_result->Reset(); - if (!g_cert_verifier_for_io_thread_testing) - return net::ERR_FAILED; - return g_cert_verifier_for_io_thread_testing->Verify( - params, verify_result, std::move(callback), out_req, net_log); - } - - void SetConfig(const Config& config) override { - if (!g_cert_verifier_for_io_thread_testing) - return; - return g_cert_verifier_for_io_thread_testing->SetConfig(config); - } -}; - #if defined(OS_MACOSX) void ObserveKeychainEvents() { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -143,46 +84,7 @@ } // namespace -class SystemURLRequestContextGetter : public net::URLRequestContextGetter { - public: - explicit SystemURLRequestContextGetter(IOThread* io_thread); - - // Implementation for net::UrlRequestContextGetter. - net::URLRequestContext* GetURLRequestContext() override; - scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner() - const override; - - protected: - ~SystemURLRequestContextGetter() override; - - private: - IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess. - scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_; - - base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_; -}; - -SystemURLRequestContextGetter::SystemURLRequestContextGetter( - IOThread* io_thread) - : io_thread_(io_thread), - network_task_runner_( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})) {} - -SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {} - -net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - DCHECK(io_thread_->globals()->system_request_context); - - return io_thread_->globals()->system_request_context; -} - -scoped_refptr<base::SingleThreadTaskRunner> -SystemURLRequestContextGetter::GetNetworkTaskRunner() const { - return network_task_runner_; -} - -IOThread::Globals::Globals() : system_request_context(nullptr) {} +IOThread::Globals::Globals() {} IOThread::Globals::~Globals() {} @@ -192,12 +94,8 @@ PrefService* local_state, policy::PolicyService* policy_service, net_log::ChromeNetLog* net_log, - extensions::EventRouterForwarder* extension_event_router_forwarder, SystemNetworkContextManager* system_network_context_manager) : net_log_(net_log), -#if BUILDFLAG(ENABLE_EXTENSIONS) - extension_event_router_forwarder_(extension_event_router_forwarder), -#endif globals_(nullptr), is_quic_allowed_on_init_(true), weak_factory_(this) { @@ -230,39 +128,16 @@ return net_log_; } -net::URLRequestContextGetter* IOThread::system_url_request_context_getter() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!base::FeatureList::IsEnabled(network::features::kNetworkService) && - !system_url_request_context_getter_.get()) { - system_url_request_context_getter_ = - base::MakeRefCounted<SystemURLRequestContextGetter>(this); - } else { - NOTREACHED(); - } - return system_url_request_context_getter_.get(); -} - void IOThread::Init() { TRACE_EVENT0("startup", "IOThread::InitAsync"); DCHECK_CURRENTLY_ON(BrowserThread::IO); - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - DCHECK(!globals_); globals_ = new Globals; -#if BUILDFLAG(ENABLE_EXTENSIONS) - globals_->extension_event_router_forwarder = - extension_event_router_forwarder_; -#endif - globals_->data_use_ascriber = std::make_unique<data_use_measurement::ChromeDataUseAscriber>(); - if (command_line.HasSwitch(network::switches::kIgnoreUrlFetcherCertRequests)) - net::URLFetcher::SetIgnoreCertificateRequests(true); - #if defined(OS_MACOSX) // Start observing Keychain events. This needs to be done on the UI thread, // as Keychain services requires a CFRunLoop. @@ -271,32 +146,17 @@ #endif ConstructSystemRequestContext(); - - // Prevent DCHECK failures when a NetworkContext is created with an encrypted - // cookie store. - if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) - content::GetNetworkServiceImpl()->set_os_crypt_is_configured(); } void IOThread::CleanUp() { base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks(); - system_url_request_context_getter_ = nullptr; - - if (globals_->cert_net_fetcher) - globals_->cert_net_fetcher->Shutdown(); - - if (globals_->system_request_context) - globals_->system_request_context->proxy_resolution_service()->OnShutdown(); - // Release objects that the net::URLRequestContext could have been pointing // to. delete globals_; globals_ = nullptr; - base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks(); - if (net_log_) net_log_->ShutDownBeforeThreadPool(); } @@ -306,96 +166,15 @@ data_reduction_proxy::RegisterPrefs(registry); } -// static -void IOThread::SetCertVerifierForTesting(net::CertVerifier* cert_verifier) { - g_cert_verifier_for_io_thread_testing = cert_verifier; -} - void IOThread::DisableQuic() { DCHECK_CURRENTLY_ON(BrowserThread::IO); globals_->quic_disabled = true; } -void IOThread::SetUpProxyService( - network::URLRequestContextBuilderMojo* builder) const { -#if defined(OS_CHROMEOS) - builder->SetDhcpFetcherFactory( - std::make_unique<chromeos::DhcpPacFileFetcherFactoryChromeos>()); -#endif -} - void IOThread::ConstructSystemRequestContext() { - if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { - globals_->deprecated_network_quality_estimator = - std::make_unique<net::NetworkQualityEstimator>( - std::make_unique<net::NetworkQualityEstimatorParams>( - std::map<std::string, std::string>()), - net_log_); - } else { - std::unique_ptr<network::URLRequestContextBuilderMojo> builder = - std::make_unique<network::URLRequestContextBuilderMojo>(); - - auto chrome_network_delegate = std::make_unique<ChromeNetworkDelegate>( - extension_event_router_forwarder()); - builder->set_network_delegate( - globals_->data_use_ascriber->CreateNetworkDelegate( - std::move(chrome_network_delegate))); - - std::unique_ptr<net::CertVerifier> cert_verifier; - if (g_cert_verifier_for_io_thread_testing) { - cert_verifier = std::make_unique<WrappedCertVerifierForIOThreadTesting>(); - } else { -#if defined(OS_CHROMEOS) - // Creates a CertVerifyProc that doesn't allow any profile-provided certs. - cert_verifier = std::make_unique<net::CachingCertVerifier>( - std::make_unique<net::MultiThreadedCertVerifier>( - base::MakeRefCounted<network::CertVerifyProcChromeOS>())); -#else -#if defined(OS_ANDROID) || defined(OS_FUCHSIA) || \ - BUILDFLAG(TRIAL_COMPARISON_CERT_VERIFIER_SUPPORTED) - globals_->cert_net_fetcher = - base::MakeRefCounted<net::CertNetFetcherImpl>(); -#endif - cert_verifier = std::make_unique<net::CachingCertVerifier>( - std::make_unique<net::MultiThreadedCertVerifier>( - net::CertVerifyProc::CreateDefault(globals_->cert_net_fetcher))); -#endif - } - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - builder->SetCertVerifier( - network::IgnoreErrorsCertVerifier::MaybeWrapCertVerifier( - command_line, switches::kUserDataDir, std::move(cert_verifier))); - - SetUpProxyService(builder.get()); - - if (!is_quic_allowed_on_init_) - globals_->quic_disabled = true; - - // File support is needed for PAC scripts that use file URLs. - // TODO(crbug.com/839566): remove file support for all cases. - // TODO(mmenke): once this code is deleted there won't be any more consumers - // of net::URLRequestFileJo and that class can be deleted. - builder->set_file_enabled(true); - - network::NetworkService* network_service = content::GetNetworkServiceImpl(); - network_service->SetUpHttpAuth(std::move(http_auth_static_params_)); - network_service->ConfigureHttpAuthPrefs( - std::move(http_auth_dynamic_params_)); - - globals_->system_network_context = - network_service->CreateNetworkContextWithBuilder( - std::move(network_context_request_), - std::move(network_context_params_), std::move(builder), - &globals_->system_request_context); - - if (globals_->cert_net_fetcher) { - globals_->cert_net_fetcher->SetURLRequestContext( - globals_->system_request_context); - } - - // This must be done after the system NetworkContext is created. - network_service->ConfigureStubHostResolver( - stub_resolver_enabled_, std::move(dns_over_https_servers_)); - } + globals_->deprecated_network_quality_estimator = + std::make_unique<net::NetworkQualityEstimator>( + std::make_unique<net::NetworkQualityEstimatorParams>( + std::map<std::string, std::string>()), + net_log_); }
diff --git a/chrome/browser/io_thread.h b/chrome/browser/io_thread.h index ac3ddda..03a0980 100644 --- a/chrome/browser/io_thread.h +++ b/chrome/browser/io_thread.h
@@ -40,27 +40,14 @@ class ChromeDataUseAscriber; } -namespace extensions { -class EventRouterForwarder; -} - namespace net { -class CertNetFetcherImpl; -class CertVerifier; -class HostResolver; class NetworkQualityEstimator; -class URLRequestContext; -class URLRequestContextGetter; } // namespace net namespace net_log { class ChromeNetLog; } -namespace network { -class URLRequestContextBuilderMojo; -} - namespace policy { class PolicyService; } // namespace policy @@ -74,15 +61,6 @@ class IOThread : public content::BrowserThreadDelegate { public: struct Globals { - class SystemRequestContextLeakChecker { - public: - explicit SystemRequestContextLeakChecker(Globals* globals); - ~SystemRequestContextLeakChecker(); - - private: - Globals* const globals_; - }; - Globals(); ~Globals(); @@ -99,54 +77,29 @@ // need to create an in-process one. std::unique_ptr<net::NetworkQualityEstimator> deprecated_network_quality_estimator; - - // HostResolver only for use in dummy in-process - // URLRequestContext when network service is enabled. - std::unique_ptr<net::HostResolver> deprecated_host_resolver; - - // When the network service is disabled, this holds on to a - // content::NetworkContext class that owns |system_request_context|. - std::unique_ptr<network::mojom::NetworkContext> system_network_context; - net::URLRequestContext* system_request_context; - // When the network service is disabled, this holds the CertNetFetcher used - // by the |system_request_context|'s CertVerifier. May be nullptr if - // CertNetFetcher is not used by the current platform. - scoped_refptr<net::CertNetFetcherImpl> cert_net_fetcher; -#if BUILDFLAG(ENABLE_EXTENSIONS) - scoped_refptr<extensions::EventRouterForwarder> - extension_event_router_forwarder; -#endif }; // |net_log| must either outlive the IOThread or be NULL. IOThread(PrefService* local_state, policy::PolicyService* policy_service, net_log::ChromeNetLog* net_log, - extensions::EventRouterForwarder* extension_event_router_forwarder, SystemNetworkContextManager* system_network_context_manager); ~IOThread() override; static void RegisterPrefs(PrefRegistrySimple* registry); - static void SetCertVerifierForTesting(net::CertVerifier* cert_verifier); // Can only be called on the IO thread. Globals* globals(); net_log::ChromeNetLog* net_log(); - // Returns a getter for the URLRequestContext. Only called on the UI thread. - net::URLRequestContextGetter* system_url_request_context_getter(); - // Dynamically disables QUIC for all NetworkContexts using the IOThread's // NetworkService. Re-enabling Quic dynamically is not supported for // simplicity and requires a browser restart. May only be called on the IO // thread. void DisableQuic(); - // Configures |builder|'s ProxyResolutionService based on prefs and policies. - void SetUpProxyService(network::URLRequestContextBuilderMojo* builder) const; - private: // BrowserThreadDelegate implementation, runs on the IO thread. // This handles initialization and destruction of state that must @@ -154,25 +107,12 @@ void Init() override; void CleanUp() override; - extensions::EventRouterForwarder* extension_event_router_forwarder() { -#if BUILDFLAG(ENABLE_EXTENSIONS) - return extension_event_router_forwarder_; -#else - return NULL; -#endif - } void ConstructSystemRequestContext(); // The NetLog is owned by the browser process, to allow logging from other // threads during shutdown, but is used most frequently on the IOThread. net_log::ChromeNetLog* net_log_; -#if BUILDFLAG(ENABLE_EXTENSIONS) - // The extensions::EventRouterForwarder allows for sending events to - // extensions from the IOThread. - extensions::EventRouterForwarder* extension_event_router_forwarder_; -#endif - // These member variables are basically global, but their lifetimes are tied // to the IOThread. IOThread owns them all, despite not using scoped_ptr. // This is because the destructor of IOThread runs on the wrong thread. All @@ -188,9 +128,6 @@ network::mojom::NetworkContextRequest network_context_request_; network::mojom::NetworkContextParamsPtr network_context_params_; - scoped_refptr<net::URLRequestContextGetter> - system_url_request_context_getter_; - bool stub_resolver_enabled_ = false; base::Optional<std::vector<network::mojom::DnsOverHttpsServerPtr>> dns_over_https_servers_;
diff --git a/chrome/browser/lifetime/browser_close_manager.cc b/chrome/browser/lifetime/browser_close_manager.cc index 9adb1cd..1c63306 100644 --- a/chrome/browser/lifetime/browser_close_manager.cc +++ b/chrome/browser/lifetime/browser_close_manager.cc
@@ -181,7 +181,7 @@ browser->tab_strip_model()->DetachWebContentsAt(0); browser->window()->DestroyBrowser(); // Destroying the browser should have removed it from the browser list. - DCHECK(!base::ContainsValue(*BrowserList::GetInstance(), browser)); + DCHECK(!base::Contains(*BrowserList::GetInstance(), browser)); } }
diff --git a/chrome/browser/local_discovery/service_discovery_client_mac_unittest.mm b/chrome/browser/local_discovery/service_discovery_client_mac_unittest.mm index 769fb98..3b032e9 100644 --- a/chrome/browser/local_discovery/service_discovery_client_mac_unittest.mm +++ b/chrome/browser/local_discovery/service_discovery_client_mac_unittest.mm
@@ -155,8 +155,8 @@ const std::vector<std::string>& metadata = last_service_description_.metadata; EXPECT_EQ(2u, metadata.size()); - EXPECT_TRUE(base::ContainsValue(metadata, "ab")); - EXPECT_TRUE(base::ContainsValue(metadata, "d=e")); + EXPECT_TRUE(base::Contains(metadata, "ab")); + EXPECT_TRUE(base::Contains(metadata, "d=e")); EXPECT_EQ(ip_address, last_service_description_.ip_address); EXPECT_EQ(kPort, last_service_description_.address.port()); @@ -210,8 +210,8 @@ const std::vector<std::string>& metadata = last_service_description_.metadata; EXPECT_EQ(2u, metadata.size()); - EXPECT_TRUE(base::ContainsValue(metadata, "a=b")); - EXPECT_TRUE(base::ContainsValue(metadata, "cd=e9")); + EXPECT_TRUE(base::Contains(metadata, "a=b")); + EXPECT_TRUE(base::Contains(metadata, "cd=e9")); EXPECT_EQ(ip_address, last_service_description_.ip_address); EXPECT_EQ(kPort, last_service_description_.address.port());
diff --git a/chrome/browser/local_discovery/service_discovery_device_lister.cc b/chrome/browser/local_discovery/service_discovery_device_lister.cc index 8a44b2b0..6472043 100644 --- a/chrome/browser/local_discovery/service_discovery_device_lister.cc +++ b/chrome/browser/local_discovery/service_discovery_device_lister.cc
@@ -71,7 +71,7 @@ } // If there is already a resolver working on this service, don't add one. - if (base::ContainsKey(resolvers_, service_name)) { + if (base::Contains(resolvers_, service_name)) { VLOG(1) << "Resolver already exists, service_name: " << service_name; return; }
diff --git a/chrome/browser/lookalikes/lookalike_url_navigation_throttle.cc b/chrome/browser/lookalikes/lookalike_url_navigation_throttle.cc index eb701f2..5a284b1b 100644 --- a/chrome/browser/lookalikes/lookalike_url_navigation_throttle.cc +++ b/chrome/browser/lookalikes/lookalike_url_navigation_throttle.cc
@@ -55,7 +55,7 @@ DCHECK(!skeletons1.empty()); DCHECK(!skeletons2.empty()); for (const std::string& skeleton1 : skeletons1) { - if (base::ContainsKey(skeletons2, skeleton1)) { + if (base::Contains(skeletons2, skeleton1)) { return true; } }
diff --git a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc index 6de79cb..f60d24b6 100644 --- a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc +++ b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc
@@ -302,7 +302,7 @@ // Clicking the link in the interstitial should also remove the original // URL from history. ui_test_utils::HistoryEnumerator enumerator(browser->profile()); - EXPECT_FALSE(base::ContainsValue(enumerator.urls(), navigated_url)); + EXPECT_FALSE(base::Contains(enumerator.urls(), navigated_url)); histograms.ExpectTotalCount(LookalikeUrlNavigationThrottle::kHistogramName, 1); @@ -355,7 +355,7 @@ // Clicking the link should cause the original URL to appear in history. ui_test_utils::HistoryEnumerator enumerator(browser->profile()); - EXPECT_TRUE(base::ContainsValue(enumerator.urls(), navigated_url)); + EXPECT_TRUE(base::Contains(enumerator.urls(), navigated_url)); histograms->ExpectTotalCount(LookalikeUrlNavigationThrottle::kHistogramName, 1);
diff --git a/chrome/browser/media/router/discovery/dial/device_description_service_unittest.cc b/chrome/browser/media/router/discovery/dial/device_description_service_unittest.cc index 906966e0..7097d74c 100644 --- a/chrome/browser/media/router/discovery/dial/device_description_service_unittest.cc +++ b/chrome/browser/media/router/discovery/dial/device_description_service_unittest.cc
@@ -222,7 +222,7 @@ device_description_service_.CleanUpCacheEntries(); EXPECT_EQ(size_t(1), description_cache_.size()); - EXPECT_TRUE(base::ContainsKey(description_cache_, device_data_3.label())); + EXPECT_TRUE(base::Contains(description_cache_, device_data_3.label())); AddToCache(device_data_3.label(), ParsedDialDeviceDescription(), true /* expired*/);
diff --git a/chrome/browser/media/router/discovery/dial/dial_media_sink_service_impl.cc b/chrome/browser/media/router/discovery/dial/dial_media_sink_service_impl.cc index dca4917..382fad6 100644 --- a/chrome/browser/media/router/discovery/dial/dial_media_sink_service_impl.cc +++ b/chrome/browser/media/router/discovery/dial/dial_media_sink_service_impl.cc
@@ -29,7 +29,7 @@ // |model_name|: device model name. bool IsDiscoveryOnly(const std::string& model_name) { std::string lower_model_name = base::ToLowerASCII(model_name); - return base::ContainsValue(kDiscoveryOnlyModelNames, lower_model_name); + return base::Contains(kDiscoveryOnlyModelNames, lower_model_name); } SinkAppStatus GetSinkAppStatusFromResponse(const DialAppInfoResult& result) { @@ -145,7 +145,7 @@ std::vector<MediaSinkInternal> sinks_to_update; std::vector<MediaSinkInternal> sinks_to_remove; for (const auto& sink : GetSinks()) { - if (!base::ContainsKey(latest_sinks_, sink.first)) + if (!base::Contains(latest_sinks_, sink.first)) sinks_to_remove.push_back(sink.second); } @@ -195,7 +195,7 @@ const DialDeviceData& device_data, const ParsedDialDeviceDescription& description_data) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!base::ContainsValue(current_devices_, device_data)) { + if (!base::Contains(current_devices_, device_data)) { DVLOG(2) << "Device data not found in current device data list..."; return; }
diff --git a/chrome/browser/media/router/media_sinks_observer.cc b/chrome/browser/media/router/media_sinks_observer.cc index 47f91ae..72478cf 100644 --- a/chrome/browser/media/router/media_sinks_observer.cc +++ b/chrome/browser/media/router/media_sinks_observer.cc
@@ -50,7 +50,7 @@ base::AutoReset<bool> reset_in_on_sinks_updated(&in_on_sinks_updated_, true); #endif - if (origins.empty() || base::ContainsValue(origins, origin_)) + if (origins.empty() || base::Contains(origins, origin_)) OnSinksReceived(sinks); else OnSinksReceived(std::vector<MediaSink>());
diff --git a/chrome/browser/media/router/mojo/media_router_mojo_impl.cc b/chrome/browser/media/router/mojo/media_router_mojo_impl.cc index a3df074..e2f4cba5 100644 --- a/chrome/browser/media/router/mojo/media_router_mojo_impl.cc +++ b/chrome/browser/media/router/mojo/media_router_mojo_impl.cc
@@ -142,7 +142,7 @@ mojom::MediaRouteProviderPtr media_route_provider_ptr, mojom::MediaRouter::RegisterMediaRouteProviderCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(!base::ContainsKey(media_route_providers_, provider_id)); + DCHECK(!base::Contains(media_route_providers_, provider_id)); media_route_provider_ptr.set_connection_error_handler( base::BindOnce(&MediaRouterMojoImpl::OnProviderConnectionError, weak_factory_.GetWeakPtr(), provider_id));
diff --git a/chrome/browser/media/router/presentation/independent_otr_profile_manager_browsertest.cc b/chrome/browser/media/router/presentation/independent_otr_profile_manager_browsertest.cc index e0494e9..bd25f277 100644 --- a/chrome/browser/media/router/presentation/independent_otr_profile_manager_browsertest.cc +++ b/chrome/browser/media/router/presentation/independent_otr_profile_manager_browsertest.cc
@@ -177,8 +177,8 @@ run_loop1.QuitWhenIdleClosure()); otr_browser1->window()->Close(); run_loop1.Run(); - ASSERT_FALSE(base::ContainsValue(*BrowserList::GetInstance(), otr_browser1)); - ASSERT_TRUE(base::ContainsValue(*BrowserList::GetInstance(), otr_browser2)); + ASSERT_FALSE(base::Contains(*BrowserList::GetInstance(), otr_browser1)); + ASSERT_TRUE(base::Contains(*BrowserList::GetInstance(), otr_browser2)); bool destroyed = false; watcher.Watch(otr_profile, &destroyed); @@ -187,7 +187,7 @@ run_loop2.QuitWhenIdleClosure()); otr_browser2->window()->Close(); run_loop2.Run(); - ASSERT_FALSE(base::ContainsValue(*BrowserList::GetInstance(), otr_browser2)); + ASSERT_FALSE(base::Contains(*BrowserList::GetInstance(), otr_browser2)); EXPECT_TRUE(destroyed); } @@ -214,10 +214,8 @@ otr_browser2->window()->Close(); run_loop1.Run(); run_loop2.Run(); - ASSERT_FALSE( - base::ContainsValue(*BrowserList::GetInstance(), otr_browser1)); - ASSERT_FALSE( - base::ContainsValue(*BrowserList::GetInstance(), otr_browser2)); + ASSERT_FALSE(base::Contains(*BrowserList::GetInstance(), otr_browser1)); + ASSERT_FALSE(base::Contains(*BrowserList::GetInstance(), otr_browser2)); watcher.Watch(otr_profile, &destroyed); } @@ -349,7 +347,7 @@ run_loop.QuitWhenIdleClosure()); otr_browser->window()->Close(); run_loop.Run(); - ASSERT_FALSE(base::ContainsValue(*BrowserList::GetInstance(), otr_browser)); + ASSERT_FALSE(base::Contains(*BrowserList::GetInstance(), otr_browser)); EXPECT_TRUE(destroyed2); watcher1.Watch(otr_profile1, &destroyed1); @@ -377,6 +375,6 @@ run_loop.QuitWhenIdleClosure()); otr_browser->window()->Close(); run_loop.Run(); - ASSERT_FALSE(base::ContainsValue(*BrowserList::GetInstance(), otr_browser)); + ASSERT_FALSE(base::Contains(*BrowserList::GetInstance(), otr_browser)); EXPECT_TRUE(destroyed); }
diff --git a/chrome/browser/media/router/presentation/local_presentation_manager.cc b/chrome/browser/media/router/presentation/local_presentation_manager.cc index a578750..1474565 100644 --- a/chrome/browser/media/router/presentation/local_presentation_manager.cc +++ b/chrome/browser/media/router/presentation/local_presentation_manager.cc
@@ -91,7 +91,7 @@ bool LocalPresentationManager::IsLocalPresentation( const std::string& presentation_id) { - return base::ContainsKey(local_presentations_, presentation_id); + return base::Contains(local_presentations_, presentation_id); } const MediaRoute* LocalPresentationManager::GetRoute(
diff --git a/chrome/browser/media/router/presentation/local_presentation_manager_unittest.cc b/chrome/browser/media/router/presentation/local_presentation_manager_unittest.cc index 2266087..3d9335cd 100644 --- a/chrome/browser/media/router/presentation/local_presentation_manager_unittest.cc +++ b/chrome/browser/media/router/presentation/local_presentation_manager_unittest.cc
@@ -49,8 +49,7 @@ void VerifyControllerSize(size_t expected, const std::string& presentationId) { - EXPECT_TRUE( - base::ContainsKey(manager_.local_presentations_, presentationId)); + EXPECT_TRUE(base::Contains(manager_.local_presentations_, presentationId)); EXPECT_EQ(expected, manager_.local_presentations_[presentationId] ->pending_controllers_.size()); }
diff --git a/chrome/browser/media/router/presentation/presentation_service_delegate_impl.cc b/chrome/browser/media/router/presentation/presentation_service_delegate_impl.cc index bb71385..cf485d80 100644 --- a/chrome/browser/media/router/presentation/presentation_service_delegate_impl.cc +++ b/chrome/browser/media/router/presentation/presentation_service_delegate_impl.cc
@@ -248,7 +248,7 @@ << "Creating BrowserPresentationConnectionProxy for [presentation_id]: " << presentation_info.id; MediaRoute::Id route_id = pid_route_it->second.media_route_id(); - if (base::ContainsKey(browser_connection_proxies_, route_id)) { + if (base::Contains(browser_connection_proxies_, route_id)) { DLOG(ERROR) << __func__ << "Already has a BrowserPresentationConnectionProxy for " << "route: " << route_id; @@ -585,7 +585,7 @@ return; } - if (!base::ContainsValue(presentation_urls, route->media_source().url())) { + if (!base::Contains(presentation_urls, route->media_source().url())) { DVLOG(2) << "Presentation URLs do not match URL of current presentation:" << route->media_source().url(); return; @@ -670,9 +670,8 @@ const content::PresentationRequest& presentation_request, mojom::RoutePresentationConnectionPtr connection, const RouteRequestResult& result) { - if (!result.route() || - !base::ContainsValue(presentation_request.presentation_urls, - result.presentation_url())) { + if (!result.route() || !base::Contains(presentation_request.presentation_urls, + result.presentation_url())) { return; }
diff --git a/chrome/browser/media/router/presentation/presentation_service_delegate_observers.cc b/chrome/browser/media/router/presentation/presentation_service_delegate_observers.cc index 4d8f90d4..e78b75f 100644 --- a/chrome/browser/media/router/presentation/presentation_service_delegate_observers.cc +++ b/chrome/browser/media/router/presentation/presentation_service_delegate_observers.cc
@@ -22,7 +22,7 @@ DCHECK(observer); content::GlobalFrameRoutingId rfh_id(render_process_id, render_frame_id); - DCHECK(!base::ContainsKey(observers_, rfh_id)); + DCHECK(!base::Contains(observers_, rfh_id)); observers_[rfh_id] = observer; }
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_manager.cc b/chrome/browser/media/router/providers/cast/cast_activity_manager.cc index 676b21a..06e908b 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_manager.cc +++ b/chrome/browser/media/router/providers/cast/cast_activity_manager.cc
@@ -182,7 +182,7 @@ if (!cast_source.ContainsApp(activity.app_id())) return false; - if (base::ContainsKey(activity.connected_clients(), cast_source.client_id())) + if (base::Contains(activity.connected_clients(), cast_source.client_id())) return false; if (activity.route().is_incognito() != incognito)
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_record.cc b/chrome/browser/media/router/providers/cast/cast_activity_record.cc index 26b1107..4a0d1dd 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_record.cc +++ b/chrome/browser/media/router/providers/cast/cast_activity_record.cc
@@ -41,7 +41,7 @@ const url::Origin& origin, int tab_id) { const std::string& client_id = source.client_id(); - DCHECK(!base::ContainsKey(connected_clients_, client_id)); + DCHECK(!base::Contains(connected_clients_, client_id)); std::unique_ptr<CastSessionClient> client = client_factory_for_test_ ? client_factory_for_test_->MakeClientForTest(client_id, origin, @@ -92,7 +92,7 @@ return cast_channel::Result::kFailed; } const std::string& message_namespace = cast_message.app_message_namespace(); - if (!base::ContainsKey(session->message_namespaces(), message_namespace)) { + if (!base::Contains(session->message_namespaces(), message_namespace)) { DLOG(ERROR) << "Disallowed message namespace: " << message_namespace; if (client && cast_message.sequence_number()) { client->SendErrorCodeToClient(
diff --git a/chrome/browser/media/router/providers/cast/cast_app_availability_tracker.cc b/chrome/browser/media/router/providers/cast/cast_app_availability_tracker.cc index 36e9344..543d3ec7 100644 --- a/chrome/browser/media/router/providers/cast/cast_app_availability_tracker.cc +++ b/chrome/browser/media/router/providers/cast/cast_app_availability_tracker.cc
@@ -13,7 +13,7 @@ base::flat_set<std::string> CastAppAvailabilityTracker::RegisterSource( const CastMediaSource& source) { - if (base::ContainsKey(registered_sources_, source.source_id())) + if (base::Contains(registered_sources_, source.source_id())) return base::flat_set<std::string>(); registered_sources_.emplace(source.source_id(), source);
diff --git a/chrome/browser/media/router/providers/cast/cast_media_route_provider.cc b/chrome/browser/media/router/providers/cast/cast_media_route_provider.cc index 46b7dd0..4f84842 100644 --- a/chrome/browser/media/router/providers/cast/cast_media_route_provider.cc +++ b/chrome/browser/media/router/providers/cast/cast_media_route_provider.cc
@@ -179,7 +179,7 @@ const std::string& media_source) { DVLOG(1) << __func__ << ", media_source: " << media_source; DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (base::ContainsKey(sink_queries_, media_source)) + if (base::Contains(sink_queries_, media_source)) return; std::unique_ptr<CastMediaSource> cast_source =
diff --git a/chrome/browser/media/router/providers/common/buffered_message_sender.cc b/chrome/browser/media/router/providers/common/buffered_message_sender.cc index 40e181a8..2df7715 100644 --- a/chrome/browser/media/router/providers/common/buffered_message_sender.cc +++ b/chrome/browser/media/router/providers/common/buffered_message_sender.cc
@@ -16,7 +16,7 @@ void BufferedMessageSender::SendMessages( const MediaRoute::Id& route_id, std::vector<mojom::RouteMessagePtr> messages) { - if (base::ContainsKey(active_routes_, route_id)) { + if (base::Contains(active_routes_, route_id)) { media_router_->OnRouteMessagesReceived(route_id, std::move(messages)); } else { auto& buffer = buffered_messages_[route_id];
diff --git a/chrome/browser/media/router/providers/dial/dial_activity_manager.cc b/chrome/browser/media/router/providers/dial/dial_activity_manager.cc index eb6a963..efbf784 100644 --- a/chrome/browser/media/router/providers/dial/dial_activity_manager.cc +++ b/chrome/browser/media/router/providers/dial/dial_activity_manager.cc
@@ -123,7 +123,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); MediaRoute::Id route_id = activity.route.media_route_id(); - DCHECK(!base::ContainsKey(records_, route_id)); + DCHECK(!base::Contains(records_, route_id)); // TODO(https://crbug.com/816628): Consider adding a timeout for transitioning // to kLaunched state to clean up unresponsive launches. records_.emplace(route_id,
diff --git a/chrome/browser/media/router/providers/openscreen/discovery/open_screen_listener.cc b/chrome/browser/media/router/providers/openscreen/discovery/open_screen_listener.cc index a283dffa..35eb384 100644 --- a/chrome/browser/media/router/providers/openscreen/discovery/open_screen_listener.cc +++ b/chrome/browser/media/router/providers/openscreen/discovery/open_screen_listener.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/media/router/providers/openscreen/discovery/open_screen_listener.h" +#include <algorithm> #include <utility> namespace media_router {
diff --git a/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.cc b/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.cc index c3fad36..b6f6b70 100644 --- a/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.cc +++ b/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.cc
@@ -111,7 +111,7 @@ base::TimeDelta timeout, bool incognito, CreateRouteCallback callback) { - DCHECK(!base::ContainsKey(presentations_, presentation_id)); + DCHECK(!base::Contains(presentations_, presentation_id)); base::Optional<Display> display = GetDisplayBySinkId(sink_id); if (!display) { std::move(callback).Run(base::nullopt, nullptr,
diff --git a/chrome/browser/media_galleries/chromeos/mtp_device_delegate_impl_chromeos.cc b/chrome/browser/media_galleries/chromeos/mtp_device_delegate_impl_chromeos.cc index 8912733e..5e1193f 100644 --- a/chrome/browser/media_galleries/chromeos/mtp_device_delegate_impl_chromeos.cc +++ b/chrome/browser/media_galleries/chromeos/mtp_device_delegate_impl_chromeos.cc
@@ -455,7 +455,7 @@ file_id_to_node_map_(file_id_to_node_map) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(file_id_to_node_map_); - DCHECK(!base::ContainsKey(*file_id_to_node_map_, file_id_)); + DCHECK(!base::Contains(*file_id_to_node_map_, file_id_)); (*file_id_to_node_map_)[file_id_] = this; } @@ -492,7 +492,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::IO); std::vector<std::string> children_to_erase; for (const auto& child : children_) { - if (base::ContainsKey(children_to_keep, child.first)) + if (base::Contains(children_to_keep, child.first)) continue; children_to_erase.push_back(child.first); }
diff --git a/chrome/browser/media_galleries/chromeos/mtp_device_task_helper_map_service.cc b/chrome/browser/media_galleries/chromeos/mtp_device_task_helper_map_service.cc index ee0d2c7f..20459d1 100644 --- a/chrome/browser/media_galleries/chromeos/mtp_device_task_helper_map_service.cc +++ b/chrome/browser/media_galleries/chromeos/mtp_device_task_helper_map_service.cc
@@ -28,7 +28,7 @@ DCHECK(!storage_name.empty()); const MTPDeviceTaskHelperKey key = GetMTPDeviceTaskHelperKey(storage_name, read_only); - DCHECK(!base::ContainsKey(task_helper_map_, key)); + DCHECK(!base::Contains(task_helper_map_, key)); MTPDeviceTaskHelper* task_helper = new MTPDeviceTaskHelper(); task_helper_map_[key] = task_helper; return task_helper;
diff --git a/chrome/browser/media_galleries/fileapi/mtp_device_map_service.cc b/chrome/browser/media_galleries/fileapi/mtp_device_map_service.cc index d2ae44b..9441a72 100644 --- a/chrome/browser/media_galleries/fileapi/mtp_device_map_service.cc +++ b/chrome/browser/media_galleries/fileapi/mtp_device_map_service.cc
@@ -35,7 +35,7 @@ DCHECK(!filesystem_id.empty()); const AsyncDelegateKey key = GetAsyncDelegateKey(device_location, read_only); - if (!base::ContainsKey(mtp_device_usage_map_, key)) { + if (!base::Contains(mtp_device_usage_map_, key)) { // Note that this initializes the delegate asynchronously, but since // the delegate will only be used from the IO thread, it is guaranteed // to be created before use of it expects it to be there. @@ -84,7 +84,7 @@ DCHECK(!device_location.empty()); const AsyncDelegateKey key = GetAsyncDelegateKey(device_location, read_only); - if (base::ContainsKey(async_delegate_map_, key)) + if (base::Contains(async_delegate_map_, key)) return; async_delegate_map_[key] = delegate; }
diff --git a/chrome/browser/media_galleries/fileapi/supported_audio_video_checker.cc b/chrome/browser/media_galleries/fileapi/supported_audio_video_checker.cc index 3f1026f..52c116d 100644 --- a/chrome/browser/media_galleries/fileapi/supported_audio_video_checker.cc +++ b/chrome/browser/media_galleries/fileapi/supported_audio_video_checker.cc
@@ -46,7 +46,7 @@ } bool HasSupportedAudioVideoExtension(const base::FilePath& file) { - return base::ContainsKey(audio_video_extensions_, file.Extension()); + return base::Contains(audio_video_extensions_, file.Extension()); } private:
diff --git a/chrome/browser/media_galleries/gallery_watch_manager.cc b/chrome/browser/media_galleries/gallery_watch_manager.cc index 683318f..867dcbf7 100644 --- a/chrome/browser/media_galleries/gallery_watch_manager.cc +++ b/chrome/browser/media_galleries/gallery_watch_manager.cc
@@ -120,7 +120,7 @@ // This can occur if the GalleryWatchManager attempts to watch the same path // again before recieving the callback. It's benign. - if (base::ContainsKey(watchers_, path)) { + if (base::Contains(watchers_, path)) { base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, base::BindOnce(callback, false)); return; @@ -211,7 +211,7 @@ GalleryWatchManagerObserver* observer) { DCHECK(browser_context); DCHECK(observer); - DCHECK(!base::ContainsKey(observers_, browser_context)); + DCHECK(!base::Contains(observers_, browser_context)); observers_[browser_context] = observer; } @@ -256,7 +256,7 @@ DCHECK(extension); WatchOwner owner(browser_context, extension->id(), gallery_id); - if (base::ContainsKey(watches_, owner)) { + if (base::Contains(watches_, owner)) { callback.Run(std::string()); return; } @@ -265,14 +265,14 @@ g_browser_process->media_file_system_registry()->GetPreferences( Profile::FromBrowserContext(browser_context)); - if (!base::ContainsKey(preferences->known_galleries(), gallery_id)) { + if (!base::Contains(preferences->known_galleries(), gallery_id)) { callback.Run(kInvalidGalleryIDError); return; } MediaGalleryPrefIdSet permitted = preferences->GalleriesForExtension(*extension); - if (!base::ContainsKey(permitted, gallery_id)) { + if (!base::Contains(permitted, gallery_id)) { callback.Run(kNoPermissionError); return; } @@ -286,7 +286,7 @@ } // Observe the preferences if we haven't already. - if (!base::ContainsKey(observed_preferences_, preferences)) { + if (!base::Contains(observed_preferences_, preferences)) { observed_preferences_.insert(preferences); preferences->AddGalleryChangeObserver(this); } @@ -295,7 +295,7 @@ EnsureBrowserContextSubscription(owner.browser_context); // Start the FilePathWatcher on |gallery_path| if necessary. - if (base::ContainsKey(watched_paths_, path)) { + if (base::Contains(watched_paths_, path)) { OnFileWatchActivated(owner, path, callback, true); } else { base::Callback<void(bool)> on_watch_added = @@ -415,7 +415,7 @@ for (auto it = owners.begin(); it != owners.end(); ++it) { Profile* profile = Profile::FromBrowserContext(it->browser_context); RemoveWatch(it->browser_context, it->extension_id, it->gallery_id); - if (base::ContainsKey(observers_, profile)) + if (base::Contains(observers_, profile)) observers_[profile]->OnGalleryWatchDropped(it->extension_id, it->gallery_id); } @@ -448,8 +448,8 @@ for (it = notification_info->second.owners.begin(); it != notification_info->second.owners.end(); ++it) { - DCHECK(base::ContainsKey(watches_, *it)); - if (base::ContainsKey(observers_, it->browser_context)) { + DCHECK(base::Contains(watches_, *it)); + if (base::Contains(observers_, it->browser_context)) { observers_[it->browser_context]->OnGalleryChanged(it->extension_id, it->gallery_id); } @@ -460,7 +460,7 @@ const std::string& extension_id, MediaGalleryPrefId pref_id) { RemoveWatch(pref->profile(), extension_id, pref_id); - if (base::ContainsKey(observers_, pref->profile())) + if (base::Contains(observers_, pref->profile())) observers_[pref->profile()]->OnGalleryWatchDropped(extension_id, pref_id); } @@ -478,7 +478,7 @@ for (auto it = extension_ids.begin(); it != extension_ids.end(); ++it) { RemoveWatch(pref->profile(), *it, pref_id); - if (base::ContainsKey(observers_, pref->profile())) + if (base::Contains(observers_, pref->profile())) observers_[pref->profile()]->OnGalleryWatchDropped(*it, pref_id); } } @@ -493,7 +493,7 @@ MediaGalleryPrefIdSet detached_ids = preferences->LookUpGalleriesByDeviceId(info.device_id()); - if (base::ContainsKey(detached_ids, it->first.gallery_id)) { + if (base::Contains(detached_ids, it->first.gallery_id)) { WatchOwner owner = it->first; DeactivateFileWatch(owner, it->second); // Post increment moves iterator to next element while deleting current.
diff --git a/chrome/browser/media_galleries/gallery_watch_manager_unittest.cc b/chrome/browser/media_galleries/gallery_watch_manager_unittest.cc index beb71bdc..3ef4260 100644 --- a/chrome/browser/media_galleries/gallery_watch_manager_unittest.cc +++ b/chrome/browser/media_galleries/gallery_watch_manager_unittest.cc
@@ -264,22 +264,22 @@ MediaGalleryPrefIdSet set1 = manager()->GetWatchSet(profile(), extension()->id()); EXPECT_EQ(1u, set1.size()); - EXPECT_TRUE(base::ContainsKey(set1, id1)); + EXPECT_TRUE(base::Contains(set1, id1)); // Test that the second watch was added correctly too. AddAndConfirmWatch(id2); MediaGalleryPrefIdSet set2 = manager()->GetWatchSet(profile(), extension()->id()); EXPECT_EQ(2u, set2.size()); - EXPECT_TRUE(base::ContainsKey(set2, id1)); - EXPECT_TRUE(base::ContainsKey(set2, id2)); + EXPECT_TRUE(base::Contains(set2, id1)); + EXPECT_TRUE(base::Contains(set2, id2)); // Remove first watch and test that the second is still in there. manager()->RemoveWatch(profile(), extension()->id(), id1); MediaGalleryPrefIdSet set3 = manager()->GetWatchSet(profile(), extension()->id()); EXPECT_EQ(1u, set3.size()); - EXPECT_TRUE(base::ContainsKey(set3, id2)); + EXPECT_TRUE(base::Contains(set3, id2)); // Try removing the first watch again and test that it has no effect. manager()->RemoveWatch(profile(), extension()->id(), id1);
diff --git a/chrome/browser/media_galleries/media_file_system_registry.cc b/chrome/browser/media_galleries/media_file_system_registry.cc index ea66b1b3..393bb0d 100644 --- a/chrome/browser/media_galleries/media_file_system_registry.cc +++ b/chrome/browser/media_galleries/media_file_system_registry.cc
@@ -166,7 +166,7 @@ void RPHReferenceManager::ReferenceFromWebContents( content::WebContents* contents) { RenderProcessHost* rph = contents->GetMainFrame()->GetProcess(); - if (!base::ContainsKey(observer_map_, rph)) { + if (!base::Contains(observer_map_, rph)) { observer_map_[rph] = std::make_unique<RPHObserver>(this, rph); } observer_map_[rph]->AddWebContentsObserver(contents); @@ -206,7 +206,7 @@ void RPHReferenceManager::RPHObserver::AddWebContentsObserver( WebContents* web_contents) { - if (base::ContainsKey(observed_web_contentses_, web_contents)) + if (base::Contains(observed_web_contentses_, web_contents)) return; observed_web_contentses_[web_contents] = @@ -386,7 +386,7 @@ const MediaGalleryPrefInfo& gallery_info = galleries_info.find(pref_id)->second; const std::string& device_id = gallery_info.device_id; - if (!base::ContainsKey(*attached_devices, device_id)) + if (!base::Contains(*attached_devices, device_id)) continue; PrefIdFsInfoMap::const_iterator existing_info = @@ -441,7 +441,7 @@ base::FilePath path = gallery.AbsolutePath(); const std::string& device_id = gallery.device_id; - if (base::ContainsKey(pref_id_map_, gallery.pref_id)) { + if (base::Contains(pref_id_map_, gallery.pref_id)) { result = base::File::FILE_OK; } else if (MediaStorageUtil::CanCreateFileSystem(device_id, path) && file_system_context_->RegisterFileSystem(device_id, fs_name, @@ -555,7 +555,7 @@ preferences->GalleriesForExtension(*extension); if (gallery == preferences->known_galleries().end() || - !base::ContainsKey(permitted_galleries, pref_id)) { + !base::Contains(permitted_galleries, pref_id)) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), base::File::FILE_ERROR_NOT_FOUND)); @@ -575,9 +575,9 @@ MediaGalleriesPreferences* MediaFileSystemRegistry::GetPreferences( Profile* profile) { // Create an empty ExtensionHostMap for this profile on first initialization. - if (!base::ContainsKey(extension_hosts_map_, profile)) { + if (!base::Contains(extension_hosts_map_, profile)) { extension_hosts_map_[profile] = ExtensionHostMap(); - DCHECK(!base::ContainsKey(profile_subscription_map_, profile)); + DCHECK(!base::Contains(profile_subscription_map_, profile)); profile_subscription_map_[profile] = MediaFileSystemRegistryShutdownNotifierFactory::GetInstance() ->Get(profile) @@ -779,7 +779,7 @@ extension_registry->enabled_extensions().GetByID(it->first)); } for (size_t i = 0; i < extensions.size(); ++i) { - if (!base::ContainsKey(extension_hosts_map_, profile)) + if (!base::Contains(extension_hosts_map_, profile)) break; auto gallery_host_it = extension_host_map.find(extensions[i]->id()); if (gallery_host_it == extension_host_map.end())
diff --git a/chrome/browser/media_galleries/media_file_system_registry_unittest.cc b/chrome/browser/media_galleries/media_file_system_registry_unittest.cc index 95d8319..0d7e362 100644 --- a/chrome/browser/media_galleries/media_file_system_registry_unittest.cc +++ b/chrome/browser/media_galleries/media_file_system_registry_unittest.cc
@@ -136,7 +136,7 @@ } void TestMediaFileSystemContext::RevokeFileSystem(const std::string& fs_name) { - if (!base::ContainsKey(file_systems_by_name_, fs_name)) + if (!base::Contains(file_systems_by_name_, fs_name)) return; EXPECT_EQ(1U, file_systems_by_name_.erase(fs_name)); } @@ -168,7 +168,7 @@ FSInfoMap* results, const std::vector<MediaFileSystemInfo>& file_systems) { for (size_t i = 0; i < file_systems.size(); ++i) { - ASSERT_FALSE(base::ContainsKey(*results, file_systems[i].pref_id)); + ASSERT_FALSE(base::Contains(*results, file_systems[i].pref_id)); (*results)[file_systems[i].pref_id] = file_systems[i]; } } @@ -733,7 +733,7 @@ for (FSInfoMap::const_iterator it = new_galleries_info.begin(); it != new_galleries_info.end(); ++it) { - if (base::ContainsKey(galleries_info, it->first)) + if (base::Contains(galleries_info, it->first)) continue; ASSERT_FALSE(found_new);
diff --git a/chrome/browser/media_galleries/media_galleries_permission_controller.cc b/chrome/browser/media_galleries/media_galleries_permission_controller.cc index 2b78e55..f7b5566 100644 --- a/chrome/browser/media_galleries/media_galleries_permission_controller.cc +++ b/chrome/browser/media_galleries/media_galleries_permission_controller.cc
@@ -180,8 +180,8 @@ for (auto iter = known_galleries_.begin(); iter != known_galleries_.end(); ++iter) { MediaGalleryPrefId pref_id = GetPrefId(iter->first); - if (!base::ContainsKey(forgotten_galleries_, iter->first) && - existing == base::ContainsKey(pref_permitted_galleries_, pref_id)) { + if (!base::Contains(forgotten_galleries_, iter->first) && + existing == base::Contains(pref_permitted_galleries_, pref_id)) { result.push_back(iter->second); } } @@ -247,7 +247,7 @@ GalleryDialogId gallery_id) { media_galleries::UsageCount(media_galleries::DIALOG_FORGET_GALLERY); if (!new_galleries_.erase(gallery_id)) { - DCHECK(base::ContainsKey(known_galleries_, gallery_id)); + DCHECK(base::Contains(known_galleries_, gallery_id)); forgotten_galleries_.insert(gallery_id); } dialog_->UpdateGalleries(); @@ -396,7 +396,7 @@ for (auto iter = pref_permitted_galleries_.begin(); iter != pref_permitted_galleries_.end(); ++iter) { GalleryDialogId gallery_id = GetDialogId(*iter); - DCHECK(base::ContainsKey(known_galleries_, gallery_id)); + DCHECK(base::Contains(known_galleries_, gallery_id)); known_galleries_[gallery_id].selected = true; } @@ -414,7 +414,7 @@ for (GalleryPermissionsMap::const_iterator iter = known_galleries_.begin(); iter != known_galleries_.end(); ++iter) { MediaGalleryPrefId pref_id = GetPrefId(iter->first); - if (base::ContainsKey(forgotten_galleries_, iter->first)) { + if (base::Contains(forgotten_galleries_, iter->first)) { preferences_->ForgetGalleryById(pref_id); } else { bool changed = preferences_->SetGalleryPermissionForExtension(
diff --git a/chrome/browser/media_galleries/media_galleries_preferences.cc b/chrome/browser/media_galleries/media_galleries_preferences.cc index f5a2998..7267e60 100644 --- a/chrome/browser/media_galleries/media_galleries_preferences.cc +++ b/chrome/browser/media_galleries/media_galleries_preferences.cc
@@ -693,7 +693,7 @@ DCHECK(IsInitialized()); DCHECK(extension); if (!include_unpermitted_galleries && - !base::ContainsKey(GalleriesForExtension(*extension), gallery_id)) + !base::Contains(GalleriesForExtension(*extension), gallery_id)) return base::FilePath(); MediaGalleriesPrefInfoMap::const_iterator it = @@ -1008,7 +1008,7 @@ new ListPrefUpdate(prefs, prefs::kMediaGalleriesRememberedGalleries)); base::ListValue* list = update->Get(); - if (!base::ContainsKey(known_galleries_, id)) + if (!base::Contains(known_galleries_, id)) return; for (auto iter = list->begin(); iter != list->end(); ++iter) { @@ -1047,7 +1047,7 @@ bool MediaGalleriesPreferences::NonAutoGalleryHasPermission( MediaGalleryPrefId id) const { DCHECK(IsInitialized()); - DCHECK(!base::ContainsKey(known_galleries_, id) || + DCHECK(!base::Contains(known_galleries_, id) || known_galleries_.find(id)->second.type != MediaGalleryPrefInfo::kAutoDetected); ExtensionPrefs* prefs = GetExtensionPrefs();
diff --git a/chrome/browser/media_galleries/media_galleries_preferences_unittest.cc b/chrome/browser/media_galleries/media_galleries_preferences_unittest.cc index 797f419f..c48af8d 100644 --- a/chrome/browser/media_galleries/media_galleries_preferences_unittest.cc +++ b/chrome/browser/media_galleries/media_galleries_preferences_unittest.cc
@@ -204,8 +204,8 @@ VerifyGalleryInfo(it->second, it->first); if (it->second.type != MediaGalleryPrefInfo::kAutoDetected && it->second.type != MediaGalleryPrefInfo::kBlackListed) { - if (!base::ContainsKey(expected_galleries_for_all, it->first) && - !base::ContainsKey(expected_galleries_for_regular, it->first)) { + if (!base::Contains(expected_galleries_for_all, it->first) && + !base::Contains(expected_galleries_for_regular, it->first)) { EXPECT_FALSE(gallery_prefs_->NonAutoGalleryHasPermission(it->first)); } else { EXPECT_TRUE(gallery_prefs_->NonAutoGalleryHasPermission(it->first));
diff --git a/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win_unittest.cc b/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win_unittest.cc index 444bfaa..ca8fe37 100644 --- a/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win_unittest.cc +++ b/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win_unittest.cc
@@ -48,7 +48,7 @@ FSInfoMap* results, const std::vector<MediaFileSystemInfo>& file_systems) { for (size_t i = 0; i < file_systems.size(); ++i) { - ASSERT_FALSE(base::ContainsKey(*results, file_systems[i].pref_id)); + ASSERT_FALSE(base::Contains(*results, file_systems[i].pref_id)); (*results)[file_systems[i].pref_id] = file_systems[i]; } }
diff --git a/chrome/browser/metrics/plugin_metrics_provider.cc b/chrome/browser/metrics/plugin_metrics_provider.cc index 2197ab1e..475484b 100644 --- a/chrome/browser/metrics/plugin_metrics_provider.cc +++ b/chrome/browser/metrics/plugin_metrics_provider.cc
@@ -334,7 +334,7 @@ PluginMetricsProvider::GetChildProcessStats( const content::ChildProcessData& data) { const base::string16& child_name = data.name; - if (!base::ContainsKey(child_process_stats_buffer_, child_name)) { + if (!base::Contains(child_process_stats_buffer_, child_name)) { child_process_stats_buffer_[child_name] = ChildProcessStats(data.process_type); }
diff --git a/chrome/browser/metrics/process_memory_metrics_emitter.cc b/chrome/browser/metrics/process_memory_metrics_emitter.cc index 6b96dc4..2dffb7c 100644 --- a/chrome/browser/metrics/process_memory_metrics_emitter.cc +++ b/chrome/browser/metrics/process_memory_metrics_emitter.cc
@@ -750,8 +750,8 @@ EmitAudioServiceMemoryMetrics( pmd, ukm::UkmRecorder::GetNewSourceID(), GetUkmRecorder(), GetProcessUptime(now, pmd.pid()), emit_metrics_for_all_processes); - } else if (base::ContainsValue(pmd.service_names(), - content::mojom::kNetworkServiceName)) { + } else if (base::Contains(pmd.service_names(), + content::mojom::kNetworkServiceName)) { EmitNetworkServiceMemoryMetrics( pmd, ukm::UkmRecorder::GetNewSourceID(), GetUkmRecorder(), GetProcessUptime(now, pmd.pid()), emit_metrics_for_all_processes); @@ -772,17 +772,31 @@ } if (emit_metrics_for_all_processes) { - size_t native_resident_kb = - global_dump_->aggregated_metrics().native_library_resident_kb(); + const auto& metrics = global_dump_->aggregated_metrics(); + int32_t native_resident_kb = metrics.native_library_resident_kb(); + int32_t native_library_resident_not_ordered_kb = + metrics.native_library_resident_not_ordered_kb(); + int32_t native_library_not_resident_ordered_kb = + metrics.native_library_not_resident_ordered_kb(); // |native_resident_kb| is only calculated for android devices that support - // code ordering. Otherwise it is equal to zero and should not be reported. - if (native_resident_kb != 0) { + // code ordering. + if (native_resident_kb != metrics.kInvalid) { // Size of the native library on android is ~40MB. // More precision is needed in the middle buckets, hence the range. base::UmaHistogramCustomCounts( "Memory.NativeLibrary.MappedAndResidentMemoryFootprint2", native_resident_kb, 1000, 100000, 100); + if (native_library_not_resident_ordered_kb != metrics.kInvalid) { + base::UmaHistogramCustomCounts( + "Memory.NativeLibrary.NotResidentOrderedCodeMemoryFootprint", + native_library_not_resident_ordered_kb, 1000, 100000, 100); + } + if (native_library_resident_not_ordered_kb != metrics.kInvalid) { + base::UmaHistogramCustomCounts( + "Memory.NativeLibrary.ResidentNotOrdereredCodeMemoryFootprint", + native_library_resident_not_ordered_kb, 1000, 100000, 100); + } } UMA_HISTOGRAM_MEMORY_LARGE_MB(
diff --git a/chrome/browser/metrics/process_memory_metrics_emitter_unittest.cc b/chrome/browser/metrics/process_memory_metrics_emitter_unittest.cc index b6a89bb..36f84c8 100644 --- a/chrome/browser/metrics/process_memory_metrics_emitter_unittest.cc +++ b/chrome/browser/metrics/process_memory_metrics_emitter_unittest.cc
@@ -326,6 +326,8 @@ constexpr int kTestRendererPrivateMemoryFootprint = 130; constexpr int kTestRendererSharedMemoryFootprint = 135; constexpr int kNativeLibraryResidentMemoryFootprint = 27560; +constexpr int kNativeLibraryResidentNotOrderedCodeFootprint = 12345; +constexpr int kNativeLibraryNotResidentOrderedCodeFootprint = 23456; #if !defined(OS_MACOSX) constexpr int kTestRendererResidentSet = 110; @@ -833,6 +835,10 @@ PopulateRendererMetrics(global_dump, expected_metrics, kTestRendererPid202); global_dump->aggregated_metrics->native_library_resident_kb = kNativeLibraryResidentMemoryFootprint; + global_dump->aggregated_metrics->native_library_not_resident_ordered_kb = + kNativeLibraryNotResidentOrderedCodeFootprint; + global_dump->aggregated_metrics->native_library_resident_not_ordered_kb = + kNativeLibraryResidentNotOrderedCodeFootprint; // No histograms should have been recorded yet. histograms.ExpectTotalCount("Memory.Renderer.PrivateMemoryFootprint", 0); @@ -845,6 +851,10 @@ histograms.ExpectTotalCount("Memory.Total.ResidentSet", 0); histograms.ExpectTotalCount( "Memory.NativeLibrary.MappedAndResidentMemoryFootprint2", 0); + histograms.ExpectTotalCount( + "Memory.NativeLibrary.NotResidentOrderedCodeMemoryFootprint", 0); + histograms.ExpectTotalCount( + "Memory.NativeLibrary.ResidentNotOrdereredCodeMemoryFootprint", 0); // Simulate some metrics emission. scoped_refptr<ProcessMemoryMetricsEmitterFake> emitter = @@ -880,6 +890,12 @@ histograms.ExpectUniqueSample( "Memory.NativeLibrary.MappedAndResidentMemoryFootprint2", kNativeLibraryResidentMemoryFootprint, 1); + histograms.ExpectUniqueSample( + "Memory.NativeLibrary.NotResidentOrderedCodeMemoryFootprint", + kNativeLibraryNotResidentOrderedCodeFootprint, 1); + histograms.ExpectUniqueSample( + "Memory.NativeLibrary.ResidentNotOrdereredCodeMemoryFootprint", + kNativeLibraryResidentNotOrderedCodeFootprint, 1); } TEST_F(ProcessMemoryMetricsEmitterTest, MainFramePMFEmitted) {
diff --git a/chrome/browser/metrics/tab_reactivation_tracker.cc b/chrome/browser/metrics/tab_reactivation_tracker.cc index c5c3471..e0803eac 100644 --- a/chrome/browser/metrics/tab_reactivation_tracker.cc +++ b/chrome/browser/metrics/tab_reactivation_tracker.cc
@@ -108,7 +108,7 @@ TabReactivationTracker::WebContentsHelper* TabReactivationTracker::GetHelper( content::WebContents* contents) { // Make sure it exists. - if (!base::ContainsKey(helper_map_, contents)) { + if (!base::Contains(helper_map_, contents)) { helper_map_.insert(std::make_pair( contents, std::make_unique<WebContentsHelper>(this, contents))); }
diff --git a/chrome/browser/metrics/tab_stats_data_store.cc b/chrome/browser/metrics/tab_stats_data_store.cc index 754dcd9..49a5db5c 100644 --- a/chrome/browser/metrics/tab_stats_data_store.cc +++ b/chrome/browser/metrics/tab_stats_data_store.cc
@@ -65,7 +65,7 @@ void TabStatsDataStore::OnTabAdded(content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(web_contents); - DCHECK(!base::ContainsKey(existing_tabs_, web_contents)); + DCHECK(!base::Contains(existing_tabs_, web_contents)); ++tab_stats_.total_tab_count; TabID tab_id = GetNewTabId(); existing_tabs_.insert(std::make_pair(web_contents, tab_id)); @@ -80,7 +80,7 @@ void TabStatsDataStore::OnTabRemoved(content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(web_contents); - DCHECK(base::ContainsKey(existing_tabs_, web_contents)); + DCHECK(base::Contains(existing_tabs_, web_contents)); DCHECK_GT(tab_stats_.total_tab_count, 0U); --tab_stats_.total_tab_count; TabID web_contents_id = GetTabID(web_contents); @@ -97,7 +97,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(old_contents); DCHECK(new_contents); - DCHECK(base::ContainsKey(existing_tabs_, old_contents)); + DCHECK(base::Contains(existing_tabs_, old_contents)); DCHECK_GT(tab_stats_.total_tab_count, 0U); TabID old_contents_id = existing_tabs_[old_contents]; existing_tabs_.erase(old_contents); @@ -132,11 +132,11 @@ } void TabStatsDataStore::OnTabInteraction(content::WebContents* web_contents) { - DCHECK(base::ContainsKey(existing_tabs_, web_contents)); + DCHECK(base::Contains(existing_tabs_, web_contents)); TabID web_contents_id = GetTabID(web_contents); // Mark the tab as interacted with in all the intervals. for (auto& interval_map : interval_maps_) { - DCHECK(base::ContainsKey(*interval_map, web_contents_id)); + DCHECK(base::Contains(*interval_map, web_contents_id)); (*interval_map)[web_contents_id].interacted_during_interval = true; } } @@ -184,7 +184,7 @@ base::Optional<TabStatsDataStore::TabID> TabStatsDataStore::GetTabIDForTesting( content::WebContents* web_contents) { - if (!base::ContainsKey(existing_tabs_, web_contents)) + if (!base::Contains(existing_tabs_, web_contents)) return base::nullopt; return GetTabID(web_contents); } @@ -228,17 +228,17 @@ TabStatsDataStore::TabID TabStatsDataStore::GetTabID( content::WebContents* web_contents) { - DCHECK(base::ContainsKey(existing_tabs_, web_contents)); + DCHECK(base::Contains(existing_tabs_, web_contents)); return existing_tabs_[web_contents]; } void TabStatsDataStore::OnTabAudibleOrVisible( content::WebContents* web_contents) { - DCHECK(base::ContainsKey(existing_tabs_, web_contents)); + DCHECK(base::Contains(existing_tabs_, web_contents)); TabID web_contents_id = GetTabID(web_contents); // Mark the tab as visible or audible in all the intervals. for (auto& interval_map : interval_maps_) { - DCHECK(base::ContainsKey(*interval_map, web_contents_id)); + DCHECK(base::Contains(*interval_map, web_contents_id)); (*interval_map)[web_contents_id].visible_or_audible_during_interval = true; } }
diff --git a/chrome/browser/metrics/tab_stats_tracker.cc b/chrome/browser/metrics/tab_stats_tracker.cc index d8e4e8a..a2cde939 100644 --- a/chrome/browser/metrics/tab_stats_tracker.cc +++ b/chrome/browser/metrics/tab_stats_tracker.cc
@@ -67,7 +67,7 @@ // Ensure that an interval is a valid one (i.e. listed in // |kTabUsageReportingIntervals|). bool IsValidInterval(base::TimeDelta interval) { - return base::ContainsValue(kTabUsageReportingIntervals, interval); + return base::Contains(kTabUsageReportingIntervals, interval); } } // namespace @@ -393,7 +393,7 @@ // If we already have a WebContentsObserver for this tab then it means that // it's already tracked and it's being dragged into a new window, there's // nothing to do here. - if (!base::ContainsKey(web_contents_usage_observers_, web_contents)) { + if (!base::Contains(web_contents_usage_observers_, web_contents)) { tab_stats_data_store_->OnTabAdded(web_contents); web_contents_usage_observers_.insert(std::make_pair( web_contents, @@ -404,7 +404,7 @@ void TabStatsTracker::OnWebContentsDestroyed( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(base::ContainsKey(web_contents_usage_observers_, web_contents)); + DCHECK(base::Contains(web_contents_usage_observers_, web_contents)); web_contents_usage_observers_.erase( web_contents_usage_observers_.find(web_contents)); tab_stats_data_store_->OnTabRemoved(web_contents);
diff --git a/chrome/browser/metrics/tab_stats_tracker_browsertest.cc b/chrome/browser/metrics/tab_stats_tracker_browsertest.cc index 514d7ec..c80e4a77 100644 --- a/chrome/browser/metrics/tab_stats_tracker_browsertest.cc +++ b/chrome/browser/metrics/tab_stats_tracker_browsertest.cc
@@ -253,10 +253,10 @@ data_store->GetTabIDForTesting(web_contents).value(); browser()->tab_strip_model()->DetachWebContentsAt( browser()->tab_strip_model()->GetIndexOfWebContents(web_contents)); - EXPECT_TRUE(base::ContainsKey(*interval_map, tab_id)); + EXPECT_TRUE(base::Contains(*interval_map, tab_id)); tab_stats_tracker_->OnInterval(kValidLongInterval, interval_map); EXPECT_EQ(1U, interval_map->size()); - EXPECT_FALSE(base::ContainsKey(*interval_map, tab_id)); + EXPECT_FALSE(base::Contains(*interval_map, tab_id)); web_contents = data_store->existing_tabs_for_testing()->begin()->first; @@ -265,7 +265,7 @@ tab_id = data_store->GetTabIDForTesting(web_contents).value(); browser()->tab_strip_model()->DetachWebContentsAt( browser()->tab_strip_model()->GetIndexOfWebContents(web_contents)); - EXPECT_TRUE(base::ContainsKey(*interval_map, tab_id)); + EXPECT_TRUE(base::Contains(*interval_map, tab_id)); tab_stats_tracker_->OnInterval(kValidLongInterval, interval_map); EXPECT_EQ(0U, interval_map->size()); }
diff --git a/chrome/browser/metrics/ukm_browsertest.cc b/chrome/browser/metrics/ukm_browsertest.cc index 32316c99..61468a7 100644 --- a/chrome/browser/metrics/ukm_browsertest.cc +++ b/chrome/browser/metrics/ukm_browsertest.cc
@@ -199,7 +199,7 @@ } bool HasSource(ukm::SourceId source_id) const { auto* service = ukm_service(); - return service && base::ContainsKey(service->sources(), source_id); + return service && base::Contains(service->sources(), source_id); } void RecordDummySource(ukm::SourceId source_id) { auto* service = ukm_service();
diff --git a/chrome/browser/net/profile_network_context_service_browsertest.cc b/chrome/browser/net/profile_network_context_service_browsertest.cc index fcc1cf1..9050cc6 100644 --- a/chrome/browser/net/profile_network_context_service_browsertest.cc +++ b/chrome/browser/net/profile_network_context_service_browsertest.cc
@@ -121,7 +121,7 @@ std::vector<std::string> encodings = base::SplitString(*simple_loader_helper.response_body(), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - EXPECT_TRUE(base::ContainsValue(encodings, "br")); + EXPECT_TRUE(base::Contains(encodings, "br")); } // Test subclass that adds switches::kDiskCacheDir to the command line, to make
diff --git a/chrome/browser/net/system_network_context_manager.cc b/chrome/browser/net/system_network_context_manager.cc index 1c943ee..ec1072f 100644 --- a/chrome/browser/net/system_network_context_manager.cc +++ b/chrome/browser/net/system_network_context_manager.cc
@@ -372,6 +372,7 @@ void SystemNetworkContextManager::DeleteInstance() { DCHECK(g_system_network_context_manager); delete g_system_network_context_manager; + g_system_network_context_manager = nullptr; } SystemNetworkContextManager::SystemNetworkContextManager(
diff --git a/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc b/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc index 4e6392d..a1983c6 100644 --- a/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc +++ b/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc
@@ -124,15 +124,6 @@ reporting_service_test_helper()->SetFailureMode( certificate_reporting_test_utils::REPORTS_SUCCESSFUL); - if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) { - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext( - system_request_context_getter_.get()); - } - // Creating the profile before the SafeBrowsingService ensures the // ServiceManagerConnection is initialized. profile_manager_ = std::make_unique<TestingProfileManager>( @@ -179,8 +170,6 @@ TestingBrowserProcess::GetGlobal()->safe_browsing_service()->ShutDown(); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr); } - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(nullptr); - system_request_context_getter_ = nullptr; TrialComparisonCertVerifierController::SetFakeOfficialBuildForTesting( false); @@ -220,7 +209,6 @@ reporting_service_test_helper_; content::TestBrowserThreadBundle thread_bundle_; scoped_refptr<safe_browsing::SafeBrowsingService> sb_service_; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; std::unique_ptr<TestingProfileManager> profile_manager_; TestingProfile* profile_;
diff --git a/chrome/browser/notifications/notification_platform_bridge_linux.cc b/chrome/browser/notifications/notification_platform_bridge_linux.cc index aa6d15f..d6210473 100644 --- a/chrome/browser/notifications/notification_platform_bridge_linux.cc +++ b/chrome/browser/notifications/notification_platform_bridge_linux.cc
@@ -444,8 +444,8 @@ capabilities_.insert(capability); } RecordMetricsForCapabilities(); - if (!base::ContainsKey(capabilities_, kCapabilityBody) || - !base::ContainsKey(capabilities_, kCapabilityActions)) { + if (!base::Contains(capabilities_, kCapabilityBody) || + !base::Contains(capabilities_, kCapabilityActions)) { OnConnectionInitializationFinishedOnTaskRunner( ConnectionInitializationStatusCode::MISSING_REQUIRED_CAPABILITIES); return; @@ -454,7 +454,7 @@ FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &NotificationPlatformBridgeLinuxImpl::SetBodyImagesSupported, this, - base::ContainsKey(capabilities_, kCapabilityBodyImages))); + base::Contains(capabilities_, kCapabilityBodyImages))); dbus::MethodCall get_server_information_call(kFreedesktopNotificationsName, "GetServerInformation"); @@ -542,9 +542,9 @@ base::UTF16ToUTF8(CreateNotificationTitle(*notification))); std::ostringstream body; - if (base::ContainsKey(capabilities_, kCapabilityBody)) { + if (base::Contains(capabilities_, kCapabilityBody)) { const bool body_markup = - base::ContainsKey(capabilities_, kCapabilityBodyMarkup); + base::Contains(capabilities_, kCapabilityBodyMarkup); if (notification->UseOriginAsContextMessage()) { std::string url_display_text = @@ -563,7 +563,7 @@ } EscapeUnsafeCharacters(&url_display_text); if (body_markup && - base::ContainsKey(capabilities_, kCapabilityBodyHyperlinks)) { + base::Contains(capabilities_, kCapabilityBodyHyperlinks)) { body << "<a href=\"" << net::EscapeForHTML(notification->origin_url().spec()) << "\">" << url_display_text << "</a>\n\n"; @@ -597,7 +597,7 @@ } } else if (notification->type() == message_center::NOTIFICATION_TYPE_IMAGE && - base::ContainsKey(capabilities_, kCapabilityBodyImages)) { + base::Contains(capabilities_, kCapabilityBodyImages)) { std::unique_ptr<ResourceFile> image_file = WriteDataToTmpFile( ResizeImageToFdoMaxSize(notification->image()).As1xPNGBytes()); if (image_file) { @@ -615,7 +615,7 @@ // Even-indexed elements in this vector are action IDs passed back to // us in OnActionInvoked(). Odd-indexed ones contain the button text. std::vector<std::string> actions; - if (base::ContainsKey(capabilities_, kCapabilityActions)) { + if (base::Contains(capabilities_, kCapabilityActions)) { data->action_start = data->action_end; for (const auto& button_info : notification->buttons()) { // FDO notification buttons can contain either an icon or a label, @@ -698,7 +698,7 @@ writer.AppendInt32( notification->never_timeout() ? kExpireTimeoutNever - : base::ContainsKey(capabilities_, kCapabilityPersistence) + : base::Contains(capabilities_, kCapabilityPersistence) ? kExpireTimeoutDefault : kExpireTimeout); @@ -907,31 +907,27 @@ // callsite, so we can't roll the below into a nice loop. UMA_HISTOGRAM_BOOLEAN( "Notifications.Freedesktop.Capabilities.ActionIcons", - base::ContainsKey(capabilities_, kCapabilityActionIcons)); + base::Contains(capabilities_, kCapabilityActionIcons)); UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.Actions", - base::ContainsKey(capabilities_, kCapabilityActions)); + base::Contains(capabilities_, kCapabilityActions)); UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.Body", - base::ContainsKey(capabilities_, kCapabilityBody)); + base::Contains(capabilities_, kCapabilityBody)); UMA_HISTOGRAM_BOOLEAN( "Notifications.Freedesktop.Capabilities.BodyHyperlinks", - base::ContainsKey(capabilities_, kCapabilityBodyHyperlinks)); - UMA_HISTOGRAM_BOOLEAN( - "Notifications.Freedesktop.Capabilities.BodyImages", - base::ContainsKey(capabilities_, kCapabilityBodyImages)); - UMA_HISTOGRAM_BOOLEAN( - "Notifications.Freedesktop.Capabilities.BodyMarkup", - base::ContainsKey(capabilities_, kCapabilityBodyMarkup)); - UMA_HISTOGRAM_BOOLEAN( - "Notifications.Freedesktop.Capabilities.IconMulti", - base::ContainsKey(capabilities_, kCapabilityIconMulti)); - UMA_HISTOGRAM_BOOLEAN( - "Notifications.Freedesktop.Capabilities.IconStatic", - base::ContainsKey(capabilities_, kCapabilityIconStatic)); + base::Contains(capabilities_, kCapabilityBodyHyperlinks)); + UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.BodyImages", + base::Contains(capabilities_, kCapabilityBodyImages)); + UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.BodyMarkup", + base::Contains(capabilities_, kCapabilityBodyMarkup)); + UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.IconMulti", + base::Contains(capabilities_, kCapabilityIconMulti)); + UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.IconStatic", + base::Contains(capabilities_, kCapabilityIconStatic)); UMA_HISTOGRAM_BOOLEAN( "Notifications.Freedesktop.Capabilities.Persistence", - base::ContainsKey(capabilities_, kCapabilityPersistence)); + base::Contains(capabilities_, kCapabilityPersistence)); UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.Sound", - base::ContainsKey(capabilities_, kCapabilitySound)); + base::Contains(capabilities_, kCapabilitySound)); } void RewriteProductLogoFile() {
diff --git a/chrome/browser/notifications/win/notification_image_retainer.cc b/chrome/browser/notifications/win/notification_image_retainer.cc index 6c25548..6a4487b 100644 --- a/chrome/browser/notifications/win/notification_image_retainer.cc +++ b/chrome/browser/notifications/win/notification_image_retainer.cc
@@ -56,7 +56,7 @@ for (base::FilePath current = file_enumerator.Next(); !current.empty(); current = file_enumerator.Next()) { // Exclude any new file created in this session. - if (!base::ContainsKey(registered_names, current.BaseName())) + if (!base::Contains(registered_names, current.BaseName())) files.push_back(std::move(current)); }
diff --git a/chrome/browser/obsolete_system/obsolete_system_mac.cc b/chrome/browser/obsolete_system/obsolete_system_mac.cc index a193fd5..532d4f9 100644 --- a/chrome/browser/obsolete_system/obsolete_system_mac.cc +++ b/chrome/browser/obsolete_system/obsolete_system_mac.cc
@@ -4,7 +4,7 @@ #include "chrome/browser/obsolete_system/obsolete_system.h" -#include "base/mac/mac_util.h" +#include "base/system/sys_info.h" #include "chrome/common/chrome_features.h" #include "chrome/common/url_constants.h" #include "chrome/grit/chromium_strings.h" @@ -12,7 +12,14 @@ // static bool ObsoleteSystem::IsObsoleteNowOrSoon() { - return base::mac::IsOS10_9() && + // Use base::SysInfo::OperatingSystemVersionNumbers() here rather than the + // preferred base::mac::IsOS*() function because the IsOS functions for + // obsolete system versions are removed to help prevent obsolete code from + // existing in the Chromium codebase. + int32_t major, minor, bugfix; + base::SysInfo::OperatingSystemVersionNumbers(&major, &minor, &bugfix); + + return ((major < 10) || (major == 10 && minor <= 9)) && base::FeatureList::IsEnabled(features::kShow10_9ObsoleteInfobar); }
diff --git a/chrome/browser/page_load_metrics/observers/session_restore_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/session_restore_page_load_metrics_observer_unittest.cc index 47af5063..b6ae506 100644 --- a/chrome/browser/page_load_metrics/observers/session_restore_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/session_restore_page_load_metrics_observer_unittest.cc
@@ -139,7 +139,7 @@ } void SimulateTimingUpdateForTab(WebContents* contents) { - ASSERT_TRUE(base::ContainsKey(testers_, contents)); + ASSERT_TRUE(base::Contains(testers_, contents)); testers_[contents]->SimulateTimingUpdate(timing_); }
diff --git a/chrome/browser/password_manager/credential_manager_browsertest.cc b/chrome/browser/password_manager/credential_manager_browsertest.cc index 84059972..856b0a89 100644 --- a/chrome/browser/password_manager/credential_manager_browsertest.cc +++ b/chrome/browser/password_manager/credential_manager_browsertest.cc
@@ -635,8 +635,8 @@ password_store->stored_passwords(); GURL www_url = https_test_server().GetURL("www.example.com", "/"); EXPECT_EQ(2U, passwords.size()); - EXPECT_TRUE(base::ContainsKey(passwords, psl_url.spec())); - EXPECT_TRUE(base::ContainsKey(passwords, www_url.spec())); + EXPECT_TRUE(base::Contains(passwords, psl_url.spec())); + EXPECT_TRUE(base::Contains(passwords, www_url.spec())); } IN_PROC_BROWSER_TEST_F(CredentialManagerBrowserTest, @@ -682,8 +682,8 @@ password_store->stored_passwords(); GURL www_url = https_test_server().GetURL("www.example.com", "/"); EXPECT_EQ(2U, passwords.size()); - EXPECT_TRUE(base::ContainsKey(passwords, psl_url.spec())); - EXPECT_TRUE(base::ContainsKey(passwords, www_url.spec())); + EXPECT_TRUE(base::Contains(passwords, psl_url.spec())); + EXPECT_TRUE(base::Contains(passwords, www_url.spec())); EXPECT_EQ(base::ASCIIToUTF16("user"), passwords[psl_url.spec()].front().username_value); EXPECT_EQ(base::ASCIIToUTF16("password"),
diff --git a/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc b/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc index fc406544..0c6ae02 100644 --- a/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc +++ b/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc
@@ -500,7 +500,7 @@ return nullptr; EXPECT_EQ("org.kde.KWallet", method_call->GetInterface()); - if (base::ContainsKey(failing_methods_, method_call->GetMember())) + if (base::Contains(failing_methods_, method_call->GetMember())) return nullptr; std::unique_ptr<dbus::Response> response; if (method_call->GetMember() == "isEnabled") {
diff --git a/chrome/browser/password_manager/password_manager_browsertest.cc b/chrome/browser/password_manager/password_manager_browsertest.cc index 72b669d..ab6c069 100644 --- a/chrome/browser/password_manager/password_manager_browsertest.cc +++ b/chrome/browser/password_manager/password_manager_browsertest.cc
@@ -135,7 +135,7 @@ base::CompareCase::SENSITIVE)) return nullptr; auto http_response = std::make_unique<net::test_server::BasicHttpResponse>(); - if (base::ContainsKey(request.headers, "Authorization")) { + if (base::Contains(request.headers, "Authorization")) { http_response->set_code(net::HTTP_OK); http_response->set_content("Success!"); } else {
diff --git a/chrome/browser/payments/service_worker_payment_app_factory_browsertest.cc b/chrome/browser/payments/service_worker_payment_app_factory_browsertest.cc index 00ab5aa..ccf5c2f 100644 --- a/chrome/browser/payments/service_worker_payment_app_factory_browsertest.cc +++ b/chrome/browser/payments/service_worker_payment_app_factory_browsertest.cc
@@ -226,7 +226,7 @@ } } ASSERT_NE(nullptr, app) << "No app found in scope " << scope; - EXPECT_TRUE(base::ContainsValue(app->enabled_methods, expected_method)) + EXPECT_TRUE(base::Contains(app->enabled_methods, expected_method)) << "Unable to find payment method " << expected_method << " in the list of enabled methods for the app installed from " << app->scope;
diff --git a/chrome/browser/performance_manager/browser_child_process_watcher.cc b/chrome/browser/performance_manager/browser_child_process_watcher.cc index d75faf7..3d67aaf9 100644 --- a/chrome/browser/performance_manager/browser_child_process_watcher.cc +++ b/chrome/browser/performance_manager/browser_child_process_watcher.cc
@@ -78,7 +78,7 @@ // It appears the exit code can be delivered either after the host is // disconnected, or perhaps before the HostConnected notification, // specifically on crash. - if (base::ContainsKey(gpu_process_nodes_, id)) { + if (base::Contains(gpu_process_nodes_, id)) { auto* process_node = gpu_process_nodes_[id].get(); PerformanceManager* performance_manager = PerformanceManager::GetInstance();
diff --git a/chrome/browser/performance_manager/graph/node_attached_data.cc b/chrome/browser/performance_manager/graph/node_attached_data.cc index f97091e..cc626fe 100644 --- a/chrome/browser/performance_manager/graph/node_attached_data.cc +++ b/chrome/browser/performance_manager/graph/node_attached_data.cc
@@ -25,7 +25,7 @@ GraphImpl::NodeAttachedDataKey data_key = std::make_pair(node, data->GetKey()); auto& map = graph->node_attached_data_map_; - DCHECK(!base::ContainsKey(map, data_key)); + DCHECK(!base::Contains(map, data_key)); map[data_key] = std::move(data); }
diff --git a/chrome/browser/performance_manager/graph/page_node_impl_unittest.cc b/chrome/browser/performance_manager/graph/page_node_impl_unittest.cc index 3392b4c..aea00cf 100644 --- a/chrome/browser/performance_manager/graph/page_node_impl_unittest.cc +++ b/chrome/browser/performance_manager/graph/page_node_impl_unittest.cc
@@ -70,8 +70,7 @@ // Ensure correct page-frame relationship has been established. EXPECT_EQ(1u, page_node->GetFrameNodes().size()); - EXPECT_TRUE( - base::ContainsValue(page_node->GetFrameNodes(), frame_node.get())); + EXPECT_TRUE(base::Contains(page_node->GetFrameNodes(), frame_node.get())); EXPECT_EQ(page_node.get(), frame_node->page_node()); frame_node.reset();
diff --git a/chrome/browser/performance_manager/graph/process_node_impl.cc b/chrome/browser/performance_manager/graph/process_node_impl.cc index c6ce2afa..2eaf4a9 100644 --- a/chrome/browser/performance_manager/graph/process_node_impl.cc +++ b/chrome/browser/performance_manager/graph/process_node_impl.cc
@@ -28,7 +28,7 @@ void ProcessNodeImpl::RemoveFrame(FrameNodeImpl* frame_node) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(base::ContainsKey(frame_nodes_, frame_node)); + DCHECK(base::Contains(frame_nodes_, frame_node)); frame_nodes_.erase(frame_node); }
diff --git a/chrome/browser/performance_manager/observers/isolation_context_metrics.cc b/chrome/browser/performance_manager/observers/isolation_context_metrics.cc index 4476fa17..fede7d3 100644 --- a/chrome/browser/performance_manager/observers/isolation_context_metrics.cc +++ b/chrome/browser/performance_manager/observers/isolation_context_metrics.cc
@@ -193,8 +193,8 @@ // Get the data related to this browsing instance. Since there is a current // main frame it must already have existed. - DCHECK(base::ContainsKey(browsing_instance_data_, - frame_node->browsing_instance_id())); + DCHECK(base::Contains(browsing_instance_data_, + frame_node->browsing_instance_id())); auto* data = &browsing_instance_data_[frame_node->browsing_instance_id()]; const BrowsingInstanceDataState old_state = GetBrowsingInstanceDataState(data);
diff --git a/chrome/browser/performance_manager/performance_manager_tab_helper.cc b/chrome/browser/performance_manager/performance_manager_tab_helper.cc index 066b67c6..9753f1a 100644 --- a/chrome/browser/performance_manager/performance_manager_tab_helper.cc +++ b/chrome/browser/performance_manager/performance_manager_tab_helper.cc
@@ -86,12 +86,12 @@ content::RenderFrameHost* render_frame_host) { DCHECK_NE(nullptr, render_frame_host); // This must not exist in the map yet. - DCHECK(!base::ContainsKey(frames_, render_frame_host)); + DCHECK(!base::Contains(frames_, render_frame_host)); content::RenderFrameHost* parent = render_frame_host->GetParent(); FrameNodeImpl* parent_frame_node = nullptr; if (parent) { - DCHECK(base::ContainsKey(frames_, parent)); + DCHECK(base::Contains(frames_, parent)); parent_frame_node = frames_[parent].get(); }
diff --git a/chrome/browser/performance_manager/performance_manager_tab_helper_unittest.cc b/chrome/browser/performance_manager/performance_manager_tab_helper_unittest.cc index 87eb31c9..d7b5ab7 100644 --- a/chrome/browser/performance_manager/performance_manager_tab_helper_unittest.cc +++ b/chrome/browser/performance_manager/performance_manager_tab_helper_unittest.cc
@@ -93,7 +93,7 @@ EXPECT_GE(num_hosts, page->GetAssociatedProcessNodes().size()); for (auto* process_node : associated_process_nodes) - EXPECT_TRUE(base::ContainsKey(process_nodes, process_node)); + EXPECT_TRUE(base::Contains(process_nodes, process_node)); EXPECT_EQ(4u, page->GetFrameNodes().size()); ASSERT_EQ(1u, page->main_frame_nodes().size());
diff --git a/chrome/browser/performance_manager/persistence/site_data/site_data_cache_impl.cc b/chrome/browser/performance_manager/persistence/site_data/site_data_cache_impl.cc index e0b0dff..95c9c184 100644 --- a/chrome/browser/performance_manager/persistence/site_data/site_data_cache_impl.cc +++ b/chrome/browser/performance_manager/persistence/site_data/site_data_cache_impl.cc
@@ -113,7 +113,7 @@ void SiteDataCacheImpl::OnSiteDataImplDestroyed(internal::SiteDataImpl* impl) { DCHECK(impl); - DCHECK(base::ContainsKey(origin_data_map_, impl->origin())); + DCHECK(base::Contains(origin_data_map_, impl->origin())); // Remove the entry for this origin as this is about to get destroyed. auto num_erased = origin_data_map_.erase(impl->origin()); DCHECK_EQ(1U, num_erased);
diff --git a/chrome/browser/performance_manager/webui_graph_dump_impl_unittest.cc b/chrome/browser/performance_manager/webui_graph_dump_impl_unittest.cc index 6b34213..e258a509 100644 --- a/chrome/browser/performance_manager/webui_graph_dump_impl_unittest.cc +++ b/chrome/browser/performance_manager/webui_graph_dump_impl_unittest.cc
@@ -98,7 +98,7 @@ size_t num_changes() const { return num_changes_; } private: - bool HasId(int64_t id) { return base::ContainsKey(id_set_, id); } + bool HasId(int64_t id) { return base::Contains(id_set_, id); } bool HasIdIfValid(int64_t id) { return id == 0u || HasId(id); } FrameMap frame_map_; @@ -187,7 +187,7 @@ browser_thread_bundle.RunUntilIdle(); EXPECT_EQ(1u, change_stream.num_changes()); - EXPECT_FALSE(base::ContainsKey(change_stream.id_set(), child_frame_id)); + EXPECT_FALSE(base::Contains(change_stream.id_set(), child_frame_id)); const auto main_page_it = change_stream.page_map().find( NodeBase::GetSerializationId(mock_graph.page.get()));
diff --git a/chrome/browser/permissions/chooser_context_base.cc b/chrome/browser/permissions/chooser_context_base.cc index ba36421..ae0f2d5 100644 --- a/chrome/browser/permissions/chooser_context_base.cc +++ b/chrome/browser/permissions/chooser_context_base.cc
@@ -146,7 +146,7 @@ } auto& object_list = objects->GetList(); - if (!base::ContainsValue(object_list, object)) + if (!base::Contains(object_list, object)) object_list.push_back(std::move(object)); SetWebsiteSetting(requesting_origin, embedding_origin, std::move(setting));
diff --git a/chrome/browser/plugins/flash_temporary_permission_tracker.cc b/chrome/browser/plugins/flash_temporary_permission_tracker.cc index 8b4e861..9aae2f3 100644 --- a/chrome/browser/plugins/flash_temporary_permission_tracker.cc +++ b/chrome/browser/plugins/flash_temporary_permission_tracker.cc
@@ -50,7 +50,7 @@ bool FlashTemporaryPermissionTracker::IsFlashEnabled(const GURL& url) { base::AutoLock lock(granted_origins_lock_); - return base::ContainsKey(granted_origins_, url.GetOrigin()); + return base::Contains(granted_origins_, url.GetOrigin()); } void FlashTemporaryPermissionTracker::FlashEnabledForWebContents(
diff --git a/chrome/browser/plugins/plugin_metadata.cc b/chrome/browser/plugins/plugin_metadata.cc index 0ba33a0..c2548c87cf 100644 --- a/chrome/browser/plugins/plugin_metadata.cc +++ b/chrome/browser/plugins/plugin_metadata.cc
@@ -61,7 +61,7 @@ } bool PluginMetadata::HasMimeType(const std::string& mime_type) const { - return base::ContainsValue(all_mime_types_, mime_type); + return base::Contains(all_mime_types_, mime_type); } bool PluginMetadata::MatchesPlugin(const content::WebPluginInfo& plugin) {
diff --git a/chrome/browser/plugins/plugin_utils.cc b/chrome/browser/plugins/plugin_utils.cc index 01ea0ba..0f0847ab 100644 --- a/chrome/browser/plugins/plugin_utils.cc +++ b/chrome/browser/plugins/plugin_utils.cc
@@ -204,8 +204,8 @@ if (MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension)) { for (const auto& supported_mime_type : handler->mime_type_set()) { - DCHECK(!base::ContainsKey(mime_type_to_extension_id_map, - supported_mime_type)); + DCHECK(!base::Contains(mime_type_to_extension_id_map, + supported_mime_type)); mime_type_to_extension_id_map[supported_mime_type] = extension_id; } }
diff --git a/chrome/browser/policy/policy_prefs_browsertest.cc b/chrome/browser/policy/policy_prefs_browsertest.cc index 5273a7e9..dc129a1 100644 --- a/chrome/browser/policy/policy_prefs_browsertest.cc +++ b/chrome/browser/policy/policy_prefs_browsertest.cc
@@ -186,7 +186,7 @@ #else #error "Unknown platform" #endif - return base::ContainsValue(supported_os_, os); + return base::Contains(supported_os_, os); } void AddSupportedOs(const std::string& os) { supported_os_.push_back(os); }
diff --git a/chrome/browser/predictors/autocomplete_action_predictor.cc b/chrome/browser/predictors/autocomplete_action_predictor.cc index 5193e4d..2e1391a 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor.cc +++ b/chrome/browser/predictors/autocomplete_action_predictor.cc
@@ -139,8 +139,7 @@ for (const auto& match : result) { const GURL& url = match.destination_url; const size_t size = url.spec().size(); - if (!base::ContainsValue(match_it->urls, url) && - size <= kMaximumStringLength && + if (!base::Contains(match_it->urls, url) && size <= kMaximumStringLength && transitional_matches_size_ + size <= kMaximumTransitionalMatchesSize) { match_it->urls.push_back(url); transitional_matches_size_ += size;
diff --git a/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc b/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc index 4495f77..6756802 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc +++ b/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc
@@ -249,7 +249,7 @@ for (size_t i = 0; i < base::size(test_url_db); ++i) { DBCacheKey key = {test_url_db[i].user_text, test_url_db[i].url}; - bool deleted = !base::ContainsValue(expected, i); + bool deleted = !base::Contains(expected, i); EXPECT_EQ(deleted, db_cache()->find(key) == db_cache()->end()); EXPECT_EQ(deleted, db_id_cache()->find(key) == db_id_cache()->end()); } @@ -406,7 +406,7 @@ bool deleted = (i < 2); EXPECT_EQ(deleted, db_cache()->find(key) == db_cache()->end()); EXPECT_EQ(deleted, db_id_cache()->find(key) == db_id_cache()->end()); - EXPECT_EQ(deleted, base::ContainsValue(id_list, all_ids[i])); + EXPECT_EQ(deleted, base::Contains(id_list, all_ids[i])); } } @@ -436,8 +436,8 @@ EXPECT_EQ(all_ids.size() - expected.size(), db_id_cache()->size()); for (auto it = all_ids.begin(); it != all_ids.end(); ++it) { - bool in_expected = base::ContainsValue(expected, *it); - bool in_list = base::ContainsValue(id_list, *it); + bool in_expected = base::Contains(expected, *it); + bool in_list = base::Contains(id_list, *it); EXPECT_EQ(in_expected, in_list); } } @@ -458,8 +458,8 @@ DBCacheKey deleted_key = {test_url_confidence_db[i].user_text, test_url_confidence_db[i].url}; - EXPECT_FALSE(base::ContainsKey(*db_cache(), deleted_key)); - EXPECT_FALSE(base::ContainsKey(*db_id_cache(), deleted_key)); + EXPECT_FALSE(base::Contains(*db_cache(), deleted_key)); + EXPECT_FALSE(base::Contains(*db_id_cache(), deleted_key)); } } @@ -484,8 +484,8 @@ for (size_t i = 0; i < count_to_remove; ++i) { DBCacheKey deleted_key = {test_url_confidence_db[i].user_text, test_url_confidence_db[i].url}; - EXPECT_FALSE(base::ContainsKey(*db_cache(), deleted_key)); - EXPECT_FALSE(base::ContainsKey(*db_id_cache(), deleted_key)); + EXPECT_FALSE(base::Contains(*db_cache(), deleted_key)); + EXPECT_FALSE(base::Contains(*db_id_cache(), deleted_key)); } } @@ -541,7 +541,7 @@ auto test = [this](const base::string16& user_text, bool should_be_registered) { predictor()->RegisterTransitionalMatches(user_text, AutocompleteResult()); - bool registered = base::ContainsValue(*transitional_matches(), user_text); + bool registered = base::Contains(*transitional_matches(), user_text); EXPECT_EQ(registered, should_be_registered); };
diff --git a/chrome/browser/predictors/loading_predictor_browsertest.cc b/chrome/browser/predictors/loading_predictor_browsertest.cc index cae25d6e..5df9cbf 100644 --- a/chrome/browser/predictors/loading_predictor_browsertest.cc +++ b/chrome/browser/predictors/loading_predictor_browsertest.cc
@@ -114,14 +114,14 @@ ConnectionTracker() {} void AcceptedSocketWithPort(uint16_t port) { - EXPECT_FALSE(base::ContainsKey(sockets_, port)); + EXPECT_FALSE(base::Contains(sockets_, port)); sockets_[port] = SocketStatus::kAccepted; CheckAccepted(); first_accept_loop_.Quit(); } void ReadFromSocketWithPort(uint16_t port) { - EXPECT_TRUE(base::ContainsKey(sockets_, port)); + EXPECT_TRUE(base::Contains(sockets_, port)); sockets_[port] = SocketStatus::kReadFrom; first_read_loop_.Quit(); } @@ -301,25 +301,25 @@ bool HasOriginAttemptedToPreconnect(const GURL& origin) { DCHECK_EQ(origin, origin.GetOrigin()); - return base::ContainsKey(preconnect_url_attempts_, origin); + return base::Contains(preconnect_url_attempts_, origin); } bool HasHostBeenLookedUp(const std::string& host) { - return base::ContainsKey(successful_dns_lookups_, host) || - base::ContainsKey(unsuccessful_dns_lookups_, host); + return base::Contains(successful_dns_lookups_, host) || + base::Contains(unsuccessful_dns_lookups_, host); } bool HostFound(const std::string& host) { - return base::ContainsKey(successful_dns_lookups_, host); + return base::Contains(successful_dns_lookups_, host); } bool HasProxyBeenLookedUp(const GURL& url) { - return base::ContainsKey(successful_proxy_lookups_, url.GetOrigin()) || - base::ContainsKey(unsuccessful_proxy_lookups_, url.GetOrigin()); + return base::Contains(successful_proxy_lookups_, url.GetOrigin()) || + base::Contains(unsuccessful_proxy_lookups_, url.GetOrigin()); } bool ProxyFound(const GURL& url) { - return base::ContainsKey(successful_proxy_lookups_, url.GetOrigin()); + return base::Contains(successful_proxy_lookups_, url.GetOrigin()); } private:
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 65cbfff9..fc3b400 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -192,7 +192,7 @@ #include "chrome/browser/ui/webui/local_discovery/local_discovery_ui.h" #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/session_duration_updater.h" #endif @@ -742,7 +742,7 @@ web_app::WebAppProvider::RegisterProfilePrefs(registry); #endif // BUILDFLAG(ENABLE_EXTENSIONS) -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) feature_engagement::SessionDurationUpdater::RegisterProfilePrefs(registry); #endif
diff --git a/chrome/browser/prerender/prerender_contents.cc b/chrome/browser/prerender/prerender_contents.cc index b0ba960..a8063d2 100644 --- a/chrome/browser/prerender/prerender_contents.cc +++ b/chrome/browser/prerender/prerender_contents.cc
@@ -500,7 +500,7 @@ session_storage_namespace_id_ != session_storage_namespace->id()) { return false; } - return base::ContainsValue(alias_urls_, url); + return base::Contains(alias_urls_, url); } void PrerenderContents::RenderProcessGone(base::TerminationStatus status) {
diff --git a/chrome/browser/prerender/prerender_nostate_prefetch_browsertest.cc b/chrome/browser/prerender/prerender_nostate_prefetch_browsertest.cc index 63487af..fea8666 100644 --- a/chrome/browser/prerender/prerender_nostate_prefetch_browsertest.cc +++ b/chrome/browser/prerender/prerender_nostate_prefetch_browsertest.cc
@@ -882,10 +882,10 @@ // Check that the URL that was explicitly navigated to is already in history. ui_test_utils::HistoryEnumerator enumerator(profile); std::vector<GURL>& urls = enumerator.urls(); - EXPECT_TRUE(base::ContainsValue(urls, navigated_url)); + EXPECT_TRUE(base::Contains(urls, navigated_url)); // Check that the URL that was prefetched is not in history. - EXPECT_FALSE(base::ContainsValue(urls, prefetched_url)); + EXPECT_FALSE(base::Contains(urls, prefetched_url)); // The loader URL is the remaining entry. EXPECT_EQ(2U, urls.size());
diff --git a/chrome/browser/previews/previews_lite_page_url_loader_interceptor.cc b/chrome/browser/previews/previews_lite_page_url_loader_interceptor.cc index f6a4ec2..b3e7e77 100644 --- a/chrome/browser/previews/previews_lite_page_url_loader_interceptor.cc +++ b/chrome/browser/previews/previews_lite_page_url_loader_interceptor.cc
@@ -97,7 +97,7 @@ } // Do not attempt to serve the same URL multiple times. - if (base::ContainsKey(urls_processed_, tentative_resource_request.url)) { + if (base::Contains(urls_processed_, tentative_resource_request.url)) { std::move(callback).Run({}); return; }
diff --git a/chrome/browser/printing/background_printing_manager.cc b/chrome/browser/printing/background_printing_manager.cc index 14fb359..e2594ef5 100644 --- a/chrome/browser/printing/background_printing_manager.cc +++ b/chrome/browser/printing/background_printing_manager.cc
@@ -152,7 +152,7 @@ bool BackgroundPrintingManager::HasPrintPreviewDialog( WebContents* preview_dialog) { - return base::ContainsKey(printing_contents_map_, preview_dialog); + return base::Contains(printing_contents_map_, preview_dialog); } BackgroundPrintingManager::PrintingContents::PrintingContents() = default;
diff --git a/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc b/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc index 10fce0f..655aa19 100644 --- a/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc +++ b/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc
@@ -108,7 +108,7 @@ "SomeToken", base::Time::Now() + base::TimeDelta::FromHours(1), std::string() /* No extra information needed for this test */)); - EXPECT_TRUE(base::ContainsKey(requested_urls, GURL(kConfirmRequest))); + EXPECT_TRUE(base::Contains(requested_urls, GURL(kConfirmRequest))); test_url_loader_factory_.AddResponse(kConfirmRequest, kSampleConfirmResponse); @@ -138,7 +138,7 @@ "SomeToken", base::Time::Now() + base::TimeDelta::FromHours(1), std::string() /* No extra information needed for this test */)); - EXPECT_TRUE(base::ContainsKey(requested_urls, GURL(kConfirmRequest))); + EXPECT_TRUE(base::Contains(requested_urls, GURL(kConfirmRequest))); test_url_loader_factory_.AddResponse(kConfirmRequest, kFailedConfirmResponseBadJson); base::RunLoop run_loop;
diff --git a/chrome/browser/printing/cloud_print/privet_notifications.cc b/chrome/browser/printing/cloud_print/privet_notifications.cc index 8087b4f7e..2258d612 100644 --- a/chrome/browser/printing/cloud_print/privet_notifications.cc +++ b/chrome/browser/printing/cloud_print/privet_notifications.cc
@@ -257,7 +257,7 @@ // If the UI is already open or a device was removed, we'll update the // existing notification but not add a new one. const bool notification_exists = - base::ContainsKey(displayed_notifications, kPrivetNotificationID); + base::Contains(displayed_notifications, kPrivetNotificationID); const bool add_new_notification = device_added && !local_discovery::LocalDiscoveryUIHandler::GetHasVisible();
diff --git a/chrome/browser/printing/print_preview_data_service.cc b/chrome/browser/printing/print_preview_data_service.cc index e932c1b78..7f5525a 100644 --- a/chrome/browser/printing/print_preview_data_service.cc +++ b/chrome/browser/printing/print_preview_data_service.cc
@@ -117,7 +117,7 @@ int32_t preview_ui_id, int index, scoped_refptr<base::RefCountedMemory> data_bytes) { - if (!base::ContainsKey(data_store_map_, preview_ui_id)) + if (!base::Contains(data_store_map_, preview_ui_id)) data_store_map_[preview_ui_id] = std::make_unique<PrintPreviewDataStore>(); data_store_map_[preview_ui_id]->SetPreviewDataForIndex(index, std::move(data_bytes));
diff --git a/chrome/browser/printing/print_view_manager.cc b/chrome/browser/printing/print_view_manager.cc index 8cdc794..136f166e 100644 --- a/chrome/browser/printing/print_view_manager.cc +++ b/chrome/browser/printing/print_view_manager.cc
@@ -213,7 +213,7 @@ auto& map = g_scripted_print_preview_closure_map.Get(); content::RenderProcessHost* rph = rfh->GetProcess(); - if (base::ContainsKey(map, rph)) { + if (base::Contains(map, rph)) { // Renderer already handling window.print(). Abort this attempt to prevent // the renderer from having multiple nested loops. If multiple nested loops // existed, then they have to exit in the right order and that is messy.
diff --git a/chrome/browser/printing/pwg_raster_converter.cc b/chrome/browser/printing/pwg_raster_converter.cc index c140bf4e..fa1827f 100644 --- a/chrome/browser/printing/pwg_raster_converter.cc +++ b/chrome/browser/printing/pwg_raster_converter.cc
@@ -280,7 +280,7 @@ const auto& types = raster_capability.value().document_types_supported; result.use_color = use_color || - !base::ContainsValue( + !base::Contains( types, cloud_devices::printer::PwgDocumentTypeSupported::SGRAY_8); return result;
diff --git a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc index bd0a4453..682fea5 100644 --- a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc +++ b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc
@@ -132,7 +132,7 @@ #include "chrome/browser/captive_portal/captive_portal_service_factory.h" #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/bookmark/bookmark_tracker_factory.h" #include "chrome/browser/feature_engagement/incognito_window/incognito_window_tracker_factory.h" #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker_factory.h" @@ -275,7 +275,7 @@ extensions::VerifyTrustAPI::GetFactoryInstance(); #endif FaviconServiceFactory::GetInstance(); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) feature_engagement::BookmarkTrackerFactory::GetInstance(); feature_engagement::IncognitoWindowTrackerFactory::GetInstance(); feature_engagement::NewTabTrackerFactory::GetInstance();
diff --git a/chrome/browser/profiling_host/background_profiling_triggers.cc b/chrome/browser/profiling_host/background_profiling_triggers.cc index be7ba7d..9f71f67 100644 --- a/chrome/browser/profiling_host/background_profiling_triggers.cc +++ b/chrome/browser/profiling_host/background_profiling_triggers.cc
@@ -169,7 +169,7 @@ // Sample a control population. for (const auto& proc : dump->process_dumps()) { - if (base::ContainsValue(profiled_pids, proc.pid()) && + if (base::Contains(profiled_pids, proc.pid()) && ShouldTriggerControlReport( GetContentProcessType(proc.process_type()))) { TriggerMemoryReport("MEMLOG_CONTROL_TRIGGER"); @@ -180,7 +180,7 @@ // Detect whether memory footprint is too high and send a memlog report. bool should_send_report = false; for (const auto& proc : dump->process_dumps()) { - if (!base::ContainsValue(profiled_pids, proc.pid())) + if (!base::Contains(profiled_pids, proc.pid())) continue; uint32_t private_footprint_kb = proc.os_dump().private_footprint_kb; @@ -205,7 +205,7 @@ // Clear the watermark for all non-profiled pids. for (auto it = pmf_at_last_upload_.begin(); it != pmf_at_last_upload_.end();) { - if (base::ContainsValue(profiled_pids, it->first)) { + if (base::Contains(profiled_pids, it->first)) { ++it; } else { it = pmf_at_last_upload_.erase(it);
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_data_store.cc b/chrome/browser/resource_coordinator/local_site_characteristics_data_store.cc index 508196e..423cc90 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_data_store.cc +++ b/chrome/browser/resource_coordinator/local_site_characteristics_data_store.cc
@@ -145,7 +145,7 @@ OnLocalSiteCharacteristicsDataImplDestroyed( internal::LocalSiteCharacteristicsDataImpl* impl) { DCHECK(impl); - DCHECK(base::ContainsKey(origin_data_map_, impl->origin())); + DCHECK(base::Contains(origin_data_map_, impl->origin())); // Remove the entry for this origin as this is about to get destroyed. auto num_erased = origin_data_map_.erase(impl->origin()); DCHECK_EQ(1U, num_erased);
diff --git a/chrome/browser/resource_coordinator/session_restore_policy.cc b/chrome/browser/resource_coordinator/session_restore_policy.cc index 3f92e3d7..28794ce6 100644 --- a/chrome/browser/resource_coordinator/session_restore_policy.cc +++ b/chrome/browser/resource_coordinator/session_restore_policy.cc
@@ -110,7 +110,7 @@ } float SessionRestorePolicy::AddTabForScoring(content::WebContents* contents) { - DCHECK(!base::ContainsKey(tab_data_, contents)); + DCHECK(!base::Contains(tab_data_, contents)); // When the first tab is added keep track of a 'now' time. This ensures that // the scoring function returns consistent values over the lifetime of the
diff --git a/chrome/browser/resource_coordinator/tab_load_tracker.cc b/chrome/browser/resource_coordinator/tab_load_tracker.cc index 143e0016..ffe4532 100644 --- a/chrome/browser/resource_coordinator/tab_load_tracker.cc +++ b/chrome/browser/resource_coordinator/tab_load_tracker.cc
@@ -119,7 +119,7 @@ void TabLoadTracker::StartTracking(content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!base::ContainsKey(tabs_, web_contents)); + DCHECK(!base::Contains(tabs_, web_contents)); LoadingState loading_state = DetermineLoadingState(web_contents); @@ -225,7 +225,7 @@ // so here we can assume the event pertains to a live web_contents and // its most recent navigation. However, the graph tracks contents that aren't // tracked by this object. - if (!base::ContainsKey(tabs_, web_contents)) + if (!base::Contains(tabs_, web_contents)) return; MaybeTransitionToLoaded(web_contents);
diff --git a/chrome/browser/resource_coordinator/tab_manager.cc b/chrome/browser/resource_coordinator/tab_manager.cc index bc718e4..a4c05081 100644 --- a/chrome/browser/resource_coordinator/tab_manager.cc +++ b/chrome/browser/resource_coordinator/tab_manager.cc
@@ -736,7 +736,7 @@ } bool TabManager::IsTabLoadingForTest(content::WebContents* contents) const { - if (base::ContainsKey(loading_contents_, contents)) + if (base::Contains(loading_contents_, contents)) return true; DCHECK_NE(LoadingState::LOADING, GetWebContentsData(contents)->tab_loading_state());
diff --git a/chrome/browser/resource_coordinator/tab_manager_browsertest.cc b/chrome/browser/resource_coordinator/tab_manager_browsertest.cc index f2d721f..e478319 100644 --- a/chrome/browser/resource_coordinator/tab_manager_browsertest.cc +++ b/chrome/browser/resource_coordinator/tab_manager_browsertest.cc
@@ -112,8 +112,7 @@ } else { LOG(ERROR) << "transition to state " << static_cast<int>(lifecycle_unit_->GetState()); - EXPECT_TRUE( - base::ContainsKey(allowed_states_, lifecycle_unit_->GetState())); + EXPECT_TRUE(base::Contains(allowed_states_, lifecycle_unit_->GetState())); } }
diff --git a/chrome/browser/resource_coordinator/tab_manager_stats_collector.cc b/chrome/browser/resource_coordinator/tab_manager_stats_collector.cc index c038972..c1d376f 100644 --- a/chrome/browser/resource_coordinator/tab_manager_stats_collector.cc +++ b/chrome/browser/resource_coordinator/tab_manager_stats_collector.cc
@@ -200,8 +200,7 @@ if (old_contents) foreground_contents_switched_to_times_.erase(old_contents); - DCHECK( - !base::ContainsKey(foreground_contents_switched_to_times_, new_contents)); + DCHECK(!base::Contains(foreground_contents_switched_to_times_, new_contents)); if (new_data->tab_loading_state() != LoadingState::LOADED) { foreground_contents_switched_to_times_.insert( std::make_pair(new_contents, NowTicks())); @@ -380,7 +379,7 @@ void TabManagerStatsCollector::OnTabIsLoaded(content::WebContents* contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!base::ContainsKey(foreground_contents_switched_to_times_, contents)) + if (!base::Contains(foreground_contents_switched_to_times_, contents)) return; base::TimeDelta switch_load_time =
diff --git a/chrome/browser/resource_coordinator/tab_metrics_logger.cc b/chrome/browser/resource_coordinator/tab_metrics_logger.cc index 0f2fb75..7c20de5 100644 --- a/chrome/browser/resource_coordinator/tab_metrics_logger.cc +++ b/chrome/browser/resource_coordinator/tab_metrics_logger.cc
@@ -186,9 +186,8 @@ // Verify that the browser is not closing. const Browser* browser = chrome::FindBrowserWithWebContents(web_contents); - if (base::ContainsKey( - BrowserList::GetInstance()->currently_closing_browsers(), - browser)) { + if (base::Contains(BrowserList::GetInstance()->currently_closing_browsers(), + browser)) { return; }
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_browsertest_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_browsertest_win.cc index b8354aa..f0a13c85 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_browsertest_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_browsertest_win.cc
@@ -155,8 +155,8 @@ // component installed. Otherwise it should be installed. std::vector<std::string> component_ids = g_browser_process->component_updater()->GetComponentIDs(); - bool sw_component_registered = base::ContainsValue( - component_ids, component_updater::kSwReporterComponentId); + bool sw_component_registered = + base::Contains(component_ids, component_updater::kSwReporterComponentId); ASSERT_EQ(policy_ != ReporterRunnerPolicy::kDisabled, sw_component_registered); }
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/srt_chrome_prompt_impl_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/srt_chrome_prompt_impl_win.cc index 635d53bb..0b02057 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/srt_chrome_prompt_impl_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/srt_chrome_prompt_impl_win.cc
@@ -93,7 +93,7 @@ [this, &verified_extension_ids](const base::string16& id) { std::string id_utf8 = base::UTF16ToUTF8(id); return crx_file::id_util::IdIsValid(id_utf8) && - base::ContainsValue(verified_extension_ids, id) && + base::Contains(verified_extension_ids, id) && extension_service_->GetInstalledExtension(id_utf8) != nullptr; }); if (!ids_are_valid) {
diff --git a/chrome/browser/safe_browsing/client_side_detection_service.cc b/chrome/browser/safe_browsing/client_side_detection_service.cc index e812e1f..c63919b 100644 --- a/chrome/browser/safe_browsing/client_side_detection_service.cc +++ b/chrome/browser/safe_browsing/client_side_detection_service.cc
@@ -208,10 +208,10 @@ if (url_loader->ResponseInfo() && url_loader->ResponseInfo()->headers) response_code = url_loader->ResponseInfo()->headers->response_code(); - if (base::ContainsKey(client_phishing_reports_, url_loader)) { + if (base::Contains(client_phishing_reports_, url_loader)) { HandlePhishingVerdict(url_loader, url_loader->GetFinalURL(), url_loader->NetError(), response_code, data); - } else if (base::ContainsKey(client_malware_reports_, url_loader)) { + } else if (base::Contains(client_malware_reports_, url_loader)) { HandleMalwareVerdict(url_loader, url_loader->GetFinalURL(), url_loader->NetError(), response_code, data); } else {
diff --git a/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc b/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc index 34ce31b..fe2a4ba6 100644 --- a/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc +++ b/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc
@@ -214,12 +214,6 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext( - system_request_context_getter_.get()); in_process_utility_thread_helper_ = std::make_unique<content::InProcessUtilityThreadHelper>(); // Start real threads for the IO and File threads so that the DCHECKs @@ -278,9 +272,7 @@ // tasks currently running. FlushThreadMessageLoops(); sb_service_ = NULL; - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(nullptr); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr); - system_request_context_getter_ = nullptr; in_process_utility_thread_helper_ = nullptr; ChromeRenderViewHostTestHarness::TearDown(); @@ -533,7 +525,6 @@ FileTypePoliciesTestOverlay policies_; scoped_refptr<FakeSafeBrowsingService> sb_service_; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; scoped_refptr<MockBinaryFeatureExtractor> binary_feature_extractor_; DownloadProtectionService* download_service_; DownloadCheckResult result_;
diff --git a/chrome/browser/safe_browsing/incident_reporting/environment_data_collection_win_unittest.cc b/chrome/browser/safe_browsing/incident_reporting/environment_data_collection_win_unittest.cc index 0d7cef6b..4a1c979 100644 --- a/chrome/browser/safe_browsing/incident_reporting/environment_data_collection_win_unittest.cc +++ b/chrome/browser/safe_browsing/incident_reporting/environment_data_collection_win_unittest.cc
@@ -50,9 +50,8 @@ const std::string& dll_path) { for (const auto& dll : process_report.dll()) { if (dll.path() == dll_path && - base::ContainsValue( - dll.feature(), - ClientIncidentReport_EnvironmentData_Process_Dll::LSP)) { + base::Contains(dll.feature(), + ClientIncidentReport_EnvironmentData_Process_Dll::LSP)) { // LSP feature found. return true; }
diff --git a/chrome/browser/safe_browsing/incident_reporting/extension_data_collection.cc b/chrome/browser/safe_browsing/incident_reporting/extension_data_collection.cc index d27c140..3f36df1 100644 --- a/chrome/browser/safe_browsing/incident_reporting/extension_data_collection.cc +++ b/chrome/browser/safe_browsing/incident_reporting/extension_data_collection.cc
@@ -77,11 +77,11 @@ std::unique_ptr<extensions::InstallSignature> signature_from_prefs = extensions::InstallSignature::FromValue(*signature); if (signature_from_prefs) { - if (base::ContainsKey(signature_from_prefs->ids, extension_id)) { + if (base::Contains(signature_from_prefs->ids, extension_id)) { extension_info->set_has_signature_validation(true); extension_info->set_signature_is_valid(true); - } else if (base::ContainsKey(signature_from_prefs->invalid_ids, - extension_id)) { + } else if (base::Contains(signature_from_prefs->invalid_ids, + extension_id)) { extension_info->set_has_signature_validation(true); extension_info->set_signature_is_valid(false); }
diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc b/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc index 031e9c55..65a06b5 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc
@@ -109,7 +109,8 @@ WebContents* web_contents, const GURL& main_frame_url, const UnsafeResourceList& unsafe_resources, - const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions& display_options) + const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions& display_options, + network::SharedURLLoaderFactory* url_loader_for_testing) : BaseBlockingPage( ui_manager, web_contents, @@ -133,8 +134,10 @@ Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory = - content::BrowserContext::GetDefaultStoragePartition(profile) - ->GetURLLoaderFactoryForBrowserProcess(); + url_loader_for_testing + ? url_loader_for_testing + : content::BrowserContext::GetDefaultStoragePartition(profile) + ->GetURLLoaderFactoryForBrowserProcess(); threat_details_in_progress_ = g_browser_process->safe_browsing_service() ->trigger_manager()
diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page.h b/chrome/browser/safe_browsing/safe_browsing_blocking_page.h index adb7fed..69ac09e 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page.h +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page.h
@@ -37,6 +37,10 @@ #include "components/safe_browsing/base_blocking_page.h" #include "components/safe_browsing/base_ui_manager.h" +namespace network { +class SharedURLLoaderFactory; +} + namespace safe_browsing { class SafeBrowsingBlockingPageFactory; @@ -111,7 +115,8 @@ content::WebContents* web_contents, const GURL& main_frame_url, const UnsafeResourceList& unsafe_resources, - const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions& display_options); + const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions& display_options, + network::SharedURLLoaderFactory* url_loader_for_testing = nullptr); // Called after the user clicks OnProceed(). If the page has malicious // subresources, then we show another interstitial.
diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page_unittest.cc b/chrome/browser/safe_browsing/safe_browsing_blocking_page_unittest.cc index 5cc4d60..a0e7aaf 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page_unittest.cc +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page_unittest.cc
@@ -9,6 +9,7 @@ #include "base/feature_list.h" #include "base/run_loop.h" #include "base/task/post_task.h" +#include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h" #include "chrome/browser/safe_browsing/test_safe_browsing_service.h" @@ -38,6 +39,8 @@ #include "content/public/test/web_contents_tester.h" #include "extensions/buildflags/buildflags.h" #include "net/url_request/url_request_test_util.h" +#include "services/network/public/cpp/features.h" +#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" @@ -75,6 +78,38 @@ namespace { +// This is used to avoid a DCHECK in ~ThreatDetails because the response wasn't +// received yet. +class CacheMissNetworkURLLoaderFactory final + : public network::mojom::URLLoaderFactory { + public: + CacheMissNetworkURLLoaderFactory() = default; + ~CacheMissNetworkURLLoaderFactory() override = default; + + // network::mojom::URLLoaderFactory implementation. + void CreateLoaderAndStart(network::mojom::URLLoaderRequest request, + int32_t routing_id, + int32_t request_id, + uint32_t options, + const network::ResourceRequest& url_request, + network::mojom::URLLoaderClientPtr client, + const net::MutableNetworkTrafficAnnotationTag& + traffic_annotation) override { + network::URLLoaderCompletionStatus status; + status.error_code = net::ERR_CACHE_MISS; + client->OnComplete(status); + } + + void Clone(network::mojom::URLLoaderFactoryRequest request) override { + bindings_.AddBinding(this, std::move(request)); + } + + private: + mojo::BindingSet<network::mojom::URLLoaderFactory> bindings_; + + DISALLOW_COPY_AND_ASSIGN(CacheMissNetworkURLLoaderFactory); +}; + // A SafeBrowingBlockingPage class that does not create windows. class TestSafeBrowsingBlockingPage : public SafeBrowsingBlockingPage { public: @@ -83,12 +118,14 @@ WebContents* web_contents, const GURL& main_frame_url, const UnsafeResourceList& unsafe_resources, - const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions& display_options) + const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions& display_options, + network::SharedURLLoaderFactory* url_loader_for_testing = nullptr) : SafeBrowsingBlockingPage(manager, web_contents, main_frame_url, unsafe_resources, - display_options) { + display_options, + url_loader_for_testing) { // Don't delay details at all for the unittest. SetThreatDetailsProceedDelayForTesting(0); DontCreateViewForTesting(); @@ -98,8 +135,17 @@ class TestSafeBrowsingBlockingPageFactory : public SafeBrowsingBlockingPageFactory { public: - TestSafeBrowsingBlockingPageFactory() { } - ~TestSafeBrowsingBlockingPageFactory() override {} + TestSafeBrowsingBlockingPageFactory() { + fake_url_loader_factory_ = + std::make_unique<CacheMissNetworkURLLoaderFactory>(); + url_loader_factory_wrapper_ = + base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( + fake_url_loader_factory_.get()); + } + ~TestSafeBrowsingBlockingPageFactory() override { + if (url_loader_factory_wrapper_) + url_loader_factory_wrapper_->Detach(); + } SafeBrowsingBlockingPage* CreateSafeBrowsingPage( BaseUIManager* manager, @@ -123,10 +169,15 @@ true, // should_open_links_in_new_tab true, // always_show_back_to_safety "cpn_safe_browsing" /* help_center_article_link */); - return new TestSafeBrowsingBlockingPage(manager, web_contents, - main_frame_url, unsafe_resources, - display_options); + return new TestSafeBrowsingBlockingPage( + manager, web_contents, main_frame_url, unsafe_resources, + display_options, url_loader_factory_wrapper_.get()); } + + private: + std::unique_ptr<CacheMissNetworkURLLoaderFactory> fake_url_loader_factory_; + scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> + url_loader_factory_wrapper_; }; class TestSafeBrowsingBlockingPageQuiet : public SafeBrowsingBlockingPage { @@ -228,6 +279,11 @@ } void SetUp() override { + // Need to use the network service path because we've removed the + // URLRequestContext path in src/chrome and unit_tests currently are running + // with network service disabled. https://crbug.com/966633 + feature_list_.InitAndEnableFeature(network::features::kNetworkService); + ChromeRenderViewHostTestHarness::SetUp(); if (is_incognito_) { @@ -237,13 +293,6 @@ SetContents(std::move(incognito_web_contents)); } - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext( - system_request_context_getter_.get()); - SafeBrowsingBlockingPage::RegisterFactory(&factory_); ResetUserResponse(); SafeBrowsingUIManager::CreateWhitelistForTesting(web_contents()); @@ -280,10 +329,13 @@ TestingBrowserProcess::GetGlobal()->safe_browsing_service()->ShutDown(); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr); SafeBrowsingBlockingPage::RegisterFactory(NULL); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(nullptr); - system_request_context_getter_ = nullptr; // Clean up singleton reference (crbug.com/110594). ThreatDetails::RegisterFactory(NULL); + + // Depends on LocalState from ChromeRenderViewHostTestHarness. + if (SystemNetworkContextManager::GetInstance()) + SystemNetworkContextManager::DeleteInstance(); + ChromeRenderViewHostTestHarness::TearDown(); } @@ -344,7 +396,6 @@ } scoped_refptr<TestSafeBrowsingUIManager> ui_manager_; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; #if BUILDFLAG(ENABLE_EXTENSIONS) extensions::TestEventRouter* test_event_router_; @@ -371,6 +422,7 @@ resource->threat_source = safe_browsing::ThreatSource::LOCAL_PVER3; } + base::test::ScopedFeatureList feature_list_; ScopedTestingLocalState scoped_testing_local_state_; UserResponse user_response_; TestSafeBrowsingBlockingPageFactory factory_; @@ -1051,13 +1103,6 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext( - system_request_context_getter_.get()); - SafeBrowsingBlockingPage::RegisterFactory(&factory_); SafeBrowsingUIManager::CreateWhitelistForTesting(web_contents()); @@ -1081,11 +1126,13 @@ TestingBrowserProcess::GetGlobal()->safe_browsing_service()->ShutDown(); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr); SafeBrowsingBlockingPage::RegisterFactory(NULL); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(nullptr); - system_request_context_getter_ = nullptr; // Clean up singleton reference (crbug.com/110594). ThreatDetails::RegisterFactory(NULL); + // Depends on LocalState from ChromeRenderViewHostTestHarness. + if (SystemNetworkContextManager::GetInstance()) + SystemNetworkContextManager::DeleteInstance(); + ChromeRenderViewHostTestHarness::TearDown(); } @@ -1140,7 +1187,6 @@ ScopedTestingLocalState scoped_testing_local_state_; UserResponse user_response_; TestSafeBrowsingBlockingQuietPageFactory factory_; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; }; // Tests showing a quiet blocking page for a malware page.
diff --git a/chrome/browser/safe_browsing/safe_browsing_service.cc b/chrome/browser/safe_browsing/safe_browsing_service.cc index 187214bf..9d73e7e3 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service.cc +++ b/chrome/browser/safe_browsing/safe_browsing_service.cc
@@ -136,14 +136,9 @@ bool result = base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); DCHECK(result); - if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) { - url_request_context_getter_ = new SafeBrowsingURLRequestContextGetter( - g_browser_process->system_request_context(), user_data_dir); - } - network_context_ = std::make_unique<safe_browsing::SafeBrowsingNetworkContext>( - url_request_context_getter_, user_data_dir, + nullptr, user_data_dir, base::BindRepeating(&SafeBrowsingService::CreateNetworkContextParams, base::Unretained(this))); @@ -186,30 +181,8 @@ services_delegate_->ShutdownServices(); - // Make sure to destruct SafeBrowsingNetworkContext first before - // |url_request_context_getter_|, as they both post tasks to the IO thread. We - // want the underlying NetworkContext C++ class to be torn down first so that - // it destroys any URLLoaders in flight. network_context_->ServiceShuttingDown(); proxy_config_monitor_.reset(); - - if (!url_request_context_getter_) - return; - - // Since URLRequestContextGetters are refcounted, can't count on clearing - // |url_request_context_getter_| to delete it, so need to shut it down first, - // which will cancel any requests that are currently using it, and prevent - // new requests from using it as well. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO, NonNestable()}, - base::BindOnce(&SafeBrowsingURLRequestContextGetter::ServiceShuttingDown, - url_request_context_getter_)); - - // Release the URLRequestContextGetter after passing it to the IOThread. It - // has to be released now rather than in the destructor because it can only - // be deleted on the IOThread, and the SafeBrowsingService outlives the IO - // thread. - url_request_context_getter_ = nullptr; } scoped_refptr<net::URLRequestContextGetter> @@ -515,7 +488,7 @@ network::mojom::NetworkContextParamsPtr SafeBrowsingService::CreateNetworkContextParams() { - auto params = g_browser_process->system_network_context_manager() + auto params = SystemNetworkContextManager::GetInstance() ->CreateDefaultNetworkContextParams(); if (!proxy_config_monitor_) { proxy_config_monitor_ =
diff --git a/chrome/browser/safe_browsing/safe_browsing_service.h b/chrome/browser/safe_browsing/safe_browsing_service.h index 2eb6375..4bf2c2f 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service.h +++ b/chrome/browser/safe_browsing/safe_browsing_service.h
@@ -267,17 +267,9 @@ // use. network::mojom::NetworkContextParamsPtr CreateNetworkContextParams(); - // The SafeBrowsingURLRequestContextGetter used to access - // |url_request_context_|. Accessed on UI thread. - // This is only valid if the network service is disabled. - scoped_refptr<SafeBrowsingURLRequestContextGetter> - url_request_context_getter_; - std::unique_ptr<ProxyConfigMonitor> proxy_config_monitor_; - // If the network service is disabled, this is a wrapper around - // |url_request_context_getter_|. Otherwise it's what owns the - // URLRequestContext inside the network service. This is used by + // This owns the URLRequestContext inside the network service. This is used by // SimpleURLLoader for safe browsing requests. std::unique_ptr<safe_browsing::SafeBrowsingNetworkContext> network_context_;
diff --git a/chrome/browser/safe_browsing/telemetry/android/android_telemetry_service_unittest.cc b/chrome/browser/safe_browsing/telemetry/android/android_telemetry_service_unittest.cc index 4013bde..b27e622e 100644 --- a/chrome/browser/safe_browsing/telemetry/android/android_telemetry_service_unittest.cc +++ b/chrome/browser/safe_browsing/telemetry/android/android_telemetry_service_unittest.cc
@@ -54,12 +54,6 @@ void SetUp() override { browser_process_ = TestingBrowserProcess::GetGlobal(); - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - browser_process_->SetSystemRequestContext( - system_request_context_getter_.get()); safe_browsing::SafeBrowsingServiceInterface::RegisterFactory( GetSafeBrowsingServiceFactory()); // TODO(crbug/925153): Port consumers of the |sb_service_| to use @@ -108,7 +102,6 @@ std::unique_ptr<TestingProfile> profile_; scoped_refptr<safe_browsing::SafeBrowsingService> sb_service_; base::test::ScopedFeatureList scoped_feature_list_; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; std::unique_ptr<AndroidTelemetryService> telemetry_service_; };
diff --git a/chrome/browser/safe_browsing/test_safe_browsing_database_helper.cc b/chrome/browser/safe_browsing/test_safe_browsing_database_helper.cc index 6220882..b52ff49 100644 --- a/chrome/browser/safe_browsing/test_safe_browsing_database_helper.cc +++ b/chrome/browser/safe_browsing/test_safe_browsing_database_helper.cc
@@ -56,7 +56,7 @@ std::unique_ptr<safe_browsing::StoreMap> store_map) override { const base::FilePath base_store_path(FILE_PATH_LITERAL("UrlDb.store")); for (const auto& id : lists_to_insert_) { - if (!base::ContainsKey(*store_map, id)) { + if (!base::Contains(*store_map, id)) { const base::FilePath store_path = base_store_path.InsertBeforeExtensionASCII(base::StringPrintf( " (%d)", base::GetUniquePathNumber( @@ -145,5 +145,5 @@ bool TestSafeBrowsingDatabaseHelper::HasListSynced( const safe_browsing::ListIdentifier& list_id) { - return base::ContainsValue(v4_db_factory_->lists(), list_id); + return base::Contains(v4_db_factory_->lists(), list_id); }
diff --git a/chrome/browser/safe_browsing/ui_manager_unittest.cc b/chrome/browser/safe_browsing/ui_manager_unittest.cc index 75f2223..bd8402f 100644 --- a/chrome/browser/safe_browsing/ui_manager_unittest.cc +++ b/chrome/browser/safe_browsing/ui_manager_unittest.cc
@@ -7,10 +7,13 @@ #include "base/bind.h" #include "base/run_loop.h" #include "base/task/post_task.h" +#include "base/test/scoped_feature_list.h" +#include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h" #include "chrome/browser/safe_browsing/test_safe_browsing_service.h" #include "chrome/browser/safe_browsing/ui_manager.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" @@ -27,6 +30,7 @@ #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/web_contents_tester.h" #include "net/url_request/url_request_test_util.h" +#include "services/network/public/cpp/features.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -76,24 +80,24 @@ class SafeBrowsingUIManagerTest : public ChromeRenderViewHostTestHarness { public: SafeBrowsingUIManagerTest() - : ChromeRenderViewHostTestHarness( - content::TestBrowserThreadBundle::REAL_IO_THREAD), - ui_manager_(new SafeBrowsingUIManager(NULL)) {} + : scoped_testing_local_state_(TestingBrowserProcess::GetGlobal()) { + ui_manager_ = new SafeBrowsingUIManager(NULL); + } ~SafeBrowsingUIManagerTest() override {} void SetUp() override { + // Need to use the network service path because we've removed the + // URLRequestContext path in src/chrome and unit_tests currently are running + // with network service disabled. https://crbug.com/966633 + feature_list_.InitAndEnableFeature(network::features::kNetworkService); + ChromeRenderViewHostTestHarness::SetUp(); SafeBrowsingUIManager::CreateWhitelistForTesting(web_contents()); safe_browsing::TestSafeBrowsingServiceFactory sb_service_factory; auto* safe_browsing_service = sb_service_factory.CreateSafeBrowsingService(); - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext( - system_request_context_getter_.get()); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService( safe_browsing_service); g_browser_process->safe_browsing_service()->Initialize(); @@ -107,8 +111,11 @@ void TearDown() override { TestingBrowserProcess::GetGlobal()->safe_browsing_service()->ShutDown(); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(nullptr); - system_request_context_getter_ = nullptr; + + // Depends on LocalState from ChromeRenderViewHostTestHarness. + if (SystemNetworkContextManager::GetInstance()) + SystemNetworkContextManager::DeleteInstance(); + ChromeRenderViewHostTestHarness::TearDown(); } @@ -167,8 +174,9 @@ SafeBrowsingUIManager* ui_manager() { return ui_manager_.get(); } private: - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; scoped_refptr<SafeBrowsingUIManager> ui_manager_; + base::test::ScopedFeatureList feature_list_; + ScopedTestingLocalState scoped_testing_local_state_; }; // Leaks memory. https://crbug.com/755118
diff --git a/chrome/browser/search/BUILD.gn b/chrome/browser/search/BUILD.gn index 3fb355e..f93d86e 100644 --- a/chrome/browser/search/BUILD.gn +++ b/chrome/browser/search/BUILD.gn
@@ -54,7 +54,7 @@ compiled_action("generate_chrome_colors_info") { tool = ":generate_colors_info" outputs = [ - "$target_gen_dir/chrome_colors/", + "$target_gen_dir/chrome_colors/generated_color_info.h", ] args = rebase_path(outputs, root_build_dir) }
diff --git a/chrome/browser/search/chrome_colors/generate_colors_info.cc b/chrome/browser/search/chrome_colors/generate_colors_info.cc index f214cc8..5d4d439 100644 --- a/chrome/browser/search/chrome_colors/generate_colors_info.cc +++ b/chrome/browser/search/chrome_colors/generate_colors_info.cc
@@ -67,10 +67,6 @@ "\n" "#endif // CHROME_BROWSER_SEARCH_CHROME_COLORS_GENERATED_COLORS_INFO_H_\n"; -// Generated file name. -const base::FilePath::CharType kColorsInfoFilename[] = - FILE_PATH_LITERAL("generated_colors_info.h"); - // Returns hex string representation for the |color| in "#FFFFFF" format. std::string SkColorToHexString(SkColor color) { return base::StringPrintf("\"#%02X%02X%02X\"", SkColorGetR(color), @@ -119,10 +115,10 @@ base::ReplaceStringPlaceholders(kFileContentTemplate, subst, NULL); base::FilePath output_path = base::FilePath::FromUTF8Unsafe(output_dir); - if (!base::DirectoryExists(output_path)) - base::CreateDirectory(output_path); + base::FilePath directory = output_path.DirName(); + if (!base::DirectoryExists(directory)) + base::CreateDirectory(directory); - output_path = output_path.Append(kColorsInfoFilename); if (base::WriteFile(output_path, output.c_str(), static_cast<uint32_t>(output.size())) <= 0) { LOG(ERROR) << "Failed to write output to " << output_path;
diff --git a/chrome/browser/sessions/session_restore_stats_collector.cc b/chrome/browser/sessions/session_restore_stats_collector.cc index 0dddbca..7172f26 100644 --- a/chrome/browser/sessions/session_restore_stats_collector.cc +++ b/chrome/browser/sessions/session_restore_stats_collector.cc
@@ -5,7 +5,6 @@ #include "chrome/browser/sessions/session_restore_stats_collector.h" #include <string> -#include <utility> #include "base/metrics/histogram_macros.h" #include "base/strings/stringprintf.h" @@ -102,21 +101,25 @@ : tab_count(0u), tabs_deferred(0u), tabs_load_started(0u), - tabs_loaded(0u) {} + tabs_loaded(0u), + tab_first_paint_reason(PAINT_FINISHED_UMA_MAX) {} SessionRestoreStatsCollector::TabState::TabState( NavigationController* controller) : controller(controller), is_deferred(false), - loading_state(TAB_IS_NOT_LOADING) { -} + was_hidden_or_occluded(false), + loading_state(TAB_IS_NOT_LOADING), + observed_host(nullptr) {} SessionRestoreStatsCollector::SessionRestoreStatsCollector( const base::TimeTicks& restore_started, std::unique_ptr<StatsReportingDelegate> reporting_delegate) : done_tracking_non_deferred_tabs_(false), got_first_foreground_load_(false), - got_first_paint_(false), + waiting_for_first_paint_(true), + non_restored_tab_painted_first_(false), + hidden_or_occluded_tab_ignored_(false), restore_started_(restore_started), waiting_for_load_tab_count_(0u), loading_tab_count_(0u), @@ -267,7 +270,7 @@ // By default tabs transition to being tracked for paint events after the // load event has been seen. However, if the first paint event has already // been seen then this is not necessary and the tab can be removed. - if (got_first_paint_) + if (!waiting_for_first_paint_) RemoveTab(tab); break; @@ -278,17 +281,23 @@ // will arrive for tabs that the collector is not explicitly tracking. // Only process this event if first paint hasn't been seen and this is a - // paint of a visible tab. + // paint of a tab that has not been hidden or occluded. RenderWidgetHost* render_widget_host = Source<RenderWidgetHost>(source).ptr(); - if (!got_first_paint_ && render_widget_host->GetView() && + if (waiting_for_first_paint_ && render_widget_host->GetView() && render_widget_host->GetView()->IsShowing()) { - got_first_paint_ = true; TabState* tab_state = GetTabState(render_widget_host); if (tab_state) { + // Ignore first paint of a restored tab that was hidden or occluded + // before first paint. If an other restored tab is painted, its + // paint time will be recorded. + if (tab_state->was_hidden_or_occluded) { + hidden_or_occluded_tab_ignored_ = true; + break; + } // This is a paint for a tab that is explicitly being tracked so // update the statistics. Otherwise the host is for a tab that's not - // being tracked thus some other tab has visibility and has rendered + // being tracked. Thus some other tab has visibility and has rendered // and there's no point in tracking the time to first paint. This can // happen because the user opened a different tab or restored tabs // to an already existing browser and an existing tab was in the @@ -297,7 +306,10 @@ tick_clock_->NowTicks() - restore_started_; DCHECK(!done_tracking_non_deferred_tabs_); tab_loader_stats_.foreground_tab_first_paint = time_to_paint; + } else { + non_restored_tab_painted_first_ = true; } + waiting_for_first_paint_ = false; // Once first paint has been observed the entire to-paint tracking // mechanism is no longer needed. @@ -328,6 +340,21 @@ ReleaseIfDoneTracking(); } +void SessionRestoreStatsCollector::RenderWidgetHostVisibilityChanged( + content::RenderWidgetHost* widget_host, + bool became_visible) { + auto* tab_state = GetTabState(widget_host); + if (tab_state && !became_visible) + tab_state->was_hidden_or_occluded = true; +} + +void SessionRestoreStatsCollector::RenderWidgetHostDestroyed( + content::RenderWidgetHost* widget_host) { + auto* tab_state = GetTabState(widget_host); + if (tab_state) + tab_state->observed_host = nullptr; +} + void SessionRestoreStatsCollector::RemoveTab(NavigationController* tab) { // Stop observing this tab. registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED, @@ -336,10 +363,11 @@ Source<NavigationController>(tab)); registrar_.Remove(this, content::NOTIFICATION_LOAD_START, Source<NavigationController>(tab)); - auto tab_it = tabs_tracked_.find(tab); DCHECK(tab_it != tabs_tracked_.end()); TabState& tab_state = tab_it->second; + if (tab_state.observed_host) + tab_state.observed_host->RemoveObserver(this); // If this tab was waiting for a NOTIFICATION_LOAD_STOP event then update // the loading counts. @@ -360,15 +388,15 @@ if (tab_state.is_deferred) --deferred_tab_count_; - // Remove the tab from the |tracked_tabs_| map. + // Remove the tab from the tabs_tracked_| map. tabs_tracked_.erase(tab_it); // It is possible for all restored contents to be destroyed or forcibly // renavigated before a first paint has arrived. This can be detected by // tabs_tracked_ containing only deferred tabs. At this point the paint // mechanism can be disabled and stats collection will stop. - if (tabs_tracked_.size() == deferred_tab_count_ && !got_first_paint_) { - got_first_paint_ = true; + if (tabs_tracked_.size() == deferred_tab_count_ && waiting_for_first_paint_) { + waiting_for_first_paint_ = false; registrar_.Remove( this, content::NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_VISUAL_PROPERTIES, @@ -388,6 +416,10 @@ auto result = tabs_tracked_.insert(std::make_pair(tab, TabState(tab))); DCHECK(result.second); TabState* tab_state = &result.first->second; + // Register for RenderWidgetHostVisibilityChanged notifications for this tab. + tab_state->observed_host = GetRenderWidgetHost(tab); + if (tab_state->observed_host) + tab_state->observed_host->AddObserver(this); return tab_state; } @@ -404,8 +436,7 @@ SessionRestoreStatsCollector::TabState* SessionRestoreStatsCollector::GetTabState(RenderWidgetHost* tab) { for (auto& pair : tabs_tracked_) { - auto* rwh = GetRenderWidgetHost(pair.first); - if (rwh == tab) + if (pair.second.observed_host == tab) return &pair.second; } // It's possible for this lookup to fail as paint events can be received for @@ -435,9 +466,20 @@ void SessionRestoreStatsCollector::ReleaseIfDoneTracking() { // If non-deferred tabs are no longer being tracked then report tab loader // statistics. - if (!done_tracking_non_deferred_tabs_ && got_first_paint_ && + if (!done_tracking_non_deferred_tabs_ && !waiting_for_first_paint_ && waiting_for_load_tab_count_ == 0) { done_tracking_non_deferred_tabs_ = true; + if (!tab_loader_stats_.foreground_tab_first_paint.is_zero()) { + tab_loader_stats_.tab_first_paint_reason = PAINT_FINISHED_UMA_DONE; + } else if (non_restored_tab_painted_first_) { + tab_loader_stats_.tab_first_paint_reason = + PAINT_FINISHED_NON_RESTORED_TAB_PAINTED_FIRST; + } else if (hidden_or_occluded_tab_ignored_) { + tab_loader_stats_.tab_first_paint_reason = + PAINT_FINISHED_UMA_NO_COMPLETELY_VISIBLE_TABS; + } else { + tab_loader_stats_.tab_first_paint_reason = PAINT_FINISHED_UMA_NO_PAINT; + } reporting_delegate_->ReportTabLoaderStats(tab_loader_stats_); } @@ -513,13 +555,13 @@ } if (!tab_loader_stats.foreground_tab_first_paint.is_zero()) { - UMA_HISTOGRAM_CUSTOM_TIMES("SessionRestore.ForegroundTabFirstPaint3", + UMA_HISTOGRAM_CUSTOM_TIMES("SessionRestore.ForegroundTabFirstPaint4", tab_loader_stats.foreground_tab_first_paint, base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMinutes(16), 50); std::string time_for_count = base::StringPrintf( - "SessionRestore.ForegroundTabFirstPaint3_%u", + "SessionRestore.ForegroundTabFirstPaint4_%u", static_cast<unsigned int>(tab_loader_stats.tab_count)); base::HistogramBase* counter_for_count = base::Histogram::FactoryTimeGet( time_for_count, base::TimeDelta::FromMilliseconds(100), @@ -527,6 +569,9 @@ base::Histogram::kUmaTargetedHistogramFlag); counter_for_count->AddTime(tab_loader_stats.foreground_tab_first_paint); } + UMA_HISTOGRAM_ENUMERATION( + "SessionRestore.ForegroundTabFirstPaint4.FinishReason", + tab_loader_stats.tab_first_paint_reason, PAINT_FINISHED_UMA_MAX); if (!tab_loader_stats.non_deferred_tabs_loaded.is_zero()) { UMA_HISTOGRAM_CUSTOM_TIMES("SessionRestore.AllTabsLoaded",
diff --git a/chrome/browser/sessions/session_restore_stats_collector.h b/chrome/browser/sessions/session_restore_stats_collector.h index 555315d..40c5e01 100644 --- a/chrome/browser/sessions/session_restore_stats_collector.h +++ b/chrome/browser/sessions/session_restore_stats_collector.h
@@ -7,7 +7,9 @@ #include <stddef.h> #include <map> +#include <memory> #include <utility> +#include <vector> #include "base/callback_list.h" #include "base/macros.h" @@ -16,6 +18,7 @@ #include "chrome/browser/sessions/session_restore_delegate.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" +#include "content/public/browser/render_widget_host_observer.h" namespace content { class NavigationController; @@ -48,8 +51,25 @@ // Rethink the collection in these cases. class SessionRestoreStatsCollector : public content::NotificationObserver, + public content::RenderWidgetHostObserver, public base::RefCounted<SessionRestoreStatsCollector> { public: + // Recorded in SessionRestore.ForegroundTabFirstPaint4.FinishReason metric. + // Values other than PAINT_FINISHED_UMA_DONE indicate why FirstPaint time + // was not recorded. + enum SessionRestorePaintFinishReasonUma { + // SessionRestore.ForegroundTabFirstPaint4_XX successfully recorded. + PAINT_FINISHED_UMA_DONE = 0, + // No tabs were visible the whole time before first paint. + PAINT_FINISHED_UMA_NO_COMPLETELY_VISIBLE_TABS = 1, + // No restored tabs were painted. + PAINT_FINISHED_UMA_NO_PAINT = 2, + // A non-restored tab was painted first. + PAINT_FINISHED_NON_RESTORED_TAB_PAINTED_FIRST = 3, + // The size of this enum. Must be the last entry. + PAINT_FINISHED_UMA_MAX = 4, + }; + // Houses all of the statistics gathered by the SessionRestoreStatsCollector // while the underlying TabLoader is active. These statistics are all reported // at once via the reporting delegate. @@ -93,11 +113,14 @@ // The time elapsed between |restore_started| and reception of the first // NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_VISUAL_PROPERTIES event for // any of the tabs involved in the session restore. If this is zero it is - // because it has not been recorded (all visible tabs were closed or - // switched away from before they were painted). Corresponds to - // "SessionRestore.ForegroundTabFirstPaint3" and its _XX variants. + // because it has not been recorded (all restored tabs were closed or + // hidden before they were painted, or were never painted). Corresponds to + // "SessionRestore.ForegroundTabFirstPaint4" and its _XX variants. base::TimeDelta foreground_tab_first_paint; + // Whether we recorded |foreground_tab_first_paint| and if not, why. + SessionRestorePaintFinishReasonUma tab_first_paint_reason; + // The time taken for all non-deferred tabs to be loaded. This corresponds // to the "SessionRestore.AllTabsLoaded" metric and its _XX variants // (vaguely named for historical reasons, as it predates the concept of @@ -149,8 +172,15 @@ // Set to true if the tab has been deferred by the TabLoader. bool is_deferred; + // True if the tab was ever hidden or occluded during the restore process. + bool was_hidden_or_occluded; + // The current loading state of the tab. TabLoadingState loading_state; + + // RenderWidgetHost* SessionRestoreStatsCollector is observing for this tab, + // if any. + content::RenderWidgetHost* observed_host; }; // Maps a NavigationController to its state. This is the primary map and @@ -166,6 +196,13 @@ const content::NotificationSource& source, const content::NotificationDetails& details) override; + // RenderWidgetHostObserver: + void RenderWidgetHostVisibilityChanged(content::RenderWidgetHost* widget_host, + bool became_visible) override; + + void RenderWidgetHostDestroyed( + content::RenderWidgetHost* widget_host) override; + // Called when a tab is no longer tracked. This is called by the 'Observe' // notification callback. Takes care of unregistering all observers and // removing the tab from all internal data structures. @@ -198,8 +235,16 @@ // Has the time for foreground tab load been recorded? bool got_first_foreground_load_; - // Has the time for foreground tab paint been recorded? - bool got_first_paint_; + // False if the time for foreground tab paint been recorded, or no more + // non-deferred tabs are left to wait for, true otherwise. + bool waiting_for_first_paint_; + + // Won't record time for foreground tab paint because a non-restored + // tab was painted first. + bool non_restored_tab_painted_first_; + + // Got first paint of tab that was hidden or occluded before being painted. + bool hidden_or_occluded_tab_ignored_; // The time the restore process started. const base::TimeTicks restore_started_;
diff --git a/chrome/browser/sessions/session_restore_stats_collector_unittest.cc b/chrome/browser/sessions/session_restore_stats_collector_unittest.cc index f0a7c5c..e641ab0 100644 --- a/chrome/browser/sessions/session_restore_stats_collector_unittest.cc +++ b/chrome/browser/sessions/session_restore_stats_collector_unittest.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/sessions/session_restore_stats_collector.h" #include <stddef.h> +#include <memory> #include <utility> #include <vector> @@ -71,13 +72,16 @@ report_stats_collector_death_call_count_++; } - void ExpectReportTabLoaderStatsCalled(size_t tab_count, - size_t tabs_deferred, - size_t tabs_load_started, - size_t tabs_loaded, - int foreground_tab_first_loaded_ms, - int foreground_tab_first_paint_ms, - int non_deferred_tabs_loaded_ms) { + void ExpectReportTabLoaderStatsCalled( + size_t tab_count, + size_t tabs_deferred, + size_t tabs_load_started, + size_t tabs_loaded, + int foreground_tab_first_loaded_ms, + int foreground_tab_first_paint_ms, + int non_deferred_tabs_loaded_ms, + SessionRestoreStatsCollector::SessionRestorePaintFinishReasonUma + finish_reason) { EXPECT_LT(0u, report_tab_loader_stats_call_count_); report_tab_loader_stats_call_count_--; @@ -91,6 +95,7 @@ tab_loader_stats_.foreground_tab_first_paint); EXPECT_EQ(base::TimeDelta::FromMilliseconds(non_deferred_tabs_loaded_ms), tab_loader_stats_.non_deferred_tabs_loaded); + EXPECT_EQ(tab_loader_stats_.tab_first_paint_reason, finish_reason); } void ExpectReportTabDeferredCalled() { @@ -192,6 +197,7 @@ class TestSessionRestoreStatsCollector : public SessionRestoreStatsCollector { public: using SessionRestoreStatsCollector::Observe; + using SessionRestoreStatsCollector::RenderWidgetHostVisibilityChanged; TestSessionRestoreStatsCollector( std::unique_ptr<const base::TickClock> tick_clock, @@ -260,10 +266,12 @@ void Show(size_t tab_index) { restored_tabs_[tab_index].contents()->WasShown(); + GenerateRenderWidgetVisiblityChanged(tab_index, /*visible=*/true); } void Hide(size_t tab_index) { restored_tabs_[tab_index].contents()->WasHidden(); + GenerateRenderWidgetVisiblityChanged(tab_index, /*visible=*/false); } // Creates a restored tab backed by dummy WebContents/NavigationController/ @@ -322,6 +330,13 @@ content::NotificationService::NoDetails()); } + void GenerateRenderWidgetVisiblityChanged(size_t tab_index, bool visible) { + content::WebContents* contents = restored_tabs_[tab_index].contents(); + content::RenderWidgetHost* host = + contents->GetRenderWidgetHostView()->GetRenderWidgetHost(); + stats_collector_->RenderWidgetHostVisibilityChanged(host, visible); + } + // Defers a tab. void DeferTab(size_t tab_index) { content::WebContents* contents = restored_tabs_[tab_index].contents(); @@ -368,7 +383,9 @@ Tick(); // 2ms. GenerateLoadStop(0); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(1, 0, 1, 1, 2, 1, 2); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 1, 0, 1, 1, 2, 1, 2, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_DONE); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -390,7 +407,9 @@ Tick(); // 2ms. GenerateRenderWidgetHostDidUpdateBackingStore(0); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(1, 0, 1, 1, 1, 2, 1); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 1, 0, 1, 1, 1, 2, 1, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_DONE); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -434,7 +453,9 @@ Tick(); // 7ms. GenerateLoadStop(2); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(3, 0, 3, 3, 2, 1, 7); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 3, 0, 3, 3, 2, 1, 7, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_DONE); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -476,7 +497,9 @@ mock_reporting_delegate.EnsureNoUnexpectedCalls(); Tick(); // 6ms. GenerateLoadStop(2); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(3, 0, 3, 3, 2, 1, 6); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 3, 0, 3, 3, 2, 1, 6, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_DONE); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -504,7 +527,9 @@ // Foreground tab finishes loading and stats get reported. Tick(); // 2ms. GenerateLoadStop(0); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(2, 1, 1, 1, 2, 1, 2); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 2, 1, 1, 1, 2, 1, 2, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_DONE); mock_reporting_delegate.EnsureNoUnexpectedCalls(); // Background tab starts loading, paints and stops loading. This fires off a @@ -553,7 +578,10 @@ // stats to be emitted, but with empty foreground paint and load values. Tick(); // 3ms. GenerateRenderWidgetHostDidUpdateBackingStore(1); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(1, 0, 1, 1, 0, 0, 2); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 1, 0, 1, 1, 0, 0, 2, + SessionRestoreStatsCollector:: + PAINT_FINISHED_NON_RESTORED_TAB_PAINTED_FIRST); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -591,7 +619,95 @@ // stats to be emitted, but with an empty foreground paint value. Tick(); // 3ms. GenerateRenderWidgetHostDidUpdateBackingStore(1); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(1, 0, 1, 1, 1, 0, 1); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 1, 0, 1, 1, 1, 0, 1, + SessionRestoreStatsCollector:: + PAINT_FINISHED_NON_RESTORED_TAB_PAINTED_FIRST); + mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); +} + +// Test that if a single restored foreground tab is occluded at any point +// before first paint, the time to first paint is not recorded, and the +// FinishReason is PAINT_FINISHED_UMA_NO_COMPLETELY_VISIBLE_TABS. +TEST_F(SessionRestoreStatsCollectorTest, ForegroundTabOccluded) { + MockStatsReportingDelegate mock_reporting_delegate; + passthrough_reporting_delegate_->set_reporting_delegate( + &mock_reporting_delegate); + + CreateRestoredTab(/*is_active=*/true); + stats_collector_->TrackTabs(restored_tabs_); + mock_reporting_delegate.ExpectReportTabTimeSinceActiveCalled(1); + mock_reporting_delegate.ExpectReportTabSiteEngagementScoreCalled(1); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); + + // Load the foreground tab. + Tick(); // 1ms. + GenerateLoadStop(0); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); + + // Mark the tab as hidden/occluded. + GenerateRenderWidgetVisiblityChanged(0, /*visible=*/false); + Tick(); // 2ms. + + // Mark the tab as visible. + GenerateRenderWidgetVisiblityChanged(0, /*visible=*/true); + // Mark the tab as having painted. This should cause the + // stats to be emitted, but with an empty foreground paint value because it + // was not visible at one point during restore. + GenerateRenderWidgetHostDidUpdateBackingStore(0); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); + // Destroy the tab. + GenerateWebContentsDestroyed(0); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 1, 0, 1, 1, 1, 0, 1, + SessionRestoreStatsCollector:: + PAINT_FINISHED_UMA_NO_COMPLETELY_VISIBLE_TABS); + mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); +} + +// Test that if the first tab painted was hidden/occluded before first paint, +// the first paint time of the second tab to be painted is recorded. +TEST_F(SessionRestoreStatsCollectorTest, FirstOfTwoTabsOccluded) { + MockStatsReportingDelegate mock_reporting_delegate; + passthrough_reporting_delegate_->set_reporting_delegate( + &mock_reporting_delegate); + + CreateRestoredTab(/*is_active=*/true); + CreateRestoredTab(/*is_active=*/true); + stats_collector_->TrackTabs(restored_tabs_); + mock_reporting_delegate.ExpectReportTabTimeSinceActiveCalled(2); + mock_reporting_delegate.ExpectReportTabSiteEngagementScoreCalled(2); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); + + // Load the first tab. + Tick(); // 1ms. + GenerateLoadStop(0); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); + + // Mark the tab as hidden/occluded. + GenerateRenderWidgetVisiblityChanged(0, /*visible=*/false); + Tick(); // 2ms. + + // Mark the tab as visible. + GenerateRenderWidgetVisiblityChanged(0, /*visible=*/true); + // Mark the tab as having painted. Because it was occluded, + // no stat should be emitted. + GenerateRenderWidgetHostDidUpdateBackingStore(0); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); + + Tick(); // 3ms. + mock_reporting_delegate.EnsureNoUnexpectedCalls(); + Tick(); // 4ms. + Tick(); // 5ms. + // Mark the second tab as loaded and painted. + GenerateLoadStop(1); + mock_reporting_delegate.EnsureNoUnexpectedCalls(); + GenerateRenderWidgetHostDidUpdateBackingStore(1); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 2, 0, 2, 2, 1, 5, 5, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_DONE); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -609,7 +725,9 @@ // Destroy the tab. Expect all timings to be zero. GenerateWebContentsDestroyed(0); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(1, 0, 1, 0, 0, 0, 0); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 1, 0, 1, 0, 0, 0, 0, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_NO_PAINT); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -631,7 +749,9 @@ // Destroy the tab. Expect both load timings to be zero. GenerateWebContentsDestroyed(0); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(1, 0, 1, 0, 0, 1, 0); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 1, 0, 1, 0, 0, 1, 0, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_DONE); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -655,7 +775,9 @@ // Reload the tab. Expect the paint timing to be zero. Tick(); // 2 ms. GenerateLoadStart(0); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(1, 0, 1, 1, 1, 0, 1); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 1, 0, 1, 1, 1, 0, 1, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_NO_PAINT); mock_reporting_delegate.ExpectReportStatsCollectorDeathCalled(); mock_reporting_delegate.EnsureNoUnexpectedCalls(); } @@ -682,7 +804,9 @@ // with all zero timings. Tick(); // 2 ms. GenerateWebContentsDestroyed(0); - mock_reporting_delegate.ExpectReportTabLoaderStatsCalled(2, 1, 1, 0, 0, 0, 0); + mock_reporting_delegate.ExpectReportTabLoaderStatsCalled( + 2, 1, 1, 0, 0, 0, 0, + SessionRestoreStatsCollector::PAINT_FINISHED_UMA_NO_PAINT); mock_reporting_delegate.EnsureNoUnexpectedCalls(); // Destroy the background tab. The collector should release itself.
diff --git a/chrome/browser/shell_integration_linux_unittest.cc b/chrome/browser/shell_integration_linux_unittest.cc index d60897b..7ae9576e 100644 --- a/chrome/browser/shell_integration_linux_unittest.cc +++ b/chrome/browser/shell_integration_linux_unittest.cc
@@ -44,7 +44,7 @@ } bool GetVar(base::StringPiece variable_name, std::string* result) override { - if (base::ContainsKey(variables_, variable_name.as_string())) { + if (base::Contains(variables_, variable_name.as_string())) { *result = variables_[variable_name.as_string()]; return true; }
diff --git a/chrome/browser/shell_integration_mac.mm b/chrome/browser/shell_integration_mac.mm index 972263575..9a76d9b9 100644 --- a/chrome/browser/shell_integration_mac.mm +++ b/chrome/browser/shell_integration_mac.mm
@@ -69,17 +69,15 @@ // behind the Chrome window. The user never sees the dialog, and therefore // never confirms the change. Make the CoreServicesUIAgent active so the // confirmation dialog comes to the front. - if (base::mac::IsAtLeastOS10_10()) { - NSString* const kCoreServicesUIAgentBundleID = - @"com.apple.coreservices.uiagent"; + NSString* const kCoreServicesUIAgentBundleID = + @"com.apple.coreservices.uiagent"; - for (NSRunningApplication* application in - [[NSWorkspace sharedWorkspace] runningApplications]) { - if ([[application bundleIdentifier] - isEqualToString:kCoreServicesUIAgentBundleID]) { - [application activateWithOptions:NSApplicationActivateAllWindows]; - break; - } + for (NSRunningApplication* application in + [[NSWorkspace sharedWorkspace] runningApplications]) { + if ([[application bundleIdentifier] + isEqualToString:kCoreServicesUIAgentBundleID]) { + [application activateWithOptions:NSApplicationActivateAllWindows]; + break; } }
diff --git a/chrome/browser/signin/chrome_signin_proxying_url_loader_factory.cc b/chrome/browser/signin/chrome_signin_proxying_url_loader_factory.cc index a15602a..87c8f10 100644 --- a/chrome/browser/signin/chrome_signin_proxying_url_loader_factory.cc +++ b/chrome/browser/signin/chrome_signin_proxying_url_loader_factory.cc
@@ -229,11 +229,11 @@ bool HasHeader(const std::string& name) override { return (original_headers_.HasHeader(name) || modified_headers_->HasHeader(name)) && - !base::ContainsValue(*removed_headers_, name); + !base::Contains(*removed_headers_, name); } void RemoveRequestHeaderByName(const std::string& name) override { - if (!base::ContainsValue(*removed_headers_, name)) + if (!base::Contains(*removed_headers_, name)) removed_headers_->push_back(name); }
diff --git a/chrome/browser/signin/chrome_signin_url_loader_throttle.cc b/chrome/browser/signin/chrome_signin_url_loader_throttle.cc index 8d074f1..35c9e3f7 100644 --- a/chrome/browser/signin/chrome_signin_url_loader_throttle.cc +++ b/chrome/browser/signin/chrome_signin_url_loader_throttle.cc
@@ -49,11 +49,11 @@ bool HasHeader(const std::string& name) override { return (original_headers_.HasHeader(name) || modified_headers_->HasHeader(name)) && - !base::ContainsValue(*headers_to_remove_, name); + !base::Contains(*headers_to_remove_, name); } void RemoveRequestHeaderByName(const std::string& name) override { - if (!base::ContainsValue(*headers_to_remove_, name)) + if (!base::Contains(*headers_to_remove_, name)) headers_to_remove_->push_back(name); }
diff --git a/chrome/browser/site_isolation/site_per_process_interactive_browsertest.cc b/chrome/browser/site_isolation/site_per_process_interactive_browsertest.cc index ca8b10b8..b0ab624 100644 --- a/chrome/browser/site_isolation/site_per_process_interactive_browsertest.cc +++ b/chrome/browser/site_isolation/site_per_process_interactive_browsertest.cc
@@ -635,7 +635,7 @@ std::vector<std::string> response_params = base::SplitString( response, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (response_params[0] == "fullscreenchange") { - EXPECT_TRUE(base::ContainsKey(remaining_events, response_params[1])); + EXPECT_TRUE(base::Contains(remaining_events, response_params[1])); remaining_events.erase(response_params[1]); } else if (response_params[0] == "resize") { resize_validated = true;
diff --git a/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc b/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc index c992625e..9f13a66 100644 --- a/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc +++ b/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
@@ -262,7 +262,7 @@ } bool SpellcheckCustomDictionary::HasWord(const std::string& word) const { - return base::ContainsKey(words_, word); + return base::Contains(words_, word); } void SpellcheckCustomDictionary::AddObserver(Observer* observer) {
diff --git a/chrome/browser/spellchecker/spellcheck_service.cc b/chrome/browser/spellchecker/spellcheck_service.cc index 0e200c5..f3791a0 100644 --- a/chrome/browser/spellchecker/spellcheck_service.cc +++ b/chrome/browser/spellchecker/spellcheck_service.cc
@@ -398,7 +398,7 @@ std::vector<std::string> filtered_dictionaries; for (const auto& dictionary : dictionaries) { - if (base::ContainsValue(accept_languages, dictionary)) { + if (base::Contains(accept_languages, dictionary)) { filtered_dictionaries.push_back(dictionary); } }
diff --git a/chrome/browser/spellchecker/spellcheck_service_unittest.cc b/chrome/browser/spellchecker/spellcheck_service_unittest.cc index 2e7e090..c2cab60 100644 --- a/chrome/browser/spellchecker/spellcheck_service_unittest.cc +++ b/chrome/browser/spellchecker/spellcheck_service_unittest.cc
@@ -45,7 +45,7 @@ for (const auto& language : languages) { dictionary.language = language; dictionary.used_for_spellcheck = - base::ContainsValue(used_for_spellcheck, language); + base::Contains(used_for_spellcheck, language); expected_dictionaries.push_back(dictionary); } }
diff --git a/chrome/browser/ssl/chrome_mock_cert_verifier.cc b/chrome/browser/ssl/chrome_mock_cert_verifier.cc index a71d933..9dc24e3 100644 --- a/chrome/browser/ssl/chrome_mock_cert_verifier.cc +++ b/chrome/browser/ssl/chrome_mock_cert_verifier.cc
@@ -12,12 +12,10 @@ void ChromeMockCertVerifier::SetUpInProcessBrowserTestFixture() { ContentMockCertVerifier::SetUpInProcessBrowserTestFixture(); - IOThread::SetCertVerifierForTesting(mock_cert_verifier_internal()); ProfileIOData::SetCertVerifierForTesting(mock_cert_verifier_internal()); } void ChromeMockCertVerifier::TearDownInProcessBrowserTestFixture() { ContentMockCertVerifier::TearDownInProcessBrowserTestFixture(); - IOThread::SetCertVerifierForTesting(nullptr); ProfileIOData::SetCertVerifierForTesting(nullptr); }
diff --git a/chrome/browser/ssl/chrome_ssl_host_state_delegate.cc b/chrome/browser/ssl/chrome_ssl_host_state_delegate.cc index 09744085..514bc60d 100644 --- a/chrome/browser/ssl/chrome_ssl_host_state_delegate.cc +++ b/chrome/browser/ssl/chrome_ssl_host_state_delegate.cc
@@ -405,9 +405,9 @@ auto entry = BrokenHostEntry(host, child_id); switch (content_type) { case MIXED_CONTENT: - return base::ContainsKey(ran_mixed_content_hosts_, entry); + return base::Contains(ran_mixed_content_hosts_, entry); case CERT_ERRORS_CONTENT: - return base::ContainsKey(ran_content_with_cert_errors_hosts_, entry); + return base::Contains(ran_content_with_cert_errors_hosts_, entry); } NOTREACHED(); return false;
diff --git a/chrome/browser/subresource_filter/subresource_filter_abusive_unittest.cc b/chrome/browser/subresource_filter/subresource_filter_abusive_unittest.cc index 76dd005..26e05ae 100644 --- a/chrome/browser/subresource_filter/subresource_filter_abusive_unittest.cc +++ b/chrome/browser/subresource_filter/subresource_filter_abusive_unittest.cc
@@ -96,7 +96,7 @@ bool DidSendConsoleMessage(const std::string& message) { const auto& messages = content::RenderFrameHostTester::For(main_rfh())->GetConsoleMessages(); - return base::ContainsValue(messages, message); + return base::Contains(messages, message); } protected:
diff --git a/chrome/browser/subresource_filter/subresource_filter_test_harness.cc b/chrome/browser/subresource_filter/subresource_filter_test_harness.cc index 68d417f..86ef164 100644 --- a/chrome/browser/subresource_filter/subresource_filter_test_harness.cc +++ b/chrome/browser/subresource_filter/subresource_filter_test_harness.cc
@@ -54,13 +54,6 @@ NavigateAndCommit(GURL("https://example.first")); - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext( - system_request_context_getter_.get()); - // Set up safe browsing service with the fake database manager. // // TODO(csharrison): This is a bit ugly. See if the instructions in @@ -120,8 +113,6 @@ // all cleanup related to these classes actually happens. TestingBrowserProcess::GetGlobal()->SetRulesetService(nullptr); TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(nullptr); - system_request_context_getter_ = nullptr; base::RunLoop().RunUntilIdle();
diff --git a/chrome/browser/subresource_filter/subresource_filter_test_harness.h b/chrome/browser/subresource_filter/subresource_filter_test_harness.h index 46b7b80..c6c8f5c3 100644 --- a/chrome/browser/subresource_filter/subresource_filter_test_harness.h +++ b/chrome/browser/subresource_filter/subresource_filter_test_harness.h
@@ -17,10 +17,6 @@ class GURL; class SubresourceFilterContentSettingsManager; -namespace net { -class URLRequestContextGetter; -} // namespace net - namespace content { class RenderFrameHost; } // namespace content @@ -74,7 +70,6 @@ scoped_configuration_; scoped_refptr<FakeSafeBrowsingDatabaseManager> fake_safe_browsing_database_; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; DISALLOW_COPY_AND_ASSIGN(SubresourceFilterTestHarness); };
diff --git a/chrome/browser/supervised_user/supervised_user_url_filter.cc b/chrome/browser/supervised_user/supervised_user_url_filter.cc index 1c2678e..adeaa3c 100644 --- a/chrome/browser/supervised_user/supervised_user_url_filter.cc +++ b/chrome/browser/supervised_user/supervised_user_url_filter.cc
@@ -339,7 +339,7 @@ static const base::NoDestructor<base::flat_set<GURL>> kWhitelistedOrigins( base::flat_set<GURL>({GURL(kFamiliesUrl).GetOrigin(), GURL(kFamiliesSecureUrl).GetOrigin()})); - if (base::ContainsKey(*kWhitelistedOrigins, effective_url.GetOrigin())) + if (base::Contains(*kWhitelistedOrigins, effective_url.GetOrigin())) return ALLOW; // Check Play Store terms of service.
diff --git a/chrome/browser/sync/sessions/browser_list_router_helper_unittest.cc b/chrome/browser/sync/sessions/browser_list_router_helper_unittest.cc index 973629d..4449039 100644 --- a/chrome/browser/sync/sessions/browser_list_router_helper_unittest.cc +++ b/chrome/browser/sync/sessions/browser_list_router_helper_unittest.cc
@@ -72,12 +72,12 @@ AddTab(browser_2.get(), gurl_2); std::vector<GURL>* handler_1_urls = handler_1.seen_urls(); - EXPECT_TRUE(base::ContainsValue(*handler_1_urls, gurl_1)); - EXPECT_FALSE(base::ContainsValue(*handler_1_urls, gurl_2)); + EXPECT_TRUE(base::Contains(*handler_1_urls, gurl_1)); + EXPECT_FALSE(base::Contains(*handler_1_urls, gurl_2)); std::vector<GURL>* handler_2_urls = handler_2.seen_urls(); - EXPECT_TRUE(base::ContainsValue(*handler_2_urls, gurl_2)); - EXPECT_FALSE(base::ContainsValue(*handler_2_urls, gurl_1)); + EXPECT_TRUE(base::Contains(*handler_2_urls, gurl_2)); + EXPECT_FALSE(base::Contains(*handler_2_urls, gurl_1)); // Add a browser for each profile. std::unique_ptr<BrowserWindow> window_3(CreateBrowserWindow()); @@ -94,12 +94,12 @@ AddTab(new_browser_in_second_profile.get(), gurl_4); handler_1_urls = handler_1.seen_urls(); - EXPECT_TRUE(base::ContainsValue(*handler_1_urls, gurl_3)); - EXPECT_FALSE(base::ContainsValue(*handler_1_urls, gurl_4)); + EXPECT_TRUE(base::Contains(*handler_1_urls, gurl_3)); + EXPECT_FALSE(base::Contains(*handler_1_urls, gurl_4)); handler_2_urls = handler_2.seen_urls(); - EXPECT_TRUE(base::ContainsValue(*handler_2_urls, gurl_4)); - EXPECT_FALSE(base::ContainsValue(*handler_2_urls, gurl_3)); + EXPECT_TRUE(base::Contains(*handler_2_urls, gurl_4)); + EXPECT_FALSE(base::Contains(*handler_2_urls, gurl_3)); // Cleanup needed for manually created browsers so they don't complain about // having open tabs when destructing.
diff --git a/chrome/browser/sync/test/integration/two_client_autofill_sync_test.cc b/chrome/browser/sync/test/integration/two_client_autofill_sync_test.cc index f206f0d..fc10f85 100644 --- a/chrome/browser/sync/test/integration/two_client_autofill_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_autofill_sync_test.cc
@@ -187,8 +187,9 @@ LOCAL_DELETION, 0); } +// Flaky on all platform. See crbug.com/971666 IN_PROC_BROWSER_TEST_F(TwoClientAutofillProfileSyncTest, - AddDuplicateProfiles_OneIsVerified) { + DISABLED_AddDuplicateProfiles_OneIsVerified) { ASSERT_TRUE(SetupClients()); base::HistogramTester histograms;
diff --git a/chrome/browser/task_manager/mock_web_contents_task_manager.cc b/chrome/browser/task_manager/mock_web_contents_task_manager.cc index 612b6b2..c11f0d0 100644 --- a/chrome/browser/task_manager/mock_web_contents_task_manager.cc +++ b/chrome/browser/task_manager/mock_web_contents_task_manager.cc
@@ -19,13 +19,13 @@ void MockWebContentsTaskManager::TaskAdded(Task* task) { DCHECK(task); - DCHECK(!base::ContainsValue(tasks_, task)); + DCHECK(!base::Contains(tasks_, task)); tasks_.push_back(task); } void MockWebContentsTaskManager::TaskRemoved(Task* task) { DCHECK(task); - DCHECK(base::ContainsValue(tasks_, task)); + DCHECK(base::Contains(tasks_, task)); tasks_.erase(std::find(tasks_.begin(), tasks_.end(), task)); }
diff --git a/chrome/browser/task_manager/providers/fallback_task_provider.cc b/chrome/browser/task_manager/providers/fallback_task_provider.cc index 757623a..f510b47 100644 --- a/chrome/browser/task_manager/providers/fallback_task_provider.cc +++ b/chrome/browser/task_manager/providers/fallback_task_provider.cc
@@ -54,7 +54,7 @@ for (const auto& source : sources_) { task_of_url_request = source->subprovider()->GetTaskOfUrlRequest(child_id, route_id); - if (base::ContainsValue(shown_tasks_, task_of_url_request)) + if (base::Contains(shown_tasks_, task_of_url_request)) return task_of_url_request; } return nullptr; @@ -164,7 +164,7 @@ void FallbackTaskProvider::OnTaskUnresponsive(Task* task) { DCHECK(task); - if (base::ContainsValue(shown_tasks_, task)) + if (base::Contains(shown_tasks_, task)) NotifyObserverTaskUnresponsive(task); }
diff --git a/chrome/browser/task_manager/providers/fallback_task_provider_unittest.cc b/chrome/browser/task_manager/providers/fallback_task_provider_unittest.cc index 2bc257d..c847db2 100644 --- a/chrome/browser/task_manager/providers/fallback_task_provider_unittest.cc +++ b/chrome/browser/task_manager/providers/fallback_task_provider_unittest.cc
@@ -90,12 +90,12 @@ // task_manager::TaskProviderObserver: void TaskAdded(Task* task) override { - EXPECT_FALSE(base::ContainsValue(seen_tasks_, task)); + EXPECT_FALSE(base::Contains(seen_tasks_, task)); seen_tasks_.emplace_back(task); } void TaskRemoved(Task* task) override { - EXPECT_TRUE(base::ContainsValue(seen_tasks_, task)); + EXPECT_TRUE(base::Contains(seen_tasks_, task)); base::Erase(seen_tasks_, task); }
diff --git a/chrome/browser/task_manager/providers/service_worker_task_provider.cc b/chrome/browser/task_manager/providers/service_worker_task_provider.cc index dc31c22..1464670 100644 --- a/chrome/browser/task_manager/providers/service_worker_task_provider.cc +++ b/chrome/browser/task_manager/providers/service_worker_task_provider.cc
@@ -56,11 +56,11 @@ #if DCHECK_IS_ON() if (is_running) { - DCHECK(!base::ContainsKey(service_worker_task_map_, key) && - !base::ContainsKey(tasks_to_be_created_, key)); + DCHECK(!base::Contains(service_worker_task_map_, key) && + !base::Contains(tasks_to_be_created_, key)); } else { - DCHECK(base::ContainsKey(service_worker_task_map_, key) || - base::ContainsKey(tasks_to_be_created_, key)); + DCHECK(base::Contains(service_worker_task_map_, key) || + base::Contains(tasks_to_be_created_, key)); } #endif // DCHECK_IS_ON() @@ -166,7 +166,7 @@ const ServiceWorkerTaskKey key(context, service_worker_running_info.version_id); - DCHECK(!base::ContainsKey(service_worker_task_map_, key)); + DCHECK(!base::Contains(service_worker_task_map_, key)); auto* host = content::RenderProcessHost::FromID( service_worker_running_info.process_id);
diff --git a/chrome/browser/themes/browser_theme_pack.cc b/chrome/browser/themes/browser_theme_pack.cc index dbd7574..bb2bb13 100644 --- a/chrome/browser/themes/browser_theme_pack.cc +++ b/chrome/browser/themes/browser_theme_pack.cc
@@ -874,7 +874,7 @@ : CustomThemeSupplier(theme_type) { scale_factors_ = ui::GetSupportedScaleFactors(); // On Windows HiDPI SCALE_FACTOR_100P may not be supported by default. - if (!base::ContainsValue(scale_factors_, ui::SCALE_FACTOR_100P)) + if (!base::Contains(scale_factors_, ui::SCALE_FACTOR_100P)) scale_factors_.push_back(ui::SCALE_FACTOR_100P); } @@ -956,7 +956,7 @@ for (size_t i = 0; i < kColorsArrayLength; ++i) { if (colors_[i].id == id) { *color = colors_[i].color; - if (base::ContainsKey(*kOpaqueColors, id)) + if (base::Contains(*kOpaqueColors, id)) *color = SkColorSetA(*color, SK_AlphaOPAQUE); return true; }
diff --git a/chrome/browser/transition_manager/full_browser_transition_manager.cc b/chrome/browser/transition_manager/full_browser_transition_manager.cc index e5b0f4180..4beed95 100644 --- a/chrome/browser/transition_manager/full_browser_transition_manager.cc +++ b/chrome/browser/transition_manager/full_browser_transition_manager.cc
@@ -37,7 +37,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); SimpleFactoryKey* key = profile->GetProfileKey(); - DCHECK(!base::ContainsKey(simple_key_to_profile_, key)); + DCHECK(!base::Contains(simple_key_to_profile_, key)); // Register the mapping so that it can be used if deferred callbacks are added // later.
diff --git a/chrome/browser/translate/translate_manager_render_view_host_unittest.cc b/chrome/browser/translate/translate_manager_render_view_host_unittest.cc index 7aaeacb..9ad8df0 100644 --- a/chrome/browser/translate/translate_manager_render_view_host_unittest.cc +++ b/chrome/browser/translate/translate_manager_render_view_host_unittest.cc
@@ -581,7 +581,7 @@ const std::string& lang = server_languages[i]; if (lang == "xx") continue; - EXPECT_TRUE(base::ContainsValue(current_supported_languages, lang)) + EXPECT_TRUE(base::Contains(current_supported_languages, lang)) << "lang=" << lang; } }
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 6c7069a..d88a40b2 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -906,6 +906,15 @@ "hid/hid_chooser.h", "hung_renderer/hung_renderer_core.cc", "hung_renderer/hung_renderer_core.h", + "in_product_help/active_tab_tracker.cc", + "in_product_help/active_tab_tracker.h", + "in_product_help/in_product_help.h", + "in_product_help/reopen_tab_in_product_help.cc", + "in_product_help/reopen_tab_in_product_help.h", + "in_product_help/reopen_tab_in_product_help_factory.cc", + "in_product_help/reopen_tab_in_product_help_factory.h", + "in_product_help/reopen_tab_in_product_help_trigger.cc", + "in_product_help/reopen_tab_in_product_help_trigger.h", "intent_picker_tab_helper.cc", "intent_picker_tab_helper.h", "javascript_dialogs/javascript_dialog_views.cc", @@ -2624,6 +2633,8 @@ "views/feature_promos/feature_promo_bubble_timeout.h", "views/feature_promos/feature_promo_bubble_view.cc", "views/feature_promos/feature_promo_bubble_view.h", + "views/feature_promos/reopen_tab_promo_controller.cc", + "views/feature_promos/reopen_tab_promo_controller.h", "views/find_bar_host.cc", "views/find_bar_host.h", "views/find_bar_view.cc", @@ -3544,22 +3555,6 @@ ] } - if (enable_desktop_in_product_help) { - sources += [ - "in_product_help/active_tab_tracker.cc", - "in_product_help/active_tab_tracker.h", - "in_product_help/in_product_help.h", - "in_product_help/reopen_tab_in_product_help.cc", - "in_product_help/reopen_tab_in_product_help.h", - "in_product_help/reopen_tab_in_product_help_factory.cc", - "in_product_help/reopen_tab_in_product_help_factory.h", - "in_product_help/reopen_tab_in_product_help_trigger.cc", - "in_product_help/reopen_tab_in_product_help_trigger.h", - "views/feature_promos/reopen_tab_promo_controller.cc", - "views/feature_promos/reopen_tab_promo_controller.h", - ] - } - if (enable_extensions) { deps += [ "//apps",
diff --git a/chrome/browser/ui/android/content_settings/popup_blocked_infobar_delegate.cc b/chrome/browser/ui/android/content_settings/popup_blocked_infobar_delegate.cc index b7f1e16..9f14487 100644 --- a/chrome/browser/ui/android/content_settings/popup_blocked_infobar_delegate.cc +++ b/chrome/browser/ui/android/content_settings/popup_blocked_infobar_delegate.cc
@@ -8,6 +8,7 @@ #include <utility> #include "chrome/browser/android/android_theme_resources.h" +#include "chrome/browser/android/feature_utilities.h" #include "chrome/browser/content_settings/chrome_content_settings_utils.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/infobars/infobar_service.h" @@ -92,12 +93,25 @@ if (!can_show_popups_) return 0; - return BUTTON_OK; + int buttons = BUTTON_OK; + if (chrome::android::IsNoTouchModeEnabled()) + buttons |= BUTTON_CANCEL; + + return buttons; } base::string16 PopupBlockedInfoBarDelegate::GetButtonLabel( InfoBarButton button) const { - return l10n_util::GetStringUTF16(IDS_POPUPS_BLOCKED_INFOBAR_BUTTON_SHOW); + switch (button) { + case BUTTON_OK: + return l10n_util::GetStringUTF16(IDS_POPUPS_BLOCKED_INFOBAR_BUTTON_SHOW); + case BUTTON_CANCEL: + return l10n_util::GetStringUTF16(IDS_PERMISSION_DENY); + default: + NOTREACHED(); + break; + } + return base::string16(); } bool PopupBlockedInfoBarDelegate::Accept() {
diff --git a/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.cc b/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.cc index d85fcac..c948d85 100644 --- a/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.cc +++ b/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.cc
@@ -204,10 +204,8 @@ TabScrubber::GetInstance(); } - if (base::FeatureList::IsEnabled(ash::features::kKioskNextShell)) { + if (base::FeatureList::IsEnabled(ash::features::kKioskNextShell)) kiosk_next_shell_client_ = std::make_unique<KioskNextShellClient>(); - kiosk_next_shell_client_->Init(); - } } void ChromeBrowserMainExtraPartsAsh::PostBrowserStart() {
diff --git a/chrome/browser/ui/ash/kiosk_next_shell_client.cc b/chrome/browser/ui/ash/kiosk_next_shell_client.cc index 866454a..028991cb 100644 --- a/chrome/browser/ui/ash/kiosk_next_shell_client.cc +++ b/chrome/browser/ui/ash/kiosk_next_shell_client.cc
@@ -7,12 +7,15 @@ #include <utility> #include "apps/launcher.h" +#include "ash/public/interfaces/constants.mojom.h" #include "base/logging.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/common/extensions/extension_constants.h" -#include "components/account_id/account_id.h" +#include "content/public/common/service_manager_connection.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/constants.h" +#include "mojo/public/cpp/bindings/interface_request.h" +#include "services/service_manager/public/cpp/connector.h" namespace { @@ -23,16 +26,20 @@ KioskNextShellClient::KioskNextShellClient() { DCHECK(!g_kiosk_next_shell_client_instance); g_kiosk_next_shell_client_instance = this; + + ash::mojom::KioskNextShellControllerPtr kiosk_next_shell_controller; + content::ServiceManagerConnection::GetForProcess() + ->GetConnector() + ->BindInterface(ash::mojom::kServiceName, &kiosk_next_shell_controller); + + ash::mojom::KioskNextShellClientPtr client; + binding_.Bind(mojo::MakeRequest(&client)); + kiosk_next_shell_controller->SetClient(std::move(client)); } KioskNextShellClient::~KioskNextShellClient() { DCHECK_EQ(this, g_kiosk_next_shell_client_instance); g_kiosk_next_shell_client_instance = nullptr; - ash::KioskNextShellController::Get()->SetClientAndLaunchSession(nullptr); -} - -void KioskNextShellClient::Init() { - ash::KioskNextShellController::Get()->SetClientAndLaunchSession(this); } // static
diff --git a/chrome/browser/ui/ash/kiosk_next_shell_client.h b/chrome/browser/ui/ash/kiosk_next_shell_client.h index 081fc87..3a087171 100644 --- a/chrome/browser/ui/ash/kiosk_next_shell_client.h +++ b/chrome/browser/ui/ash/kiosk_next_shell_client.h
@@ -5,25 +5,27 @@ #ifndef CHROME_BROWSER_UI_ASH_KIOSK_NEXT_SHELL_CLIENT_H_ #define CHROME_BROWSER_UI_ASH_KIOSK_NEXT_SHELL_CLIENT_H_ -#include "ash/public/cpp/kiosk_next_shell.h" +#include "ash/public/interfaces/kiosk_next_shell.mojom.h" #include "base/macros.h" +#include "components/account_id/account_id.h" +#include "mojo/public/cpp/bindings/binding.h" -class KioskNextShellClient : public ash::KioskNextShellClient { +class KioskNextShellClient : public ash::mojom::KioskNextShellClient { public: KioskNextShellClient(); ~KioskNextShellClient() override; - void Init(); - // Returns the singleton KioskNextShellClient instance, if it exists. static KioskNextShellClient* Get(); - // ash::KioskNextShellClient: + // mojom::KioskNextShellClient: void LaunchKioskNextShell(const AccountId& account_id) override; bool has_launched() const { return has_launched_; } private: + mojo::Binding<ash::mojom::KioskNextShellClient> binding_{this}; + // True once the KioskNextShell has been launched. bool has_launched_ = false;
diff --git a/chrome/browser/ui/ash/system_tray_client.cc b/chrome/browser/ui/ash/system_tray_client.cc index 3fba3f8..959da4c 100644 --- a/chrome/browser/ui/ash/system_tray_client.cc +++ b/chrome/browser/ui/ash/system_tray_client.cc
@@ -4,9 +4,9 @@ #include "chrome/browser/ui/ash/system_tray_client.h" +#include "ash/public/cpp/locale_update_controller.h" #include "ash/public/cpp/system_tray.h" #include "ash/public/cpp/update_types.h" -#include "ash/public/interfaces/locale.mojom.h" #include "base/command_line.h" #include "base/logging.h" #include "base/memory/weak_ptr.h" @@ -184,7 +184,7 @@ } void SystemTrayClient::SetLocaleList( - std::vector<ash::mojom::LocaleInfoPtr> locale_list, + std::vector<ash::LocaleInfo> locale_list, const std::string& current_locale_iso_code) { system_tray_->SetLocaleList(std::move(locale_list), current_locale_iso_code); }
diff --git a/chrome/browser/ui/ash/system_tray_client.h b/chrome/browser/ui/ash/system_tray_client.h index fb681ff..1e9d5a2 100644 --- a/chrome/browser/ui/ash/system_tray_client.h +++ b/chrome/browser/ui/ash/system_tray_client.h
@@ -6,13 +6,13 @@ #define CHROME_BROWSER_UI_ASH_SYSTEM_TRAY_CLIENT_H_ #include "ash/public/cpp/system_tray_client.h" -#include "ash/public/interfaces/locale.mojom-forward.h" #include "base/macros.h" #include "chrome/browser/chromeos/system/system_clock_observer.h" #include "chrome/browser/upgrade_detector/upgrade_observer.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" namespace ash { +struct LocaleInfo; class SystemTray; enum class LoginStatus; enum class NotificationStyle; @@ -45,7 +45,7 @@ void SetPrimaryTrayEnabled(bool enabled); void SetPrimaryTrayVisible(bool visible); void SetPerformanceTracingIconVisible(bool visible); - void SetLocaleList(std::vector<ash::mojom::LocaleInfoPtr> locale_list, + void SetLocaleList(std::vector<ash::LocaleInfo> locale_list, const std::string& current_locale_iso_code); // ash::SystemTrayClient:
diff --git a/chrome/browser/ui/blocked_content/safe_browsing_triggered_popup_blocker_unittest.cc b/chrome/browser/ui/blocked_content/safe_browsing_triggered_popup_blocker_unittest.cc index 0dcc3856..73d4a641 100644 --- a/chrome/browser/ui/blocked_content/safe_browsing_triggered_popup_blocker_unittest.cc +++ b/chrome/browser/ui/blocked_content/safe_browsing_triggered_popup_blocker_unittest.cc
@@ -52,12 +52,6 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - system_request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext( - system_request_context_getter_.get()); // Set up safe browsing service with the fake database manager. // // TODO(csharrison): This is a bit ugly. See if the instructions in @@ -93,8 +87,6 @@ // all cleanup related to these classes actually happens. TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr); base::RunLoop().RunUntilIdle(); - TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(nullptr); - system_request_context_getter_ = nullptr; ChromeRenderViewHostTestHarness::TearDown(); } @@ -149,7 +141,6 @@ std::unique_ptr<base::test::ScopedFeatureList> scoped_feature_list_; scoped_refptr<FakeSafeBrowsingDatabaseManager> fake_safe_browsing_database_; SafeBrowsingTriggeredPopupBlocker* popup_blocker_ = nullptr; - scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingTriggeredPopupBlockerTest); };
diff --git a/chrome/browser/ui/browser.cc b/chrome/browser/ui/browser.cc index e9165bee..38ac6e4 100644 --- a/chrome/browser/ui/browser.cc +++ b/chrome/browser/ui/browser.cc
@@ -2717,7 +2717,7 @@ const BrowserList::BrowserSet& closing_browsers = BrowserList::GetInstance()->currently_closing_browsers(); - return base::ContainsKey(closing_browsers, this); + return base::Contains(closing_browsers, this); } bool Browser::ShouldStartShutdown() const {
diff --git a/chrome/browser/ui/browser_command_controller.cc b/chrome/browser/ui/browser_command_controller.cc index 66dc103..e4773b83 100644 --- a/chrome/browser/ui/browser_command_controller.cc +++ b/chrome/browser/ui/browser_command_controller.cc
@@ -85,7 +85,7 @@ #include "ui/base/ime/linux/text_edit_key_bindings_delegate_auralinux.h" #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/bookmark/bookmark_tracker.h" #include "chrome/browser/feature_engagement/bookmark/bookmark_tracker_factory.h" #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h" @@ -387,7 +387,7 @@ break; case IDC_NEW_TAB: { NewTab(browser_); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) // This is not in NewTab() to avoid tracking programmatic creation of new // tabs by extensions. auto* new_tab_tracker = @@ -497,7 +497,7 @@ SavePage(browser_); break; case IDC_BOOKMARK_PAGE: -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) feature_engagement::BookmarkTrackerFactory::GetInstance() ->GetForProfile(profile()) ->OnBookmarkAdded(); @@ -505,7 +505,7 @@ BookmarkCurrentPageAllowingExtensionOverrides(browser_); break; case IDC_BOOKMARK_ALL_TABS: -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) feature_engagement::BookmarkTrackerFactory::GetInstance() ->GetForProfile(profile()) ->OnBookmarkAdded(); @@ -1291,7 +1291,7 @@ // Go through all the command ids, skip the whitelisted ones. for (int id : command_updater->GetAllIds()) { - if (base::ContainsValue(kWhitelistedIds, id)) { + if (base::Contains(kWhitelistedIds, id)) { continue; } DCHECK(!command_updater->IsCommandEnabled(id));
diff --git a/chrome/browser/ui/browser_command_controller_browsertest.cc b/chrome/browser/ui/browser_command_controller_browsertest.cc index 49507cc2..97330e2 100644 --- a/chrome/browser/ui/browser_command_controller_browsertest.cc +++ b/chrome/browser/ui/browser_command_controller_browsertest.cc
@@ -152,7 +152,7 @@ // Go through all the command ids and make sure all non-whitelisted commands // are disabled. for (int id : command_updater->GetAllIds()) { - if (base::ContainsValue(kWhitelistedIds, id)) { + if (base::Contains(kWhitelistedIds, id)) { continue; } EXPECT_FALSE(command_updater->IsCommandEnabled(id));
diff --git a/chrome/browser/ui/browser_command_controller_interactive_browsertest.cc b/chrome/browser/ui/browser_command_controller_interactive_browsertest.cc index de54f37..126f466 100644 --- a/chrome/browser/ui/browser_command_controller_interactive_browsertest.cc +++ b/chrome/browser/ui/browser_command_controller_interactive_browsertest.cc
@@ -112,21 +112,11 @@ ASSERT_NO_FATAL_FAILURE(SendJsFullscreenShortcutAndWait()); ASSERT_NO_FATAL_FAILURE(SendShortcutsAndExpectPrevented()); -#if defined(OS_MACOSX) - // On 10.9 or earlier, sending the exit fullscreen shortcut will crash the - // binary. See http://crbug.com/740250. - if (base::mac::IsAtLeastOS10_10()) { - // Current page should exit browser fullscreen mode. - ASSERT_NO_FATAL_FAILURE(SendFullscreenShortcutAndWait()); - ASSERT_FALSE(IsActiveTabFullscreen()); - ASSERT_FALSE(IsInBrowserFullscreen()); - } -#else + // Current page should exit browser fullscreen mode. ASSERT_NO_FATAL_FAILURE(SendFullscreenShortcutAndWait()); ASSERT_FALSE(IsActiveTabFullscreen()); ASSERT_FALSE(IsInBrowserFullscreen()); -#endif ASSERT_NO_FATAL_FAILURE(FinishTestAndVerifyResult()); } @@ -142,12 +132,6 @@ #endif IN_PROC_BROWSER_TEST_F(BrowserCommandControllerInteractiveTest, MAYBE_ShortcutsShouldTakeEffectInBrowserFullscreen) { -#if defined(OS_MACOSX) - // On 10.9 or earlier, sending the exit fullscreen shortcut will crash the - // binary. See http://crbug.com/740250. - if (base::mac::IsAtMostOS10_9()) - return; -#endif ASSERT_NO_FATAL_FAILURE(SendShortcutsAndExpectNotPrevented(false)); }
diff --git a/chrome/browser/ui/browser_commands.cc b/chrome/browser/ui/browser_commands.cc index aa64b3d..0838033 100644 --- a/chrome/browser/ui/browser_commands.cc +++ b/chrome/browser/ui/browser_commands.cc
@@ -128,7 +128,7 @@ #include "components/rlz/rlz_tracker.h" // nogncheck #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/incognito_window/incognito_window_tracker.h" #include "chrome/browser/feature_engagement/incognito_window/incognito_window_tracker_factory.h" #endif @@ -608,7 +608,7 @@ } void NewIncognitoWindow(Profile* profile) { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) feature_engagement::IncognitoWindowTrackerFactory::GetInstance() ->GetForProfile(profile) ->OnIncognitoWindowOpened(); @@ -629,12 +629,10 @@ UMA_HISTOGRAM_ENUMERATION("Tab.NewTab", TabStripModel::NEW_TAB_COMMAND, TabStripModel::NEW_TAB_ENUM_COUNT); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) // Notify IPH that new tab was opened. auto* reopen_tab_iph = ReopenTabInProductHelpFactory::GetForProfile(browser->profile()); reopen_tab_iph->NewTabOpened(); -#endif if (browser->is_type_tabbed()) { AddTabAt(browser, GURL(), -1, true);
diff --git a/chrome/browser/ui/browser_tab_restorer.cc b/chrome/browser/ui/browser_tab_restorer.cc index 4ac02c8..deb5acb 100644 --- a/chrome/browser/ui/browser_tab_restorer.cc +++ b/chrome/browser/ui/browser_tab_restorer.cc
@@ -103,11 +103,9 @@ void RestoreTab(Browser* browser) { base::RecordAction(base::UserMetricsAction("RestoreTab")); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) auto* reopen_tab_iph = ReopenTabInProductHelpFactory::GetForProfile(browser->profile()); reopen_tab_iph->TabReopened(); -#endif sessions::TabRestoreService* service = TabRestoreServiceFactory::GetForProfile(browser->profile());
diff --git a/chrome/browser/ui/browser_window.h b/chrome/browser/ui/browser_window.h index 3b6db2e..3acdf53 100644 --- a/chrome/browser/ui/browser_window.h +++ b/chrome/browser/ui/browser_window.h
@@ -19,9 +19,9 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_bubble_type.h" +#include "chrome/browser/ui/in_product_help/in_product_help.h" #include "chrome/common/buildflags.h" #include "components/content_settings/core/common/content_settings_types.h" -#include "components/feature_engagement/buildflags.h" #include "components/signin/core/browser/signin_header_helper.h" #include "components/translate/core/common/translate_errors.h" #include "ui/base/base_window.h" @@ -32,10 +32,6 @@ #error This file should only be included on desktop. #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) -#include "chrome/browser/ui/in_product_help/in_product_help.h" -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - class Browser; class DownloadShelf; class ExclusiveAccessContext; @@ -465,10 +461,8 @@ const base::Callback<void(ImeWarningBubblePermissionStatus status)>& callback) = 0; -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) // Shows in-product help for the given feature. virtual void ShowInProductHelpPromo(InProductHelpFeature iph_feature) = 0; -#endif // Returns the platform-specific ID of the workspace the browser window // currently resides in.
diff --git a/chrome/browser/ui/login/login_handler_browsertest.cc b/chrome/browser/ui/login/login_handler_browsertest.cc index 2ff1513..ae8250c 100644 --- a/chrome/browser/ui/login/login_handler_browsertest.cc +++ b/chrome/browser/ui/login/login_handler_browsertest.cc
@@ -1702,4 +1702,43 @@ ASSERT_EQ(1u, observer.handlers().size()); } +// Tests that FTP auth prompts do not appear when credentials have been +// previously entered and cached. +IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, FtpAuthWithCache) { + net::SpawnedTestServer ftp_server( + net::SpawnedTestServer::TYPE_FTP, + base::FilePath(FILE_PATH_LITERAL("chrome/test/data/ftp"))); + ftp_server.set_no_anonymous_ftp_user(true); + ASSERT_TRUE(ftp_server.Start()); + + content::WebContents* contents = + browser()->tab_strip_model()->GetActiveWebContents(); + NavigationController* controller = &contents->GetController(); + LoginPromptBrowserTestObserver observer; + observer.Register(content::Source<NavigationController>(controller)); + + // Navigate to an FTP server and wait for the auth prompt to appear. + WindowedAuthNeededObserver auth_needed_waiter(controller); + ui_test_utils::NavigateToURL(browser(), ftp_server.GetURL("")); + auth_needed_waiter.Wait(); + ASSERT_EQ(1u, observer.handlers().size()); + + // Supply credentials and wait for the page to successfully load. + LoginHandler* handler = *observer.handlers().begin(); + WindowedAuthSuppliedObserver auth_supplied_waiter(controller); + handler->SetAuth(base::ASCIIToUTF16("chrome"), base::ASCIIToUTF16("chrome")); + auth_supplied_waiter.Wait(); + const base::string16 kExpectedTitle = base::ASCIIToUTF16("Index of /"); + content::TitleWatcher title_watcher(contents, kExpectedTitle); + EXPECT_EQ(kExpectedTitle, title_watcher.WaitAndGetTitle()); + + // Navigate away and then back to the FTP server. There should be no auth + // prompt because the credentials are cached. + ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); + content::TitleWatcher revisit_title_watcher(contents, kExpectedTitle); + ui_test_utils::NavigateToURL(browser(), ftp_server.GetURL("")); + EXPECT_EQ(kExpectedTitle, revisit_title_watcher.WaitAndGetTitle()); + EXPECT_EQ(0u, observer.handlers().size()); +} + } // namespace
diff --git a/chrome/browser/ui/omnibox/chrome_omnibox_client.cc b/chrome/browser/ui/omnibox/chrome_omnibox_client.cc index 1dfa25e..d5c7ea7 100644 --- a/chrome/browser/ui/omnibox/chrome_omnibox_client.cc +++ b/chrome/browser/ui/omnibox/chrome_omnibox_client.cc
@@ -78,7 +78,7 @@ #include "ui/gfx/vector_icon_types.h" #include "url/gurl.h" -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h" #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker_factory.h" #endif @@ -463,7 +463,7 @@ // We could go further to try to analyze the difference between the previous // and current URLs, but users edit URLs rarely enough that this is a // reasonable approximation. -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) if (controller_->GetLocationBarModel()->ShouldDisplayURL()) { feature_engagement::NewTabTrackerFactory::GetInstance() ->GetForProfile(profile_)
diff --git a/chrome/browser/ui/tabs/tab_strip_model.cc b/chrome/browser/ui/tabs/tab_strip_model.cc index c5c87a4..c4d3551 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.cc +++ b/chrome/browser/ui/tabs/tab_strip_model.cc
@@ -45,7 +45,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h" #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker_factory.h" #endif @@ -1126,7 +1126,7 @@ TabStripModel::NEW_TAB_ENUM_COUNT); delegate()->AddTabAt(GURL(), context_index + 1, true, GetTabGroupForTab(context_index)); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) auto* new_tab_tracker = feature_engagement::NewTabTrackerFactory::GetInstance() ->GetForProfile(profile_);
diff --git a/chrome/browser/ui/toolbar/back_forward_menu_model.cc b/chrome/browser/ui/toolbar/back_forward_menu_model.cc index b4e24ac..6b645b61 100644 --- a/chrome/browser/ui/toolbar/back_forward_menu_model.cc +++ b/chrome/browser/ui/toolbar/back_forward_menu_model.cc
@@ -227,7 +227,7 @@ void BackForwardMenuModel::FetchFavicon(NavigationEntry* entry) { // If the favicon has already been requested for this menu, don't do // anything. - if (base::ContainsKey(requested_favicons_, entry->GetUniqueID())) + if (base::Contains(requested_favicons_, entry->GetUniqueID())) return; requested_favicons_.insert(entry->GetUniqueID());
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.h b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.h index 5eb09d8..0c0130ed 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.h +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.h
@@ -128,7 +128,9 @@ FRIEND_TEST_ALL_PREFIXES(BrowserNonClientFrameViewAshTest, AvatarDisplayOnTeleportedWindow); FRIEND_TEST_ALL_PREFIXES(BrowserNonClientFrameViewAshTest, - HeaderVisibilityInOverviewAndSplitview); + BrowserHeaderVisibilityInTabletModeTest); + FRIEND_TEST_ALL_PREFIXES(BrowserNonClientFrameViewAshTest, + AppHeaderVisibilityInTabletModeTest); FRIEND_TEST_ALL_PREFIXES(BrowserNonClientFrameViewAshTest, ImmersiveModeTopViewInset); FRIEND_TEST_ALL_PREFIXES(BrowserNonClientFrameViewAshBackButtonTest,
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc index b72c3168..a795793 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc
@@ -1246,8 +1246,10 @@ EXPECT_EQ(0, window->GetProperty(aura::client::kTopViewInset)); } +// Test that for a browser window, its caption buttons are always hidden in +// tablet mode. IN_PROC_BROWSER_TEST_P(BrowserNonClientFrameViewAshTest, - HeaderVisibilityInOverviewAndSplitview) { + BrowserHeaderVisibilityInTabletModeTest) { BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); Widget* widget = browser_view->GetWidget(); BrowserNonClientFrameViewAsh* frame_view = GetFrameViewAsh(browser_view); @@ -1256,15 +1258,30 @@ aura::client::kResizeBehaviorKey, aura::client::kResizeBehaviorCanMaximize | aura::client::kResizeBehaviorCanResize); + EXPECT_TRUE(frame_view->caption_button_container_->GetVisible()); - // Test that the header is invisible for the browser window in overview mode - // and visible when not in overview mode. ToggleOverview(); EXPECT_FALSE(frame_view->caption_button_container_->GetVisible()); ToggleOverview(); EXPECT_TRUE(frame_view->caption_button_container_->GetVisible()); - // Create another browser window. + ASSERT_NO_FATAL_FAILURE( + ash::ShellTestApi().EnableTabletModeWindowManager(true)); + EXPECT_FALSE(frame_view->caption_button_container_->GetVisible()); + ToggleOverview(); + EXPECT_FALSE(frame_view->caption_button_container_->GetVisible()); + ToggleOverview(); + EXPECT_FALSE(frame_view->caption_button_container_->GetVisible()); + ash::Shell::Get()->split_view_controller()->SnapWindow( + widget->GetNativeWindow(), ash::SplitViewController::LEFT); + EXPECT_FALSE(frame_view->caption_button_container_->GetVisible()); +} + +// Test that for a browser app window, its caption buttons may or may not hide +// in tablet mode. +IN_PROC_BROWSER_TEST_P(BrowserNonClientFrameViewAshTest, + AppHeaderVisibilityInTabletModeTest) { + // Create a browser app window. Browser::CreateParams params = Browser::CreateParams::CreateForApp( "test_browser_app", true /* trusted_source */, gfx::Rect(), browser()->profile(), true); @@ -1278,33 +1295,22 @@ aura::client::kResizeBehaviorKey, aura::client::kResizeBehaviorCanMaximize | aura::client::kResizeBehaviorCanResize); - - // Test that when one browser window is snapped, the header is visible for - // the snapped browser window, but invisible for the browser window still in - // overview mode. - ASSERT_NO_FATAL_FAILURE( - ash::ShellTestApi().EnableTabletModeWindowManager(true)); - ash::Shell* shell = ash::Shell::Get(); - ash::SplitViewController* split_view_controller = - shell->split_view_controller(); - ToggleOverview(); - split_view_controller->SnapWindow(widget->GetNativeWindow(), - ash::SplitViewController::LEFT); - // TODO(crbug.com/970904): Test first frame header visibility here and below. EXPECT_FALSE(frame_view2->caption_button_container_->GetVisible()); - - // When both browser windows are snapped, the headers are both visible. - split_view_controller->SnapWindow(widget2->GetNativeWindow(), - ash::SplitViewController::RIGHT); + ToggleOverview(); EXPECT_TRUE(frame_view2->caption_button_container_->GetVisible()); - // Toggle overview mode while splitview mode is active. Test that the header - // is visible for the snapped browser window but not for the other browser - // window in overview mode. + ASSERT_NO_FATAL_FAILURE( + ash::ShellTestApi().EnableTabletModeWindowManager(true)); ToggleOverview(); - EXPECT_FALSE(frame_view2->caption_button_container_->GetVisible()); + + ToggleOverview(); + EXPECT_TRUE(frame_view2->caption_button_container_->GetVisible()); + + ash::Shell::Get()->split_view_controller()->SnapWindow( + widget2->GetNativeWindow(), ash::SplitViewController::RIGHT); + EXPECT_TRUE(frame_view2->caption_button_container_->GetVisible()); } // Regression test for https://crbug.com/879851.
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 02d72d64..ae49232 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -56,6 +56,8 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window_state.h" +#include "chrome/browser/ui/in_product_help/reopen_tab_in_product_help.h" +#include "chrome/browser/ui/in_product_help/reopen_tab_in_product_help_factory.h" #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/recently_audible_helper.h" #include "chrome/browser/ui/sad_tab_helper.h" @@ -204,11 +206,6 @@ #include "ui/views/win/scoped_fullscreen_visibility.h" #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) -#include "chrome/browser/ui/in_product_help/reopen_tab_in_product_help.h" -#include "chrome/browser/ui/in_product_help/reopen_tab_in_product_help_factory.h" -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - #if BUILDFLAG(ENABLE_ONE_CLICK_SIGNIN) #include "chrome/browser/ui/sync/one_click_signin_links_delegate_impl.h" #include "chrome/browser/ui/views/sync/one_click_signin_dialog_view.h" @@ -930,9 +927,7 @@ } void BrowserView::OnTabRestored(int command_id) { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) reopen_tab_promo_controller_.OnTabReopened(command_id); -#endif } void BrowserView::ZoomChangedForActiveTab(bool can_show_bubble) { @@ -3053,12 +3048,10 @@ GetWidget()->ShowEmojiPanel(); } -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) void BrowserView::ShowInProductHelpPromo(InProductHelpFeature iph_feature) { if (iph_feature == InProductHelpFeature::kReopenTab) reopen_tab_promo_controller_.ShowPromo(); } -#endif bool BrowserView::DoCutCopyPasteForWebContents( WebContents* contents,
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h index 0d111bd..fcfaa4fa 100644 --- a/chrome/browser/ui/views/frame/browser_view.h +++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -28,6 +28,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" #include "chrome/browser/ui/views/exclusive_access_bubble_views_context.h" #include "chrome/browser/ui/views/extensions/extension_keybinding_registry_views.h" +#include "chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.h" #include "chrome/browser/ui/views/frame/browser_frame.h" #include "chrome/browser/ui/views/frame/contents_web_view.h" #include "chrome/browser/ui/views/frame/immersive_mode_controller.h" @@ -48,10 +49,6 @@ #include "ui/views/widget/widget_observer.h" #include "ui/views/window/client_view.h" -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) -#include "chrome/browser/ui/views/feature_promos/reopen_tab_promo_controller.h" -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - // NOTE: For more information about the objects and files in this directory, // view: http://dev.chromium.org/developers/design-documents/browser-window @@ -433,9 +430,7 @@ BookmarkBarView* GetBookmarkBarView() const; LocationBarView* GetLocationBarView() const; -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) void ShowInProductHelpPromo(InProductHelpFeature iph_feature) override; -#endif // TabStripModelObserver: void OnTabStripModelChanged( @@ -842,9 +837,7 @@ std::unique_ptr<FullscreenControlHost> fullscreen_control_host_; -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) ReopenTabPromoController reopen_tab_promo_controller_{this}; -#endif struct ResizeSession { // The time when user started resizing the window.
diff --git a/chrome/browser/ui/views/layout_provider_unittest.cc b/chrome/browser/ui/views/layout_provider_unittest.cc index 2f79ca9e..f84eab9f 100644 --- a/chrome/browser/ui/views/layout_provider_unittest.cc +++ b/chrome/browser/ui/views/layout_provider_unittest.cc
@@ -151,11 +151,7 @@ EXPECT_EQ(14, title_font.GetFontSize()); EXPECT_EQ(17, title_font.GetHeight()); EXPECT_EQ(14, title_font.GetBaseline()); - if (base::mac::IsOS10_9()) { - EXPECT_EQ(11, title_font.GetCapHeight()); - } else { - EXPECT_EQ(10, title_font.GetCapHeight()); - } + EXPECT_EQ(10, title_font.GetCapHeight()); #else EXPECT_EQ(15, title_font.GetFontSize()); EXPECT_EQ(18, title_font.GetHeight()); @@ -163,15 +159,7 @@ EXPECT_EQ(11, title_font.GetCapHeight()); #endif -#if defined(OS_MACOSX) - if (base::mac::IsOS10_9()) { - EXPECT_EQ(7, title_font.GetExpectedTextWidth(1)); - } else { - EXPECT_EQ(8, title_font.GetExpectedTextWidth(1)); - } -#else EXPECT_EQ(8, title_font.GetExpectedTextWidth(1)); -#endif gfx::FontList small_font = rb.GetFontList(ui::ResourceBundle::SmallFont); gfx::FontList base_font = rb.GetFontList(ui::ResourceBundle::BaseFont);
diff --git a/chrome/browser/ui/views/omnibox/omnibox_view_views.cc b/chrome/browser/ui/views/omnibox/omnibox_view_views.cc index 9fab44f..7e5b15b 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_view_views.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_view_views.cc
@@ -82,7 +82,7 @@ #include "chrome/browser/browser_process.h" #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h" #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker_factory.h" #endif @@ -1258,7 +1258,7 @@ if (location_bar_view_ && model()->is_keyword_hint()) location_bar_view_->Layout(); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) // The user must be starting a session in the same tab as a previous one in // order to display the new tab in-product help promo. While focusing the // omnibox is not always a precursor to starting a new session, we don't
diff --git a/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.cc b/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.cc index ffc4d16..69f1c10 100644 --- a/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.cc +++ b/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.cc
@@ -345,6 +345,8 @@ plugin_vm::RecordPluginVmSetupResultHistogram( plugin_vm::PluginVmSetupResult::kSuccess); + plugin_vm::RecordPluginVmSetupTimeHistogram(base::TimeTicks::Now() - + setup_start_tick_); } base::string16 PluginVmLauncherView::GetBigMessage() const { @@ -496,6 +498,10 @@ } void PluginVmLauncherView::StartPluginVmImageDownload() { + // In each case setup starts from this function (when dialog is opened or + // retry button is clicked). + setup_start_tick_ = base::TimeTicks::Now(); + state_ = State::START_DOWNLOADING; OnStateUpdated();
diff --git a/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.h b/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.h index eb96e22..bf68fa0 100644 --- a/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.h +++ b/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.h
@@ -90,6 +90,7 @@ views::Label* download_progress_message_label_ = nullptr; views::Label* time_left_message_label_ = nullptr; views::ImageView* big_image_ = nullptr; + base::TimeTicks setup_start_tick_; DISALLOW_COPY_AND_ASSIGN(PluginVmLauncherView); };
diff --git a/chrome/browser/ui/views/tabs/browser_tab_strip_controller.cc b/chrome/browser/ui/views/tabs/browser_tab_strip_controller.cc index 38a34662..b08af08 100644 --- a/chrome/browser/ui/views/tabs/browser_tab_strip_controller.cc +++ b/chrome/browser/ui/views/tabs/browser_tab_strip_controller.cc
@@ -54,7 +54,7 @@ #include "ui/views/widget/widget.h" #include "url/origin.h" -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h" #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker_factory.h" #endif @@ -317,7 +317,6 @@ } void BrowserTabStripController::CreateNewTab() { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) // This must be called before AddTabAt() so that OmniboxFocused is called // after NewTabOpened. TODO(collinbaker): remove omnibox focusing from // triggering conditions (since it is always focused for new tabs) and move @@ -325,11 +324,10 @@ auto* reopen_tab_iph = ReopenTabInProductHelpFactory::GetForProfile( browser_view_->browser()->profile()); reopen_tab_iph->NewTabOpened(); -#endif model_->delegate()->AddTabAt(GURL(), -1, true); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) auto* new_tab_tracker = feature_engagement::NewTabTrackerFactory::GetInstance()->GetForProfile( browser_view_->browser()->profile());
diff --git a/chrome/browser/ui/views/tabs/new_tab_button.cc b/chrome/browser/ui/views/tabs/new_tab_button.cc index cf9ea00a..f5021728 100644 --- a/chrome/browser/ui/views/tabs/new_tab_button.cc +++ b/chrome/browser/ui/views/tabs/new_tab_button.cc
@@ -36,7 +36,7 @@ #include "ui/views/win/hwnd_util.h" #endif -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h" #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker_factory.h" #endif @@ -207,7 +207,7 @@ } void NewTabButton::OnWidgetDestroying(views::Widget* widget) { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) feature_engagement::NewTabTrackerFactory::GetInstance() ->GetForProfile(tab_strip_->controller()->GetProfile()) ->OnPromoClosed();
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller.cc b/chrome/browser/ui/views/tabs/tab_drag_controller.cc index d55a70a1..7b9fdfa 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller.cc
@@ -12,7 +12,9 @@ #include "base/auto_reset.h" #include "base/bind.h" #include "base/callback.h" +#include "base/feature_list.h" #include "base/i18n/rtl.h" +#include "base/logging.h" #include "base/macros.h" #include "base/numerics/ranges.h" #include "base/stl_util.h" @@ -26,6 +28,7 @@ #include "chrome/browser/ui/sad_tab_helper.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h" +#include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/tabs/tab.h" #include "chrome/browser/ui/views/tabs/tab_strip.h" @@ -473,9 +476,9 @@ source_context_->AsView()->GetWidget()->GetNativeWindow()); if (source_tab->width() > 0) { - offset_to_width_ratio_ = static_cast<float>( - source_tab->GetMirroredXInView(source_tab_offset)) / - static_cast<float>(source_tab->width()); + offset_to_width_ratio_ = + float{source_tab->GetMirroredXInView(source_tab_offset)} / + float{source_tab->width()}; } InitWindowCreatePoint(); initial_selection_model_ = std::move(initial_selection_model); @@ -543,7 +546,7 @@ } current_state_ = DragState::kDraggingTabs; Attach(source_context_, gfx::Point()); - if (static_cast<int>(drag_data_.size()) == + if (int{drag_data_.size()} == source_context_->GetTabStripModel()->count()) { views::Widget* widget = GetAttachedBrowserWidget(); gfx::Rect new_bounds; @@ -751,8 +754,8 @@ static const int kMinimumDragDistance = 10; int x_offset = abs(point_in_screen.x() - start_point_in_screen_.x()); int y_offset = abs(point_in_screen.y() - start_point_in_screen_.y()); - return sqrt(pow(static_cast<float>(x_offset), 2) + - pow(static_cast<float>(y_offset), 2)) > kMinimumDragDistance; + return sqrt(pow(float{x_offset}, 2) + pow(float{y_offset}, 2)) > + kMinimumDragDistance; } TabDragController::Liveness TabDragController::ContinueDragging( @@ -906,8 +909,7 @@ void TabDragController::DragActiveTabStacked( const gfx::Point& point_in_screen) { - if (attached_context_->GetTabCount() != - static_cast<int>(initial_tab_positions_.size())) + if (attached_context_->GetTabCount() != int{initial_tab_positions_.size()}) return; // TODO: should cancel drag if this happens. int delta = point_in_screen.x() - start_point_in_screen_.x(); @@ -957,7 +959,7 @@ TabStripModel* attached_model = attached_context_->GetTabStripModel(); int to_index = attached_context_->GetInsertionIndexForDraggedBounds( GetDraggedViewTabStripBounds(dragged_view_point), false, - static_cast<int>(drag_data_.size()), mouse_has_ever_moved_left_, + int{drag_data_.size()}, mouse_has_ever_moved_left_, mouse_has_ever_moved_right_); bool do_move = true; // While dragging within a tabstrip the expectation is the insertion index @@ -999,6 +1001,9 @@ initial_move_); did_layout = true; } + if (base::FeatureList::IsEnabled(features::kDragToPinTabs)) { + UpdatePinnednessOfDraggedTab(to_index); + } attached_model->MoveSelectedTabsTo(to_index); // Move may do nothing in certain situations (such as when dragging pinned @@ -1155,6 +1160,7 @@ std::vector<Tab*> tabs = GetTabsMatchingDraggedContents(attached_context_); + TabStripModel* attached_model = attached_context_->GetTabStripModel(); if (tabs.empty()) { // Transitioning from detached to attached to a new context. Add tabs to // the new model. @@ -1178,7 +1184,7 @@ tab_strip_point.Offset(0, -mouse_offset_.y()); int index = attached_context_->GetInsertionIndexForDraggedBounds( GetDraggedViewTabStripBounds(tab_strip_point), true, - static_cast<int>(drag_data_.size()), mouse_has_ever_moved_left_, + int{drag_data_.size()}, mouse_has_ever_moved_left_, mouse_has_ever_moved_right_); attach_index_ = index; attach_x_ = tab_strip_point.x(); @@ -1191,10 +1197,26 @@ DCHECK_EQ(1u, drag_data_.size()); add_types |= TabStripModel::ADD_ACTIVE; } + const int target_index = index + i; + + if (base::FeatureList::IsEnabled(features::kDragToPinTabs)) { + if (drag_data_[i].pinned) { + // Attaching a tab is effectively an insertion at the target index. A + // pinned tab will only need to unpin if the previous tab is unpinned. + drag_data_[i].pinned = !CheckValidPinnedness( + target_index - 1, TabAnimationState::TabPinnedness::kUnpinned); + } else { + // An unpinned tab will only need to be pinned if the tab to the right + // of it is is pinned. + drag_data_[i].pinned = CheckValidPinnedness( + target_index, TabAnimationState::TabPinnedness::kPinned); + } + } if (drag_data_[i].pinned) add_types |= TabStripModel::ADD_PINNED; - attached_context_->GetTabStripModel()->InsertWebContentsAt( - index + i, std::move(drag_data_[i].owned_contents), add_types); + + attached_model->InsertWebContentsAt( + target_index, std::move(drag_data_[i].owned_contents), add_types); // If a sad tab is showing, the SadTabView needs to be updated. SadTabHelper* sad_tab_helper = @@ -1202,14 +1224,13 @@ if (sad_tab_helper) sad_tab_helper->ReinstallInWebView(); } - tabs = GetTabsMatchingDraggedContents(attached_context_); } DCHECK_EQ(tabs.size(), drag_data_.size()); for (size_t i = 0; i < drag_data_.size(); ++i) drag_data_[i].attached_tab = tabs[i]; - ResetSelection(attached_context_->GetTabStripModel()); + ResetSelection(attached_model); // This should be called after ResetSelection() in order to generate // bounds correctly. http://crbug.com/836004 @@ -1234,8 +1255,7 @@ attached_context_->OwnDragController(this); SetTabDraggingInfo(); attached_context_tabs_closed_tracker_ = - std::make_unique<DraggedTabsClosedTracker>( - attached_context_->GetTabStripModel(), this); + std::make_unique<DraggedTabsClosedTracker>(attached_model, this); } void TabDragController::Detach(ReleaseCapture release_capture) { @@ -1297,7 +1317,7 @@ void TabDragController::DetachIntoNewBrowserAndRunMoveLoop( const gfx::Point& point_in_screen) { if (attached_context_->GetTabStripModel()->count() == - static_cast<int>(drag_data_.size())) { + int{drag_data_.size()}) { // All the tabs in a browser are being dragged but all the tabs weren't // initially being dragged. For this to happen the user would have to // start dragging a set of tabs, the other tabs close, then detach. @@ -1920,12 +1940,12 @@ // If the new tabstrip is smaller than the old resize the tabs. if (dragged_context_width < tab_area_width) { const float leading_ratio = - drag_bounds->front().x() / static_cast<float>(tab_area_width); + drag_bounds->front().x() / float{tab_area_width}; *drag_bounds = CalculateBoundsForDraggedTabs(); if (drag_bounds->back().right() < dragged_context_width) { const int delta_x = std::min( - static_cast<int>(leading_ratio * dragged_context_width), + int{leading_ratio * dragged_context_width}, dragged_context_width - (drag_bounds->back().right() - drag_bounds->front().x())); OffsetX(delta_x, drag_bounds); @@ -2091,6 +2111,49 @@ #endif } +void TabDragController::UpdatePinnednessOfDraggedTab(int to_index) { + TabStripModel* attached_model = attached_context_->GetTabStripModel(); + const int selected_count = + int{attached_model->selection_model().selected_indices().size()}; + for (int i = 0; i < selected_count; i++) { + const int current_index = + attached_model->selection_model().selected_indices()[i]; + const int target_index = to_index + i; + if (current_index != target_index) { + // When dragging a tab to the target index, the tab is effectively + // swapping places with the tab at its target index.This means that + // if the current tab is pinned but the tab it is swapping with is + // not, the current tab will need to be unpinned. The opposite is + // true when moving an unpinned tab. + if (attached_model->IsTabPinned(current_index) && + CheckValidPinnedness(target_index, + TabAnimationState::TabPinnedness::kUnpinned)) { + attached_model->SetTabPinned(current_index, false); + } else if (!attached_model->IsTabPinned(current_index) && + CheckValidPinnedness( + target_index, TabAnimationState::TabPinnedness::kPinned)) { + attached_model->SetTabPinned(current_index, true); + } + } + } +} + +bool TabDragController::CheckValidPinnedness( + int index, + TabAnimationState::TabPinnedness expected_pinnedness) { + TabStripModel* attached_model = attached_context_->GetTabStripModel(); + + if (!attached_model->ContainsIndex(index)) + return false; + + TabAnimationState::TabPinnedness pinnedness = + attached_model->IsTabPinned(index) + ? TabAnimationState::TabPinnedness::kPinned + : TabAnimationState::TabPinnedness::kUnpinned; + + return expected_pinnedness == pinnedness; +} + void TabDragController::SetDeferredTargetTabstrip( TabDragContext* deferred_target_context) { #if defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller.h b/chrome/browser/ui/views/tabs/tab_drag_controller.h index 653d681..4e7846b 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller.h +++ b/chrome/browser/ui/views/tabs/tab_drag_controller.h
@@ -14,6 +14,7 @@ #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" +#include "chrome/browser/ui/views/tabs/tab_animation_state.h" #include "chrome/browser/ui/views/tabs/tab_drag_context.h" #include "chrome/browser/ui/views/tabs/tab_strip_types.h" #include "ui/base/models/list_selection_model.h" @@ -494,6 +495,19 @@ // is showing a modal). bool ShouldDisallowDrag(gfx::NativeWindow window); + // Helper method for TabDragController::MoveAttached to update the pinnedness + // of the tab being moved by checking the pinnedness of the tabs being + // dragged with the pinnedness of the tab at the target dragged location. + // TODO (crbug.com/971676): This will swap and update the pinnedness of + // multi-selected tabs one at a time, which is unintended. + void UpdatePinnednessOfDraggedTab(int to_index); + + // Helper method that checks if the index is valid in the TabDragContext and + // the pin at the index has the expected pinned value. + bool CheckValidPinnedness( + int index, + TabAnimationState::TabPinnedness expected_pinnedness); + EventSource event_source_; // The TabDragContext the drag originated from. This is set to null
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc b/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc index 3ad4e5f..2a9d72a 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc
@@ -23,6 +23,7 @@ #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/test/bind_test_util.h" +#include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "chrome/browser/chrome_notification_types.h" @@ -31,6 +32,7 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/native_browser_frame_factory.h" #include "chrome/browser/ui/views/tabs/tab.h" @@ -421,6 +423,50 @@ #endif // OS_MACOSX } + // Set up the test environment with 4 tabs. Two pinned and two unpinned. + void SetUpDragToChangePinnednessTest() { + AddTabAndResetBrowser(browser()); + AddTabAndResetBrowser(browser()); + AddTabAndResetBrowser(browser()); + + TabStrip* tab_strip = GetTabStripForBrowser(browser()); + TabStripModel* model = browser()->tab_strip_model(); + + model->SetTabPinned(0, true); + model->SetTabPinned(1, true); + StopAnimating(tab_strip); + ASSERT_TRUE(model->IsTabPinned(0)); + ASSERT_TRUE(model->IsTabPinned(1)); + ASSERT_FALSE(model->IsTabPinned(2)); + ASSERT_FALSE(model->IsTabPinned(3)); + EXPECT_EQ("0 1 2 3", IDString(model)); + } + + // Set up the test environment another browser with two unpinned tabs. + Browser* SetUpSecondBrowserWithTwoUnpinnedTabs() { + Browser* browser2 = CreateAnotherBrowserAndResize(); + AddTabAndResetBrowser(browser2); + ResetIDs(browser2->tab_strip_model(), 100); + return browser2; + } + + void SelectIndicies(TabStrip* tabstrip, + TabStripModel* model, + std::vector<int> indicies) { + DCHECK(!indicies.empty()); + // The last tab opened will automatically be selected. Simulating a click to + // select the first index will ensure others are no longer selected. + ASSERT_TRUE(PressInput( + GetCenterInScreenCoordinates(tabstrip->tab_at(indicies.at(0))))); + ASSERT_TRUE(ReleaseInput()); + + if (indicies.size() > 1) { + for (auto it = std::next(indicies.begin()); it != indicies.end(); ++it) { + model->ToggleSelectionAt(*it); + } + } + } + InputSource input_source() const { return strstr(GetParam(), "mouse") ? INPUT_SOURCE_MOUSE : INPUT_SOURCE_TOUCH; @@ -595,6 +641,23 @@ Browser* browser() const { return InProcessBrowserTest::browser(); } + void DragToSeparateWindowBeforeFirstTab(TabStrip* tabstrip_to) { + gfx::Point tab_left_center = + tabstrip_to->tab_at(0)->GetLocalBounds().left_center(); + views::View::ConvertPointToScreen(tabstrip_to->tab_at(0), &tab_left_center); + ASSERT_TRUE(DragInputToAsync(tab_left_center)); + } + + void DragToSeparateWindowAfterFirstTab(TabStrip* tabstrip_to) { + gfx::Point tab_right_center = + tabstrip_to->tab_at(0)->GetLocalBounds().right_center(); + views::View::ConvertPointToScreen(tabstrip_to->tab_at(0), + &tab_right_center); + ASSERT_TRUE(DragInputToAsync(tab_right_center)); + } + + base::test::ScopedFeatureList scoped_feature_list_; + private: #if defined(OS_CHROMEOS) // The root window for the event generator. @@ -606,12 +669,6 @@ // Creates a browser with two tabs, drags the second to the first. IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, DragInSameWindow) { - // TODO(sky): this won't work with touch as it requires a long press. - if (input_source() == INPUT_SOURCE_TOUCH) { - VLOG(1) << "Test is DISABLED for touch input."; - return; - } - AddTabAndResetBrowser(browser()); TabStrip* tab_strip = GetTabStripForBrowser(browser()); @@ -633,6 +690,160 @@ EXPECT_FALSE(tab_strip->GetWidget()->HasCapture()); } +// Creates a browser with four tabs two pinned two unpinned. With the +// kDragToPinTabs flag off, dragging tabs between pinned and unpinned will have +// no effect +IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, + DragInSameWindow_CannotDragBetweenPinnedness) { + scoped_feature_list_.InitAndDisableFeature(features::kDragToPinTabs); + SetUpDragToChangePinnednessTest(); + + TabStrip* tab_strip = GetTabStripForBrowser(browser()); + TabStripModel* model = browser()->tab_strip_model(); + + // Dragging an unpinned tab before a pinned tab will have no effect. + ASSERT_TRUE(PressInput(GetCenterInScreenCoordinates(tab_strip->tab_at(2)))); + ASSERT_TRUE(DragInputTo(GetCenterInScreenCoordinates(tab_strip->tab_at(1)))); + ASSERT_TRUE(ReleaseInput()); + EXPECT_EQ("0 1 2 3", IDString(model)); + EXPECT_TRUE(model->IsTabPinned(0)); + EXPECT_TRUE(model->IsTabPinned(1)); + EXPECT_FALSE(model->IsTabPinned(2)); + EXPECT_FALSE(model->IsTabPinned(3)); + + // Dragging a pinned tab after an unpinned tab will have no effect. + ASSERT_TRUE(PressInput(GetCenterInScreenCoordinates(tab_strip->tab_at(1)))); + ASSERT_TRUE(DragInputTo(GetCenterInScreenCoordinates(tab_strip->tab_at(2)))); + ASSERT_TRUE(ReleaseInput()); + EXPECT_EQ("0 1 2 3", IDString(model)); + EXPECT_TRUE(model->IsTabPinned(0)); + EXPECT_TRUE(model->IsTabPinned(1)); + EXPECT_FALSE(model->IsTabPinned(2)); + EXPECT_FALSE(model->IsTabPinned(3)); +} + +// Creates a browser with four tabs two pinned two unpinned. With the +// kDragToPinTabs flag on, dragging unpinned tabs before a pinned tab will +// pin the unpinned tab. +IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, + DragInSameWindow_DragUnpinnedBeforePinned) { + scoped_feature_list_.InitAndEnableFeature(features::kDragToPinTabs); + SetUpDragToChangePinnednessTest(); + + TabStrip* tab_strip = GetTabStripForBrowser(browser()); + TabStripModel* model = browser()->tab_strip_model(); + + SelectIndicies(tab_strip, model, std::vector<int>{2, 3}); + ASSERT_TRUE(PressInput(GetCenterInScreenCoordinates(tab_strip->tab_at(2)))); + ASSERT_TRUE(DragInputTo(GetCenterInScreenCoordinates(tab_strip->tab_at(0)))); + ASSERT_TRUE(ReleaseInput()); + StopAnimating(tab_strip); + EXPECT_EQ("2 3 0 1", IDString(model)); + EXPECT_TRUE(model->IsTabPinned(0)); + EXPECT_TRUE(model->IsTabPinned(1)); + EXPECT_TRUE(model->IsTabPinned(2)); + EXPECT_TRUE(model->IsTabPinned(3)); +} + +// Creates a browser with four tabs two pinned two unpinned. With the +// kDragToPinTabs flag on, dragging pinned tabs after the unpinned tab will +// unpin the pinned tab. +IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, + DragInSameWindow_DragPinnedAfterUnpinned) { + scoped_feature_list_.InitAndEnableFeature(features::kDragToPinTabs); + SetUpDragToChangePinnednessTest(); + + TabStrip* tab_strip = GetTabStripForBrowser(browser()); + TabStripModel* model = browser()->tab_strip_model(); + + SelectIndicies(tab_strip, model, std::vector<int>{0, 1}); + + // TODO (crbug.com/965681): Investigate and fix the dragging case for dragging + // pinned tabs to after unpinned tabs. + gfx::Point tab_2 = GetCenterInScreenCoordinates(tab_strip->tab_at(2)); + gfx::Point tab_2_left_center = + tab_strip->tab_at(2)->GetLocalBounds().left_center(); + views::View::ConvertPointToScreen(tab_strip->tab_at(2), &tab_2_left_center); + ASSERT_TRUE(PressInput(GetCenterInScreenCoordinates(tab_strip->tab_at(0)))); + ASSERT_TRUE(DragInputTo(tab_2_left_center)); + ASSERT_TRUE(DragInputTo(tab_2)); + ASSERT_TRUE(ReleaseInput()); + StopAnimating(tab_strip); + EXPECT_FALSE(model->IsTabPinned(0)); + EXPECT_FALSE(model->IsTabPinned(1)); + EXPECT_FALSE(model->IsTabPinned(2)); + EXPECT_FALSE(model->IsTabPinned(3)); +} + +// Creates one browser with a single pinned tab as well as another browser +// (browser2) with one pinned tab and one unpinned tab. With the kDragToPinTabs +// flag on, dragging a both tabs from browser2 to the other browser to the left +// of the first pinned tab will pin both tabs dragged. +IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, + DragToPinInNewWindow) { + scoped_feature_list_.InitAndEnableFeature(features::kDragToPinTabs); + + TabStrip* tab_strip = GetTabStripForBrowser(browser()); + TabStripModel* model = browser()->tab_strip_model(); + model->SetTabPinned(0, true); + StopAnimating(tab_strip); + + // Create another browser. + Browser* browser2 = SetUpSecondBrowserWithTwoUnpinnedTabs(); + TabStrip* tab_strip2 = GetTabStripForBrowser(browser2); + browser2->tab_strip_model()->SetTabPinned(0, true); + StopAnimating(tab_strip2); + + SelectIndicies(tab_strip2, browser2->tab_strip_model(), + std::vector<int>{0, 1}); + + // This should be moving the entire window. + DragTabAndNotify(tab_strip2, + base::BindOnce(&DetachToBrowserTabDragControllerTest:: + DragToSeparateWindowBeforeFirstTab, + base::Unretained(this), tab_strip)); + ASSERT_TRUE(ReleaseInput()); + + EXPECT_EQ(3, model->count()); + EXPECT_TRUE(model->IsTabPinned(0)); + EXPECT_TRUE(model->IsTabPinned(1)); + EXPECT_TRUE(model->IsTabPinned(2)); +} + +// Creates one browser with a single unpinned tab as well as another browser +// (browser2) with one pinned tab and one unpinned tab. With the kDragToPinTabs +// flag on, dragging a both tabs from browser2 to the other browser to the right +// of the unpinned tab will unpin both tabs dragged. +IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, + DragToPinEnabled_DragToUnpinInNewWindow) { + scoped_feature_list_.InitAndEnableFeature(features::kDragToPinTabs); + + TabStrip* tab_strip = GetTabStripForBrowser(browser()); + TabStripModel* model = browser()->tab_strip_model(); + + // Create another browser. + Browser* browser2 = SetUpSecondBrowserWithTwoUnpinnedTabs(); + TabStrip* tab_strip2 = GetTabStripForBrowser(browser2); + browser2->tab_strip_model()->SetTabPinned(0, true); + StopAnimating(tab_strip2); + + SelectIndicies(tab_strip2, browser2->tab_strip_model(), + std::vector<int>{0, 1}); + + // This should be moving the entire window. + DragTabAndNotify(tab_strip2, + base::BindOnce(&DetachToBrowserTabDragControllerTest:: + DragToSeparateWindowAfterFirstTab, + base::Unretained(this), tab_strip)); + + ASSERT_TRUE(ReleaseInput()); + + EXPECT_EQ(3, model->count()); + EXPECT_FALSE(model->IsTabPinned(0)); + EXPECT_FALSE(model->IsTabPinned(1)); + EXPECT_FALSE(model->IsTabPinned(2)); +} + #if defined(USE_AURA) bool SubtreeShouldBeExplored(aura::Window* window, const gfx::Point& local_point) {
diff --git a/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc b/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc index bde927f..3e2387f 100644 --- a/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc +++ b/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc
@@ -15,6 +15,7 @@ #include "cc/paint/paint_flags.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_otr_state.h" +#include "chrome/browser/ui/in_product_help/in_product_help.h" #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/toolbar/app_menu_model.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" @@ -48,9 +49,6 @@ #include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.h" #endif // defined(OS_CHROMEOS) -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) -#include "chrome/browser/ui/in_product_help/in_product_help.h" - namespace { // Button background and icon colors for in-product help promos. The first is @@ -141,7 +139,6 @@ }; } // namespace -#endif // static bool BrowserAppMenuButton::g_open_app_immediately_for_testing = false; @@ -177,7 +174,6 @@ UpdateIcon(); } -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) void BrowserAppMenuButton::SetPromoFeature( base::Optional<InProductHelpFeature> promo_feature) { if (promo_feature_ == promo_feature) @@ -212,7 +208,6 @@ UpdateIcon(); SchedulePaint(); } -#endif void BrowserAppMenuButton::ShowMenu(int run_types) { if (IsMenuShowing()) @@ -225,10 +220,10 @@ #endif Browser* browser = toolbar_view_->browser(); - bool alert_reopen_tab_items = false; -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - alert_reopen_tab_items = promo_feature_ == InProductHelpFeature::kReopenTab; -#endif + + bool alert_reopen_tab_items = + promo_feature_ == InProductHelpFeature::kReopenTab; + base::TimeTicks menu_open_time = base::TimeTicks::Now(); RunMenu( @@ -283,7 +278,6 @@ } base::Optional<SkColor> BrowserAppMenuButton::GetPromoHighlightColor() const { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) if (promo_feature_) { return ToolbarButton::AdjustHighlightColorForContrast( GetThemeProvider(), kFeaturePromoHighlightDarkColor, @@ -291,7 +285,7 @@ kFeaturePromoHighlightDarkExtremeColor, kFeaturePromoHighlightLightExtremeColor); } -#endif + return base::nullopt; } @@ -362,7 +356,6 @@ std::unique_ptr<views::InkDropMask> BrowserAppMenuButton::CreateInkDropMask() const { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) if (promo_feature_) { // This gets the latest ink drop insets. |SetTrailingMargin()| is called // whenever our margins change (i.e. due to the window maximizing or @@ -375,7 +368,6 @@ ink_drop_insets, corner_radius, kFeaturePromoPulseInsetDip); } -#endif return AppMenuButton::CreateInkDropMask(); } @@ -387,11 +379,9 @@ } base::string16 BrowserAppMenuButton::GetTooltipText(const gfx::Point& p) const { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) // Suppress tooltip when IPH is showing. if (promo_feature_) return base::string16(); -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) return AppMenuButton::GetTooltipText(p); }
diff --git a/chrome/browser/ui/views/toolbar/browser_app_menu_button.h b/chrome/browser/ui/views/toolbar/browser_app_menu_button.h index 8361ef7b..9176836e 100644 --- a/chrome/browser/ui/views/toolbar/browser_app_menu_button.h +++ b/chrome/browser/ui/views/toolbar/browser_app_menu_button.h
@@ -19,9 +19,7 @@ #include "ui/views/view.h" class ToolbarView; -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) enum class InProductHelpFeature; -#endif // The app menu button in the main browser window (as opposed to hosted app // windows, which is implemented in HostedAppMenuButton). @@ -42,12 +40,10 @@ // with the menu. void ShowMenu(int run_types); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) // Called to inform the button that it's being used as an anchor for a promo // for |promo_feature|. When this is non-null, the button is highlighted in a // noticeable color, and the menu item appearance may be affected. void SetPromoFeature(base::Optional<InProductHelpFeature> promo_feature); -#endif // views::MenuButton: gfx::Rect GetAnchorBoundsInScreen() const override; @@ -98,10 +94,8 @@ // Our owning toolbar view. ToolbarView* const toolbar_view_; -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) // The feature, if any, for which this button is anchoring a promo. base::Optional<InProductHelpFeature> promo_feature_; -#endif ScopedObserver<ui::MaterialDesignController, ui::MaterialDesignControllerObserver>
diff --git a/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc b/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc index c108af6..71f9cdb 100644 --- a/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc +++ b/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc
@@ -38,7 +38,7 @@ #include "services/identity/public/cpp/identity_manager.h" #include "ui/base/text/bytes_formatting.h" -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) #include "chrome/browser/feature_engagement/incognito_window/incognito_window_tracker.h" #include "chrome/browser/feature_engagement/incognito_window/incognito_window_tracker_factory.h" #endif @@ -278,7 +278,7 @@ content::BrowsingDataFilterBuilder::BLACKLIST), remover, std::move(callback)); -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) feature_engagement::IncognitoWindowTrackerFactory::GetInstance() ->GetForProfile(profile_) ->OnBrowsingDataCleared();
diff --git a/chrome/browser/usb/usb_chooser_context.cc b/chrome/browser/usb/usb_chooser_context.cc index fdb444b8..c3e534b 100644 --- a/chrome/browser/usb/usb_chooser_context.cc +++ b/chrome/browser/usb/usb_chooser_context.cc
@@ -246,7 +246,7 @@ // always be called after device initialization in UsbChooserController // which always returns after the device list initialization in this // class. - DCHECK(base::ContainsKey(devices_, guid)); + DCHECK(base::Contains(devices_, guid)); objects.push_back(std::make_unique<ChooserContextBase::Object>( requesting_origin, embedding_origin, DeviceInfoToValue(*devices_[guid]), @@ -326,7 +326,7 @@ continue; for (const std::string& guid : map_entry.second) { - DCHECK(base::ContainsKey(devices_, guid)); + DCHECK(base::Contains(devices_, guid)); objects.push_back(std::make_unique<ChooserContextBase::Object>( requesting_origin, embedding_origin, DeviceInfoToValue(*devices_[guid]), @@ -440,7 +440,7 @@ auto it = ephemeral_devices_.find( std::make_pair(requesting_origin, embedding_origin)); if (it != ephemeral_devices_.end() && - base::ContainsKey(it->second, device_info.guid)) { + base::Contains(it->second, device_info.guid)) { return true; } @@ -543,7 +543,7 @@ device::mojom::UsbDeviceInfoPtr device_info) { DCHECK(device_info); // Update the device list. - DCHECK(!base::ContainsKey(devices_, device_info->guid)); + DCHECK(!base::Contains(devices_, device_info->guid)); devices_.insert(std::make_pair(device_info->guid, device_info->Clone())); // Notify all observers. @@ -555,7 +555,7 @@ device::mojom::UsbDeviceInfoPtr device_info) { DCHECK(device_info); // Update the device list. - DCHECK(base::ContainsKey(devices_, device_info->guid)); + DCHECK(base::Contains(devices_, device_info->guid)); devices_.erase(device_info->guid); // Notify all device observers.
diff --git a/chrome/browser/usb/usb_policy_allowed_devices_unittest.cc b/chrome/browser/usb/usb_policy_allowed_devices_unittest.cc index 9c669bf0..3225754f 100644 --- a/chrome/browser/usb/usb_policy_allowed_devices_unittest.cc +++ b/chrome/browser/usb/usb_policy_allowed_devices_unittest.cc
@@ -136,29 +136,27 @@ EXPECT_EQ(map.size(), 3ul); auto device_key = std::make_pair(1234, 5678); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& first_urls = map.at(device_key); - EXPECT_TRUE(base::ContainsKey( + EXPECT_TRUE(base::Contains( first_urls, MakeOriginPair("https://google.com", "https://google.com"))); - EXPECT_TRUE( - base::ContainsKey(first_urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(first_urls, MakeOriginPair("https://crbug.com"))); device_key = std::make_pair(4321, -1); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& second_urls = map.at(device_key); - EXPECT_TRUE(base::ContainsKey( + EXPECT_TRUE(base::Contains( second_urls, MakeOriginPair("https://google.com", "https://google.com"))); - EXPECT_TRUE( - base::ContainsKey(second_urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(second_urls, MakeOriginPair("https://crbug.com"))); device_key = std::make_pair(-1, -1); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& third_urls = map.at(device_key); EXPECT_TRUE( - base::ContainsKey(third_urls, MakeOriginPair("https://www.youtube.com"))); + base::Contains(third_urls, MakeOriginPair("https://www.youtube.com"))); } TEST_P(UsbPolicyAllowedDevicesTest, @@ -177,29 +175,27 @@ EXPECT_EQ(map.size(), 3ul); auto device_key = std::make_pair(1234, 5678); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& first_urls = map.at(device_key); - EXPECT_TRUE(base::ContainsKey( + EXPECT_TRUE(base::Contains( first_urls, MakeOriginPair("https://google.com", "https://google.com"))); - EXPECT_TRUE( - base::ContainsKey(first_urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(first_urls, MakeOriginPair("https://crbug.com"))); device_key = std::make_pair(4321, -1); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& second_urls = map.at(device_key); - EXPECT_TRUE(base::ContainsKey( + EXPECT_TRUE(base::Contains( second_urls, MakeOriginPair("https://google.com", "https://google.com"))); - EXPECT_TRUE( - base::ContainsKey(second_urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(second_urls, MakeOriginPair("https://crbug.com"))); device_key = std::make_pair(-1, -1); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& third_urls = map.at(device_key); EXPECT_TRUE( - base::ContainsKey(third_urls, MakeOriginPair("https://www.youtube.com"))); + base::Contains(third_urls, MakeOriginPair("https://www.youtube.com"))); } TEST_P(UsbPolicyAllowedDevicesTest, @@ -216,29 +212,27 @@ EXPECT_EQ(map.size(), 3ul); auto device_key = std::make_pair(1234, 5678); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& first_urls = map.at(device_key); - EXPECT_TRUE(base::ContainsKey( + EXPECT_TRUE(base::Contains( first_urls, MakeOriginPair("https://google.com", "https://google.com"))); - EXPECT_TRUE( - base::ContainsKey(first_urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(first_urls, MakeOriginPair("https://crbug.com"))); device_key = std::make_pair(4321, -1); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& second_urls = map.at(device_key); - EXPECT_TRUE(base::ContainsKey( + EXPECT_TRUE(base::Contains( second_urls, MakeOriginPair("https://google.com", "https://google.com"))); - EXPECT_TRUE( - base::ContainsKey(second_urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(second_urls, MakeOriginPair("https://crbug.com"))); device_key = std::make_pair(-1, -1); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& third_urls = map.at(device_key); EXPECT_TRUE( - base::ContainsKey(third_urls, MakeOriginPair("https://www.youtube.com"))); + base::Contains(third_urls, MakeOriginPair("https://www.youtube.com"))); // Ensure that the allowed devices can be removed dynamically. pref_value.reset(new base::Value(base::Value::Type::LIST)); @@ -279,14 +273,13 @@ ASSERT_EQ(map.size(), 1ul); auto device_key = std::make_pair(1234, 5678); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); // Ensure a device has all of the URL patterns allowed to access it. const auto& urls = map.at(device_key); - EXPECT_TRUE(base::ContainsKey(urls, MakeOriginPair("https://google.com"))); - EXPECT_TRUE(base::ContainsKey(urls, MakeOriginPair("https://crbug.com"))); - EXPECT_TRUE( - base::ContainsKey(urls, MakeOriginPair("https://www.youtube.com"))); + EXPECT_TRUE(base::Contains(urls, MakeOriginPair("https://google.com"))); + EXPECT_TRUE(base::Contains(urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(urls, MakeOriginPair("https://www.youtube.com"))); } namespace { @@ -527,31 +520,28 @@ EXPECT_EQ(map.size(), 4ul); auto device_key = std::make_pair(1234, 5678); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& first_urls = map.at(device_key); - EXPECT_TRUE( - base::ContainsKey(first_urls, MakeOriginPair("https://crbug.com"))); - EXPECT_TRUE( - base::ContainsKey(first_urls, MakeOriginPair("https://google.com"))); + EXPECT_TRUE(base::Contains(first_urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(first_urls, MakeOriginPair("https://google.com"))); device_key = std::make_pair(4321, -1); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& second_urls = map.at(device_key); - EXPECT_TRUE( - base::ContainsKey(second_urls, MakeOriginPair("https://crbug.com"))); + EXPECT_TRUE(base::Contains(second_urls, MakeOriginPair("https://crbug.com"))); EXPECT_FALSE( - base::ContainsKey(second_urls, MakeOriginPair("https://google.com"))); + base::Contains(second_urls, MakeOriginPair("https://google.com"))); device_key = std::make_pair(-1, -1); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& third_urls = map.at(device_key); EXPECT_TRUE( - base::ContainsKey(third_urls, MakeOriginPair("https://www.youtube.com"))); + base::Contains(third_urls, MakeOriginPair("https://www.youtube.com"))); device_key = std::make_pair(1111, 2222); - ASSERT_TRUE(base::ContainsKey(map, device_key)); + ASSERT_TRUE(base::Contains(map, device_key)); const auto& fourth_urls = map.at(device_key); EXPECT_TRUE( - base::ContainsKey(fourth_urls, MakeOriginPair("https://www.ebay.com"))); + base::Contains(fourth_urls, MakeOriginPair("https://www.ebay.com"))); } #endif // defined(OS_CHROMEOS)
diff --git a/chrome/browser/vr/testapp/vr_testapp.cc b/chrome/browser/vr/testapp/vr_testapp.cc index 71ee103..e2d37fb 100644 --- a/chrome/browser/vr/testapp/vr_testapp.cc +++ b/chrome/browser/vr/testapp/vr_testapp.cc
@@ -8,8 +8,8 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" @@ -284,9 +284,10 @@ base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kUseGL, gl::kGLImplementationEGLName); - // Build UI thread message loop. This is used by platform + // Build UI thread task executor. This is used by platform // implementations for event polling & running background tasks. - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::ThreadPoolInstance::CreateAndStartWithDefaultParams("VrUiViewer"); ui::OzonePlatform::InitParams params;
diff --git a/chrome/browser/vr/webxr_vr_input_browser_test.cc b/chrome/browser/vr/webxr_vr_input_browser_test.cc index a977f4e..fd02497 100644 --- a/chrome/browser/vr/webxr_vr_input_browser_test.cc +++ b/chrome/browser/vr/webxr_vr_input_browser_test.cc
@@ -526,6 +526,61 @@ t->EndTest(); } +// Tests that axes data is still reported on the secondary axes even if +// the button is not supported (we see this case with WMR through OpenVR where +// the secondary axes button is reserved by the system, but we still get valid +// data for the axes, there may be other controllers where this is the case). +// Because this is specifically a bug in the OpenVR runtime/with configurable +// controllers, not testing WMR. +IN_PROC_BROWSER_TEST_F(WebXrVrOpenVrBrowserTest, TestInputAxesWithNoButton) { + WebXrControllerInputMock my_mock; + + // Create a controller that supports all reserved buttons, except the + // secondary axis. (Though it is a valid axis) + uint64_t supported_buttons = + device::XrButtonMaskFromId(device::XrButtonId::kAxisTrigger) | + device::XrButtonMaskFromId(device::XrButtonId::kAxisPrimary) | + device::XrButtonMaskFromId(device::XrButtonId::kGrip); + + std::map<device::XrButtonId, unsigned int> axis_types = { + {device::XrButtonId::kAxisPrimary, GetPrimaryAxisType()}, + {device::XrButtonId::kAxisTrigger, device::XrAxisType::kTrigger}, + {device::XrButtonId::kAxisSecondary, GetSecondaryAxisType()}, + }; + + unsigned int controller_index = my_mock.CreateAndConnectController( + device::ControllerRole::kControllerRoleRight, axis_types, + supported_buttons); + + LoadUrlAndAwaitInitialization( + GetFileUrlForHtmlTestFile("test_webxr_gamepad_support")); + EnterSessionWithUserGestureOrFail(); + + // Setup some state on the optional buttons (as TestGamepadMinimumData should + // ensure proper state on the required buttons). + // Set a value on the secondary set of axes. + my_mock.SetAxes(controller_index, device::XrButtonId::kAxisSecondary, 0.25, + -0.25); + // Controller should meet the requirements for the 'xr-standard' mapping. + PollJavaScriptBooleanOrFail("isMappingEqualTo('xr-standard')", + WebVrBrowserTestBase::kPollTimeoutShort); + + // Controller should have all required and optional xr-standard buttons + PollJavaScriptBooleanOrFail("isButtonCountEqualTo(4)", + WebXrVrBrowserTestBase::kPollTimeoutShort); + + // The secondary set of axes should be set appropriately. + PollJavaScriptBooleanOrFail("areAxesValuesEqualTo(1, 0.25, -0.25)", + WebVrBrowserTestBase::kPollTimeoutShort); + + // If we have a non-zero axis value, the button should be touched. + PollJavaScriptBooleanOrFail("isButtonTouchedEqualTo(3, true)", + WebVrBrowserTestBase::kPollTimeoutShort); + + RunJavaScriptOrFail("done()"); + EndTest(); +} + // Ensure that if a Gamepad has all required buttons, an extra button not // mapped in the xr-standard specification, and is missing reserved buttons // from the XR Standard specification, that the extra button does not appear
diff --git a/chrome/browser/web_applications/bookmark_apps/external_web_apps_unittest.cc b/chrome/browser/web_applications/bookmark_apps/external_web_apps_unittest.cc index 35920850..203c770 100644 --- a/chrome/browser/web_applications/bookmark_apps/external_web_apps_unittest.cc +++ b/chrome/browser/web_applications/bookmark_apps/external_web_apps_unittest.cc
@@ -207,7 +207,7 @@ EXPECT_EQ(test_install_options_list.size(), install_options_list.size()); for (const auto install_option : test_install_options_list) { - EXPECT_TRUE(base::ContainsValue(install_options_list, install_option)); + EXPECT_TRUE(base::Contains(install_options_list, install_option)); } }
diff --git a/chrome/browser/web_applications/components/pending_app_manager.cc b/chrome/browser/web_applications/components/pending_app_manager.cc index 7dff0fa..575bb50b 100644 --- a/chrome/browser/web_applications/components/pending_app_manager.cc +++ b/chrome/browser/web_applications/components/pending_app_manager.cc
@@ -42,7 +42,7 @@ return install_options.install_source == install_source; })); // Only one concurrent SynchronizeInstalledApps() expected per InstallSource. - DCHECK(!base::ContainsKey(synchronize_requests_, install_source)); + DCHECK(!base::Contains(synchronize_requests_, install_source)); std::vector<GURL> current_urls = GetInstalledAppUrls(install_source); std::sort(current_urls.begin(), current_urls.end());
diff --git a/chrome/browser/web_applications/components/web_app_icon_generator_unittest.cc b/chrome/browser/web_applications/components/web_app_icon_generator_unittest.cc index 44ea633..265905a0 100644 --- a/chrome/browser/web_applications/components/web_app_icon_generator_unittest.cc +++ b/chrome/browser/web_applications/components/web_app_icon_generator_unittest.cc
@@ -44,7 +44,7 @@ for (const auto& icon : icons_to_check) { if (!icon.source_url.is_empty()) { bool found = false; - if (base::ContainsKey(size_map, icon.bitmap.width())) { + if (base::Contains(size_map, icon.bitmap.width())) { const BitmapAndSource& mapped_icon = size_map.at(icon.bitmap.width()); if (mapped_icon.source_url == icon.source_url && mapped_icon.bitmap.width() == icon.bitmap.width()) {
diff --git a/chrome/browser/web_applications/components/web_app_install_utils.cc b/chrome/browser/web_applications/components/web_app_install_utils.cc index 40e60b7..0a457f5 100644 --- a/chrome/browser/web_applications/components/web_app_install_utils.cc +++ b/chrome/browser/web_applications/components/web_app_install_utils.cc
@@ -70,8 +70,8 @@ // should have added ANY if there was no purpose specified in the manifest). DCHECK(!icon.purpose.empty()); - if (!base::ContainsValue(icon.purpose, - blink::Manifest::ImageResource::Purpose::ANY)) { + if (!base::Contains(icon.purpose, + blink::Manifest::ImageResource::Purpose::ANY)) { continue; }
diff --git a/chrome/browser/web_applications/components/web_app_shortcut_linux_unittest.cc b/chrome/browser/web_applications/components/web_app_shortcut_linux_unittest.cc index a371926..d4e76bc 100644 --- a/chrome/browser/web_applications/components/web_app_shortcut_linux_unittest.cc +++ b/chrome/browser/web_applications/components/web_app_shortcut_linux_unittest.cc
@@ -43,7 +43,7 @@ } bool GetVar(base::StringPiece variable_name, std::string* result) override { - if (base::ContainsKey(variables_, variable_name.as_string())) { + if (base::Contains(variables_, variable_name.as_string())) { *result = variables_[variable_name.as_string()]; return true; }
diff --git a/chrome/browser/web_applications/extensions/bookmark_app_helper_installation_task_unittest.cc b/chrome/browser/web_applications/extensions/bookmark_app_helper_installation_task_unittest.cc index ded660c..2bb15ba 100644 --- a/chrome/browser/web_applications/extensions/bookmark_app_helper_installation_task_unittest.cc +++ b/chrome/browser/web_applications/extensions/bookmark_app_helper_installation_task_unittest.cc
@@ -124,7 +124,7 @@ void SetNextFinalizeInstallResult(const GURL& url, web_app::InstallResultCode code) { - DCHECK(!base::ContainsKey(next_finalize_install_results_, url)); + DCHECK(!base::Contains(next_finalize_install_results_, url)); web_app::AppId app_id; if (code == web_app::InstallResultCode::kSuccess) { @@ -135,8 +135,7 @@ void SetNextUninstallExternalWebAppResult(const GURL& app_url, bool uninstalled) { - DCHECK( - !base::ContainsKey(next_uninstall_external_web_app_results_, app_url)); + DCHECK(!base::Contains(next_uninstall_external_web_app_results_, app_url)); next_uninstall_external_web_app_results_[app_url] = { GetAppIdForUrl(app_url), uninstalled}; @@ -144,7 +143,7 @@ void SetNextCreateOsShortcutsResult(const web_app::AppId& app_id, bool shortcut_created) { - DCHECK(!base::ContainsKey(next_create_os_shortcuts_results_, app_id)); + DCHECK(!base::Contains(next_create_os_shortcuts_results_, app_id)); next_create_os_shortcuts_results_[app_id] = shortcut_created; } @@ -168,8 +167,8 @@ void FinalizeInstall(const WebApplicationInfo& web_app_info, const FinalizeOptions& options, InstallFinalizedCallback callback) override { - DCHECK(base::ContainsKey(next_finalize_install_results_, - web_app_info.app_url)); + DCHECK( + base::Contains(next_finalize_install_results_, web_app_info.app_url)); web_app_info_list_.push_back(web_app_info); finalize_options_list_.push_back(options); @@ -192,8 +191,7 @@ void UninstallExternalWebApp( const GURL& app_url, UninstallExternalWebAppCallback callback) override { - DCHECK( - base::ContainsKey(next_uninstall_external_web_app_results_, app_url)); + DCHECK(base::Contains(next_uninstall_external_web_app_results_, app_url)); uninstall_external_web_app_urls_.push_back(app_url); web_app::AppId app_id; @@ -217,7 +215,7 @@ void CreateOsShortcuts(const web_app::AppId& app_id, bool add_to_desktop, CreateOsShortcutsCallback callback) override { - DCHECK(base::ContainsKey(next_create_os_shortcuts_results_, app_id)); + DCHECK(base::Contains(next_create_os_shortcuts_results_, app_id)); ++num_create_os_shortcuts_calls_; bool shortcut_created = next_create_os_shortcuts_results_[app_id]; next_create_os_shortcuts_results_.erase(app_id);
diff --git a/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc b/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc index 99d43f5..3e91651 100644 --- a/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc +++ b/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc
@@ -74,7 +74,7 @@ void SetNextFinalizeInstallResult(const GURL& url, web_app::InstallResultCode code) { - DCHECK(!base::ContainsKey(next_finalize_install_results_, url)); + DCHECK(!base::Contains(next_finalize_install_results_, url)); web_app::AppId app_id; if (code == web_app::InstallResultCode::kSuccess) { @@ -85,8 +85,7 @@ void SetNextUninstallExternalWebAppResult(const GURL& app_url, bool uninstalled) { - DCHECK( - !base::ContainsKey(next_uninstall_external_web_app_results_, app_url)); + DCHECK(!base::Contains(next_uninstall_external_web_app_results_, app_url)); next_uninstall_external_web_app_results_[app_url] = { GetAppIdForUrl(app_url), uninstalled}; @@ -94,7 +93,7 @@ void SetNextCreateOsShortcutsResult(const web_app::AppId& app_id, bool shortcut_created) { - DCHECK(!base::ContainsKey(next_create_os_shortcuts_results_, app_id)); + DCHECK(!base::Contains(next_create_os_shortcuts_results_, app_id)); next_create_os_shortcuts_results_[app_id] = shortcut_created; } @@ -121,8 +120,8 @@ void FinalizeInstall(const WebApplicationInfo& web_app_info, const FinalizeOptions& options, InstallFinalizedCallback callback) override { - DCHECK(base::ContainsKey(next_finalize_install_results_, - web_app_info.app_url)); + DCHECK( + base::Contains(next_finalize_install_results_, web_app_info.app_url)); web_app_info_list_.push_back(web_app_info); finalize_options_list_.push_back(options); @@ -145,8 +144,7 @@ void UninstallExternalWebApp( const GURL& app_url, UninstallExternalWebAppCallback callback) override { - DCHECK( - base::ContainsKey(next_uninstall_external_web_app_results_, app_url)); + DCHECK(base::Contains(next_uninstall_external_web_app_results_, app_url)); uninstall_external_web_app_urls_.push_back(app_url); web_app::AppId app_id; @@ -170,7 +168,7 @@ void CreateOsShortcuts(const web_app::AppId& app_id, bool add_to_desktop, CreateOsShortcutsCallback callback) override { - DCHECK(base::ContainsKey(next_create_os_shortcuts_results_, app_id)); + DCHECK(base::Contains(next_create_os_shortcuts_results_, app_id)); ++num_create_os_shortcuts_calls_; add_to_desktop_ = add_to_desktop; bool shortcut_created = next_create_os_shortcuts_results_[app_id];
diff --git a/chrome/browser/web_applications/extensions/pending_bookmark_app_manager_unittest.cc b/chrome/browser/web_applications/extensions/pending_bookmark_app_manager_unittest.cc index 14b2f65..06a3c25be 100644 --- a/chrome/browser/web_applications/extensions/pending_bookmark_app_manager_unittest.cc +++ b/chrome/browser/web_applications/extensions/pending_bookmark_app_manager_unittest.cc
@@ -90,7 +90,7 @@ void SetNextInstallationTaskResult(const GURL& app_url, web_app::InstallResultCode result_code) { - DCHECK(!base::ContainsKey(next_installation_task_results_, app_url)); + DCHECK(!base::Contains(next_installation_task_results_, app_url)); next_installation_task_results_[app_url] = result_code; } @@ -110,7 +110,7 @@ } web_app::InstallResultCode GetNextInstallationTaskResult(const GURL& url) { - DCHECK(base::ContainsKey(next_installation_task_results_, url)); + DCHECK(base::Contains(next_installation_task_results_, url)); auto result = next_installation_task_results_.at(url); next_installation_task_results_.erase(url); return result;
diff --git a/chrome/browser/web_applications/test/test_app_registrar.cc b/chrome/browser/web_applications/test/test_app_registrar.cc index dc2dc7d..d1bbbb6 100644 --- a/chrome/browser/web_applications/test/test_app_registrar.cc +++ b/chrome/browser/web_applications/test/test_app_registrar.cc
@@ -19,12 +19,12 @@ } void TestAppRegistrar::RemoveAsInstalled(const AppId& app_id) { - DCHECK(base::ContainsKey(installed_apps_, app_id)); + DCHECK(base::Contains(installed_apps_, app_id)); installed_apps_.erase(app_id); } void TestAppRegistrar::AddAsExternalAppUninstalledByUser(const AppId& app_id) { - DCHECK(!base::ContainsKey(uninstalled_external_apps_, app_id)); + DCHECK(!base::Contains(uninstalled_external_apps_, app_id)); uninstalled_external_apps_.insert(app_id); } @@ -36,12 +36,12 @@ } bool TestAppRegistrar::IsInstalled(const AppId& app_id) const { - return base::ContainsKey(installed_apps_, app_id); + return base::Contains(installed_apps_, app_id); } bool TestAppRegistrar::WasExternalAppUninstalledByUser( const AppId& app_id) const { - return base::ContainsKey(uninstalled_external_apps_, app_id); + return base::Contains(uninstalled_external_apps_, app_id); } bool TestAppRegistrar::HasScopeUrl(const AppId& app_id) const {
diff --git a/chrome/browser/web_applications/test/test_install_finalizer.cc b/chrome/browser/web_applications/test/test_install_finalizer.cc index c7cf533..8f58bf1 100644 --- a/chrome/browser/web_applications/test/test_install_finalizer.cc +++ b/chrome/browser/web_applications/test/test_install_finalizer.cc
@@ -46,7 +46,7 @@ void TestInstallFinalizer::UninstallExternalWebApp( const GURL& app_url, UninstallExternalWebAppCallback callback) { - DCHECK(base::ContainsKey(next_uninstall_external_web_app_results_, app_url)); + DCHECK(base::Contains(next_uninstall_external_web_app_results_, app_url)); uninstall_external_web_app_urls_.push_back(app_url); base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -115,7 +115,7 @@ void TestInstallFinalizer::SetNextUninstallExternalWebAppResult( const GURL& app_url, bool uninstalled) { - DCHECK(!base::ContainsKey(next_uninstall_external_web_app_results_, app_url)); + DCHECK(!base::Contains(next_uninstall_external_web_app_results_, app_url)); next_uninstall_external_web_app_results_[app_url] = uninstalled; }
diff --git a/chrome/browser/web_applications/test/test_web_app_ui_delegate.cc b/chrome/browser/web_applications/test/test_web_app_ui_delegate.cc index a667a18..2ff9c80 100644 --- a/chrome/browser/web_applications/test/test_web_app_ui_delegate.cc +++ b/chrome/browser/web_applications/test/test_web_app_ui_delegate.cc
@@ -23,7 +23,7 @@ } size_t TestWebAppUiDelegate::GetNumWindowsForApp(const AppId& app_id) { - DCHECK(base::ContainsKey(app_id_to_num_windows_map_, app_id)); + DCHECK(base::Contains(app_id_to_num_windows_map_, app_id)); return app_id_to_num_windows_map_[app_id]; }
diff --git a/chrome/browser/web_applications/test/test_web_app_url_loader.cc b/chrome/browser/web_applications/test/test_web_app_url_loader.cc index 30ae2542..0996b2b 100644 --- a/chrome/browser/web_applications/test/test_web_app_url_loader.cc +++ b/chrome/browser/web_applications/test/test_web_app_url_loader.cc
@@ -26,7 +26,7 @@ std::tie(url, callback) = std::move(pending_requests_.front()); pending_requests_.pop(); - DCHECK(base::ContainsKey(next_result_map_, url)); + DCHECK(base::Contains(next_result_map_, url)); auto result = next_result_map_[url]; next_result_map_.erase(url); @@ -35,7 +35,7 @@ } void TestWebAppUrlLoader::SetNextLoadUrlResult(const GURL& url, Result result) { - DCHECK(!base::ContainsKey(next_result_map_, url)) << url; + DCHECK(!base::Contains(next_result_map_, url)) << url; next_result_map_[url] = result; } @@ -47,7 +47,7 @@ return; } - DCHECK(base::ContainsKey(next_result_map_, url)) << url; + DCHECK(base::Contains(next_result_map_, url)) << url; auto result = next_result_map_[url]; next_result_map_.erase(url);
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model.cc b/chrome/browser/webauthn/authenticator_request_dialog_model.cc index 8d1de85..f3ffd4ce 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model.cc +++ b/chrome/browser/webauthn/authenticator_request_dialog_model.cc
@@ -40,8 +40,8 @@ if (transport_availability.request_type == device::FidoRequestHandlerBase::RequestType::kGetAssertion && !transport_availability.has_empty_allow_list && - base::ContainsKey(candidate_transports, - device::FidoTransportProtocol::kInternal)) { + base::Contains(candidate_transports, + device::FidoTransportProtocol::kInternal)) { // For GetAssertion requests, auto advance to Touch ID if the keychain // contains one of the allowedCredentials. if (transport_availability.has_recognized_mac_touch_id_credential) @@ -53,7 +53,7 @@ // select caBLE in that case for GetAssertion operations. if (transport_availability.request_type == device::FidoRequestHandlerBase::RequestType::kGetAssertion && - base::ContainsKey( + base::Contains( candidate_transports, AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy)) { return AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy; @@ -66,7 +66,7 @@ if (transport_availability.request_type == device::FidoRequestHandlerBase::RequestType::kGetAssertion && last_used_transport && - base::ContainsKey(candidate_transports, *last_used_transport) && + base::Contains(candidate_transports, *last_used_transport) && *last_used_transport != device::FidoTransportProtocol::kInternal) { return *last_used_transport; }
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc b/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc index b348daf..71ac97a 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc +++ b/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc
@@ -303,11 +303,11 @@ transports_info.request_type = test_case.request_type; transports_info.available_transports = test_case.available_transports; - if (base::ContainsKey(test_case.transport_params, - TransportAvailabilityParam::kHasTouchIdCredential)) + if (base::Contains(test_case.transport_params, + TransportAvailabilityParam::kHasTouchIdCredential)) transports_info.has_recognized_mac_touch_id_credential = true; - if (base::ContainsKey( + if (base::Contains( test_case.transport_params, TransportAvailabilityParam::kHasWinNativeAuthenticator)) { transports_info.has_win_native_api_authenticator = true;
diff --git a/chrome/browser/win/conflicts/enumerate_shell_extensions_unittest.cc b/chrome/browser/win/conflicts/enumerate_shell_extensions_unittest.cc index 18c8c998..9398677a 100644 --- a/chrome/browser/win/conflicts/enumerate_shell_extensions_unittest.cc +++ b/chrome/browser/win/conflicts/enumerate_shell_extensions_unittest.cc
@@ -132,8 +132,8 @@ ASSERT_EQ(3u, shell_extension_paths.size()); for (size_t i = 0; i < base::size(kTestCases); i++) { // The inefficiency is fine as long as the number of test cases stays small. - EXPECT_TRUE(base::ContainsValue(shell_extension_paths, - base::FilePath(kTestCases[i].path))); + EXPECT_TRUE(base::Contains(shell_extension_paths, + base::FilePath(kTestCases[i].path))); } } @@ -191,7 +191,7 @@ ASSERT_EQ(5u, shell_extension_paths.size()); for (size_t i = 0; i < base::size(kTestCases); ++i) { // The inefficiency is fine as long as the number of test cases stays small. - EXPECT_TRUE(base::ContainsValue(shell_extension_paths, - base::FilePath(kTestCases[i].path))); + EXPECT_TRUE(base::Contains(shell_extension_paths, + base::FilePath(kTestCases[i].path))); } }
diff --git a/chrome/browser/win/conflicts/module_blacklist_cache_util_unittest.cc b/chrome/browser/win/conflicts/module_blacklist_cache_util_unittest.cc index 76c1d191..12d0524 100644 --- a/chrome/browser/win/conflicts/module_blacklist_cache_util_unittest.cc +++ b/chrome/browser/win/conflicts/module_blacklist_cache_util_unittest.cc
@@ -197,7 +197,7 @@ // ModuleListFilter: bool IsWhitelisted(base::StringPiece module_basename_hash, base::StringPiece module_code_id_hash) const override { - return base::ContainsKey( + return base::Contains( whitelisted_modules_, std::make_pair(module_basename_hash, module_code_id_hash)); }
diff --git a/chrome/chrome_cleaner/chrome_utils/extensions_util.cc b/chrome/chrome_cleaner/chrome_utils/extensions_util.cc index 35d0874..f1ed9d9 100644 --- a/chrome/chrome_cleaner/chrome_utils/extensions_util.cc +++ b/chrome/chrome_cleaner/chrome_utils/extensions_util.cc
@@ -238,7 +238,7 @@ base::WrapRefCounted(new RefValue(json->Clone())); for (const auto& entry : *default_extensions) { base::string16 extension_id = base::UTF8ToUTF16(entry.first); - if (!base::ContainsValue(default_extension_whitelist, extension_id)) { + if (!base::Contains(default_extension_whitelist, extension_id)) { policies->emplace_back(extension_id, extensions_file, saved_json); } }
diff --git a/chrome/chrome_cleaner/engines/target/sandboxed_test_helpers.cc b/chrome/chrome_cleaner/engines/target/sandboxed_test_helpers.cc index e3c9c98..df66d2a 100644 --- a/chrome/chrome_cleaner/engines/target/sandboxed_test_helpers.cc +++ b/chrome/chrome_cleaner/engines/target/sandboxed_test_helpers.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/bind_helpers.h" +#include "base/task/single_thread_task_executor.h" #include "chrome/chrome_cleaner/engines/common/engine_result_codes.h" #include "chrome/chrome_cleaner/os/early_exit.h" #include "chrome/chrome_cleaner/os/initializer.h" @@ -138,7 +139,7 @@ } void SandboxChildProcess::UnbindRequestsPtrs() { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; base::RunLoop run_loop; if (GetCleanerEngineRequestsProxy() != nullptr) { mojo_task_runner_->PostTask(
diff --git a/chrome/chrome_cleaner/engines/target/test_engine_delegate.cc b/chrome/chrome_cleaner/engines/target/test_engine_delegate.cc index f638d214..1d42c31 100644 --- a/chrome/chrome_cleaner/engines/target/test_engine_delegate.cc +++ b/chrome/chrome_cleaner/engines/target/test_engine_delegate.cc
@@ -174,8 +174,8 @@ scoped_refptr<EngineFileRequestsProxy> privileged_file_calls, scoped_refptr<EngineScanResultsProxy> report_result_calls) { // Only check the Startup folder, assuming it's enabled - if (!base::ContainsValue(enabled_trace_locations, - UwS_TraceLocation_FOUND_IN_SHELL)) { + if (!base::Contains(enabled_trace_locations, + UwS_TraceLocation_FOUND_IN_SHELL)) { return EngineResultCode::kSuccess; }
diff --git a/chrome/chrome_cleaner/executables/chrome_cleaner_main.cc b/chrome/chrome_cleaner/executables/chrome_cleaner_main.cc index db4d1f2..46d06881 100644 --- a/chrome/chrome_cleaner/executables/chrome_cleaner_main.cc +++ b/chrome/chrome_cleaner/executables/chrome_cleaner_main.cc
@@ -18,10 +18,10 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" @@ -97,7 +97,7 @@ if (succeeded) *succeeded = success; // Use a task instead of a direct call to QuitWhenIdle, in case we are called - // synchronously because of an upload error, and the message loop is not + // synchronously because of an upload error, and the task executor is not // running yet. base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(quit_closure)); @@ -517,9 +517,10 @@ LOG(ERROR) << "Failed to remove zone identifier."; } - // Many pieces of code below need a message loop to have been instantiated + // Many pieces of code below need a task executor to have been instantiated // before them. - base::MessageLoopForUI ui_message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); // The rebooter must be at the outermost scope so it can be called to reboot // before exiting, when appropriate.
diff --git a/chrome/chrome_cleaner/executables/chrome_reporter_main.cc b/chrome/chrome_cleaner/executables/chrome_reporter_main.cc index 5fa1e4f..2a5c3b4d 100644 --- a/chrome/chrome_cleaner/executables/chrome_reporter_main.cc +++ b/chrome/chrome_cleaner/executables/chrome_reporter_main.cc
@@ -19,10 +19,10 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop.h" #include "base/sequenced_task_runner.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/win/registry.h" @@ -230,11 +230,12 @@ ®istry_logger); } - // Many pieces of code below need a message loop to have been instantiated + // Many pieces of code below need a task executor to have been instantiated // before them. base::ThreadPoolInstance::CreateAndStartWithDefaultParams( "software reporter"); - base::MessageLoopForUI ui_message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); shutdown_sequence.mojo_task_runner = MojoTaskRunner::Create();
diff --git a/chrome/chrome_cleaner/os/disk_util.cc b/chrome/chrome_cleaner/os/disk_util.cc index 37a54b4e..19aea33 100644 --- a/chrome/chrome_cleaner/os/disk_util.cc +++ b/chrome/chrome_cleaner/os/disk_util.cc
@@ -476,7 +476,7 @@ } bool IsCompanyOnIgnoredReportingList(const base::string16& company_name) { - return base::ContainsValue(kCompanyIgnoredReportingList, company_name); + return base::Contains(kCompanyIgnoredReportingList, company_name); } bool IsExecutableOnIgnoredReportingList(const base::FilePath& file_path) {
diff --git a/chrome/chrome_cleaner/os/disk_util_unittest.cc b/chrome/chrome_cleaner/os/disk_util_unittest.cc index e63f836..8495a232 100644 --- a/chrome/chrome_cleaner/os/disk_util_unittest.cc +++ b/chrome/chrome_cleaner/os/disk_util_unittest.cc
@@ -390,7 +390,7 @@ base::FilePath no_wildcard_path(sub_dir.GetPath()); CollectMatchingPaths(no_wildcard_path, &matches); EXPECT_EQ(1UL, matches.size()); - EXPECT_TRUE(base::ContainsValue(matches, sub_dir.GetPath())); + EXPECT_TRUE(base::Contains(matches, sub_dir.GetPath())); } TEST(DiskUtilTests, CollectExecutableMatchingPaths) {
diff --git a/chrome/chrome_cleaner/os/task_scheduler_unittest.cc b/chrome/chrome_cleaner/os/task_scheduler_unittest.cc index fa3ad9c..b289cf01 100644 --- a/chrome/chrome_cleaner/os/task_scheduler_unittest.cc +++ b/chrome/chrome_cleaner/os/task_scheduler_unittest.cc
@@ -207,8 +207,8 @@ std::vector<base::string16> task_names; EXPECT_TRUE(task_scheduler_->GetTaskNameList(&task_names)); - EXPECT_TRUE(base::ContainsValue(task_names, kTaskName1)); - EXPECT_TRUE(base::ContainsValue(task_names, kTaskName2)); + EXPECT_TRUE(base::Contains(task_names, kTaskName1)); + EXPECT_TRUE(base::Contains(task_names, kTaskName2)); EXPECT_TRUE(task_scheduler_->DeleteTask(kTaskName1)); EXPECT_TRUE(task_scheduler_->DeleteTask(kTaskName2)); @@ -228,7 +228,7 @@ std::vector<base::string16> task_names; EXPECT_TRUE(task_scheduler_->GetTaskNameList(&task_names)); - EXPECT_TRUE(base::ContainsValue(task_names, kTaskName1)); + EXPECT_TRUE(base::Contains(task_names, kTaskName1)); EXPECT_TRUE(task_scheduler_->DeleteTask(kTaskName1)); }
diff --git a/chrome/chrome_cleaner/parsers/json_parser/json_splicer_unittest.cc b/chrome/chrome_cleaner/parsers/json_parser/json_splicer_unittest.cc index 45abdf1..71db051 100644 --- a/chrome/chrome_cleaner/parsers/json_parser/json_splicer_unittest.cc +++ b/chrome/chrome_cleaner/parsers/json_parser/json_splicer_unittest.cc
@@ -49,13 +49,13 @@ } bool IsDaysOfWeek(const std::vector<base::Value>& list) { - return base::ContainsValue(list, base::Value("sunday")) && - base::ContainsValue(list, base::Value("monday")) && - base::ContainsValue(list, base::Value("tuesday")) && - base::ContainsValue(list, base::Value("wednesday")) && - base::ContainsValue(list, base::Value("thursday")) && - base::ContainsValue(list, base::Value("friday")) && - base::ContainsValue(list, base::Value("saturday")); + return base::Contains(list, base::Value("sunday")) && + base::Contains(list, base::Value("monday")) && + base::Contains(list, base::Value("tuesday")) && + base::Contains(list, base::Value("wednesday")) && + base::Contains(list, base::Value("thursday")) && + base::Contains(list, base::Value("friday")) && + base::Contains(list, base::Value("saturday")); } class JsonSplicerImplTest : public testing::Test {
diff --git a/chrome/chrome_cleaner/pup_data/pup_data_unittest.cc b/chrome/chrome_cleaner/pup_data/pup_data_unittest.cc index 127529c..99672fb5a 100644 --- a/chrome/chrome_cleaner/pup_data/pup_data_unittest.cc +++ b/chrome/chrome_cleaner/pup_data/pup_data_unittest.cc
@@ -654,9 +654,9 @@ const std::vector<UwSId>* pup_ids = PUPData::GetUwSIds(); EXPECT_EQ(pup_ids->size(), 2UL); - EXPECT_TRUE(base::ContainsValue(*pup_ids, k24ID)); - EXPECT_TRUE(base::ContainsValue(*pup_ids, k42ID)); - EXPECT_FALSE(base::ContainsValue(*pup_ids, k12ID)); + EXPECT_TRUE(base::Contains(*pup_ids, k24ID)); + EXPECT_TRUE(base::Contains(*pup_ids, k42ID)); + EXPECT_FALSE(base::Contains(*pup_ids, k12ID)); } TEST_F(PUPDataTest, InitializeTest) {
diff --git a/chrome/chrome_cleaner/test/test_scoped_service_handle.cc b/chrome/chrome_cleaner/test/test_scoped_service_handle.cc index d85ed59..0316e18 100644 --- a/chrome/chrome_cleaner/test/test_scoped_service_handle.cc +++ b/chrome/chrome_cleaner/test/test_scoped_service_handle.cc
@@ -171,7 +171,7 @@ for (const ServiceStatus& service : services) { base::string16 service_name = service.service_name; base::ProcessId pid = service.service_status_process.dwProcessId; - if (base::ContainsValue(process_ids, pid)) { + if (base::Contains(process_ids, pid)) { if (!StopService(service_name.c_str())) return AssertionFailure() << "Could not stop service " << service_name; stopped_service_names.push_back(service_name);
diff --git a/chrome/chrome_watcher/chrome_watcher_main.cc b/chrome/chrome_watcher/chrome_watcher_main.cc index 2c1385f7f..558fb37 100644 --- a/chrome/chrome_watcher/chrome_watcher_main.cc +++ b/chrome/chrome_watcher/chrome_watcher_main.cc
@@ -415,7 +415,7 @@ base::win::RegisterInvalidParamHandler(); base::win::SetupCRT(cmd_line); - // Run a UI message loop on the main thread. + // Run a UI task executor on the main thread. base::PlatformThread::SetName("WatcherMainThread"); base::SingleThreadTaskExecutor main_thread_task_executor( base::MessagePump::Type::UI);
diff --git a/chrome/common/extensions/api/autotest_private.idl b/chrome/common/extensions/api/autotest_private.idl index 69c6a85..9267e71 100644 --- a/chrome/common/extensions/api/autotest_private.idl +++ b/chrome/common/extensions/api/autotest_private.idl
@@ -9,7 +9,8 @@ namespace autotestPrivate { enum ShelfAlignmentType { - Bottom, Left, Right, BottomLocked + // BottomLocked not supported by shelf_prefs. + Bottom, Left, Right }; dictionary LoginStatusDict {
diff --git a/chrome/common/extensions/command_unittest.cc b/chrome/common/extensions/command_unittest.cc index cc5fa72..adc1807 100644 --- a/chrome/common/extensions/command_unittest.cc +++ b/chrome/common/extensions/command_unittest.cc
@@ -67,7 +67,7 @@ if (data.key[0] != '\0') { std::string current_platform = extensions::Command::CommandPlatform(); if (platform_specific_only && - !base::ContainsValue(platforms, current_platform)) { + !base::Contains(platforms, current_platform)) { // Given a |current_platform| without a |suggested_key|, |default| is // used. However, some keys, such as Search on Chrome OS, are only valid // for platform specific entries. Skip the test in this case.
diff --git a/chrome/installer/mac/BUILD.gn b/chrome/installer/mac/BUILD.gn index 0ea8416..8834cc2 100644 --- a/chrome/installer/mac/BUILD.gn +++ b/chrome/installer/mac/BUILD.gn
@@ -19,6 +19,8 @@ process_version_rc_template("sign_config") { visibility = [ ":copy_signing" ] + process_only = true + template_file = "signing/config.py.in" output = "$_packaging_dir/signing/config.py"
diff --git a/chrome/installer/util/delete_old_versions.cc b/chrome/installer/util/delete_old_versions.cc index 8d851ba..46a42d5 100644 --- a/chrome/installer/util/delete_old_versions.cc +++ b/chrome/installer/util/delete_old_versions.cc
@@ -87,7 +87,7 @@ bool success = true; for (const base::FilePath& directory_name : directories) { // Delete the directory if it doesn't have a matching executable. - if (!base::ContainsKey(executables, directory_name)) { + if (!base::Contains(executables, directory_name)) { const base::FilePath directory_path = install_dir.Append(directory_name); LOG(WARNING) << "Attempting to delete stray directory " << directory_path.value(); @@ -113,7 +113,7 @@ const auto& executables_for_version = version_and_executables.second; // Don't delete the executables if they have a matching directory. - if (base::ContainsKey(directories, version_dir_name)) + if (base::Contains(directories, version_dir_name)) continue; // Delete executables for version |version_dir_name|.
diff --git a/chrome/renderer/content_settings_observer.cc b/chrome/renderer/content_settings_observer.cc index 65ccd52..33a76ca8 100644 --- a/chrome/renderer/content_settings_observer.cc +++ b/chrome/renderer/content_settings_observer.cc
@@ -165,8 +165,8 @@ const std::string& identifier) { // If the empty string is in here, it means all plugins are allowed. // TODO(bauerb): Remove this once we only pass in explicit identifiers. - return base::ContainsKey(temporarily_allowed_plugins_, identifier) || - base::ContainsKey(temporarily_allowed_plugins_, std::string()); + return base::Contains(temporarily_allowed_plugins_, identifier) || + base::Contains(temporarily_allowed_plugins_, std::string()); } void ContentSettingsObserver::DidBlockContentType(
diff --git a/chrome/renderer/media/chrome_key_systems.cc b/chrome/renderer/media/chrome_key_systems.cc index 0ef05ece..b1c80064 100644 --- a/chrome/renderer/media/chrome_key_systems.cc +++ b/chrome/renderer/media/chrome_key_systems.cc
@@ -282,22 +282,22 @@ #endif // Session types. - bool cdm_supports_temporary_session = base::ContainsValue( + bool cdm_supports_temporary_session = base::Contains( capability->session_types, media::CdmSessionType::kTemporary); if (!cdm_supports_temporary_session) { DVLOG(1) << "Temporary session must be supported."; return; } - bool cdm_supports_persistent_license = base::ContainsValue( + bool cdm_supports_persistent_license = base::Contains( capability->session_types, media::CdmSessionType::kPersistentLicense); auto persistent_license_support = GetPersistentLicenseSupport(cdm_supports_persistent_license); // TODO(xhwang): Check more conditions as needed. auto persistent_usage_record_support = - base::ContainsValue(capability->session_types, - media::CdmSessionType::kPersistentUsageRecord) + base::Contains(capability->session_types, + media::CdmSessionType::kPersistentUsageRecord) ? EmeSessionTypeSupport::SUPPORTED : EmeSessionTypeSupport::NOT_SUPPORTED;
diff --git a/chrome/renderer/page_load_metrics/page_timing_metrics_sender.cc b/chrome/renderer/page_load_metrics/page_timing_metrics_sender.cc index e0607ae5..d3f7e20 100644 --- a/chrome/renderer/page_load_metrics/page_timing_metrics_sender.cc +++ b/chrome/renderer/page_load_metrics/page_timing_metrics_sender.cc
@@ -127,7 +127,7 @@ const network::ResourceResponseHead& response_head, content::ResourceType resource_type, content::PreviewsState previews_state) { - DCHECK(!base::ContainsKey(page_resource_data_use_, resource_id)); + DCHECK(!base::Contains(page_resource_data_use_, resource_id)); auto resource_it = page_resource_data_use_.emplace( std::piecewise_construct, std::forward_as_tuple(resource_id),
diff --git a/chrome/renderer/pepper/pepper_uma_host.cc b/chrome/renderer/pepper/pepper_uma_host.cc index edd2751..f31b969 100644 --- a/chrome/renderer/pepper/pepper_uma_host.cc +++ b/chrome/renderer/pepper/pepper_uma_host.cc
@@ -117,11 +117,11 @@ } if (IsPluginWhitelisted() && - base::ContainsKey(allowed_histogram_prefixes_, HashPrefix(histogram))) { + base::Contains(allowed_histogram_prefixes_, HashPrefix(histogram))) { return true; } - if (base::ContainsKey(allowed_plugin_base_names_, plugin_base_name_.value())) + if (base::Contains(allowed_plugin_base_names_, plugin_base_name_.value())) return true; LOG(ERROR) << "Host or histogram name is not allowed to use the UMA API.";
diff --git a/chrome/service/cloud_print/cloud_print_service_helpers.cc b/chrome/service/cloud_print/cloud_print_service_helpers.cc index 2483370..894222f 100644 --- a/chrome/service/cloud_print/cloud_print_service_helpers.cc +++ b/chrome/service/cloud_print/cloud_print_service_helpers.cc
@@ -82,7 +82,7 @@ } bool IsDryRunJob(const std::vector<std::string>& tags) { - return base::ContainsValue(tags, kCloudPrintServiceTagDryRunFlag); + return base::Contains(tags, kCloudPrintServiceTagDryRunFlag); } std::string GetCloudPrintAuthHeaderFromStore() {
diff --git a/chrome/services/cups_proxy/printer_installer_unittest.cc b/chrome/services/cups_proxy/printer_installer_unittest.cc index 3d2b432..9aee45f2 100644 --- a/chrome/services/cups_proxy/printer_installer_unittest.cc +++ b/chrome/services/cups_proxy/printer_installer_unittest.cc
@@ -39,7 +39,7 @@ // Service delegate overrides. bool IsPrinterInstalled(const Printer& printer) override { - if (!base::ContainsKey(installed_printers_, printer.id())) { + if (!base::Contains(installed_printers_, printer.id())) { return false; } @@ -47,7 +47,7 @@ } base::Optional<Printer> GetPrinter(const std::string& id) override { - if (!base::ContainsKey(installed_printers_, id)) { + if (!base::Contains(installed_printers_, id)) { return base::nullopt; }
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index e597684..b2e2a8f 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -1450,13 +1450,6 @@ } } - if (enable_desktop_in_product_help) { - sources += [ - "../browser/ui/views/feature_promos/feature_promo_dialog_browsertest.cc", - "../browser/ui/views/feature_promos/reopen_tab_promo_controller_dialog_browsertest.cc", - ] - } - if (enable_extensions) { sources += [ "../browser/apps/platform_apps/api/browser/browser_apitest.cc", @@ -1761,6 +1754,8 @@ "../browser/ui/views/extensions/media_galleries_dialog_views_browsertest.cc", "../browser/ui/views/extensions/pwa_confirmation_dialog_view_browsertest.cc", "../browser/ui/views/external_protocol_dialog_browsertest.cc", + "../browser/ui/views/feature_promos/feature_promo_dialog_browsertest.cc", + "../browser/ui/views/feature_promos/reopen_tab_promo_controller_dialog_browsertest.cc", "../browser/ui/views/folder_upload_confirmation_view_browsertest.cc", "../browser/ui/views/frame/browser_frame_browsertest.cc", "../browser/ui/views/frame/browser_non_client_frame_view_browsertest.cc", @@ -1892,6 +1887,7 @@ "../browser/chromeos/arc/intent_helper/arc_settings_service_browsertest.cc", "../browser/chromeos/arc/user_session/arc_user_session_service_browsertest.cc", "../browser/chromeos/attestation/attestation_policy_browsertest.cc", + "../browser/chromeos/base/locale_util_browsertest.cc", "../browser/chromeos/child_accounts/child_account_test_utils.cc", "../browser/chromeos/child_accounts/child_account_test_utils.h", "../browser/chromeos/child_accounts/parent_access_code/parent_access_service_browsertest.cc", @@ -2256,7 +2252,7 @@ [ "../browser/ui/views/ime/input_ime_apitest_nonchromeos.cc" ] } } - if (enable_desktop_in_product_help) { + if (enable_legacy_desktop_in_product_help) { sources += [ "../browser/feature_engagement/incognito_window/incognito_window_tracker_browsertest.cc", "../browser/feature_engagement/new_tab/new_tab_tracker_browsertest.cc", @@ -3633,6 +3629,9 @@ "../browser/ui/extensions/extension_action_view_controller_unittest.cc", "../browser/ui/extensions/extension_message_bubble_bridge_unittest.cc", "../browser/ui/global_error/global_error_service_unittest.cc", + "../browser/ui/in_product_help/active_tab_tracker_unittest.cc", + "../browser/ui/in_product_help/reopen_tab_in_product_help_trigger_unittest.cc", + "../browser/ui/in_product_help/reopen_tab_in_product_help_unittest.cc", "../browser/ui/omnibox/chrome_omnibox_navigation_observer_unittest.cc", "../browser/ui/omnibox/clipboard_utils_unittest.cc", "../browser/ui/page_info/permission_menu_model_unittest.cc", @@ -3734,6 +3733,7 @@ "//chrome/services/app_service/public/cpp:icon_loader_test_support", "//chrome/services/app_service/public/cpp:unit_tests", "//components/chrome_cleaner/test:test_name_helper", + "//components/feature_engagement/test:test_support", "//components/send_tab_to_self:test_support", "//components/signin/core/browser:signin_buildflags", "//components/sync:test_support", @@ -3867,18 +3867,14 @@ } } - if (enable_desktop_in_product_help) { + if (enable_legacy_desktop_in_product_help) { sources += [ "../browser/feature_engagement/bookmark/bookmark_tracker_unittest.cc", "../browser/feature_engagement/feature_tracker_unittest.cc", "../browser/feature_engagement/incognito_window/incognito_window_tracker_unittest.cc", "../browser/feature_engagement/new_tab/new_tab_tracker_unittest.cc", "../browser/feature_engagement/session_duration_updater_unittest.cc", - "../browser/ui/in_product_help/active_tab_tracker_unittest.cc", - "../browser/ui/in_product_help/reopen_tab_in_product_help_trigger_unittest.cc", - "../browser/ui/in_product_help/reopen_tab_in_product_help_unittest.cc", ] - deps += [ "//components/feature_engagement/test:test_support" ] } if (is_chromeos) {
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/partnercustomizations/TestPartnerBrowserCustomizationsDelayedProvider.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/partnercustomizations/TestPartnerBrowserCustomizationsDelayedProvider.java index cb7d750..f4a4750b 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/partnercustomizations/TestPartnerBrowserCustomizationsDelayedProvider.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/partnercustomizations/TestPartnerBrowserCustomizationsDelayedProvider.java
@@ -12,6 +12,7 @@ import org.chromium.base.annotations.MainDex; import java.util.List; +import java.util.concurrent.CountDownLatch; /** * PartnerBrowserCustomizationsProvider example for testing. This adds one second latency for @@ -22,14 +23,20 @@ public class TestPartnerBrowserCustomizationsDelayedProvider extends TestPartnerBrowserCustomizationsProvider { private static String sUriPathToDelay; + private static CountDownLatch sLatch; public TestPartnerBrowserCustomizationsDelayedProvider() { super(); mTag = TestPartnerBrowserCustomizationsDelayedProvider.class.getSimpleName(); } + public static void unblockQuery() { + sLatch.countDown(); + } + private void setUriPathToDelay(String path) { sUriPathToDelay = path; + sLatch = new CountDownLatch(1); } @Override @@ -48,7 +55,7 @@ if (sUriPathToDelay == null || (pathSegments != null && !pathSegments.isEmpty() && TextUtils.equals(pathSegments.get(0), sUriPathToDelay))) { - Thread.sleep(1000); + sLatch.await(); } } catch (InterruptedException e) { assert false;
diff --git a/chrome/test/base/chrome_unit_test_suite.cc b/chrome/test/base/chrome_unit_test_suite.cc index 60b17e8..0918712 100644 --- a/chrome/test/base/chrome_unit_test_suite.cc +++ b/chrome/test/base/chrome_unit_test_suite.cc
@@ -12,6 +12,7 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_content_browser_client.h" +#include "chrome/browser/data_use_measurement/chrome_data_use_measurement.h" #include "chrome/browser/profiles/profile_shortcut_manager.h" #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" #include "chrome/browser/update_client/chrome_update_query_params_delegate.h" @@ -61,6 +62,10 @@ } void OnTestEnd(const testing::TestInfo& test_info) override { + // To ensure that NetworkConnectionTracker doesn't complain in unit_tests + // about outstanding listeners. + data_use_measurement::ChromeDataUseMeasurement::DeleteInstance(); + browser_content_client_.reset(); utility_content_client_.reset(); content_client_.reset();
diff --git a/chrome/test/base/test_browser_window.h b/chrome/test/base/test_browser_window.h index f8f433a..fb7da23 100644 --- a/chrome/test/base/test_browser_window.h +++ b/chrome/test/base/test_browser_window.h
@@ -185,9 +185,7 @@ bool IsVisibleOnAllWorkspaces() const override; void ShowEmojiPanel() override {} -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) void ShowInProductHelpPromo(InProductHelpFeature iph_feature) override {} -#endif protected: void DestroyBrowser() override {}
diff --git a/chrome/test/base/testing_browser_process.cc b/chrome/test/base/testing_browser_process.cc index 93016b48..f055e01 100644 --- a/chrome/test/base/testing_browser_process.cc +++ b/chrome/test/base/testing_browser_process.cc
@@ -35,10 +35,9 @@ #include "content/public/browser/notification_service.h" #include "extensions/buildflags/buildflags.h" #include "media/media_buildflags.h" -#include "net/url_request/url_request_context_getter.h" #include "printing/buildflags/buildflags.h" -#include "services/network/public/cpp/network_quality_tracker.h" #include "services/network/test/test_network_connection_tracker.h" +#include "services/network/test/test_network_quality_tracker.h" #include "testing/gtest/include/gtest/gtest.h" #if BUILDFLAG(ENABLE_BACKGROUND_MODE) @@ -88,7 +87,6 @@ is_shutting_down_(false), local_state_(nullptr), io_thread_(nullptr), - system_request_context_(nullptr), rappor_service_(nullptr), platform_part_(new TestingBrowserProcessPlatformPart()), test_network_connection_tracker_( @@ -164,11 +162,11 @@ network::NetworkQualityTracker* TestingBrowserProcess::network_quality_tracker() { - if (!network_quality_tracker_) { - network_quality_tracker_ = std::make_unique<network::NetworkQualityTracker>( - base::BindRepeating(&content::GetNetworkService)); + if (!test_network_quality_tracker_) { + test_network_quality_tracker_ = + std::make_unique<network::TestNetworkQualityTracker>(); } - return network_quality_tracker_.get(); + return test_network_quality_tracker_.get(); } WatchDogThread* TestingBrowserProcess::watchdog_thread() { @@ -277,10 +275,6 @@ return optimization_guide_service_.get(); } -net::URLRequestContextGetter* TestingBrowserProcess::system_request_context() { - return system_request_context_; -} - BrowserProcessPlatformPart* TestingBrowserProcess::platform_part() { return platform_part_.get(); } @@ -444,11 +438,6 @@ return nullptr; } -void TestingBrowserProcess::SetSystemRequestContext( - net::URLRequestContextGetter* context_getter) { - system_request_context_ = context_getter; -} - void TestingBrowserProcess::SetSharedURLLoaderFactory( scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory) { shared_url_loader_factory_ = shared_url_loader_factory;
diff --git a/chrome/test/base/testing_browser_process.h b/chrome/test/base/testing_browser_process.h index 07a4ad31..55d8e75d 100644 --- a/chrome/test/base/testing_browser_process.h +++ b/chrome/test/base/testing_browser_process.h
@@ -45,8 +45,8 @@ } namespace network { -class NetworkQualityTracker; class TestNetworkConnectionTracker; +class TestNetworkQualityTracker; } namespace policy { @@ -99,7 +99,6 @@ override; optimization_guide::OptimizationGuideService* optimization_guide_service() override; - net::URLRequestContextGetter* system_request_context() override; BrowserProcessPlatformPart* platform_part() override; extensions::EventRouterForwarder* extension_event_router_forwarder() override; @@ -152,7 +151,6 @@ void SetOptimizationGuideService( std::unique_ptr<optimization_guide::OptimizationGuideService> optimization_guide_service); - void SetSystemRequestContext(net::URLRequestContextGetter* context_getter); void SetSharedURLLoaderFactory( scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory); void SetNotificationUIManager( @@ -177,7 +175,8 @@ std::unique_ptr<policy::ChromeBrowserPolicyConnector> browser_policy_connector_; bool created_browser_policy_connector_ = false; - std::unique_ptr<network::NetworkQualityTracker> network_quality_tracker_; + std::unique_ptr<network::TestNetworkQualityTracker> + test_network_quality_tracker_; std::unique_ptr<ProfileManager> profile_manager_; std::unique_ptr<NotificationUIManager> notification_ui_manager_; std::unique_ptr<NotificationPlatformBridge> notification_platform_bridge_; @@ -206,7 +205,6 @@ // The following objects are not owned by TestingBrowserProcess: PrefService* local_state_; IOThread* io_thread_; - net::URLRequestContextGetter* system_request_context_; scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_; rappor::RapporServiceImpl* rappor_service_;
diff --git a/chrome/test/base/ui_test_utils.cc b/chrome/test/base/ui_test_utils.cc index 746c8d1..fc90694b 100644 --- a/chrome/test/base/ui_test_utils.cc +++ b/chrome/test/base/ui_test_utils.cc
@@ -94,7 +94,7 @@ BrowserAddedObserver observer; new_browser = observer.WaitForSingleNewBrowser(); // The new browser should never be in |excluded_browsers|. - DCHECK(!base::ContainsKey(excluded_browsers, new_browser)); + DCHECK(!base::Contains(excluded_browsers, new_browser)); } return new_browser; }
diff --git a/chrome/test/chromedriver/capabilities_unittest.cc b/chrome/test/chromedriver/capabilities_unittest.cc index 824a0d2..34f1c04c 100644 --- a/chrome/test/chromedriver/capabilities_unittest.cc +++ b/chrome/test/chromedriver/capabilities_unittest.cc
@@ -509,8 +509,8 @@ ASSERT_TRUE(status.IsOk()); ASSERT_EQ(2u, capabilities.exclude_switches.size()); const std::set<std::string>& switches = capabilities.exclude_switches; - ASSERT_TRUE(base::ContainsKey(switches, "switch1")); - ASSERT_TRUE(base::ContainsKey(switches, "switch2")); + ASSERT_TRUE(base::Contains(switches, "switch1")); + ASSERT_TRUE(base::Contains(switches, "switch2")); } TEST(ParseCapabilities, UseRemoteBrowser) {
diff --git a/chrome/test/chromedriver/chrome/device_manager.cc b/chrome/test/chromedriver/chrome/device_manager.cc index 2558656..e1ddf77 100644 --- a/chrome/test/chromedriver/chrome/device_manager.cc +++ b/chrome/test/chromedriver/chrome/device_manager.cc
@@ -218,7 +218,7 @@ if (status.IsError()) return status; - if (!base::ContainsValue(devices, device_serial)) + if (!base::Contains(devices, device_serial)) return Status(kUnknownError, "Device " + device_serial + " is not online"); @@ -246,5 +246,5 @@ } bool DeviceManager::IsDeviceLocked(const std::string& device_serial) { - return base::ContainsValue(active_devices_, device_serial); + return base::Contains(active_devices_, device_serial); }
diff --git a/chrome/test/chromedriver/chrome/devtools_http_client.cc b/chrome/test/chromedriver/chrome/devtools_http_client.cc index b529a081..61a5369c 100644 --- a/chrome/test/chromedriver/chrome/devtools_http_client.cc +++ b/chrome/test/chromedriver/chrome/devtools_http_client.cc
@@ -155,7 +155,7 @@ } bool DevToolsHttpClient::IsBrowserWindow(const WebViewInfo& view) const { - return base::ContainsKey(*window_types_, view.type) || + return base::Contains(*window_types_, view.type) || (view.type == WebViewInfo::kOther && (view.url == "chrome://print/" || view.url == "chrome://media-router/"));
diff --git a/chrome/test/chromedriver/commands.cc b/chrome/test/chromedriver/commands.cc index eb0ddabb..dc45e2a4 100644 --- a/chrome/test/chromedriver/commands.cc +++ b/chrome/test/chromedriver/commands.cc
@@ -272,7 +272,7 @@ status_tmp.code() != kChromeNotReachable) { status.AddDetails("failed to check if window was closed: " + status_tmp.message()); - } else if (!base::ContainsValue(web_view_ids, session->window)) { + } else if (!base::Contains(web_view_ids, session->window)) { status = Status(kOk); } }
diff --git a/chrome/test/chromedriver/net/test_http_server.cc b/chrome/test/chromedriver/net/test_http_server.cc index ed869c3..9f6ac99 100644 --- a/chrome/test/chromedriver/net/test_http_server.cc +++ b/chrome/test/chromedriver/net/test_http_server.cc
@@ -33,7 +33,7 @@ } bool TestHttpServer::Start() { - base::Thread::Options options(base::MessageLoop::TYPE_IO, 0); + base::Thread::Options options(base::MessagePump::Type::IO, 0); bool thread_started = thread_.StartWithOptions(options); EXPECT_TRUE(thread_started); if (!thread_started)
diff --git a/chrome/test/chromedriver/server/chromedriver_server.cc b/chrome/test/chromedriver/server/chromedriver_server.cc index 44b794c..b913909 100644 --- a/chrome/test/chromedriver/server/chromedriver_server.cc +++ b/chrome/test/chromedriver/server/chromedriver_server.cc
@@ -20,7 +20,6 @@ #include "base/files/file_util.h" #include "base/lazy_instance.h" #include "base/logging.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" @@ -29,6 +28,7 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/synchronization/waitable_event.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/threading/thread.h" #include "base/threading/thread_local.h" @@ -202,7 +202,7 @@ const HttpResponseSenderFunc& send_response_func) { if (!whitelisted_ips.empty()) { const net::IPAddress& peer_address = request.peer.address(); - if (!base::ContainsValue(whitelisted_ips, peer_address)) { + if (!base::Contains(whitelisted_ips, peer_address)) { LOG(WARNING) << "unauthorized access from " << request.peer.ToString(); std::unique_ptr<net::HttpServerResponseInfo> response( new net::HttpServerResponseInfo(net::HTTP_UNAUTHORIZED)); @@ -356,7 +356,7 @@ CHECK(io_thread.StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0))); - base::MessageLoop cmd_loop; + base::SingleThreadTaskExecutor main_task_executor; base::RunLoop cmd_run_loop; HttpHandler handler(cmd_run_loop.QuitClosure(), io_thread.task_runner(), url_base, adb_port); @@ -364,10 +364,10 @@ base::Bind(&HandleRequestOnCmdThread, &handler, whitelisted_ips); io_thread.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&StartServerOnIOThread, port, allow_remote, - base::Bind(&HandleRequestOnIOThread, - cmd_loop.task_runner(), handle_request_func))); + FROM_HERE, base::BindOnce(&StartServerOnIOThread, port, allow_remote, + base::Bind(&HandleRequestOnIOThread, + main_task_executor.task_runner(), + handle_request_func))); // Run the command loop. This loop is quit after the response for a shutdown // request is posted to the IO loop. After the command loop quits, a task // is posted to the IO loop to stop the server. Lastly, the IO thread is
diff --git a/chrome/test/data/extensions/api_test/autotest_private/test.js b/chrome/test/data/extensions/api_test/autotest_private/test.js index 2a0f0cf..2d51358a 100644 --- a/chrome/test/data/extensions/api_test/autotest_private/test.js +++ b/chrome/test/data/extensions/api_test/autotest_private/test.js
@@ -335,7 +335,9 @@ } } chrome.test.assertTrue(displayId != "-1"); - var behaviors = ["always", "never", "hidden"]; + // SHELF_AUTO_HIDE_ALWAYS_HIDDEN not supported by shelf_prefs. + // TODO(ricardoq): Use enums in IDL instead of hardcoded strings. + var behaviors = ["always", "never"]; var l = behaviors.length; for (var i = 0; i < l; i++) { var behavior = behaviors[i]; @@ -365,19 +367,24 @@ } } chrome.test.assertTrue(displayId != "-1"); - // When running 'browser_tests', Chrome OS reports itself as locked, - // so the only valid shelf is Bottom Locked. - var alignment = chrome.autotestPrivate.ShelfAlignmentType.BOTTOM_LOCKED; - chrome.autotestPrivate.setShelfAlignment(displayId, alignment, - function() { - chrome.test.assertNoLastError(); - chrome.autotestPrivate.getShelfAlignment(displayId, - function(newAlignment) { + // SHELF_ALIGNMENT_BOTTOM_LOCKED not supported by shelf_prefs. + var alignments = [chrome.autotestPrivate.ShelfAlignmentType.LEFT, + chrome.autotestPrivate.ShelfAlignmentType.BOTTOM, + chrome.autotestPrivate.ShelfAlignmentType.RIGHT] + var l = alignments.length; + for (var i = 0; i < l; i++) { + var alignment = alignments[i]; + chrome.autotestPrivate.setShelfAlignment(displayId, alignment, + function() { chrome.test.assertNoLastError(); - chrome.test.assertEq(newAlignment, alignment); - chrome.test.succeed(); + chrome.autotestPrivate.getShelfAlignment(displayId, + function(newAlignment) { + chrome.test.assertNoLastError(); + chrome.test.assertEq(newAlignment, alignment); + }); }); - }); + } + chrome.test.succeed(); }); }, ];
diff --git a/chrome/test/data/extensions/api_test/proxy/events/parse_error.js b/chrome/test/data/extensions/api_test/proxy/events/parse_error.js index 67338ab..0b0079f 100644 --- a/chrome/test/data/extensions/api_test/proxy/events/parse_error.js +++ b/chrome/test/data/extensions/api_test/proxy/events/parse_error.js
@@ -5,16 +5,31 @@ // proxy api test // browser_tests.exe --gtest_filter=ProxySettingsApiTest.ProxyEventsParseError -var expected_error = { - error: "net::ERR_PAC_SCRIPT_FAILED", +// TODO(crbug.com/943636): remove old error once +// https://chromium-review.googlesource.com/c/v8/v8/+/1593307 is rolled into +// chromium. + +var expected_error_v1 = { details: "line: 1: Uncaught SyntaxError: Unexpected token !", + error: "net::ERR_PAC_SCRIPT_FAILED", + fatal: false +}; + +var expected_error_v2 = { + details: "line: 1: Uncaught SyntaxError: Unexpected token '!'", + error: "net::ERR_PAC_SCRIPT_FAILED", fatal: false }; function test() { // Install error handler and get the test server config. chrome.proxy.onProxyError.addListener(function (error) { - chrome.test.assertEq(expected_error, error); + const actualErrorJson = JSON.stringify(error); + chrome.test.assertTrue( + actualErrorJson == JSON.stringify(expected_error_v1) || + actualErrorJson == JSON.stringify(expected_error_v2), + actualErrorJson + ); chrome.test.notifyPass(); });
diff --git a/chrome/test/media_router/media_router_e2e_browsertest.cc b/chrome/test/media_router/media_router_e2e_browsertest.cc index cb8d10a..46cd8b93 100644 --- a/chrome/test/media_router/media_router_e2e_browsertest.cc +++ b/chrome/test/media_router/media_router_e2e_browsertest.cc
@@ -109,7 +109,7 @@ } bool MediaRouterE2EBrowserTest::IsSinkDiscovered() const { - return base::ContainsKey(observer_->sink_map, receiver_); + return base::Contains(observer_->sink_map, receiver_); } bool MediaRouterE2EBrowserTest::IsRouteCreated() const {
diff --git a/chrome/test/pixel/skia_gold_pixel_diff.cc b/chrome/test/pixel/skia_gold_pixel_diff.cc index d678775..794edd2b 100644 --- a/chrome/test/pixel/skia_gold_pixel_diff.cc +++ b/chrome/test/pixel/skia_gold_pixel_diff.cc
@@ -14,6 +14,7 @@ #include "base/command_line.h" #include "base/files/file.h" #include "base/files/file_util.h" +#include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/logging.h" #include "base/path_service.h" @@ -40,21 +41,31 @@ std::string kBuildRevisionKey = "build-revision"; +std::string kNoLuciAuth = "no-luci-auth"; + SkiaGoldPixelDiff::SkiaGoldPixelDiff() = default; SkiaGoldPixelDiff::~SkiaGoldPixelDiff() = default; -void SkiaGoldPixelDiff::Init(BrowserWindow* browser, - const std::string& screenshot_prefix) { - auto* cmd_line = base::CommandLine::ForCurrentProcess(); - ASSERT_TRUE(cmd_line->HasSwitch(kBuildRevisionKey)) - << "Missing switch " << kBuildRevisionKey; - build_revision_ = cmd_line->GetSwitchValueASCII(kBuildRevisionKey); - initialized_ = true; - prefix_ = screenshot_prefix; - browser_ = browser; - base::CreateNewTempDirectory( - FILE_PATH_LITERAL("SkiaGoldTemp"), &working_dir_); +base::FilePath GetAbsoluteSrcRelativePath(base::FilePath::StringType path) { + base::FilePath root_path; + base::PathService::Get(base::BasePathKey::DIR_SOURCE_ROOT, &root_path); + return base::MakeAbsoluteFilePath(root_path.Append(path)); +} + +// Append args after program. +// The base::Commandline.AppendArg append the arg at +// the end which doesn't work for us. +void AppendArgsJustAfterProgram(base::CommandLine& cmd, + base::CommandLine::StringVector args) { + base::CommandLine::StringVector& argv = + const_cast<base::CommandLine::StringVector&>(cmd.argv()); + int args_size = args.size(); + argv.resize(argv.size() + args_size); + for (int i = argv.size() - args_size; i > 1; --i) { + argv[i + args_size - 1] = argv[i - 1]; + } + argv.insert(argv.begin() + 1, args.begin(), args.end()); } // Fill in test environment to the keys_file. The format is json. @@ -107,38 +118,77 @@ return true; } +int SkiaGoldPixelDiff::LaunchProcess(base::CommandLine::StringType& cmdline) { + base::Process sub_process = base::LaunchProcess( + cmdline, base::LaunchOptionsForTest()); + int exit_code; + sub_process.WaitForExit(&exit_code); + return exit_code; +} + +void SkiaGoldPixelDiff::InitSkiaGold() { + base::ScopedAllowBlockingForTesting allow_blocking; + base::CommandLine cmd(GetAbsoluteSrcRelativePath(kSkiaGoldCtl)); + cmd.AppendSwitchPath("work-dir", working_dir_); + if (luci_auth_) { + cmd.AppendArg("--luci"); + } + AppendArgsJustAfterProgram(cmd, {FILE_PATH_LITERAL("auth")}); + base::CommandLine::StringType cmd_str = cmd.GetCommandLineString(); + LOG(INFO) << "Skia Gold Auth Commandline: " << cmd_str; + int exit_code = LaunchProcess(cmd_str); + ASSERT_EQ(exit_code, 0); + + base::FilePath json_temp_file = working_dir_.Append( + FILE_PATH_LITERAL("keys_file.txt")); + FillInTestEnvironment(json_temp_file); + base::FilePath failure_temp_file = working_dir_.Append( + FILE_PATH_LITERAL("failure.log")); + cmd = base::CommandLine(GetAbsoluteSrcRelativePath(kSkiaGoldCtl)); + cmd.AppendSwitchASCII("instance", kSkiaGoldInstance); + cmd.AppendSwitchPath("work-dir", working_dir_); + cmd.AppendSwitchPath("keys-file", json_temp_file); + cmd.AppendSwitchPath("failure-file", failure_temp_file); + cmd.AppendSwitch("passfail"); + cmd.AppendSwitchASCII("commit", build_revision_); + AppendArgsJustAfterProgram(cmd, {FILE_PATH_LITERAL("imgtest"), FILE_PATH_LITERAL("init")}); + cmd_str = cmd.GetCommandLineString(); + LOG(INFO) << "Skia Gold imgtest init Commandline: " << cmd_str; + exit_code = LaunchProcess(cmd_str); + ASSERT_EQ(exit_code, 0); +} + +void SkiaGoldPixelDiff::Init(BrowserWindow* browser, + const std::string& screenshot_prefix) { + auto* cmd_line = base::CommandLine::ForCurrentProcess(); + ASSERT_TRUE(cmd_line->HasSwitch(kBuildRevisionKey)) + << "Missing switch " << kBuildRevisionKey; + build_revision_ = cmd_line->GetSwitchValueASCII(kBuildRevisionKey); + if (cmd_line->HasSwitch(kNoLuciAuth)) { + luci_auth_ = false; + } + initialized_ = true; + prefix_ = screenshot_prefix; + browser_ = browser; + base::CreateNewTempDirectory( + FILE_PATH_LITERAL("SkiaGoldTemp"), &working_dir_); + + InitSkiaGold(); +} + bool SkiaGoldPixelDiff::UploadToSkiaGoldServer( const base::FilePath& local_file_path, const std::string& remote_golden_image_name) { base::ScopedAllowBlockingForTesting allow_blocking; - base::FilePath json_temp_file = working_dir_.Append( - FILE_PATH_LITERAL("keys_file.txt")); - FillInTestEnvironment(json_temp_file); - base::FilePath root_path; - base::PathService::Get(base::BasePathKey::DIR_SOURCE_ROOT, &root_path); - base::FilePath goldctl = base::MakeAbsoluteFilePath( - root_path.Append(kSkiaGoldCtl)); - base::CommandLine cmd(goldctl); - cmd.AppendArg("imgtest"); - cmd.AppendArg("add"); + base::CommandLine cmd(GetAbsoluteSrcRelativePath(kSkiaGoldCtl)); cmd.AppendSwitchASCII("test-name", remote_golden_image_name); - cmd.AppendSwitchASCII("instance", kSkiaGoldInstance); - cmd.AppendSwitchASCII("keys-file", json_temp_file.AsUTF8Unsafe()); cmd.AppendSwitchPath("png-file", local_file_path); - cmd.AppendSwitchASCII("work-dir", working_dir_.AsUTF8Unsafe()); - cmd.AppendSwitchASCII("failure-file", "failure.log"); - cmd.AppendSwitch("passfail"); - cmd.AppendSwitchASCII("commit", build_revision_); - - LOG(INFO) << "Skia Gold Commandline: " << cmd.GetCommandLineString(); - base::Process sub_process = base::LaunchProcess( - cmd, base::LaunchOptionsForTest()); - int exit_code; - sub_process.WaitForExit(&exit_code); - LOG(INFO) << "exit code" <<exit_code; - // TODO(svenzheng): return correct value when this function can - // correctly compare images. - return true; + cmd.AppendSwitchPath("work-dir", working_dir_); + AppendArgsJustAfterProgram(cmd, {FILE_PATH_LITERAL("imgtest"), FILE_PATH_LITERAL("add")}); + base::CommandLine::StringType cmd_str = cmd.GetCommandLineString(); + LOG(INFO) << "Skia Gold Commandline: " << cmd_str; + int exit_code = LaunchProcess(cmd_str); + return exit_code == 0; } bool SkiaGoldPixelDiff::GrabWindowSnapshotInternal(gfx::NativeWindow window, @@ -201,6 +251,5 @@ << ". Return code: " << ret_code; return false; } - UploadToSkiaGoldServer(temporary_path, name); - return true; + return UploadToSkiaGoldServer(temporary_path, name); }
diff --git a/chrome/test/pixel/skia_gold_pixel_diff.h b/chrome/test/pixel/skia_gold_pixel_diff.h index e965ce70..d85d6081 100644 --- a/chrome/test/pixel/skia_gold_pixel_diff.h +++ b/chrome/test/pixel/skia_gold_pixel_diff.h
@@ -6,6 +6,7 @@ #define CHROME_TEST_PIXEL_SKIA_GOLD_PIXEL_DIFF_H_ #include <string> +#include "base/command_line.h" #include "base/files/file_path.h" #include "ui/gfx/native_widget_types.h" @@ -65,11 +66,15 @@ virtual bool GrabWindowSnapshotInternal(gfx::NativeWindow window, const gfx::Rect& snapshot_bounds, gfx::Image* image); + void InitSkiaGold(); + virtual int LaunchProcess(base::CommandLine::StringType& cmdline); private: std::string prefix_; BrowserWindow* browser_; bool initialized_ = false; + // Use luci auth on bots. Don't use luci auth for local development. + bool luci_auth_ = true; std::string build_revision_; // The working dir for goldctl. It's the dir for storing temporary files. base::FilePath working_dir_;
diff --git a/chrome/test/pixel/skia_gold_pixel_diff_unittest.cc b/chrome/test/pixel/skia_gold_pixel_diff_unittest.cc index 35e44a9..0043706c 100644 --- a/chrome/test/pixel/skia_gold_pixel_diff_unittest.cc +++ b/chrome/test/pixel/skia_gold_pixel_diff_unittest.cc
@@ -38,6 +38,9 @@ *image = gfx::Image::CreateFrom1xBitmap(bitmap); return true; } + int LaunchProcess(base::CommandLine::StringType& cmdline) { + return 0; + } }; class SkiaGoldPixelDiffTest : public ::testing::Test {
diff --git a/chrome/tools/service_discovery_sniffer/service_discovery_sniffer.cc b/chrome/tools/service_discovery_sniffer/service_discovery_sniffer.cc index 3d7b5dc..80e8f568 100644 --- a/chrome/tools/service_discovery_sniffer/service_discovery_sniffer.cc +++ b/chrome/tools/service_discovery_sniffer/service_discovery_sniffer.cc
@@ -9,8 +9,8 @@ #include "base/at_exit.h" #include "base/bind.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "chrome/browser/local_discovery/service_discovery_client_impl.h" #include "net/dns/mdns_client.h" @@ -98,7 +98,7 @@ int main(int argc, char** argv) { base::AtExitManager at_exit_manager; - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); if (argc != 2) { printf("Please provide exactly 1 argument.\n");
diff --git a/chrome/updater/updater.cc b/chrome/updater/updater.cc index e52e839..65171a6 100644 --- a/chrome/updater/updater.cc +++ b/chrome/updater/updater.cc
@@ -18,11 +18,11 @@ #include "base/files/file_path.h" #include "base/logging.h" #include "base/memory/scoped_refptr.h" -#include "base/message_loop/message_loop.h" #include "base/optional.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/task/post_task.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/task_runner.h" #include "base/threading/platform_thread.h" @@ -150,7 +150,8 @@ installer->FindInstallOfApp(); const auto component = installer->MakeCrxComponent(); - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::RunLoop runloop; DCHECK(base::ThreadTaskRunnerHandle::IsSet());
diff --git a/chrome/utility/importer/firefox_importer_unittest_utils.h b/chrome/utility/importer/firefox_importer_unittest_utils.h index 83ccc38..adf061d 100644 --- a/chrome/utility/importer/firefox_importer_unittest_utils.h +++ b/chrome/utility/importer/firefox_importer_unittest_utils.h
@@ -17,7 +17,7 @@ class FFDecryptorServerChannelListener; namespace base { -class MessageLoopForIO; +class SingleThreadTaskExecutor; } // On OS X NSSDecryptor needs to run in a separate process. To allow us to use @@ -44,7 +44,7 @@ #if defined(OS_MACOSX) base::Process child_process_; std::unique_ptr<FFDecryptorServerChannelListener> listener_; - std::unique_ptr<base::MessageLoopForIO> message_loop_; + std::unique_ptr<base::SingleThreadTaskExecutor> main_task_executor_; #else NSSDecryptor decryptor_; #endif // !OS_MACOSX
diff --git a/chrome/utility/importer/firefox_importer_unittest_utils_mac.cc b/chrome/utility/importer/firefox_importer_unittest_utils_mac.cc index ce267d3..9b003a7 100644 --- a/chrome/utility/importer/firefox_importer_unittest_utils_mac.cc +++ b/chrome/utility/importer/firefox_importer_unittest_utils_mac.cc
@@ -11,7 +11,6 @@ #include "base/files/file_util.h" #include "base/files/scoped_file.h" #include "base/location.h" -#include "base/message_loop/message_loop.h" #include "base/posix/global_descriptors.h" #include "base/process/kill.h" #include "base/process/launch.h" @@ -19,6 +18,7 @@ #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/test/multiprocess_test.h" #include "base/test/test_timeouts.h" #include "base/threading/thread_task_runner_handle.h" @@ -180,8 +180,9 @@ } bool FFUnitTestDecryptorProxy::Setup(const base::FilePath& nss_path) { - // Create a new message loop and spawn the child process. - message_loop_ = std::make_unique<base::MessageLoopForIO>(); + // Create a new task executor and spawn the child process. + main_task_executor_ = std::make_unique<base::SingleThreadTaskExecutor>( + base::MessagePump::Type::IO); mojo::OutgoingInvitation invitation; std::string token = base::NumberToString(base::RandUint64()); @@ -240,7 +241,7 @@ // Entry function in child process. MULTIPROCESS_TEST_MAIN(NSSDecrypterChildProcess) { - base::MessageLoopForIO main_message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); auto* command_line = base::CommandLine::ForCurrentProcess(); auto endpoint = mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine(
diff --git a/chrome/utility/importer/ie_importer_win.cc b/chrome/utility/importer/ie_importer_win.cc index 6be8496..d66b303 100644 --- a/chrome/utility/importer/ie_importer_win.cc +++ b/chrome/utility/importer/ie_importer_win.cc
@@ -520,7 +520,7 @@ GURL url(url_string); // Skips the URLs that are invalid or have other schemes. - if (!url.is_valid() || !base::ContainsValue(kSchemes, url.scheme())) + if (!url.is_valid() || !base::Contains(kSchemes, url.scheme())) continue; ImporterURLRow row(url);
diff --git a/chromecast/crash/linux/crash_uploader.cc b/chromecast/crash/linux/crash_uploader.cc index 3ff1b33..16d96f4 100644 --- a/chromecast/crash/linux/crash_uploader.cc +++ b/chromecast/crash/linux/crash_uploader.cc
@@ -11,7 +11,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "chromecast/base/cast_paths.h" @@ -40,8 +40,8 @@ // interfere with user playback. setpriority(PRIO_PROCESS, 0, 19); - // Create the main message loop. - base::MessageLoopForIO message_loop; + // Create the main task executor. + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); std::unique_ptr<chromecast::CastSysInfo> sys_info = chromecast::CreateSysInfo();
diff --git a/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc b/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc index 1bc8111..4e840cc 100644 --- a/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc +++ b/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc
@@ -6,9 +6,9 @@ #include <vector> #include "base/at_exit.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_for_io.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "chromecast/external_mojo/external_service_support/process_setup.h" #include "chromecast/external_mojo/public/cpp/external_mojo_broker.h" #include "mojo/core/embedder/embedder.h" @@ -20,7 +20,7 @@ base::AtExitManager exit_manager; chromecast::external_service_support::CommonProcessInitialization(argc, argv); - base::MessageLoopForIO main_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::RunLoop run_loop; mojo::core::Configuration mojo_config; @@ -28,7 +28,7 @@ mojo::core::Init(mojo_config); mojo::core::ScopedIPCSupport ipc_support( - main_loop.task_runner(), + io_task_executor.task_runner(), mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); chromecast::external_mojo::ExternalMojoBroker broker;
diff --git a/chromecast/external_mojo/external_service_support/standalone_service_main.cc b/chromecast/external_mojo/external_service_support/standalone_service_main.cc index 9f4dfd20..8982d5b 100644 --- a/chromecast/external_mojo/external_service_support/standalone_service_main.cc +++ b/chromecast/external_mojo/external_service_support/standalone_service_main.cc
@@ -7,8 +7,8 @@ #include "base/at_exit.h" #include "base/bind.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_for_io.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "chromecast/external_mojo/external_service_support/external_connector.h" #include "chromecast/external_mojo/external_service_support/process_setup.h" @@ -40,13 +40,13 @@ base::AtExitManager exit_manager; chromecast::external_service_support::CommonProcessInitialization(argc, argv); - base::MessageLoopForIO main_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::RunLoop run_loop; mojo::core::Init(); mojo::core::ScopedIPCSupport ipc_support( - main_loop.task_runner(), + io_task_executor.task_runner(), mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); base::ThreadPoolInstance::CreateAndStartWithDefaultParams(
diff --git a/chromecast/tracing/tracing_service_main.cc b/chromecast/tracing/tracing_service_main.cc index c0be51d..7914e21 100644 --- a/chromecast/tracing/tracing_service_main.cc +++ b/chromecast/tracing/tracing_service_main.cc
@@ -15,13 +15,13 @@ #include "base/command_line.h" #include "base/logging.h" #include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_current.h" #include "base/message_loop/message_pump_for_io.h" #include "base/posix/eintr_wrapper.h" #include "base/posix/unix_domain_socket.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "chromecast/tracing/ftrace.h" @@ -401,7 +401,7 @@ LOG(INFO) << "Starting system tracing service..."; - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); chromecast::tracing::TracingService service; if (!service.Init())
diff --git a/chromeos/network/proxy/proxy_config_service_impl.cc b/chromeos/network/proxy/proxy_config_service_impl.cc index eaf4dbb1..26ae3a0b 100644 --- a/chromeos/network/proxy/proxy_config_service_impl.cc +++ b/chromeos/network/proxy/proxy_config_service_impl.cc
@@ -73,11 +73,13 @@ local_state_pref_registrar_.Add(::onc::prefs::kDeviceOpenNetworkConfiguration, proxy_change_callback); - // Register for changes to the default network. - NetworkStateHandler* state_handler = - NetworkHandler::Get()->network_state_handler(); - state_handler->AddObserver(this, FROM_HERE); - DefaultNetworkChanged(state_handler->DefaultNetwork()); + if (NetworkHandler::IsInitialized()) { // null in unit tests. + // Register for changes to the default network. + NetworkStateHandler* state_handler = + NetworkHandler::Get()->network_state_handler(); + state_handler->AddObserver(this, FROM_HERE); + DefaultNetworkChanged(state_handler->DefaultNetwork()); + } } ProxyConfigServiceImpl::~ProxyConfigServiceImpl() {
diff --git a/chromeos/services/device_sync/cryptauth_device_manager_impl.cc b/chromeos/services/device_sync/cryptauth_device_manager_impl.cc index 3851887..9f926cf 100644 --- a/chromeos/services/device_sync/cryptauth_device_manager_impl.cc +++ b/chromeos/services/device_sync/cryptauth_device_manager_impl.cc
@@ -384,28 +384,25 @@ // these deprecated fields, instead of software features. To work around this, // these pref values are migrated to software features locally. if (old_unlock_key_value_from_prefs) { - if (!base::ContainsValue( - external_device->supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))) { + if (!base::Contains(external_device->supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))) { external_device->add_supported_software_features( SoftwareFeatureEnumToString( cryptauth::SoftwareFeature::EASY_UNLOCK_HOST)); } - if (!base::ContainsValue( - external_device->enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))) { + if (!base::Contains(external_device->enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))) { external_device->add_enabled_software_features( SoftwareFeatureEnumToString( cryptauth::SoftwareFeature::EASY_UNLOCK_HOST)); } } if (old_mobile_hotspot_supported_from_prefs) { - if (!base::ContainsValue( - external_device->supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))) { + if (!base::Contains(external_device->supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))) { external_device->add_supported_software_features( SoftwareFeatureEnumToString( cryptauth::SoftwareFeature::MAGIC_TETHER_HOST)); @@ -645,10 +642,9 @@ CryptAuthDeviceManagerImpl::GetUnlockKeys() const { std::vector<cryptauth::ExternalDeviceInfo> unlock_keys; for (const auto& device : synced_devices_) { - if (base::ContainsValue( - device.enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))) { + if (base::Contains(device.enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))) { unlock_keys.push_back(device); } } @@ -659,10 +655,9 @@ CryptAuthDeviceManagerImpl::GetPixelUnlockKeys() const { std::vector<cryptauth::ExternalDeviceInfo> unlock_keys; for (const auto& device : synced_devices_) { - if (base::ContainsValue( - device.enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST)) && + if (base::Contains(device.enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST)) && device.pixel_phone()) { unlock_keys.push_back(device); } @@ -674,10 +669,9 @@ CryptAuthDeviceManagerImpl::GetTetherHosts() const { std::vector<cryptauth::ExternalDeviceInfo> tether_hosts; for (const auto& device : synced_devices_) { - if (base::ContainsValue( - device.supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))) { + if (base::Contains(device.supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))) { tether_hosts.push_back(device); } } @@ -688,10 +682,9 @@ CryptAuthDeviceManagerImpl::GetPixelTetherHosts() const { std::vector<cryptauth::ExternalDeviceInfo> tether_hosts; for (const auto& device : synced_devices_) { - if (base::ContainsValue( - device.supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST)) && + if (base::Contains(device.supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST)) && device.pixel_phone()) tether_hosts.push_back(device); }
diff --git a/chromeos/services/device_sync/cryptauth_device_manager_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_device_manager_impl_unittest.cc index 27b5687..5832552 100644 --- a/chromeos/services/device_sync/cryptauth_device_manager_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_device_manager_impl_unittest.cc
@@ -161,16 +161,16 @@ device.supported_software_features_size()); for (const auto& software_feature : expected_device.supported_software_features()) { - EXPECT_TRUE(base::ContainsValue(device.supported_software_features(), - software_feature)); + EXPECT_TRUE(base::Contains(device.supported_software_features(), + software_feature)); } EXPECT_EQ(expected_device.enabled_software_features_size(), device.enabled_software_features_size()); for (const auto& software_feature : expected_device.enabled_software_features()) { - EXPECT_TRUE(base::ContainsValue(device.enabled_software_features(), - software_feature)); + EXPECT_TRUE( + base::Contains(device.enabled_software_features(), software_feature)); } } } @@ -366,13 +366,13 @@ enabled_software_features.size()); for (auto supported_software_feature : expected_device.supported_software_features()) { - EXPECT_TRUE(base::ContainsValue( + EXPECT_TRUE(base::Contains( supported_software_features, SoftwareFeatureStringToEnum(supported_software_feature))); } for (auto enabled_software_feature : expected_device.enabled_software_features()) { - EXPECT_TRUE(base::ContainsValue( + EXPECT_TRUE(base::Contains( enabled_software_features, SoftwareFeatureStringToEnum(enabled_software_feature))); } @@ -735,18 +735,18 @@ EXPECT_EQ(2, synced_devices[0].supported_software_features().size()); EXPECT_TRUE( - base::ContainsValue(synced_devices[0].supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); + base::Contains(synced_devices[0].supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); EXPECT_TRUE( - base::ContainsValue(synced_devices[0].supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); + base::Contains(synced_devices[0].supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); EXPECT_EQ(1, synced_devices[0].enabled_software_features().size()); EXPECT_TRUE( - base::ContainsValue(synced_devices[0].enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); + base::Contains(synced_devices[0].enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); } TEST_F(DeviceSyncCryptAuthDeviceManagerImplTest, SyncSucceedsForFirstTime) { @@ -1109,21 +1109,21 @@ EXPECT_FALSE(synced_device.mobile_hotspot_supported()); EXPECT_TRUE( - base::ContainsValue(synced_device.supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); + base::Contains(synced_device.supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); EXPECT_TRUE( - base::ContainsValue(synced_device.enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); + base::Contains(synced_device.enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); EXPECT_TRUE( - base::ContainsValue(synced_device.supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); + base::Contains(synced_device.supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); EXPECT_FALSE( - base::ContainsValue(synced_device.enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); + base::Contains(synced_device.enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); } TEST_F(DeviceSyncCryptAuthDeviceManagerImplTest, @@ -1160,21 +1160,21 @@ EXPECT_FALSE(synced_device.mobile_hotspot_supported()); EXPECT_TRUE( - base::ContainsValue(synced_device.supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); + base::Contains(synced_device.supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); EXPECT_TRUE( - base::ContainsValue(synced_device.enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); + base::Contains(synced_device.enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); EXPECT_TRUE( - base::ContainsValue(synced_device.supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); + base::Contains(synced_device.supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); EXPECT_FALSE( - base::ContainsValue(synced_device.enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); + base::Contains(synced_device.enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); } // Regression test for crbug.com/888031. @@ -1210,21 +1210,21 @@ // CryptAuthDeviceManager should recognize that the SoftwareFeature prefs had // been stored as refs, and convert them to their full string representations. EXPECT_TRUE( - base::ContainsValue(synced_device.supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); + base::Contains(synced_device.supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); EXPECT_TRUE( - base::ContainsValue(synced_device.enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); + base::Contains(synced_device.enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::EASY_UNLOCK_HOST))); EXPECT_TRUE( - base::ContainsValue(synced_device.supported_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); + base::Contains(synced_device.supported_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); EXPECT_FALSE( - base::ContainsValue(synced_device.enabled_software_features(), - SoftwareFeatureEnumToString( - cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); + base::Contains(synced_device.enabled_software_features(), + SoftwareFeatureEnumToString( + cryptauth::SoftwareFeature::MAGIC_TETHER_HOST))); } TEST_F(DeviceSyncCryptAuthDeviceManagerImplTest,
diff --git a/chromeos/services/device_sync/cryptauth_device_registry.cc b/chromeos/services/device_sync/cryptauth_device_registry.cc index fe02774..32ad90ae 100644 --- a/chromeos/services/device_sync/cryptauth_device_registry.cc +++ b/chromeos/services/device_sync/cryptauth_device_registry.cc
@@ -35,7 +35,7 @@ } void CryptAuthDeviceRegistry::DeleteDevice(const std::string& instance_id) { - DCHECK(base::ContainsKey(instance_id_to_device_map_, instance_id)); + DCHECK(base::Contains(instance_id_to_device_map_, instance_id)); instance_id_to_device_map_.erase(instance_id); OnDeviceRegistryUpdated();
diff --git a/chromeos/services/device_sync/cryptauth_key_bundle.cc b/chromeos/services/device_sync/cryptauth_key_bundle.cc index f8dabff..1abd4eca 100644 --- a/chromeos/services/device_sync/cryptauth_key_bundle.cc +++ b/chromeos/services/device_sync/cryptauth_key_bundle.cc
@@ -110,7 +110,7 @@ } // Return nullopt if duplicate handles exist. - if (base::ContainsKey(bundle.handle_to_key_map(), key->handle())) + if (base::Contains(bundle.handle_to_key_map(), key->handle())) return base::nullopt; bundle.AddKey(*key); @@ -168,7 +168,7 @@ } void CryptAuthKeyBundle::DeleteKey(const std::string& handle) { - DCHECK(base::ContainsKey(handle_to_key_map_, handle)); + DCHECK(base::Contains(handle_to_key_map_, handle)); handle_to_key_map_.erase(handle); }
diff --git a/chromeos/services/device_sync/cryptauth_key_registry_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_key_registry_impl_unittest.cc index c7a2b67..08088c7 100644 --- a/chromeos/services/device_sync/cryptauth_key_registry_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_key_registry_impl_unittest.cc
@@ -187,10 +187,8 @@ key_registry()->GetKeyBundle(CryptAuthKeyBundle::Name::kLegacyMasterKey); ASSERT_TRUE(key_bundle); - EXPECT_FALSE( - base::ContainsKey(key_bundle->handle_to_key_map(), "sym-handle")); - EXPECT_TRUE( - base::ContainsKey(key_bundle->handle_to_key_map(), "asym-handle")); + EXPECT_FALSE(base::Contains(key_bundle->handle_to_key_map(), "sym-handle")); + EXPECT_TRUE(base::Contains(key_bundle->handle_to_key_map(), "asym-handle")); CryptAuthKeyBundle expected_bundle( CryptAuthKeyBundle::Name::kLegacyMasterKey);
diff --git a/chromeos/services/device_sync/cryptauth_v2_enroller_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_v2_enroller_impl_unittest.cc index f5298eb..c43a8ae4 100644 --- a/chromeos/services/device_sync/cryptauth_v2_enroller_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_v2_enroller_impl_unittest.cc
@@ -433,8 +433,7 @@ name_key_pair : expected_new_keys) { const CryptAuthKeyBundle::Name& bundle_name = name_key_pair.first; const CryptAuthKey& key = name_key_pair.second; - ASSERT_TRUE( - base::ContainsKey(key_creator()->keys_to_create(), bundle_name)); + ASSERT_TRUE(base::Contains(key_creator()->keys_to_create(), bundle_name)); const CryptAuthKeyCreator::CreateKeyData& create_key_data = key_creator()->keys_to_create().find(bundle_name)->second;
diff --git a/components/BUILD.gn b/components/BUILD.gn index 3f8e79f4..525606f 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -344,7 +344,6 @@ deps += [ "//components/arc:unit_tests", "//components/ownership:unit_tests", - "//components/pairing:unit_tests", "//components/timers:unit_tests", "//components/user_manager:unit_tests", ]
diff --git a/components/content_settings/core/browser/cookie_settings.cc b/components/content_settings/core/browser/cookie_settings.cc index 47430ee..ddc490d 100644 --- a/components/content_settings/core/browser/cookie_settings.cc +++ b/components/content_settings/core/browser/cookie_settings.cc
@@ -5,11 +5,14 @@ #include "components/content_settings/core/browser/cookie_settings.h" #include "base/bind.h" +#include "base/feature_list.h" #include "base/logging.h" #include "components/content_settings/core/browser/content_settings_utils.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/content_settings/core/common/content_settings_utils.h" +#include "components/content_settings/core/common/features.h" #include "components/content_settings/core/common/pref_names.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" @@ -26,13 +29,17 @@ const char* extension_scheme) : host_content_settings_map_(host_content_settings_map), extension_scheme_(extension_scheme), - block_third_party_cookies_( - prefs->GetBoolean(prefs::kBlockThirdPartyCookies)) { + block_third_party_cookies_(false) { pref_change_registrar_.Init(prefs); pref_change_registrar_.Add( prefs::kBlockThirdPartyCookies, - base::Bind(&CookieSettings::OnBlockThirdPartyCookiesChanged, + base::Bind(&CookieSettings::OnCookiePreferencesChanged, base::Unretained(this))); + pref_change_registrar_.Add( + prefs::kCookieControlsEnabled, + base::Bind(&CookieSettings::OnCookiePreferencesChanged, + base::Unretained(this))); + OnCookiePreferencesChanged(); } ContentSetting CookieSettings::GetDefaultCookieSetting( @@ -52,6 +59,9 @@ registry->RegisterBooleanPref( prefs::kBlockThirdPartyCookies, false, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); + registry->RegisterBooleanPref( + prefs::kCookieControlsEnabled, false, + user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); } void CookieSettings::SetDefaultCookieSetting(ContentSetting setting) { @@ -74,6 +84,30 @@ CONTENT_SETTING_DEFAULT); } +bool CookieSettings::IsThirdPartyAccessAllowed(const GURL& first_party_url) { + // Use GURL() as an opaque primary url to check if any site + // could access cookies in a 3p context on |first_party_url|. + return IsCookieAccessAllowed(GURL(), first_party_url); +} + +void CookieSettings::SetThirdPartyCookieSetting(const GURL& first_party_url, + ContentSetting setting) { + DCHECK(IsValidSetting(setting)); + host_content_settings_map_->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::FromURLNoWildcard(first_party_url), + ContentSettingsType::CONTENT_SETTINGS_TYPE_COOKIES, std::string(), + setting); +} + +void CookieSettings::ResetThirdPartyCookieSetting(const GURL& first_party_url) { + host_content_settings_map_->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::FromURLNoWildcard(first_party_url), + ContentSettingsType::CONTENT_SETTINGS_TYPE_COOKIES, std::string(), + CONTENT_SETTING_DEFAULT); +} + bool CookieSettings::IsStorageDurable(const GURL& origin) const { // TODO(dgrogan): Don't use host_content_settings_map_ directly. // https://crbug.com/539538 @@ -138,12 +172,20 @@ CookieSettings::~CookieSettings() { } -void CookieSettings::OnBlockThirdPartyCookiesChanged() { +void CookieSettings::OnCookiePreferencesChanged() { DCHECK(thread_checker_.CalledOnValidThread()); - base::AutoLock auto_lock(lock_); - block_third_party_cookies_ = pref_change_registrar_.prefs()->GetBoolean( - prefs::kBlockThirdPartyCookies); + bool new_block_third_party_cookies = + pref_change_registrar_.prefs()->GetBoolean( + prefs::kBlockThirdPartyCookies) || + (base::FeatureList::IsEnabled(kImprovedCookieControls) && + pref_change_registrar_.prefs()->GetBoolean( + prefs::kCookieControlsEnabled)); + + if (block_third_party_cookies_ != new_block_third_party_cookies) { + base::AutoLock auto_lock(lock_); + block_third_party_cookies_ = new_block_third_party_cookies; + } } bool CookieSettings::ShouldBlockThirdPartyCookies() const {
diff --git a/components/content_settings/core/browser/cookie_settings.h b/components/content_settings/core/browser/cookie_settings.h index 6d3abef..d339149c 100644 --- a/components/content_settings/core/browser/cookie_settings.h +++ b/components/content_settings/core/browser/cookie_settings.h
@@ -70,8 +70,31 @@ // This should only be called on the UI thread. void ResetCookieSetting(const GURL& primary_url); + // Returns true if cookies are allowed for *most* third parties on |url|. + // There might be rules allowing or blocking specific third parties from + // accessing cookies. + // + // This should only be called on the UI thread. + bool IsThirdPartyAccessAllowed(const GURL& first_party_url); + + // Sets the cookie setting for the site and third parties embedded in it. + // + // This should only be called on the UI thread. + void SetThirdPartyCookieSetting(const GURL& first_party_url, + ContentSetting setting); + + // Resets the third party cookie setting for the given url. + // + // This should only be called on the UI thread. + void ResetThirdPartyCookieSetting(const GURL& first_party_url); + bool IsStorageDurable(const GURL& origin) const; + // Returns true if third party cookies should be blocked. + // + // This method may be called on any thread. + bool ShouldBlockThirdPartyCookies() const; + // Detaches the |CookieSettings| from |PrefService|. This methods needs to be // called before destroying the service. Afterwards, only const methods can be // called. @@ -88,12 +111,7 @@ private: ~CookieSettings() override; - void OnBlockThirdPartyCookiesChanged(); - - // Returns true if the "block third party cookies" preference is set. - // - // This method may be called on any thread. - bool ShouldBlockThirdPartyCookies() const; + void OnCookiePreferencesChanged(); base::ThreadChecker thread_checker_; scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
diff --git a/components/content_settings/core/browser/cookie_settings_unittest.cc b/components/content_settings/core/browser/cookie_settings_unittest.cc index 57ce3858..d9cca79 100644 --- a/components/content_settings/core/browser/cookie_settings_unittest.cc +++ b/components/content_settings/core/browser/cookie_settings_unittest.cc
@@ -4,9 +4,11 @@ #include "components/content_settings/core/browser/cookie_settings.h" +#include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings_pattern.h" +#include "components/content_settings/core/common/features.h" #include "components/content_settings/core/common/pref_names.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "extensions/buildflags/buildflags.h" @@ -103,6 +105,26 @@ EXPECT_FALSE(cookie_settings_->IsCookieSessionOnly(kBlockedSite)); } +TEST_F(CookieSettingsTest, CookiesControlsEnabled) { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kImprovedCookieControls); + ASSERT_TRUE( + cookie_settings_->IsCookieAccessAllowed(kBlockedSite, kFirstPartySite)); + prefs_.SetBoolean(prefs::kCookieControlsEnabled, true); + EXPECT_FALSE( + cookie_settings_->IsCookieAccessAllowed(kBlockedSite, kFirstPartySite)); +} + +TEST_F(CookieSettingsTest, CookiesControlsEnabledButFeatureDisabled) { + base::test::ScopedFeatureList features; + features.InitAndDisableFeature(kImprovedCookieControls); + ASSERT_TRUE( + cookie_settings_->IsCookieAccessAllowed(kBlockedSite, kFirstPartySite)); + prefs_.SetBoolean(prefs::kCookieControlsEnabled, true); + EXPECT_TRUE( + cookie_settings_->IsCookieAccessAllowed(kBlockedSite, kFirstPartySite)); +} + TEST_F(CookieSettingsTest, CookiesAllowThirdParty) { EXPECT_TRUE( cookie_settings_->IsCookieAccessAllowed(kBlockedSite, kFirstPartySite)); @@ -335,6 +357,32 @@ cookie_settings_->IsCookieAccessAllowed(kBlockedSite, kExtensionURL)); } +TEST_F(CookieSettingsTest, ThirdPartyException) { + EXPECT_TRUE(cookie_settings_->IsThirdPartyAccessAllowed(kFirstPartySite)); + EXPECT_TRUE( + cookie_settings_->IsCookieAccessAllowed(kHttpsSite, kFirstPartySite)); + + prefs_.SetBoolean(prefs::kBlockThirdPartyCookies, true); + EXPECT_FALSE(cookie_settings_->IsThirdPartyAccessAllowed(kFirstPartySite)); + EXPECT_FALSE( + cookie_settings_->IsCookieAccessAllowed(kHttpsSite, kFirstPartySite)); + + cookie_settings_->SetThirdPartyCookieSetting(kFirstPartySite, + CONTENT_SETTING_ALLOW); + EXPECT_TRUE(cookie_settings_->IsThirdPartyAccessAllowed(kFirstPartySite)); + EXPECT_TRUE( + cookie_settings_->IsCookieAccessAllowed(kHttpsSite, kFirstPartySite)); + + cookie_settings_->ResetThirdPartyCookieSetting(kFirstPartySite); + EXPECT_FALSE(cookie_settings_->IsThirdPartyAccessAllowed(kFirstPartySite)); + EXPECT_FALSE( + cookie_settings_->IsCookieAccessAllowed(kHttpsSite, kFirstPartySite)); + + cookie_settings_->SetCookieSetting(kHttpsSite, CONTENT_SETTING_ALLOW); + EXPECT_FALSE(cookie_settings_->IsThirdPartyAccessAllowed(kFirstPartySite)); + EXPECT_TRUE( + cookie_settings_->IsCookieAccessAllowed(kHttpsSite, kFirstPartySite)); +} } // namespace } // namespace content_settings
diff --git a/components/content_settings/core/common/BUILD.gn b/components/content_settings/core/common/BUILD.gn index d838eea..f396acdb2 100644 --- a/components/content_settings/core/common/BUILD.gn +++ b/components/content_settings/core/common/BUILD.gn
@@ -18,6 +18,8 @@ "content_settings_utils.h", "cookie_settings_base.cc", "cookie_settings_base.h", + "features.cc", + "features.h", "pref_names.cc", "pref_names.h", ]
diff --git a/components/content_settings/core/common/features.cc b/components/content_settings/core/common/features.cc new file mode 100644 index 0000000..1f434f70 --- /dev/null +++ b/components/content_settings/core/common/features.cc
@@ -0,0 +1,14 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/content_settings/core/common/features.h" + +#include "base/feature_list.h" + +namespace content_settings { + +const base::Feature kImprovedCookieControls{"ImprovedCookieControls", + base::FEATURE_DISABLED_BY_DEFAULT}; + +} \ No newline at end of file
diff --git a/components/content_settings/core/common/features.h b/components/content_settings/core/common/features.h new file mode 100644 index 0000000..817b2f1c --- /dev/null +++ b/components/content_settings/core/common/features.h
@@ -0,0 +1,19 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_FEATURES_H_ +#define COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_FEATURES_H_ + +namespace base { +struct Feature; +} // namespace base + +namespace content_settings { + +// Feature to enable a better cookie controls ui. +extern const base::Feature kImprovedCookieControls; + +} // namespace content_settings + +#endif // COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_FEATURES_H_ \ No newline at end of file
diff --git a/components/content_settings/core/common/pref_names.cc b/components/content_settings/core/common/pref_names.cc index 9e18100..c70caec 100644 --- a/components/content_settings/core/common/pref_names.cc +++ b/components/content_settings/core/common/pref_names.cc
@@ -10,6 +10,10 @@ // regardless of other content settings. const char kBlockThirdPartyCookies[] = "profile.block_third_party_cookies"; +// Boolean that is true if the new cookie controls UI is enabled. This will +// block third-party cookies similar to kBlockThirdPartyCookies. +const char kCookieControlsEnabled[] = "profile.cookie_controls_enabled"; + // Version of the pattern format used to define content settings. const char kContentSettingsVersion[] = "profile.content_settings.pref_version";
diff --git a/components/content_settings/core/common/pref_names.h b/components/content_settings/core/common/pref_names.h index 4ce1bf8..539cc2a 100644 --- a/components/content_settings/core/common/pref_names.h +++ b/components/content_settings/core/common/pref_names.h
@@ -13,7 +13,11 @@ // some of these are generated by WebsiteSettingsInfo from content settings // names. +// TODO(crbug.com/967668): Remove direct access to these preferences and +// replace with CookieSettings::ShouldBlockThirdPartyCookies(). extern const char kBlockThirdPartyCookies[]; +extern const char kCookieControlsEnabled[]; + extern const char kContentSettingsVersion[]; extern const char kContentSettingsWindowLastTabIndex[];
diff --git a/components/cronet/android/cronet_library_loader.cc b/components/cronet/android/cronet_library_loader.cc index 5f1b0d75..121f662f 100644 --- a/components/cronet/android/cronet_library_loader.cc +++ b/components/cronet/android/cronet_library_loader.cc
@@ -18,9 +18,9 @@ #include "base/feature_list.h" #include "base/logging.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_current.h" #include "base/synchronization/waitable_event.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "build/build_config.h" #include "components/cronet/android/buildflags.h" @@ -50,9 +50,9 @@ namespace cronet { namespace { -// MessageLoop on the init thread, which is where objects that receive Java -// notifications generally live. -base::MessageLoop* g_init_message_loop = nullptr; +// SingleThreadTaskExecutor on the init thread, which is where objects that +// receive Java notifications generally live. +base::SingleThreadTaskExecutor* g_init_task_executor = nullptr; #if !BUILDFLAG(INTEGRATED_MODE) net::NetworkChangeNotifier* g_network_change_notifier = nullptr; @@ -79,8 +79,8 @@ } // namespace bool OnInitThread() { - DCHECK(g_init_message_loop); - return g_init_message_loop->task_runner()->RunsTasksInCurrentSequence(); + DCHECK(g_init_task_executor); + return g_init_task_executor->task_runner()->RunsTasksInCurrentSequence(); } // In integrated mode, Cronet native library is built and loaded together with @@ -108,10 +108,11 @@ #endif void JNI_CronetLibraryLoader_CronetInitOnInitThread(JNIEnv* env) { - // Initialize message loop for init thread. + // Initialize SingleThreadTaskExecutor for init thread. DCHECK(!base::MessageLoopCurrent::IsSet()); - DCHECK(!g_init_message_loop); - g_init_message_loop = new base::MessageLoop(base::MessageLoop::Type::JAVA); + DCHECK(!g_init_task_executor); + g_init_task_executor = + new base::SingleThreadTaskExecutor(base::MessageLoop::Type::JAVA); // In integrated mode, NetworkChangeNotifier has been initialized by the host. #if BUILDFLAG(INTEGRATED_MODE) @@ -144,11 +145,11 @@ void PostTaskToInitThread(const base::Location& posted_from, base::OnceClosure task) { g_init_thread_init_done.Wait(); - g_init_message_loop->task_runner()->PostTask(posted_from, std::move(task)); + g_init_task_executor->task_runner()->PostTask(posted_from, std::move(task)); } void EnsureInitialized() { - if (g_init_message_loop) { + if (g_init_task_executor) { // Ensure that init is done on the init thread. g_init_thread_init_done.Wait(); return;
diff --git a/components/cronet/ios/cronet_global_state_ios.mm b/components/cronet/ios/cronet_global_state_ios.mm index 50c5f60..d453db8d 100644 --- a/components/cronet/ios/cronet_global_state_ios.mm +++ b/components/cronet/ios/cronet_global_state_ios.mm
@@ -33,7 +33,7 @@ url::Initialize(); - ios_global_state::BuildMessageLoop(); + ios_global_state::BuildSingleThreadTaskExecutor(); ios_global_state::CreateNetworkChangeNotifier(); }
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.h b/components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.h index 3dab94a..9eb411b 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.h +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.h
@@ -10,8 +10,8 @@ #include <string> #include <utility> -#include "base/message_loop/message_loop.h" #include "base/strings/string_piece.h" +#include "base/task/single_thread_task_executor.h" #include "base/time/clock.h" #include "base/time/time.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" @@ -68,7 +68,7 @@ base::StringPiece group_name); protected: - base::MessageLoopForIO message_loop_; + base::SingleThreadTaskExecutor io_task_executor_{base::MessagePump::Type::IO}; std::unique_ptr<DataReductionProxyTestContext> test_context_; std::unique_ptr<DataReductionProxySettings> settings_; base::Time last_update_time_;
diff --git a/components/exo/wayland/clients/blur_main.cc b/components/exo/wayland/clients/blur_main.cc index 76e34663..c6de1318 100644 --- a/components/exo/wayland/clients/blur_main.cc +++ b/components/exo/wayland/clients/blur_main.cc
@@ -8,8 +8,8 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "components/exo/wayland/clients/blur.h" namespace switches { @@ -33,7 +33,8 @@ if (!params.FromCommandLine(*command_line)) return 1; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); exo::wayland::clients::Blur client; if (!client.Init(params)) return 1;
diff --git a/components/exo/wayland/clients/explicit_synchronization.cc b/components/exo/wayland/clients/explicit_synchronization.cc index 0c9b04c..13bcacc 100644 --- a/components/exo/wayland/clients/explicit_synchronization.cc +++ b/components/exo/wayland/clients/explicit_synchronization.cc
@@ -9,7 +9,7 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/files/scoped_file.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "components/exo/wayland/clients/client_helper.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkSurface.h" @@ -130,7 +130,8 @@ if (!params.FromCommandLine(*command_line)) return 1; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); exo::wayland::clients::ExplicitSynchronizationClient client; if (!client.Init(params)) return 1;
diff --git a/components/exo/wayland/clients/fullscreen_shell_main.cc b/components/exo/wayland/clients/fullscreen_shell_main.cc index 5cd751b..5b36cbce 100644 --- a/components/exo/wayland/clients/fullscreen_shell_main.cc +++ b/components/exo/wayland/clients/fullscreen_shell_main.cc
@@ -6,7 +6,7 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" int main(int argc, char* argv[]) { base::AtExitManager exit_manager; @@ -21,7 +21,8 @@ if (!params.FromCommandLine(*command_line)) return 1; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); exo::wayland::clients::FullscreenClient client; if (!client.Init(params))
diff --git a/components/exo/wayland/clients/rects.cc b/components/exo/wayland/clients/rects.cc index febeba1..34c0d369 100644 --- a/components/exo/wayland/clients/rects.cc +++ b/components/exo/wayland/clients/rects.cc
@@ -21,11 +21,11 @@ #include "base/containers/circular_deque.h" #include "base/logging.h" #include "base/memory/shared_memory.h" -#include "base/message_loop/message_loop.h" #include "base/scoped_generic.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" +#include "base/task/single_thread_task_executor.h" #include "base/time/time.h" #include "components/exo/wayland/clients/client_base.h" #include "components/exo/wayland/clients/client_helper.h" @@ -572,7 +572,8 @@ return 1; } - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); exo::wayland::clients::RectsClient client; return client.Run(params, max_frames_pending, num_rects, num_benchmark_runs, base::TimeDelta::FromMilliseconds(benchmark_interval_ms),
diff --git a/components/exo/wayland/clients/simple_main.cc b/components/exo/wayland/clients/simple_main.cc index 42a5ec0..5e4367b 100644 --- a/components/exo/wayland/clients/simple_main.cc +++ b/components/exo/wayland/clients/simple_main.cc
@@ -8,7 +8,7 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "components/exo/wayland/clients/simple.h" namespace switches { @@ -24,7 +24,8 @@ if (!params.FromCommandLine(*command_line)) return 1; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); exo::wayland::clients::Simple client; if (!client.Init(params)) return 1;
diff --git a/components/exo/wayland/clients/subsurface.cc b/components/exo/wayland/clients/subsurface.cc index c8b7f780..e3ed80c 100644 --- a/components/exo/wayland/clients/subsurface.cc +++ b/components/exo/wayland/clients/subsurface.cc
@@ -4,8 +4,8 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/stl_util.h" +#include "base/task/single_thread_task_executor.h" #include "components/exo/wayland/clients/client_base.h" #include "components/exo/wayland/clients/client_helper.h" #include "third_party/skia/include/core/SkCanvas.h" @@ -154,7 +154,8 @@ if (!params.FromCommandLine(*command_line)) return 1; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); exo::wayland::clients::SubSurfaceClient client; client.Run(params); return 1;
diff --git a/components/exo/wayland/clients/vulkan.cc b/components/exo/wayland/clients/vulkan.cc index 06d4e5f..23f7327 100644 --- a/components/exo/wayland/clients/vulkan.cc +++ b/components/exo/wayland/clients/vulkan.cc
@@ -4,8 +4,8 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/stl_util.h" +#include "base/task/single_thread_task_executor.h" #include "components/exo/wayland/clients/client_base.h" #include "components/exo/wayland/clients/client_helper.h" #include "third_party/skia/include/core/SkCanvas.h" @@ -174,7 +174,8 @@ if (!params.FromCommandLine(*command_line)) return 1; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); exo::wayland::clients::VulkanClient client; client.Run(params); return 1;
diff --git a/components/exo/wayland/clients/yuv.cc b/components/exo/wayland/clients/yuv.cc index ceff47c..7b9cba13 100644 --- a/components/exo/wayland/clients/yuv.cc +++ b/components/exo/wayland/clients/yuv.cc
@@ -9,7 +9,7 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "components/exo/wayland/clients/client_base.h" #include "components/exo/wayland/clients/client_helper.h" @@ -136,7 +136,8 @@ params.bo_usage = GBM_BO_USE_SCANOUT | GBM_BO_USE_LINEAR | GBM_BO_USE_TEXTURING; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); exo::wayland::clients::YuvClient client; client.Run(params); return 1;
diff --git a/components/feature_engagement/BUILD.gn b/components/feature_engagement/BUILD.gn index cbfe588..3a8788a 100644 --- a/components/feature_engagement/BUILD.gn +++ b/components/feature_engagement/BUILD.gn
@@ -12,7 +12,7 @@ buildflag_header("buildflags") { header = "buildflags.h" - flags = [ "ENABLE_DESKTOP_IN_PRODUCT_HELP=$enable_desktop_in_product_help" ] + flags = [ "ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP=$enable_legacy_desktop_in_product_help" ] } group("feature_engagement") {
diff --git a/components/feature_engagement/features.gni b/components/feature_engagement/features.gni index 72eaa1d7..67b93f7 100644 --- a/components/feature_engagement/features.gni +++ b/components/feature_engagement/features.gni
@@ -3,7 +3,5 @@ # found in the LICENSE file. declare_args() { - # In-Product Help is only available in Windows and Linux OS for - # desktop. - enable_desktop_in_product_help = is_win || (is_linux && !is_chromeos) + enable_legacy_desktop_in_product_help = false }
diff --git a/components/feature_engagement/public/event_constants.cc b/components/feature_engagement/public/event_constants.cc index ac1ebc2..f43a1f87 100644 --- a/components/feature_engagement/public/event_constants.cc +++ b/components/feature_engagement/public/event_constants.cc
@@ -11,7 +11,21 @@ namespace events { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +#if defined(OS_IOS) || defined(OS_WIN) || defined(OS_MACOSX) || \ + defined(OS_LINUX) || defined(OS_CHROMEOS) +const char kNewTabOpened[] = "new_tab_opened"; +#endif // defined(OS_IOS) || defined(OS_WIN) || defined(OS_MACOSX) || + // defined(OS_LINUX) || defined(OS_CHROMEOS) + +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_CHROMEOS) +const char kReopenTabConditionsMet[] = "reopen_tab_conditions_met"; +const char kTabReopened[] = "tab_reopened"; + +const char kFocusModeOpened[] = "focus_mode_opened"; +const char kFocusModeConditionsMet[] = "focus_mode_conditions_met"; + +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) const char kBookmarkAdded[] = "bookmark_added"; const char kBookmarkSessionTimeMet[] = "bookmark_session_time_met"; @@ -21,17 +35,9 @@ const char kIncognitoWindowOpened[] = "incognito_window_opened"; const char kIncognitoWindowSessionTimeMet[] = "incognito_window_session_time_met"; - -const char kReopenTabConditionsMet[] = "reopen_tab_conditions_met"; -const char kTabReopened[] = "tab_reopened"; - -const char kFocusModeOpened[] = "focus_mode_opened"; -const char kFocusModeConditionsMet[] = "focus_mode_conditions_met"; -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - -#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_IOS) -const char kNewTabOpened[] = "new_tab_opened"; -#endif // defined(OS_WIN) || defined(OS_LINUX) || defined(OS_IOS) +#endif // BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_CHROMEOS) #if defined(OS_IOS) const char kChromeOpened[] = "chrome_opened";
diff --git a/components/feature_engagement/public/event_constants.h b/components/feature_engagement/public/event_constants.h index 18d1ccd..559369911 100644 --- a/components/feature_engagement/public/event_constants.h +++ b/components/feature_engagement/public/event_constants.h
@@ -12,7 +12,34 @@ namespace events { -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) +// Desktop and IOS. +#if defined(OS_IOS) || defined(OS_WIN) || defined(OS_MACOSX) || \ + defined(OS_LINUX) || defined(OS_CHROMEOS) +// The user has explicitly opened a new tab via an entry point from inside of +// Chrome. +extern const char kNewTabOpened[]; +#endif // defined(OS_IOS) || defined(OS_WIN) || defined(OS_MACOSX) || + // defined(OS_LINUX) || defined(OS_CHROMEOS) + +// Desktop +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_CHROMEOS) +// All conditions for reopen closed tab IPH were met. Since this IPH needs to +// track user events (opening/closing tabs, focusing the omnibox, etc) on the +// second level, it must be done manually. +extern const char kReopenTabConditionsMet[]; +// The user reopened a previously closed tab. +extern const char kTabReopened[]; + +// All the events declared below are the string names of deferred onboarding +// events for the Focus Mode feature. + +// The user has opened a Focus Mode window. +extern const char kFocusModeOpened[]; +// All conditions for show Focus Mode IPH were met. +extern const char kFocusModeConditionsMet[]; + +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) // All the events declared below are the string names of deferred onboarding // events for the Bookmark feature. @@ -40,32 +67,10 @@ // IncognitoWindowPromo by accumulating 2 hours of active session time (one-off // event). extern const char kIncognitoWindowSessionTimeMet[]; +#endif // BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) -// All conditions for reopen closed tab IPH were met. Since this IPH needs to -// track user events (opening/closing tabs, focusing the omnibox, etc) on the -// second level, it must be done manually. -extern const char kReopenTabConditionsMet[]; -// The user reopened a previously closed tab. -extern const char kTabReopened[]; - -// All the events declared below are the string names of deferred onboarding -// events for the Focus Mode feature. - -// The user has opened a Focus Mode window. -extern const char kFocusModeOpened[]; -// All conditions for show Focus Mode IPH were met. -extern const char kFocusModeConditionsMet[]; -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - -#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_IOS) -// This event is included in the deferred onboarding events for the New Tab -// described above, but it is also used on iOS, so it must be compiled -// separately. - -// The user has explicitly opened a new tab via an entry point from inside of -// Chrome. -extern const char kNewTabOpened[]; -#endif // defined(OS_WIN) || defined(OS_LINUX) || defined(OS_IOS) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_CHROMEOS) #if defined(OS_IOS) // The user has opened Chrome (cold start or from background).
diff --git a/components/feature_engagement/public/feature_constants.cc b/components/feature_engagement/public/feature_constants.cc index 131c0a2..71c1ee9 100644 --- a/components/feature_engagement/public/feature_constants.cc +++ b/components/feature_engagement/public/feature_constants.cc
@@ -14,6 +14,24 @@ const base::Feature kIPHDummyFeature{"IPH_Dummy", base::FEATURE_DISABLED_BY_DEFAULT}; +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_CHROMEOS) +const base::Feature kIPHReopenTabFeature{"IPH_ReopenTab", + base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kIPHFocusModeFeature{"IPH_FocusMode", + base::FEATURE_DISABLED_BY_DEFAULT}; + +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) +const base::Feature kIPHBookmarkFeature{"IPH_Bookmark", + base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kIPHIncognitoWindowFeature{ + "IPH_IncognitoWindow", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kIPHNewTabFeature{"IPH_NewTab", + base::FEATURE_DISABLED_BY_DEFAULT}; +#endif // BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_CHROMEOS) + #if defined(OS_ANDROID) const base::Feature kIPHDataSaverDetailFeature{ "IPH_DataSaverDetail", base::FEATURE_ENABLED_BY_DEFAULT}; @@ -77,19 +95,6 @@ "IPH_ExploreSitesTile", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_ANDROID) -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) -const base::Feature kIPHBookmarkFeature{"IPH_Bookmark", - base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kIPHIncognitoWindowFeature{ - "IPH_IncognitoWindow", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kIPHNewTabFeature{"IPH_NewTab", - base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kIPHReopenTabFeature{"IPH_ReopenTab", - base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kIPHFocusModeFeature{"IPH_FocusMode", - base::FEATURE_DISABLED_BY_DEFAULT}; -#endif // BUILDFLAG(ENABLE_DESKTOP_IPH) - #if defined(OS_IOS) const base::Feature kIPHBottomToolbarTipFeature{ "IPH_BottomToolbarTip", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/feature_engagement/public/feature_constants.h b/components/feature_engagement/public/feature_constants.h index 529c25f..5a43fea9 100644 --- a/components/feature_engagement/public/feature_constants.h +++ b/components/feature_engagement/public/feature_constants.h
@@ -17,6 +17,19 @@ // A feature to ensure all arrays can contain at least one feature. extern const base::Feature kIPHDummyFeature; +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_CHROMEOS) +extern const base::Feature kIPHReopenTabFeature; +extern const base::Feature kIPHFocusModeFeature; + +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) +extern const base::Feature kIPHBookmarkFeature; +extern const base::Feature kIPHIncognitoWindowFeature; +extern const base::Feature kIPHNewTabFeature; +#endif // BUILDFLAG(ENABLE_LEGACY_DESKTOP_IPH) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_CHROMEOS) + // All the features declared for Android below that are also used in Java, // should also be declared in: // org.chromium.components.feature_engagement.FeatureConstants. @@ -53,14 +66,6 @@ extern const base::Feature kIPHExploreSitesTileFeature; #endif // defined(OS_ANDROID) -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) -extern const base::Feature kIPHBookmarkFeature; -extern const base::Feature kIPHIncognitoWindowFeature; -extern const base::Feature kIPHNewTabFeature; -extern const base::Feature kIPHReopenTabFeature; -extern const base::Feature kIPHFocusModeFeature; -#endif // BUILDFLAG(ENABLE_DESKTOP_IPH) - #if defined(OS_IOS) extern const base::Feature kIPHBottomToolbarTipFeature; extern const base::Feature kIPHLongPressToolbarTipFeature;
diff --git a/components/feature_engagement/public/feature_list.cc b/components/feature_engagement/public/feature_list.cc index 640ac03d..a0c4ac7f 100644 --- a/components/feature_engagement/public/feature_list.cc +++ b/components/feature_engagement/public/feature_list.cc
@@ -1,4 +1,4 @@ -/// Copyright 2017 The Chromium Authors. All rights reserved. +// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -48,13 +48,6 @@ &kIPHTranslateMenuButtonFeature, &kIPHExploreSitesTileFeature, #endif // defined(OS_ANDROID) -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - &kIPHBookmarkFeature, - &kIPHIncognitoWindowFeature, - &kIPHNewTabFeature, - &kIPHReopenTabFeature, - &kIPHFocusModeFeature, -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) #if defined(OS_IOS) &kIPHBottomToolbarTipFeature, &kIPHLongPressToolbarTipFeature, @@ -63,6 +56,17 @@ &kIPHBadgedReadingListFeature, &kIPHBadgedTranslateManualTriggerFeature, #endif // defined(OS_IOS) +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_CHROMEOS) + &kIPHReopenTabFeature, + &kIPHFocusModeFeature, +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) + &kIPHBookmarkFeature, + &kIPHIncognitoWindowFeature, + &kIPHNewTabFeature, +#endif // BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_CHROMEOS) }; } // namespace
diff --git a/components/feature_engagement/public/feature_list.h b/components/feature_engagement/public/feature_list.h index eedcfd63..722c741c 100644 --- a/components/feature_engagement/public/feature_list.h +++ b/components/feature_engagement/public/feature_list.h
@@ -95,13 +95,6 @@ "IPH_TranslateMenuButton"); DEFINE_VARIATION_PARAM(kIPHExploreSitesTileFeature, "IPH_ExploreSitesTile"); #endif // defined(OS_ANDROID) -#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) -DEFINE_VARIATION_PARAM(kIPHBookmarkFeature, "IPH_Bookmark"); -DEFINE_VARIATION_PARAM(kIPHIncognitoWindowFeature, "IPH_IncognitoWindow"); -DEFINE_VARIATION_PARAM(kIPHNewTabFeature, "IPH_NewTab"); -DEFINE_VARIATION_PARAM(kIPHReopenTabFeature, "IPH_ReopenTab"); -DEFINE_VARIATION_PARAM(kIPHFocusModeFeature, "IPH_FocusMode"); -#endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) #if defined(OS_IOS) DEFINE_VARIATION_PARAM(kIPHBottomToolbarTipFeature, "IPH_BottomToolbarTip"); DEFINE_VARIATION_PARAM(kIPHLongPressToolbarTipFeature, @@ -113,6 +106,18 @@ "IPH_BadgedTranslateManualTrigger"); #endif // defined(OS_IOS) +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_CHROMEOS) +DEFINE_VARIATION_PARAM(kIPHReopenTabFeature, "IPH_ReopenTab"); +DEFINE_VARIATION_PARAM(kIPHFocusModeFeature, "IPH_FocusMode"); +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) +DEFINE_VARIATION_PARAM(kIPHBookmarkFeature, "IPH_Bookmark"); +DEFINE_VARIATION_PARAM(kIPHIncognitoWindowFeature, "IPH_IncognitoWindow"); +DEFINE_VARIATION_PARAM(kIPHNewTabFeature, "IPH_NewTab"); +#endif // BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_CHROMEOS) + } // namespace // Defines the array of which features should be listed in the chrome://flags @@ -151,12 +156,6 @@ VARIATION_ENTRY(kIPHTabGroupsYourTabsAreTogetherFeature), VARIATION_ENTRY(kIPHTranslateMenuButtonFeature), VARIATION_ENTRY(kIPHExploreSitesTileFeature), -#elif BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) - VARIATION_ENTRY(kIPHBookmarkFeature), - VARIATION_ENTRY(kIPHIncognitoWindowFeature), - VARIATION_ENTRY(kIPHNewTabFeature), - VARIATION_ENTRY(kIPHReopenTabFeature), - VARIATION_ENTRY(kIPHFocusModeFeature), #elif defined(OS_IOS) VARIATION_ENTRY(kIPHBottomToolbarTipFeature), VARIATION_ENTRY(kIPHLongPressToolbarTipFeature), @@ -164,9 +163,17 @@ VARIATION_ENTRY(kIPHNewIncognitoTabTipFeature), VARIATION_ENTRY(kIPHBadgedReadingListFeature), VARIATION_ENTRY(kIPHBadgedTranslateManualTriggerFeature), -#else - VARIATION_ENTRY(kIPHDummyFeature), // Ensures non-empty array. -#endif +#elif defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_CHROMEOS) + VARIATION_ENTRY(kIPHReopenTabFeature), + VARIATION_ENTRY(kIPHFocusModeFeature), +#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) + VARIATION_ENTRY(kIPHBookmarkFeature), + VARIATION_ENTRY(kIPHIncognitoWindowFeature), + VARIATION_ENTRY(kIPHNewTabFeature), +#endif // BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_CHROMEOS) }; #undef DEFINE_VARIATION_PARAM
diff --git a/components/gcm_driver/crypto/BUILD.gn b/components/gcm_driver/crypto/BUILD.gn index 8b5656e..8aa1574 100644 --- a/components/gcm_driver/crypto/BUILD.gn +++ b/components/gcm_driver/crypto/BUILD.gn
@@ -17,6 +17,8 @@ "gcm_key_store.h", "gcm_message_cryptographer.cc", "gcm_message_cryptographer.h", + "json_web_token_util.cc", + "json_web_token_util.h", "message_payload_parser.cc", "message_payload_parser.h", "p256_key_util.cc", @@ -57,6 +59,7 @@ "gcm_encryption_provider_unittest.cc", "gcm_key_store_unittest.cc", "gcm_message_cryptographer_unittest.cc", + "json_web_token_util_unittest.cc", "message_payload_parser_unittest.cc", "p256_key_util_unittest.cc", ]
diff --git a/components/gcm_driver/crypto/json_web_token_util.cc b/components/gcm_driver/crypto/json_web_token_util.cc new file mode 100644 index 0000000..be62d7c --- /dev/null +++ b/components/gcm_driver/crypto/json_web_token_util.cc
@@ -0,0 +1,82 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/gcm_driver/crypto/json_web_token_util.h" + +#include <stdint.h> + +#include "base/base64url.h" +#include "base/json/json_writer.h" +#include "base/strings/strcat.h" +#include "crypto/ec_private_key.h" +#include "crypto/ec_signature_creator.h" + +namespace { +const char kKeyAlg[] = "alg"; +const char kAlgES256[] = "ES256"; + +const char kKeyTyp[] = "typ"; +const char kTypJwt[] = "JWT"; +} // namespace + +namespace gcm { + +base::Optional<std::string> CreateJSONWebToken( + const base::Value& claims, + crypto::ECPrivateKey* private_key) { + if (!claims.is_dict()) { + LOG(ERROR) << "claims is not a dictionary"; + return base::nullopt; + } + + // Generate header. + base::Value header(base::Value::Type::DICTIONARY); + header.SetKey(kKeyAlg, base::Value(kAlgES256)); + header.SetKey(kKeyTyp, base::Value(kTypJwt)); + + // Serialize header. + std::string header_serialized; + if (!base::JSONWriter::Write(header, &header_serialized)) { + LOG(ERROR) << "Failed to write header as JSON"; + return base::nullopt; + } + std::string header_base64; + base::Base64UrlEncode(header_serialized, + base::Base64UrlEncodePolicy::OMIT_PADDING, + &header_base64); + + // Serialize claims as payload. + std::string payload_serialized; + if (!base::JSONWriter::Write(claims, &payload_serialized)) { + LOG(ERROR) << "Failed to write claims as JSON"; + return base::nullopt; + } + std::string payload_base64; + base::Base64UrlEncode(payload_serialized, + base::Base64UrlEncodePolicy::OMIT_PADDING, + &payload_base64); + std::string data = base::StrCat({header_base64, ".", payload_base64}); + + // Create signature. + auto signer = crypto::ECSignatureCreator::Create(private_key); + std::vector<uint8_t> der_signature, raw_signature; + if (!signer->Sign((const uint8_t*)data.data(), data.size(), &der_signature)) { + LOG(ERROR) << "Failed to create DER signature"; + return base::nullopt; + } + if (!signer->DecodeSignature(der_signature, &raw_signature)) { + LOG(ERROR) << "Failed to decode DER signature"; + return base::nullopt; + } + + // Serialize signature. + std::string signature_base64; + base::Base64UrlEncode(std::string(raw_signature.begin(), raw_signature.end()), + base::Base64UrlEncodePolicy::OMIT_PADDING, + &signature_base64); + + return base::StrCat({data, ".", signature_base64}); +} + +} // namespace gcm
diff --git a/components/gcm_driver/crypto/json_web_token_util.h b/components/gcm_driver/crypto/json_web_token_util.h new file mode 100644 index 0000000..a33782b --- /dev/null +++ b/components/gcm_driver/crypto/json_web_token_util.h
@@ -0,0 +1,33 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_GCM_DRIVER_CRYPTO_JSON_WEB_TOKEN_UTIL_H_ +#define COMPONENTS_GCM_DRIVER_CRYPTO_JSON_WEB_TOKEN_UTIL_H_ + +#include <string> + +#include "base/optional.h" +#include "base/values.h" + +namespace crypto { +class ECPrivateKey; +} + +namespace gcm { + +// Creates JSON web token with provided |payload|, and sign with provided +// |private_key|, as per RFC7519. +// |claims|: A Value of DICTIONARY type containing claims between two parties. +// |private_key|: An elliptic curve (EC) private key. +// Note: Currently only ES256 is supported, as ECPrivateKey only supports +// NIST P-256 curve and ECSignatureCreator is hardcoded to SHA256. +// +// https://tools.ietf.org/html/rfc7519 +base::Optional<std::string> CreateJSONWebToken( + const base::Value& claims, + crypto::ECPrivateKey* private_key); + +} // namespace gcm + +#endif // COMPONENTS_GCM_DRIVER_CRYPTO_JSON_WEB_TOKEN_UTIL_H_
diff --git a/components/gcm_driver/crypto/json_web_token_util_unittest.cc b/components/gcm_driver/crypto/json_web_token_util_unittest.cc new file mode 100644 index 0000000..2d34eec --- /dev/null +++ b/components/gcm_driver/crypto/json_web_token_util_unittest.cc
@@ -0,0 +1,107 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/gcm_driver/crypto/json_web_token_util.h" + +#include <stdint.h> + +#include "base/base64.h" +#include "base/base64url.h" +#include "base/json/json_reader.h" +#include "base/optional.h" +#include "crypto/ec_private_key.h" +#include "crypto/signature_verifier.h" +#include "testing/gtest/include/gtest/gtest.h" + +#include "third_party/boringssl/src/include/openssl/bn.h" +#include "third_party/boringssl/src/include/openssl/ecdsa.h" +#include "third_party/boringssl/src/include/openssl/mem.h" + +namespace gcm { + +namespace { + +// An ASN.1-encoded PrivateKeyInfo block from PKCS #8. +const char kPrivateKey[] = + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgS8wRbDOWz0lKExvIVQiRKtPAP8" + "dgHUHAw5gyOd5d4jKhRANCAARZb49Va5MD/KcWtc0oiWc2e8njBDtQzj0mzcOl1fDSt16Pvu6p" + "fTU3MTWnImDNnkPxtXm58K7Uax8jFxA4TeXJ"; + +TEST(JSONWebTokenUtilTest, VerifiesCreateJSONWebToken) { + std::string private_key_info; + ASSERT_TRUE(base::Base64Decode(kPrivateKey, &private_key_info)); + std::unique_ptr<crypto::ECPrivateKey> private_key = + crypto::ECPrivateKey::CreateFromPrivateKeyInfo(std::vector<uint8_t>( + private_key_info.begin(), private_key_info.end())); + ASSERT_TRUE(private_key); + + // Create JWS. + base::Value claims(base::Value::Type::DICTIONARY); + claims.SetKey("aud", base::Value("https://chromium.org")); + base::Optional<std::string> jwt = + CreateJSONWebToken(claims, private_key.get()); + ASSERT_TRUE(jwt); + + // Decompose JWS into data and signautre. + std::string::size_type dot_position = jwt->rfind("."); + ASSERT_NE(std::string::npos, dot_position); + + std::string data = jwt->substr(0, dot_position); + std::string signature; + ASSERT_TRUE(base::Base64UrlDecode(jwt->substr(dot_position + 1), + base::Base64UrlDecodePolicy::IGNORE_PADDING, + &signature)); + + // Encode the signature. + bssl::UniquePtr<ECDSA_SIG> ec_sig(ECDSA_SIG_new()); + ASSERT_TRUE(ec_sig); + + std::string::size_type half_size = signature.size() / 2; + ASSERT_TRUE(BN_bin2bn((uint8_t*)signature.data(), half_size, ec_sig->r)); + ASSERT_TRUE( + BN_bin2bn((uint8_t*)signature.data() + half_size, half_size, ec_sig->s)); + + uint8_t* der; + size_t der_len; + ASSERT_TRUE(ECDSA_SIG_to_bytes(&der, &der_len, ec_sig.get())); + std::vector<uint8_t> der_signature(der, der + der_len); + OPENSSL_free(der); + + // Verify DER signature using SignatureVerifier. + std::vector<uint8_t> public_key_info; + ASSERT_TRUE(private_key->ExportPublicKey(&public_key_info)); + + crypto::SignatureVerifier verifier; + ASSERT_TRUE(verifier.VerifyInit(crypto::SignatureVerifier::ECDSA_SHA256, + der_signature, public_key_info)); + + verifier.VerifyUpdate(base::as_bytes(base::make_span(data))); + ASSERT_TRUE(verifier.VerifyFinal()); + + std::string::size_type data_dot_position = data.find("."); + ASSERT_NE(std::string::npos, data_dot_position); + + // Verify header. + std::string header_decoded; + ASSERT_TRUE(base::Base64UrlDecode(data.substr(0, data_dot_position), + base::Base64UrlDecodePolicy::IGNORE_PADDING, + &header_decoded)); + base::Optional<base::Value> header_value = + base::JSONReader::Read(header_decoded); + ASSERT_TRUE(header_value); + ASSERT_TRUE(header_value->is_dict()); + ASSERT_EQ(base::Value("ES256"), header_value->ExtractKey("alg")); + ASSERT_EQ(base::Value("JWT"), header_value->ExtractKey("typ")); + + // Verify payload. + std::string payload_decoded; + ASSERT_TRUE(base::Base64UrlDecode(data.substr(data_dot_position + 1), + base::Base64UrlDecodePolicy::IGNORE_PADDING, + &payload_decoded)); + ASSERT_EQ(claims, base::JSONReader::Read(payload_decoded)); +} + +} // namespace + +} // namespace gcm
diff --git a/components/handoff/handoff_manager.mm b/components/handoff/handoff_manager.mm index d01752c7..c34d167 100644 --- a/components/handoff/handoff_manager.mm +++ b/components/handoff/handoff_manager.mm
@@ -22,20 +22,19 @@ @interface HandoffManager () // The active user activity. -@property(nonatomic, retain) - NSUserActivity* userActivity API_AVAILABLE(macos(10.10)); +@property(nonatomic, retain) NSUserActivity* userActivity; // Whether the URL of the current tab should be exposed for Handoff. - (BOOL)shouldUseActiveURL; // Updates the active NSUserActivity. -- (void)updateUserActivity API_AVAILABLE(macos(10.10)); +- (void)updateUserActivity; @end @implementation HandoffManager { GURL _activeURL; - NSUserActivity* _userActivity API_AVAILABLE(macos(10.10)); + NSUserActivity* _userActivity; handoff::Origin _origin; } @@ -69,11 +68,6 @@ } - (void)updateActiveURL:(const GURL&)url { -#if defined(OS_MACOSX) && !defined(OS_IOS) - // Handoff is only available on OSX 10.10+. - DCHECK(base::mac::IsAtLeastOS10_10()); -#endif - _activeURL = url; [self updateUserActivity]; }
diff --git a/components/metrics/net/net_metrics_log_uploader.cc b/components/metrics/net/net_metrics_log_uploader.cc index c86b269..205fd59 100644 --- a/components/metrics/net/net_metrics_log_uploader.cc +++ b/components/metrics/net/net_metrics_log_uploader.cc
@@ -102,21 +102,21 @@ })"); } DCHECK_EQ(service_type, metrics::MetricsLogUploader::UKM); + // TODO(https://crbug.com/951781): Update this annotation once Unity is + // enabled on ChromeOS by default. return net::DefineNetworkTrafficAnnotation("metrics_report_ukm", R"( semantics { sender: "Metrics UKM Log Uploader" description: - "Report of usage statistics that are keyed by URLs to Chromium, " - "sent only if the profile has History Sync. This includes " - "information about the web pages you visit and your usage of them, " - "such as page load speed. This will also include URLs and " - "statistics related to downloaded files. If Extension Sync is " - "enabled, these statistics will also include information about " - "the extensions that have been installed from Chrome Web Store. " - "Google only stores usage statistics associated with published " - "extensions, and URLs that are known by Google’s search index. " - "Usage statistics are tied to a pseudonymous machine identifier " - "and not to your email address." + "Report of usage statistics that are keyed by URLs to Chromium. This " + "includes information about the web pages you visit and your usage " + "of them, such as page load speed. This will also include URLs and " + "statistics related to downloaded files. These statistics may also " + "include information about the extensions that have been installed " + "from Chrome Web Store. Google only stores usage statistics " + "associated with published extensions, and URLs that are known by " + "Google’s search index. Usage statistics are tied to a " + "pseudonymous machine identifier and not to your email address." trigger: "Reports are automatically generated on startup and at intervals " "while Chromium is running with Sync enabled." @@ -127,11 +127,19 @@ policy { cookies_allowed: NO setting: - "Users can enable or disable this feature by disabling " - "'Automatically send usage statistics and crash reports to Google' " - "in Chromium's settings under Advanced Settings, Privacy. This is " - "only enabled if all active profiles have History/Extension Sync " - "enabled without a Sync passphrase." + "On ChromeOS, users can enable or disable this feature by disabling " + "'Automatically send diagnostic and usage data to Google' in " + "Chrome's settings under Advanced Settings, Privacy. This is only " + "enabled if all active profiles have History Sync enabled without a " + "Sync passphrase. " + "On all other platforms, users can enable or disable this feature by " + "disabling 'Make searches and browsing better' in Chrome's settings " + "under Advanced Settings, Privacy. This has to be enabled for all " + "active profiles. This is only enabled if the user has " + "'Help improve Chrome's features and performance' enabled in the " + "same settings menu. " + "On all platforms, information about the installed extensions is " + "sent only if Extension Sync is enabled." chrome_policy { MetricsReportingEnabled { policy_options {mode: MANDATORY}
diff --git a/components/nacl/loader/nacl_helper_linux.cc b/components/nacl/loader/nacl_helper_linux.cc index 97bc556..6fddb88 100644 --- a/components/nacl/loader/nacl_helper_linux.cc +++ b/components/nacl/loader/nacl_helper_linux.cc
@@ -25,13 +25,13 @@ #include "base/command_line.h" #include "base/files/scoped_file.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/posix/eintr_wrapper.h" #include "base/posix/global_descriptors.h" #include "base/posix/unix_domain_socket.h" #include "base/process/kill.h" #include "base/process/process_handle.h" #include "base/rand_util.h" +#include "base/task/single_thread_task_executor.h" #include "build/build_config.h" #include "components/nacl/common/nacl_switches.h" #include "components/nacl/loader/sandbox_linux/nacl_sandbox_linux.h" @@ -121,7 +121,7 @@ // The Mojo EDK must be initialized before using IPC. mojo::core::Init(); - base::MessageLoopForIO main_message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); #if defined(OS_NACL_NONSFI) CHECK(uses_nonsfi_mode); nacl::nonsfi::NonSfiListener listener;
diff --git a/components/nacl/loader/nacl_helper_win_64.cc b/components/nacl/loader/nacl_helper_win_64.cc index be9ad77..996ad7a 100644 --- a/components/nacl/loader/nacl_helper_win_64.cc +++ b/components/nacl/loader/nacl_helper_win_64.cc
@@ -9,12 +9,12 @@ #include "base/command_line.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/power_monitor/power_monitor.h" #include "base/power_monitor/power_monitor_device_source.h" #include "base/process/launch.h" #include "base/process/memory.h" #include "base/strings/string_util.h" +#include "base/task/single_thread_task_executor.h" #include "base/timer/hi_res_timer_manager.h" #include "base/win/process_startup_helper.h" #include "components/nacl/broker/nacl_broker_listener.h" @@ -35,7 +35,7 @@ // main() routine for the NaCl broker process. // This is necessary for supporting NaCl in Chrome on Win64. int NaClBrokerMain(const content::MainFunctionParams& parameters) { - base::MessageLoopForIO main_message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::PlatformThread::SetName("CrNaClBrokerMain"); mojo::core::Init();
diff --git a/components/nacl/loader/nacl_main.cc b/components/nacl/loader/nacl_main.cc index b4c3bf6..dcffb2e 100644 --- a/components/nacl/loader/nacl_main.cc +++ b/components/nacl/loader/nacl_main.cc
@@ -5,9 +5,9 @@ #include <utility> #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/power_monitor/power_monitor.h" #include "base/power_monitor/power_monitor_device_source.h" +#include "base/task/single_thread_task_executor.h" #include "base/timer/hi_res_timer_manager.h" #include "build/build_config.h" #include "components/nacl/loader/nacl_listener.h" @@ -24,7 +24,8 @@ mojo::core::Init(); // The main thread of the plugin services IO. - base::MessageLoopForIO main_message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::IO); base::PlatformThread::SetName("CrNaClMain"); std::unique_ptr<base::PowerMonitorSource> power_monitor_source(
diff --git a/components/omnibox/browser/suggestion_answer.cc b/components/omnibox/browser/suggestion_answer.cc index 151e55f7..a0c9049a 100644 --- a/components/omnibox/browser/suggestion_answer.cc +++ b/components/omnibox/browser/suggestion_answer.cc
@@ -55,6 +55,12 @@ SuggestionAnswer::TextField::TextField() = default; SuggestionAnswer::TextField::~TextField() = default; +SuggestionAnswer::TextField::TextField(const TextField&) = default; +SuggestionAnswer::TextField::TextField(TextField&&) noexcept = default; +SuggestionAnswer::TextField& SuggestionAnswer::TextField::operator=( + const TextField&) = default; +SuggestionAnswer::TextField& SuggestionAnswer::TextField::operator=( + TextField&&) noexcept = default; // static bool SuggestionAnswer::TextField::ParseTextField(const base::Value& field_json, @@ -93,9 +99,12 @@ SuggestionAnswer::ImageLine::ImageLine() : num_text_lines_(1) {} SuggestionAnswer::ImageLine::ImageLine(const ImageLine& line) = default; +SuggestionAnswer::ImageLine::ImageLine(ImageLine&&) noexcept = default; SuggestionAnswer::ImageLine& SuggestionAnswer::ImageLine::operator=( const ImageLine& line) = default; +SuggestionAnswer::ImageLine& SuggestionAnswer::ImageLine::operator=( + ImageLine&&) noexcept = default; SuggestionAnswer::ImageLine::~ImageLine() {} @@ -251,9 +260,14 @@ SuggestionAnswer::SuggestionAnswer(const SuggestionAnswer& answer) = default; +SuggestionAnswer::SuggestionAnswer(SuggestionAnswer&&) noexcept = default; + SuggestionAnswer& SuggestionAnswer::operator=(const SuggestionAnswer& answer) = default; +SuggestionAnswer& SuggestionAnswer::operator=(SuggestionAnswer&&) noexcept = + default; + SuggestionAnswer::~SuggestionAnswer() = default; // static
diff --git a/components/omnibox/browser/suggestion_answer.h b/components/omnibox/browser/suggestion_answer.h index 31be937c..2840ace 100644 --- a/components/omnibox/browser/suggestion_answer.h +++ b/components/omnibox/browser/suggestion_answer.h
@@ -125,6 +125,10 @@ public: TextField(); ~TextField(); + TextField(const TextField&); + TextField(TextField&&) noexcept; + TextField& operator=(const TextField&); + TextField& operator=(TextField&&) noexcept; // Parses |field_json| dictionary and populates |text_field| with the // contents. If any of the required elements is missing, returns false and @@ -162,7 +166,9 @@ public: ImageLine(); explicit ImageLine(const ImageLine& line); + ImageLine(ImageLine&&) noexcept; ImageLine& operator=(const ImageLine& line); + ImageLine& operator=(ImageLine&&) noexcept; ~ImageLine(); // Parses dictionary |line_json| and populates |image_line| with the @@ -213,7 +219,9 @@ SuggestionAnswer(); SuggestionAnswer(const SuggestionAnswer& answer); + SuggestionAnswer(SuggestionAnswer&&) noexcept; SuggestionAnswer& operator=(const SuggestionAnswer& answer); + SuggestionAnswer& operator=(SuggestionAnswer&&) noexcept; ~SuggestionAnswer(); // Parses dictionary |answer_json| and fills a SuggestionAnswer containing the
diff --git a/components/pairing/BUILD.gn b/components/pairing/BUILD.gn deleted file mode 100644 index ee1b970..0000000 --- a/components/pairing/BUILD.gn +++ /dev/null
@@ -1,60 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//third_party/protobuf/proto_library.gni") - -source_set("pairing") { - sources = [ - "bluetooth_controller_pairing_controller.cc", - "bluetooth_controller_pairing_controller.h", - "bluetooth_host_pairing_controller.cc", - "bluetooth_host_pairing_controller.h", - "bluetooth_pairing_constants.cc", - "bluetooth_pairing_constants.h", - "controller_pairing_controller.cc", - "controller_pairing_controller.h", - "fake_controller_pairing_controller.cc", - "fake_controller_pairing_controller.h", - "fake_host_pairing_controller.cc", - "fake_host_pairing_controller.h", - "host_pairing_controller.cc", - "host_pairing_controller.h", - "message_buffer.cc", - "message_buffer.h", - "proto_decoder.cc", - "proto_decoder.h", - "shark_connection_listener.cc", - "shark_connection_listener.h", - ] - - deps = [ - ":proto", - "//base", - "//chromeos/constants", - "//device/bluetooth", - "//net", - "//services/device/public/mojom", - "//services/device/public/mojom:constants", - "//services/service_manager/public/cpp", - ] -} - -source_set("unit_tests") { - testonly = true - sources = [ - "message_buffer_unittest.cc", - ] - - deps = [ - ":pairing", - "//net", - "//testing/gtest", - ] -} - -proto_library("proto") { - sources = [ - "pairing_api.proto", - ] -}
diff --git a/components/pairing/DEPS b/components/pairing/DEPS deleted file mode 100644 index b9096780..0000000 --- a/components/pairing/DEPS +++ /dev/null
@@ -1,8 +0,0 @@ -include_rules = [ - "+chromeos/constants", - "+device/bluetooth", - "+mojo/public/cpp", - "+net", # For IOBuffer - "+services/device/public/mojom", - "+services/service_manager/public/cpp", -]
diff --git a/components/pairing/OWNERS b/components/pairing/OWNERS deleted file mode 100644 index 022d75b..0000000 --- a/components/pairing/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -achuith@chromium.org -zork@chromium.org
diff --git a/components/pairing/bluetooth_controller_pairing_controller.cc b/components/pairing/bluetooth_controller_pairing_controller.cc deleted file mode 100644 index df1bb69..0000000 --- a/components/pairing/bluetooth_controller_pairing_controller.cc +++ /dev/null
@@ -1,523 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/bluetooth_controller_pairing_controller.h" - -#include <utility> - -#include "base/bind.h" -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "components/pairing/bluetooth_pairing_constants.h" -#include "components/pairing/pairing_api.pb.h" -#include "device/bluetooth/bluetooth_adapter_factory.h" -#include "device/bluetooth/bluetooth_discovery_session.h" -#include "net/base/io_buffer.h" - -namespace { -const int kReceiveSize = 16384; -} - -namespace pairing_chromeos { - -BluetoothControllerPairingController::BluetoothControllerPairingController() - : current_stage_(STAGE_NONE), - proto_decoder_(new ProtoDecoder(this)), - ptr_factory_(this) { -} - -BluetoothControllerPairingController::~BluetoothControllerPairingController() { - Reset(); -} - -device::BluetoothDevice* BluetoothControllerPairingController::GetController() { - DCHECK(!controller_device_id_.empty()); - device::BluetoothDevice* device = adapter_->GetDevice(controller_device_id_); - if (!device) { - LOG(ERROR) << "Lost connection to controller."; - ChangeStage(STAGE_ESTABLISHING_CONNECTION_ERROR); - } - - return device; -} - -void BluetoothControllerPairingController::ChangeStage(Stage new_stage) { - if (current_stage_ == new_stage) - return; - VLOG(1) << "ChangeStage " << new_stage; - current_stage_ = new_stage; - for (ControllerPairingController::Observer& observer : observers_) - observer.PairingStageChanged(new_stage); -} - -void BluetoothControllerPairingController::Reset() { - controller_device_id_.clear(); - discovery_session_.reset(); - - if (socket_.get()) { - socket_->Close(); - socket_ = NULL; - } - - if (adapter_.get()) { - adapter_->RemoveObserver(this); - adapter_ = NULL; - } -} - -void BluetoothControllerPairingController::DeviceFound( - device::BluetoothDevice* device) { - DCHECK_EQ(current_stage_, STAGE_DEVICES_DISCOVERY); - DCHECK(thread_checker_.CalledOnValidThread()); - - device::BluetoothDevice::UUIDSet uuids = device->GetUUIDs(); - if (base::StartsWith(device->GetNameForDisplay(), - base::ASCIIToUTF16(kDeviceNamePrefix), - base::CompareCase::INSENSITIVE_ASCII) && - base::ContainsKey(uuids, device::BluetoothUUID(kPairingServiceUUID))) { - discovered_devices_.insert(device->GetAddress()); - for (ControllerPairingController::Observer& observer : observers_) - observer.DiscoveredDevicesListChanged(); - } -} - -void BluetoothControllerPairingController::DeviceLost( - device::BluetoothDevice* device) { - DCHECK_EQ(current_stage_, STAGE_DEVICES_DISCOVERY); - DCHECK(thread_checker_.CalledOnValidThread()); - std::set<std::string>::iterator ix = - discovered_devices_.find(device->GetAddress()); - if (ix != discovered_devices_.end()) { - discovered_devices_.erase(ix); - for (ControllerPairingController::Observer& observer : observers_) - observer.DiscoveredDevicesListChanged(); - } -} - -void BluetoothControllerPairingController::SendBuffer( - scoped_refptr<net::IOBuffer> io_buffer, int size) { - socket_->Send( - io_buffer, size, - base::Bind(&BluetoothControllerPairingController::OnSendComplete, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothControllerPairingController::OnErrorWithMessage, - ptr_factory_.GetWeakPtr())); -} - -void BluetoothControllerPairingController::OnSetPowered() { - DCHECK(thread_checker_.CalledOnValidThread()); - adapter_->StartDiscoverySession( - base::Bind(&BluetoothControllerPairingController::OnStartDiscoverySession, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothControllerPairingController::OnError, - ptr_factory_.GetWeakPtr())); -} - -void BluetoothControllerPairingController::OnGetAdapter( - scoped_refptr<device::BluetoothAdapter> adapter) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!adapter_.get()); - adapter_ = adapter; - adapter_->AddObserver(this); - - if (adapter_->IsPowered()) { - OnSetPowered(); - } else { - adapter_->SetPowered( - true, - base::Bind(&BluetoothControllerPairingController::OnSetPowered, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothControllerPairingController::OnError, - ptr_factory_.GetWeakPtr())); - } -} - -void BluetoothControllerPairingController::OnStartDiscoverySession( - std::unique_ptr<device::BluetoothDiscoverySession> discovery_session) { - DCHECK(thread_checker_.CalledOnValidThread()); - discovery_session_ = std::move(discovery_session); - ChangeStage(STAGE_DEVICES_DISCOVERY); - - for (auto* device : adapter_->GetDevices()) - DeviceFound(device); -} - -void BluetoothControllerPairingController::OnConnect() { - DCHECK(thread_checker_.CalledOnValidThread()); - device::BluetoothDevice* device = GetController(); - if (device) { - device->ConnectToService( - device::BluetoothUUID(kPairingServiceUUID), - base::Bind(&BluetoothControllerPairingController::OnConnectToService, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothControllerPairingController::OnErrorWithMessage, - ptr_factory_.GetWeakPtr())); - } -} - -void BluetoothControllerPairingController::OnConnectToService( - scoped_refptr<device::BluetoothSocket> socket) { - DCHECK(thread_checker_.CalledOnValidThread()); - socket_ = socket; - - socket_->Receive( - kReceiveSize, - base::Bind(&BluetoothControllerPairingController::OnReceiveComplete, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothControllerPairingController::OnReceiveError, - ptr_factory_.GetWeakPtr())); - ChangeStage(STAGE_PAIRING_DONE); -} - -void BluetoothControllerPairingController::OnSendComplete(int bytes_sent) {} - -void BluetoothControllerPairingController::OnReceiveComplete( - int bytes, scoped_refptr<net::IOBuffer> io_buffer) { - DCHECK(thread_checker_.CalledOnValidThread()); - proto_decoder_->DecodeIOBuffer(bytes, io_buffer); - - socket_->Receive( - kReceiveSize, - base::Bind(&BluetoothControllerPairingController::OnReceiveComplete, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothControllerPairingController::OnReceiveError, - ptr_factory_.GetWeakPtr())); -} - -void BluetoothControllerPairingController::OnError() { - LOG(ERROR) << "Pairing initialization failed"; - ChangeStage(STAGE_INITIALIZATION_ERROR); - Reset(); -} - -void BluetoothControllerPairingController::OnErrorWithMessage( - const std::string& message) { - LOG(ERROR) << message; - ChangeStage(STAGE_INITIALIZATION_ERROR); - Reset(); -} - -void BluetoothControllerPairingController::OnConnectError( - device::BluetoothDevice::ConnectErrorCode error_code) { - DCHECK(thread_checker_.CalledOnValidThread()); - device::BluetoothDevice* device = GetController(); - - if (device && device->IsPaired()) { - // The connection attempt is only used to start the pairing between the - // devices. If the connection fails, it's not a problem as long as pairing - // was successful. - OnConnect(); - } else { - // This can happen if the confirmation dialog times out. - ChangeStage(STAGE_ESTABLISHING_CONNECTION_ERROR); - } -} - -void BluetoothControllerPairingController::OnReceiveError( - device::BluetoothSocket::ErrorReason reason, - const std::string& error_message) { - LOG(ERROR) << reason << ", " << error_message; - Reset(); -} - -void BluetoothControllerPairingController::AddObserver( - ControllerPairingController::Observer* observer) { - observers_.AddObserver(observer); -} - -void BluetoothControllerPairingController::RemoveObserver( - ControllerPairingController::Observer* observer) { - observers_.RemoveObserver(observer); -} - -ControllerPairingController::Stage -BluetoothControllerPairingController::GetCurrentStage() { - return current_stage_; -} - -void BluetoothControllerPairingController::StartPairing() { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(current_stage_ == STAGE_NONE || - current_stage_ == STAGE_DEVICE_NOT_FOUND || - current_stage_ == STAGE_ESTABLISHING_CONNECTION_ERROR || - current_stage_ == STAGE_HOST_ENROLLMENT_ERROR); - if (!device::BluetoothAdapterFactory::IsBluetoothSupported()) { - ChangeStage(STAGE_INITIALIZATION_ERROR); - return; - } - - device::BluetoothAdapterFactory::GetAdapter( - base::BindOnce(&BluetoothControllerPairingController::OnGetAdapter, - ptr_factory_.GetWeakPtr())); -} - -ControllerPairingController::DeviceIdList -BluetoothControllerPairingController::GetDiscoveredDevices() { - DCHECK_EQ(current_stage_, STAGE_DEVICES_DISCOVERY); - return DeviceIdList(discovered_devices_.begin(), discovered_devices_.end()); -} - -void BluetoothControllerPairingController::ChooseDeviceForPairing( - const std::string& device_id) { - DCHECK_EQ(current_stage_, STAGE_DEVICES_DISCOVERY); - DCHECK(discovered_devices_.count(device_id)); - discovery_session_.reset(); - controller_device_id_ = device_id; - - device::BluetoothDevice* device = GetController(); - - if (device) { - ChangeStage(STAGE_ESTABLISHING_CONNECTION); - if (device->IsPaired()) { - OnConnect(); - } else { - device->Connect( - this, - base::Bind(&BluetoothControllerPairingController::OnConnect, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothControllerPairingController::OnConnectError, - ptr_factory_.GetWeakPtr())); - } - } -} - -void BluetoothControllerPairingController::RepeatDiscovery() { - DCHECK(current_stage_ == STAGE_DEVICE_NOT_FOUND || - current_stage_ == STAGE_ESTABLISHING_CONNECTION_ERROR || - current_stage_ == STAGE_HOST_ENROLLMENT_ERROR); - Reset(); - StartPairing(); -} - -std::string BluetoothControllerPairingController::GetConfirmationCode() { - DCHECK_EQ(current_stage_, STAGE_WAITING_FOR_CODE_CONFIRMATION); - DCHECK(!confirmation_code_.empty()); - return confirmation_code_; -} - -void BluetoothControllerPairingController::SetConfirmationCodeIsCorrect( - bool correct) { - DCHECK_EQ(current_stage_, STAGE_WAITING_FOR_CODE_CONFIRMATION); - - device::BluetoothDevice* device = GetController(); - if (!device) - return; - - if (correct) { - device->ConfirmPairing(); - // Once pairing is confirmed, the connection will either be successful, or - // fail. Either case is acceptable as long as the devices are paired. - } else { - device->RejectPairing(); - controller_device_id_.clear(); - RepeatDiscovery(); - } -} - -void BluetoothControllerPairingController::SetHostNetwork( - const std::string& onc_spec) { - pairing_api::AddNetwork add_network; - add_network.set_api_version(kPairingAPIVersion); - add_network.mutable_parameters()->set_onc_spec(onc_spec); - - int size = 0; - scoped_refptr<net::IOBuffer> io_buffer( - ProtoDecoder::SendHostNetwork(add_network, &size)); - - SendBuffer(io_buffer, size); -} - -void BluetoothControllerPairingController::SetHostConfiguration( - bool accepted_eula, - const std::string& lang, - const std::string& timezone, - bool send_reports, - const std::string& keyboard_layout) { - VLOG(1) << "SetHostConfiguration lang=" << lang - << ", timezone=" << timezone - << ", keyboard_layout=" << keyboard_layout; - - pairing_api::ConfigureHost host_config; - host_config.set_api_version(kPairingAPIVersion); - host_config.mutable_parameters()->set_accepted_eula(accepted_eula); - host_config.mutable_parameters()->set_lang(lang); - host_config.mutable_parameters()->set_timezone(timezone); - host_config.mutable_parameters()->set_send_reports(send_reports); - host_config.mutable_parameters()->set_keyboard_layout(keyboard_layout); - - int size = 0; - scoped_refptr<net::IOBuffer> io_buffer( - ProtoDecoder::SendConfigureHost(host_config, &size)); - - SendBuffer(io_buffer, size); -} - -void BluetoothControllerPairingController::OnAuthenticationDone( - const std::string& domain, - const std::string& auth_token) { - DCHECK_EQ(current_stage_, STAGE_WAITING_FOR_CREDENTIALS); - - pairing_api::PairDevices pair_devices; - pair_devices.set_api_version(kPairingAPIVersion); - pair_devices.mutable_parameters()->set_admin_access_token(auth_token); - pair_devices.mutable_parameters()->set_enrolling_domain(domain); - - int size = 0; - scoped_refptr<net::IOBuffer> io_buffer( - ProtoDecoder::SendPairDevices(pair_devices, &size)); - - SendBuffer(io_buffer, size); - ChangeStage(STAGE_HOST_ENROLLMENT_IN_PROGRESS); -} - -void BluetoothControllerPairingController::StartSession() { - DCHECK_EQ(current_stage_, STAGE_HOST_ENROLLMENT_SUCCESS); - ChangeStage(STAGE_FINISHED); -} - -void BluetoothControllerPairingController::OnHostStatusMessage( - const pairing_api::HostStatus& message) { - pairing_api::HostStatusParameters::UpdateStatus update_status = - message.parameters().update_status(); - pairing_api::HostStatusParameters::EnrollmentStatus enrollment_status = - message.parameters().enrollment_status(); - pairing_api::HostStatusParameters::Connectivity connectivity = - message.parameters().connectivity(); - VLOG(1) << "OnHostStatusMessage, update_status=" << update_status; - // TODO(zork): Check domain. (http://crbug.com/405761) - if (connectivity == pairing_api::HostStatusParameters::CONNECTIVITY_NONE) { - ChangeStage(STAGE_HOST_NETWORK_ERROR); - } else if (enrollment_status == - pairing_api::HostStatusParameters::ENROLLMENT_STATUS_SUCCESS) { - // TODO(achuith, zork): Need to ensure that controller has also successfully - // enrolled. - CompleteSetup(); - } else if (enrollment_status == - pairing_api::HostStatusParameters::ENROLLMENT_STATUS_FAILURE) { - ChangeStage(STAGE_HOST_ENROLLMENT_ERROR); - // Reboot the host if enrollment failed. - pairing_api::Reboot reboot; - reboot.set_api_version(kPairingAPIVersion); - int size = 0; - scoped_refptr<net::IOBuffer> io_buffer( - ProtoDecoder::SendRebootHost(reboot, &size)); - SendBuffer(io_buffer, size); - } else if (update_status == - pairing_api::HostStatusParameters::UPDATE_STATUS_UPDATING) { - ChangeStage(STAGE_HOST_UPDATE_IN_PROGRESS); - } else if (update_status == - pairing_api::HostStatusParameters::UPDATE_STATUS_UPDATED) { - ChangeStage(STAGE_WAITING_FOR_CREDENTIALS); - } -} - -void BluetoothControllerPairingController::CompleteSetup() { - pairing_api::CompleteSetup complete_setup; - complete_setup.set_api_version(kPairingAPIVersion); - // TODO(zork): Get AddAnother from UI (http://crbug.com/405757) - complete_setup.mutable_parameters()->set_add_another(false); - - int size = 0; - scoped_refptr<net::IOBuffer> io_buffer( - ProtoDecoder::SendCompleteSetup(complete_setup, &size)); - - SendBuffer(io_buffer, size); - ChangeStage(STAGE_HOST_ENROLLMENT_SUCCESS); -} - -void BluetoothControllerPairingController::OnConfigureHostMessage( - const pairing_api::ConfigureHost& message) { - NOTREACHED(); -} - -void BluetoothControllerPairingController::OnPairDevicesMessage( - const pairing_api::PairDevices& message) { - NOTREACHED(); -} - -void BluetoothControllerPairingController::OnCompleteSetupMessage( - const pairing_api::CompleteSetup& message) { - NOTREACHED(); -} - -void BluetoothControllerPairingController::OnErrorMessage( - const pairing_api::Error& message) { - LOG(ERROR) << message.parameters().code() << ", " << - message.parameters().description(); - ChangeStage(STAGE_HOST_ENROLLMENT_ERROR); -} - -void BluetoothControllerPairingController::OnAddNetworkMessage( - const pairing_api::AddNetwork& message) { - NOTREACHED(); -} - -void BluetoothControllerPairingController::OnRebootMessage( - const pairing_api::Reboot& message) { - NOTREACHED(); -} - -void BluetoothControllerPairingController::DeviceAdded( - device::BluetoothAdapter* adapter, - device::BluetoothDevice* device) { - DCHECK_EQ(adapter, adapter_.get()); - DeviceFound(device); -} - -void BluetoothControllerPairingController::DeviceRemoved( - device::BluetoothAdapter* adapter, - device::BluetoothDevice* device) { - DCHECK_EQ(adapter, adapter_.get()); - DeviceLost(device); -} - -void BluetoothControllerPairingController::RequestPinCode( - device::BluetoothDevice* device) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothControllerPairingController::RequestPasskey( - device::BluetoothDevice* device) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothControllerPairingController::DisplayPinCode( - device::BluetoothDevice* device, - const std::string& pincode) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothControllerPairingController::DisplayPasskey( - device::BluetoothDevice* device, - uint32_t passkey) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothControllerPairingController::KeysEntered( - device::BluetoothDevice* device, - uint32_t entered) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothControllerPairingController::ConfirmPasskey( - device::BluetoothDevice* device, - uint32_t passkey) { - confirmation_code_ = base::StringPrintf("%06d", passkey); - ChangeStage(STAGE_WAITING_FOR_CODE_CONFIRMATION); -} - -void BluetoothControllerPairingController::AuthorizePairing( - device::BluetoothDevice* device) { - // Disallow unknown device. - device->RejectPairing(); -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/bluetooth_controller_pairing_controller.h b/components/pairing/bluetooth_controller_pairing_controller.h deleted file mode 100644 index a7ebbb9..0000000 --- a/components/pairing/bluetooth_controller_pairing_controller.h +++ /dev/null
@@ -1,131 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_BLUETOOTH_CONTROLLER_PAIRING_CONTROLLER_H_ -#define COMPONENTS_PAIRING_BLUETOOTH_CONTROLLER_PAIRING_CONTROLLER_H_ - -#include <stdint.h> - -#include <memory> -#include <set> - -#include "base/macros.h" -#include "base/observer_list.h" -#include "base/threading/thread_checker.h" -#include "components/pairing/controller_pairing_controller.h" -#include "components/pairing/proto_decoder.h" -#include "device/bluetooth/bluetooth_adapter.h" -#include "device/bluetooth/bluetooth_device.h" -#include "device/bluetooth/bluetooth_socket.h" - -namespace net { -class IOBuffer; -} - -namespace pairing_chromeos { - -class BluetoothControllerPairingController - : public ControllerPairingController, - public ProtoDecoder::Observer, - public device::BluetoothAdapter::Observer, - public device::BluetoothDevice::PairingDelegate { - public: - BluetoothControllerPairingController(); - ~BluetoothControllerPairingController() override; - - private: - void ChangeStage(Stage new_stage); - device::BluetoothDevice* GetController(); - void Reset(); - void DeviceFound(device::BluetoothDevice* device); - void DeviceLost(device::BluetoothDevice* device); - void SendBuffer(scoped_refptr<net::IOBuffer> io_buffer, int size); - void CompleteSetup(); - - void OnSetPowered(); - void OnGetAdapter(scoped_refptr<device::BluetoothAdapter> adapter); - void OnStartDiscoverySession( - std::unique_ptr<device::BluetoothDiscoverySession> discovery_session); - void OnConnect(); - void OnConnectToService(scoped_refptr<device::BluetoothSocket> socket); - void OnSendComplete(int bytes_sent); - void OnReceiveComplete(int bytes, scoped_refptr<net::IOBuffer> io_buffer); - - void OnError(); - void OnErrorWithMessage(const std::string& message); - void OnConnectError(device::BluetoothDevice::ConnectErrorCode error_code); - void OnReceiveError(device::BluetoothSocket::ErrorReason reason, - const std::string& error_message); - - // ControllerPairingController: - void AddObserver(ControllerPairingController::Observer* observer) override; - void RemoveObserver(ControllerPairingController::Observer* observer) override; - Stage GetCurrentStage() override; - void StartPairing() override; - DeviceIdList GetDiscoveredDevices() override; - void ChooseDeviceForPairing(const std::string& device_id) override; - void RepeatDiscovery() override; - std::string GetConfirmationCode() override; - void SetConfirmationCodeIsCorrect(bool correct) override; - void SetHostNetwork(const std::string& onc_spec) override; - void SetHostConfiguration(bool accepted_eula, - const std::string& lang, - const std::string& timezone, - bool send_reports, - const std::string& keyboard_layout) override; - void OnAuthenticationDone(const std::string& domain, - const std::string& auth_token) override; - void StartSession() override; - - // ProtoDecoder::Observer: - void OnHostStatusMessage(const pairing_api::HostStatus& message) override; - void OnConfigureHostMessage( - const pairing_api::ConfigureHost& message) override; - void OnPairDevicesMessage(const pairing_api::PairDevices& message) override; - void OnCompleteSetupMessage( - const pairing_api::CompleteSetup& message) override; - void OnErrorMessage(const pairing_api::Error& message) override; - void OnAddNetworkMessage(const pairing_api::AddNetwork& message) override; - void OnRebootMessage(const pairing_api::Reboot& message) override; - - // BluetoothAdapter::Observer: - void DeviceAdded(device::BluetoothAdapter* adapter, - device::BluetoothDevice* device) override; - void DeviceRemoved(device::BluetoothAdapter* adapter, - device::BluetoothDevice* device) override; - - // device::BluetoothDevice::PairingDelegate: - void RequestPinCode(device::BluetoothDevice* device) override; - void RequestPasskey(device::BluetoothDevice* device) override; - void DisplayPinCode(device::BluetoothDevice* device, - const std::string& pincode) override; - void DisplayPasskey(device::BluetoothDevice* device, - uint32_t passkey) override; - void KeysEntered(device::BluetoothDevice* device, uint32_t entered) override; - void ConfirmPasskey(device::BluetoothDevice* device, - uint32_t passkey) override; - void AuthorizePairing(device::BluetoothDevice* device) override; - - Stage current_stage_; - scoped_refptr<device::BluetoothAdapter> adapter_; - std::unique_ptr<device::BluetoothDiscoverySession> discovery_session_; - scoped_refptr<device::BluetoothSocket> socket_; - std::string controller_device_id_; - - std::string confirmation_code_; - std::set<std::string> discovered_devices_; - - std::unique_ptr<ProtoDecoder> proto_decoder_; - - base::ThreadChecker thread_checker_; - base::ObserverList<ControllerPairingController::Observer>::Unchecked - observers_; - base::WeakPtrFactory<BluetoothControllerPairingController> ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothControllerPairingController); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_BLUETOOTH_CONTROLLER_PAIRING_CONTROLLER_H_
diff --git a/components/pairing/bluetooth_host_pairing_controller.cc b/components/pairing/bluetooth_host_pairing_controller.cc deleted file mode 100644 index 75a39a6..0000000 --- a/components/pairing/bluetooth_host_pairing_controller.cc +++ /dev/null
@@ -1,590 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/bluetooth_host_pairing_controller.h" - -#include <utility> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/hash/hash.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/strings/stringprintf.h" -#include "chromeos/constants/devicetype.h" -#include "components/pairing/bluetooth_pairing_constants.h" -#include "components/pairing/pairing_api.pb.h" -#include "components/pairing/proto_decoder.h" -#include "device/bluetooth/bluetooth_adapter_factory.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#include "net/base/io_buffer.h" -#include "services/device/public/mojom/constants.mojom.h" -#include "services/service_manager/public/cpp/connector.h" - -namespace pairing_chromeos { - -namespace { -const int kReceiveSize = 16384; - -pairing_api::HostStatusParameters::Connectivity PairingApiConnectivityStatus( - HostPairingController::Connectivity connectivity_status) { - switch (connectivity_status) { - case HostPairingController::CONNECTIVITY_UNTESTED: - return pairing_api::HostStatusParameters::CONNECTIVITY_UNTESTED; - case HostPairingController::CONNECTIVITY_NONE: - return pairing_api::HostStatusParameters::CONNECTIVITY_NONE; - case HostPairingController::CONNECTIVITY_LIMITED: - return pairing_api::HostStatusParameters::CONNECTIVITY_LIMITED; - case HostPairingController::CONNECTIVITY_CONNECTING: - return pairing_api::HostStatusParameters::CONNECTIVITY_CONNECTING; - case HostPairingController::CONNECTIVITY_CONNECTED: - return pairing_api::HostStatusParameters::CONNECTIVITY_CONNECTED; - default: - NOTREACHED(); - return pairing_api::HostStatusParameters::CONNECTIVITY_UNTESTED; - } -} - -pairing_api::HostStatusParameters::UpdateStatus PairingApiUpdateStatus( - HostPairingController::UpdateStatus update_status) { - switch(update_status) { - case HostPairingController::UPDATE_STATUS_UNKNOWN: - return pairing_api::HostStatusParameters::UPDATE_STATUS_UNKNOWN; - case HostPairingController::UPDATE_STATUS_UPDATING: - return pairing_api::HostStatusParameters::UPDATE_STATUS_UPDATING; - case HostPairingController::UPDATE_STATUS_REBOOTING: - return pairing_api::HostStatusParameters::UPDATE_STATUS_REBOOTING; - case HostPairingController::UPDATE_STATUS_UPDATED: - return pairing_api::HostStatusParameters::UPDATE_STATUS_UPDATED; - default: - NOTREACHED(); - return pairing_api::HostStatusParameters::UPDATE_STATUS_UNKNOWN; - } -} - -pairing_api::HostStatusParameters::EnrollmentStatus PairingApiEnrollmentStatus( - HostPairingController::EnrollmentStatus enrollment_status) { - switch(enrollment_status) { - case HostPairingController::ENROLLMENT_STATUS_UNKNOWN: - return pairing_api::HostStatusParameters::ENROLLMENT_STATUS_UNKNOWN; - case HostPairingController::ENROLLMENT_STATUS_ENROLLING: - return pairing_api::HostStatusParameters::ENROLLMENT_STATUS_ENROLLING; - case HostPairingController::ENROLLMENT_STATUS_FAILURE: - return pairing_api::HostStatusParameters::ENROLLMENT_STATUS_FAILURE; - case HostPairingController::ENROLLMENT_STATUS_SUCCESS: - return pairing_api::HostStatusParameters::ENROLLMENT_STATUS_SUCCESS; - default: - NOTREACHED(); - return pairing_api::HostStatusParameters::ENROLLMENT_STATUS_UNKNOWN; - } -} - -} // namespace - -BluetoothHostPairingController::BluetoothHostPairingController( - service_manager::Connector* connector) - : proto_decoder_(std::make_unique<ProtoDecoder>(this)) { - DCHECK(connector); - connector->BindInterface(device::mojom::kServiceName, - mojo::MakeRequest(&input_device_manager_)); -} - -BluetoothHostPairingController::~BluetoothHostPairingController() { - Reset(); -} - -void BluetoothHostPairingController::SetDelegateForTesting( - TestDelegate* delegate) { - delegate_ = delegate; -} - -scoped_refptr<device::BluetoothAdapter> -BluetoothHostPairingController::GetAdapterForTesting() { - return adapter_; -} - -void BluetoothHostPairingController::ChangeStage(Stage new_stage) { - if (current_stage_ == new_stage) - return; - VLOG(1) << "ChangeStage " << new_stage; - current_stage_ = new_stage; - for (Observer& observer : observers_) - observer.PairingStageChanged(new_stage); -} - -void BluetoothHostPairingController::SendHostStatus() { - pairing_api::HostStatus host_status; - - host_status.set_api_version(kPairingAPIVersion); - if (!enrollment_domain_.empty()) - host_status.mutable_parameters()->set_domain(enrollment_domain_); - if (!permanent_id_.empty()) - host_status.mutable_parameters()->set_permanent_id(permanent_id_); - - // TODO(zork): Get these values from the UI. (http://crbug.com/405744) - host_status.mutable_parameters()->set_connectivity( - PairingApiConnectivityStatus(connectivity_status_)); - host_status.mutable_parameters()->set_update_status( - PairingApiUpdateStatus(update_status_)); - host_status.mutable_parameters()->set_enrollment_status( - PairingApiEnrollmentStatus(enrollment_status_)); - - // TODO(zork): Get a list of other paired controllers. - // (http://crbug.com/405757) - - int size = 0; - scoped_refptr<net::IOBuffer> io_buffer( - ProtoDecoder::SendHostStatus(host_status, &size)); - - controller_socket_->Send( - io_buffer, size, - base::Bind(&BluetoothHostPairingController::OnSendComplete, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::OnSendError, - ptr_factory_.GetWeakPtr())); -} - -void BluetoothHostPairingController::SendErrorCodeAndMessage() { - if (error_code_ == - static_cast<int>(HostPairingController::ErrorCode::ERROR_NONE)) { - return; - } - - pairing_api::Error error_status; - error_status.set_api_version(kPairingAPIVersion); - error_status.mutable_parameters()->set_code(error_code_); - error_status.mutable_parameters()->set_description(error_message_); - - int size = 0; - scoped_refptr<net::IOBuffer> io_buffer( - ProtoDecoder::SendError(error_status, &size)); - - controller_socket_->Send( - io_buffer, size, - base::Bind(&BluetoothHostPairingController::OnSendComplete, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::OnSendError, - ptr_factory_.GetWeakPtr())); -} - -void BluetoothHostPairingController::Reset() { - if (adapter_.get()) { - device::BluetoothDevice* device = - adapter_->GetDevice(controller_device_address_); - if (device && device->IsPaired()) { - device->Forget(base::Bind(&BluetoothHostPairingController::OnForget, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::OnForget, - ptr_factory_.GetWeakPtr())); - return; - } - } - OnForget(); -} - -void BluetoothHostPairingController::OnGetAdapter( - scoped_refptr<device::BluetoothAdapter> adapter) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(!adapter_.get()); - adapter_ = adapter; - - if (adapter_->IsPresent()) { - SetPowered(); - } else { - // Set the name once the adapter is present. - adapter_->AddObserver(this); - } -} - -void BluetoothHostPairingController::SetPowered() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - if (adapter_->IsPowered()) { - was_powered_ = true; - OnSetPowered(); - } else { - adapter_->SetPowered( - true, - base::Bind(&BluetoothHostPairingController::OnSetPowered, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::OnSetError, - ptr_factory_.GetWeakPtr())); - } -} - -void BluetoothHostPairingController::OnSetPowered() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - adapter_->AddPairingDelegate( - this, device::BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_HIGH); - - device::BluetoothAdapter::ServiceOptions options; - options.name.reset(new std::string(kPairingServiceName)); - - adapter_->CreateRfcommService( - device::BluetoothUUID(kPairingServiceUUID), options, - base::Bind(&BluetoothHostPairingController::OnCreateService, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::OnCreateServiceError, - ptr_factory_.GetWeakPtr())); -} - -void BluetoothHostPairingController::OnCreateService( - scoped_refptr<device::BluetoothSocket> socket) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - service_socket_ = socket; - - service_socket_->Accept( - base::Bind(&BluetoothHostPairingController::OnAccept, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::OnAcceptError, - ptr_factory_.GetWeakPtr())); - - adapter_->SetDiscoverable( - true, - base::Bind(&BluetoothHostPairingController::OnSetDiscoverable, - ptr_factory_.GetWeakPtr(), true), - base::Bind(&BluetoothHostPairingController::OnSetError, - ptr_factory_.GetWeakPtr())); -} - -void BluetoothHostPairingController::OnAccept( - const device::BluetoothDevice* device, - scoped_refptr<device::BluetoothSocket> socket) { - controller_device_address_ = device->GetAddress(); - - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - adapter_->SetDiscoverable( - false, - base::Bind(&BluetoothHostPairingController::OnSetDiscoverable, - ptr_factory_.GetWeakPtr(), false), - base::Bind(&BluetoothHostPairingController::OnSetError, - ptr_factory_.GetWeakPtr())); - controller_socket_ = socket; - - SendHostStatus(); - - controller_socket_->Receive( - kReceiveSize, - base::Bind(&BluetoothHostPairingController::OnReceiveComplete, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::OnReceiveError, - ptr_factory_.GetWeakPtr())); -} - -void BluetoothHostPairingController::OnSetDiscoverable(bool change_stage) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - if (change_stage) { - DCHECK_EQ(current_stage_, STAGE_NONE); - ChangeStage(STAGE_WAITING_FOR_CONTROLLER); - } -} - -void BluetoothHostPairingController::OnSendComplete(int bytes_sent) {} - -void BluetoothHostPairingController::OnReceiveComplete( - int bytes, scoped_refptr<net::IOBuffer> io_buffer) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - proto_decoder_->DecodeIOBuffer(bytes, io_buffer); - - if (controller_socket_.get()) { - controller_socket_->Receive( - kReceiveSize, - base::Bind(&BluetoothHostPairingController::OnReceiveComplete, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::OnReceiveError, - ptr_factory_.GetWeakPtr())); - } -} - -void BluetoothHostPairingController::OnCreateServiceError( - const std::string& message) { - LOG(ERROR) << message; - ChangeStage(STAGE_INITIALIZATION_ERROR); -} - -void BluetoothHostPairingController::OnSetError() { - adapter_->RemovePairingDelegate(this); - ChangeStage(STAGE_INITIALIZATION_ERROR); -} - -void BluetoothHostPairingController::OnAcceptError( - const std::string& error_message) { - LOG(ERROR) << error_message; - ChangeStage(STAGE_CONTROLLER_CONNECTION_ERROR); -} - -void BluetoothHostPairingController::OnSendError( - const std::string& error_message) { - LOG(ERROR) << error_message; - if (enrollment_status_ != ENROLLMENT_STATUS_ENROLLING && - enrollment_status_ != ENROLLMENT_STATUS_SUCCESS) { - ChangeStage(STAGE_CONTROLLER_CONNECTION_ERROR); - } -} - -void BluetoothHostPairingController::PowerOffAdapterIfApplicable( - std::vector<InputDeviceInfoPtr> devices) { - bool use_bluetooth = false; - for (auto& device : devices) { - if (device->type == device::mojom::InputDeviceType::TYPE_BLUETOOTH) { - use_bluetooth = true; - break; - } - } - if (!was_powered_ && !use_bluetooth) { - adapter_->SetPowered( - false, base::Bind(&BluetoothHostPairingController::ResetAdapter, - ptr_factory_.GetWeakPtr()), - base::Bind(&BluetoothHostPairingController::ResetAdapter, - ptr_factory_.GetWeakPtr())); - } else { - ResetAdapter(); - } -} - -void BluetoothHostPairingController::ResetAdapter() { - adapter_->RemoveObserver(this); - adapter_ = nullptr; - if (delegate_) - delegate_->OnAdapterReset(); -} - -void BluetoothHostPairingController::OnForget() { - if (controller_socket_.get()) { - controller_socket_->Close(); - controller_socket_ = nullptr; - } - - if (service_socket_.get()) { - service_socket_->Close(); - service_socket_ = nullptr; - } - - if (adapter_.get()) { - if (adapter_->IsDiscoverable()) { - adapter_->SetDiscoverable(false, base::DoNothing(), base::DoNothing()); - } - - input_device_manager_->GetDevices(base::BindOnce( - &BluetoothHostPairingController::PowerOffAdapterIfApplicable, - ptr_factory_.GetWeakPtr())); - } - ChangeStage(STAGE_NONE); -} - -void BluetoothHostPairingController::SetControllerDeviceAddressForTesting( - const std::string& address) { - controller_device_address_ = address; -} - -void BluetoothHostPairingController::OnReceiveError( - device::BluetoothSocket::ErrorReason reason, - const std::string& error_message) { - LOG(ERROR) << reason << ", " << error_message; - ChangeStage(STAGE_CONTROLLER_CONNECTION_ERROR); -} - -void BluetoothHostPairingController::OnHostStatusMessage( - const pairing_api::HostStatus& message) { - NOTREACHED(); -} - -void BluetoothHostPairingController::OnConfigureHostMessage( - const pairing_api::ConfigureHost& message) { - ChangeStage(STAGE_SETUP_BASIC_CONFIGURATION); - for (Observer& observer : observers_) { - observer.ConfigureHostRequested( - message.parameters().accepted_eula(), message.parameters().lang(), - message.parameters().timezone(), message.parameters().send_reports(), - message.parameters().keyboard_layout()); - } -} - -void BluetoothHostPairingController::OnPairDevicesMessage( - const pairing_api::PairDevices& message) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - enrollment_domain_ = message.parameters().enrolling_domain(); - ChangeStage(STAGE_ENROLLING); - for (Observer& observer : observers_) - observer.EnrollHostRequested(message.parameters().admin_access_token()); -} - -void BluetoothHostPairingController::OnCompleteSetupMessage( - const pairing_api::CompleteSetup& message) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - if (current_stage_ != STAGE_ENROLLMENT_SUCCESS) { - ChangeStage(STAGE_ENROLLMENT_ERROR); - } else { - // TODO(zork): Handle adding another controller. (http://crbug.com/405757) - ChangeStage(STAGE_FINISHED); - } - Reset(); -} - -void BluetoothHostPairingController::OnErrorMessage( - const pairing_api::Error& message) { - NOTREACHED(); -} - -void BluetoothHostPairingController::OnRebootMessage( - const pairing_api::Reboot& message) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - for (Observer& observer : observers_) - observer.RebootHostRequested(); -} - -void BluetoothHostPairingController::OnAddNetworkMessage( - const pairing_api::AddNetwork& message) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - for (Observer& observer : observers_) - observer.AddNetworkRequested(message.parameters().onc_spec()); -} - -void BluetoothHostPairingController::AdapterPresentChanged( - device::BluetoothAdapter* adapter, - bool present) { - DCHECK_EQ(adapter, adapter_.get()); - if (present) { - adapter_->RemoveObserver(this); - SetPowered(); - } -} - -void BluetoothHostPairingController::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void BluetoothHostPairingController::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -HostPairingController::Stage BluetoothHostPairingController::GetCurrentStage() { - return current_stage_; -} - -void BluetoothHostPairingController::StartPairing() { - DCHECK_EQ(current_stage_, STAGE_NONE); - const bool bluetooth_supported = - device::BluetoothAdapterFactory::IsBluetoothSupported(); - if (!bluetooth_supported) { - ChangeStage(STAGE_INITIALIZATION_ERROR); - return; - } - - device::BluetoothAdapterFactory::GetAdapter( - base::BindOnce(&BluetoothHostPairingController::OnGetAdapter, - ptr_factory_.GetWeakPtr())); -} - -std::string BluetoothHostPairingController::GetDeviceName() { - return adapter_.get() ? adapter_->GetName() : std::string(); -} - -std::string BluetoothHostPairingController::GetConfirmationCode() { - DCHECK_EQ(current_stage_, STAGE_WAITING_FOR_CODE_CONFIRMATION); - return confirmation_code_; -} - -std::string BluetoothHostPairingController::GetEnrollmentDomain() { - return enrollment_domain_; -} - -void BluetoothHostPairingController::OnNetworkConnectivityChanged( - Connectivity connectivity_status) { - connectivity_status_ = connectivity_status; - if (connectivity_status == CONNECTIVITY_NONE) { - ChangeStage(STAGE_SETUP_NETWORK_ERROR); - SendErrorCodeAndMessage(); - } else { - SendHostStatus(); - } -} - -void BluetoothHostPairingController::OnUpdateStatusChanged( - UpdateStatus update_status) { - update_status_ = update_status; - if (update_status == UPDATE_STATUS_UPDATED) - ChangeStage(STAGE_WAITING_FOR_CREDENTIALS); - SendHostStatus(); -} - -void BluetoothHostPairingController::OnEnrollmentStatusChanged( - EnrollmentStatus enrollment_status) { - DCHECK_EQ(current_stage_, STAGE_ENROLLING); - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - enrollment_status_ = enrollment_status; - if (enrollment_status == ENROLLMENT_STATUS_SUCCESS) { - ChangeStage(STAGE_ENROLLMENT_SUCCESS); - SendHostStatus(); - } else if (enrollment_status == ENROLLMENT_STATUS_FAILURE) { - ChangeStage(STAGE_ENROLLMENT_ERROR); - SendErrorCodeAndMessage(); - } -} - -void BluetoothHostPairingController::SetPermanentId( - const std::string& permanent_id) { - permanent_id_ = permanent_id; -} - -void BluetoothHostPairingController::SetErrorCodeAndMessage( - int error_code, - const std::string& error_message) { - error_code_ = error_code; - error_message_ = error_message; -} - -void BluetoothHostPairingController::RequestPinCode( - device::BluetoothDevice* device) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothHostPairingController::RequestPasskey( - device::BluetoothDevice* device) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothHostPairingController::DisplayPinCode( - device::BluetoothDevice* device, - const std::string& pincode) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothHostPairingController::DisplayPasskey( - device::BluetoothDevice* device, - uint32_t passkey) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothHostPairingController::KeysEntered( - device::BluetoothDevice* device, - uint32_t entered) { - // Disallow unknown device. - device->RejectPairing(); -} - -void BluetoothHostPairingController::ConfirmPasskey( - device::BluetoothDevice* device, - uint32_t passkey) { - // If a new connection is occurring, reset the stage. This can occur if the - // pairing times out, or a new controller connects. - if (current_stage_ == STAGE_WAITING_FOR_CODE_CONFIRMATION) - ChangeStage(STAGE_WAITING_FOR_CONTROLLER); - - confirmation_code_ = base::StringPrintf("%06d", passkey); - device->ConfirmPairing(); - ChangeStage(STAGE_WAITING_FOR_CODE_CONFIRMATION); -} - -void BluetoothHostPairingController::AuthorizePairing( - device::BluetoothDevice* device) { - // Disallow unknown device. - device->RejectPairing(); -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/bluetooth_host_pairing_controller.h b/components/pairing/bluetooth_host_pairing_controller.h deleted file mode 100644 index 36c5ec9..0000000 --- a/components/pairing/bluetooth_host_pairing_controller.h +++ /dev/null
@@ -1,181 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_BLUETOOTH_HOST_PAIRING_CONTROLLER_H_ -#define COMPONENTS_PAIRING_BLUETOOTH_HOST_PAIRING_CONTROLLER_H_ - -#include <stdint.h> - -#include <memory> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "base/threading/thread_checker.h" -#include "components/pairing/host_pairing_controller.h" -#include "components/pairing/proto_decoder.h" -#include "device/bluetooth/bluetooth_adapter.h" -#include "device/bluetooth/bluetooth_device.h" -#include "device/bluetooth/bluetooth_socket.h" -#include "services/device/public/mojom/input_service.mojom.h" - -namespace service_manager { -class Connector; -} - -namespace device { -class BluetoothAdapter; -} - -namespace net { -class IOBuffer; -} - -namespace chromeos { -class BluetoothHostPairingNoInputTest; -} - -namespace pairing_chromeos { - -class BluetoothHostPairingController - : public HostPairingController, - public ProtoDecoder::Observer, - public device::BluetoothAdapter::Observer, - public device::BluetoothDevice::PairingDelegate { - public: - using Observer = HostPairingController::Observer; - using InputDeviceInfoPtr = device::mojom::InputDeviceInfoPtr; - - // An interface that is used for testing purpose. - class TestDelegate { - public: - virtual void OnAdapterReset() = 0; - - protected: - TestDelegate() {} - virtual ~TestDelegate() {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestDelegate); - }; - - explicit BluetoothHostPairingController( - service_manager::Connector* connector); - ~BluetoothHostPairingController() override; - - // These functions should be only used in tests. - void SetDelegateForTesting(TestDelegate* delegate); - scoped_refptr<device::BluetoothAdapter> GetAdapterForTesting(); - - private: - friend class chromeos::BluetoothHostPairingNoInputTest; - - void ChangeStage(Stage new_stage); - void SendHostStatus(); - void SendErrorCodeAndMessage(); - - void OnGetAdapter(scoped_refptr<device::BluetoothAdapter> adapter); - void SetPowered(); - void OnSetPowered(); - void OnCreateService(scoped_refptr<device::BluetoothSocket> socket); - void OnSetDiscoverable(bool change_stage); - void OnAccept(const device::BluetoothDevice* device, - scoped_refptr<device::BluetoothSocket> socket); - void OnSendComplete(int bytes_sent); - void OnReceiveComplete(int bytes, scoped_refptr<net::IOBuffer> io_buffer); - - void OnCreateServiceError(const std::string& message); - void OnSetError(); - void OnAcceptError(const std::string& error_message); - void OnSendError(const std::string& error_message); - void OnReceiveError(device::BluetoothSocket::ErrorReason reason, - const std::string& error_message); - void PowerOffAdapterIfApplicable(std::vector<InputDeviceInfoPtr> devices); - void ResetAdapter(); - void OnForget(); - - void SetControllerDeviceAddressForTesting(const std::string& address); - - // HostPairingController: - void AddObserver(Observer* observer) override; - void RemoveObserver(Observer* observer) override; - Stage GetCurrentStage() override; - void StartPairing() override; - std::string GetDeviceName() override; - std::string GetConfirmationCode() override; - std::string GetEnrollmentDomain() override; - void OnNetworkConnectivityChanged(Connectivity connectivity_status) override; - void OnUpdateStatusChanged(UpdateStatus update_status) override; - void OnEnrollmentStatusChanged(EnrollmentStatus enrollment_status) override; - void SetPermanentId(const std::string& permanent_id) override; - void SetErrorCodeAndMessage(int error_code, - const std::string& error_message) override; - void Reset() override; - - // ProtoDecoder::Observer: - void OnHostStatusMessage(const pairing_api::HostStatus& message) override; - void OnConfigureHostMessage( - const pairing_api::ConfigureHost& message) override; - void OnPairDevicesMessage(const pairing_api::PairDevices& message) override; - void OnCompleteSetupMessage( - const pairing_api::CompleteSetup& message) override; - void OnErrorMessage(const pairing_api::Error& message) override; - void OnAddNetworkMessage(const pairing_api::AddNetwork& message) override; - void OnRebootMessage(const pairing_api::Reboot& message) override; - - // BluetoothAdapter::Observer: - void AdapterPresentChanged(device::BluetoothAdapter* adapter, - bool present) override; - - // device::BluetoothDevice::PairingDelegate: - void RequestPinCode(device::BluetoothDevice* device) override; - void RequestPasskey(device::BluetoothDevice* device) override; - void DisplayPinCode(device::BluetoothDevice* device, - const std::string& pincode) override; - void DisplayPasskey(device::BluetoothDevice* device, - uint32_t passkey) override; - void KeysEntered(device::BluetoothDevice* device, uint32_t entered) override; - void ConfirmPasskey(device::BluetoothDevice* device, - uint32_t passkey) override; - void AuthorizePairing(device::BluetoothDevice* device) override; - - Stage current_stage_ = STAGE_NONE; - std::string confirmation_code_; - std::string enrollment_domain_; - Connectivity connectivity_status_ = CONNECTIVITY_UNTESTED; - UpdateStatus update_status_ = UPDATE_STATUS_UNKNOWN; - EnrollmentStatus enrollment_status_ = ENROLLMENT_STATUS_UNKNOWN; - std::string permanent_id_; - std::string controller_device_address_; - bool was_powered_ = false; - - // The format of the |error_code_| is: - // [0, "no error"] - // [1*, "network error"] - // [2*, "authentication error"], e.g., [21, "Service unavailable"], ... - // [3*, "enrollment error"], e.g., [31, "DMserver registration error"], ... - // [4*, "other error"] - // The |error_code_| and |error_message_| will pass over to the master device - // to assist error diagnosis. - int error_code_ = 0; - std::string error_message_; - - scoped_refptr<device::BluetoothAdapter> adapter_; - scoped_refptr<device::BluetoothSocket> service_socket_; - scoped_refptr<device::BluetoothSocket> controller_socket_; - std::unique_ptr<ProtoDecoder> proto_decoder_; - TestDelegate* delegate_ = nullptr; - - device::mojom::InputDeviceManagerPtr input_device_manager_; - THREAD_CHECKER(thread_checker_); - base::ObserverList<Observer>::Unchecked observers_; - base::WeakPtrFactory<BluetoothHostPairingController> ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(BluetoothHostPairingController); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_BLUETOOTH_HOST_PAIRING_CONTROLLER_H_
diff --git a/components/pairing/bluetooth_pairing_constants.cc b/components/pairing/bluetooth_pairing_constants.cc deleted file mode 100644 index 21507d0..0000000 --- a/components/pairing/bluetooth_pairing_constants.cc +++ /dev/null
@@ -1,14 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/bluetooth_pairing_constants.h" - -namespace pairing_chromeos { - -const char* kPairingServiceUUID = "f035ff16-c025-468e-bb16-967704d141ea"; -const char* kPairingServiceName = "ChromeOSDevicePairing"; -const char* kDeviceNamePrefix = "Chrome"; -const int kPairingAPIVersion = 1; - -} // namespace pairing_chromeos
diff --git a/components/pairing/bluetooth_pairing_constants.h b/components/pairing/bluetooth_pairing_constants.h deleted file mode 100644 index c098679..0000000 --- a/components/pairing/bluetooth_pairing_constants.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_BLUETOOTH_PAIRING_CONSTANTS_H_ -#define COMPONENTS_PAIRING_BLUETOOTH_PAIRING_CONSTANTS_H_ - -namespace pairing_chromeos { - -extern const char* kPairingServiceUUID; -extern const char* kPairingServiceName; -extern const char* kDeviceNamePrefix; -extern const int kPairingAPIVersion; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_BLUETOOTH_PAIRING_CONSTANTS_H_
diff --git a/components/pairing/controller_pairing_controller.cc b/components/pairing/controller_pairing_controller.cc deleted file mode 100644 index 448332fd..0000000 --- a/components/pairing/controller_pairing_controller.cc +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/controller_pairing_controller.h" - -namespace pairing_chromeos { - -ControllerPairingController::Observer::Observer() { -} - -ControllerPairingController::Observer::~Observer() { -} - -ControllerPairingController::ControllerPairingController() { -} - -ControllerPairingController::~ControllerPairingController() { -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/controller_pairing_controller.h b/components/pairing/controller_pairing_controller.h deleted file mode 100644 index 2eca3040..0000000 --- a/components/pairing/controller_pairing_controller.h +++ /dev/null
@@ -1,113 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_CONTROLLER_PAIRING_CONTROLLER_H_ -#define COMPONENTS_PAIRING_CONTROLLER_PAIRING_CONTROLLER_H_ - -#include <string> -#include <vector> - -#include "base/macros.h" - -namespace pairing_chromeos { - -class ControllerPairingController { - public: - enum Stage { - STAGE_NONE, - STAGE_INITIALIZATION_ERROR, - STAGE_DEVICES_DISCOVERY, - STAGE_DEVICE_NOT_FOUND, - STAGE_ESTABLISHING_CONNECTION, - STAGE_ESTABLISHING_CONNECTION_ERROR, - STAGE_WAITING_FOR_CODE_CONFIRMATION, - STAGE_PAIRING_DONE, - STAGE_HOST_NETWORK_ERROR, - STAGE_HOST_UPDATE_IN_PROGRESS, - STAGE_HOST_CONNECTION_LOST, - STAGE_WAITING_FOR_CREDENTIALS, - STAGE_HOST_ENROLLMENT_IN_PROGRESS, - STAGE_HOST_ENROLLMENT_ERROR, - STAGE_HOST_ENROLLMENT_SUCCESS, - STAGE_FINISHED - }; - - class Observer { - public: - Observer(); - virtual ~Observer(); - - // Called when pairing has moved on from one stage to another. - virtual void PairingStageChanged(Stage new_stage) = 0; - - // Called when new device was discovered or existing device was lost. - // This notification is made only on |STAGE_DEVICES_DISCOVERY| stage. - virtual void DiscoveredDevicesListChanged() = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(Observer); - }; - - typedef std::vector<std::string> DeviceIdList; - - ControllerPairingController(); - virtual ~ControllerPairingController(); - - // Returns current stage of pairing process. - virtual Stage GetCurrentStage() = 0; - - // Starts pairing process. Can be called only on |STAGE_NONE| stage. - virtual void StartPairing() = 0; - - // Returns list of discovered devices. Can be called only on - // |STAGE_DEVICES_DISCOVERY| stage. - virtual DeviceIdList GetDiscoveredDevices() = 0; - - // This method is called to start pairing with the device having |device_id| - // ID. Can be called only on |STAGE_DEVICES_DISCOVERY| stage. - virtual void ChooseDeviceForPairing(const std::string& device_id) = 0; - - // Rescan for devices to pair with. Can be called only on - // stages |STAGE_DEVICE_NOT_FOUND|, |STAGE_ESTABLISHING_CONNECTION_ERROR|, - // |STAGE_HOST_ENROLLMENT_ERROR|. - virtual void RepeatDiscovery() = 0; - - // Returns pairing confirmation code. - // Could be called only on |STATE_WAITING_FOR_CODE_CONFIRMATION| stage. - virtual std::string GetConfirmationCode() = 0; - - // Called to confirm or deny confirmation code. Can be called only on - // |STAGE_WAITING_FOR_CODE_CONFIRMATION| stage. - virtual void SetConfirmationCodeIsCorrect(bool correct) = 0; - - // Set the values that will be sent to the host to set its network. - virtual void SetHostNetwork(const std::string& onc_spec) = 0; - - // Set the values that will be sent to the host if it needs to be configured. - virtual void SetHostConfiguration(bool accepted_eula, - const std::string& lang, - const std::string& timezone, - bool send_reports, - const std::string& keyboard_layout) = 0; - - // Called when user successfully authenticated on GAIA page. Can be called - // only on |STAGE_WAITING_FOR_CREDENTIALS| stage. - // |auth_token| will be sent to the host to be used for enrollment. - virtual void OnAuthenticationDone(const std::string& domain, - const std::string& auth_token) = 0; - - // Installs app and starts session. - // Can be called only on |STAGE_HOST_ENROLLMENT_SUCCESS| stage. - virtual void StartSession() = 0; - - virtual void AddObserver(Observer* observer) = 0; - virtual void RemoveObserver(Observer* observer) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(ControllerPairingController); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_CONTROLLER_PAIRING_CONTROLLER_H_
diff --git a/components/pairing/fake_controller_pairing_controller.cc b/components/pairing/fake_controller_pairing_controller.cc deleted file mode 100644 index d72f2f1..0000000 --- a/components/pairing/fake_controller_pairing_controller.cc +++ /dev/null
@@ -1,348 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/fake_controller_pairing_controller.h" - -#include <map> - -#include "base/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/rand_util.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "base/threading/thread_task_runner_handle.h" - -namespace pairing_chromeos { - -FakeControllerPairingController::FakeControllerPairingController( - const std::string& config) - : current_stage_(STAGE_NONE), - should_fail_on_connecting_(false), - connection_lost_begin_(STAGE_NONE), - connection_lost_end_(STAGE_NONE), - enrollment_should_fail_(false) { - ApplyConfig(config); - AddObserver(this); -} - -FakeControllerPairingController::~FakeControllerPairingController() { - RemoveObserver(this); -} - -void FakeControllerPairingController::ApplyConfig(const std::string& config) { - typedef std::vector<std::string> Tokens; - - base::StringPairs kv_pairs; - CHECK(base::SplitStringIntoKeyValuePairs(config, ':', ',', &kv_pairs)) - << "Wrong config format."; - std::map<std::string, std::string> dict(kv_pairs.begin(), kv_pairs.end()); - - if (dict.count("async_duration")) { - int ms = 0; - CHECK(base::StringToInt(dict["async_duration"], &ms)) - << "Wrong 'async_duration' format."; - async_duration_ = base::TimeDelta::FromMilliseconds(ms); - } else { - async_duration_ = base::TimeDelta::FromMilliseconds(3000); - } - - should_fail_on_connecting_ = - dict.count("fail_connecting") && (dict["fail_connecting"] == "1"); - - enrollment_should_fail_ = - dict.count("fail_enrollment") && (dict["fail_enrollment"] == "1"); - - if (dict.count("connection_lost")) { - Tokens lost_begin_end = base::SplitString( - dict["connection_lost"], "-", base::KEEP_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - CHECK_EQ(2u, lost_begin_end.size()) << "Wrong 'connection_lost' format."; - int begin = 0; - int end = 0; - CHECK(base::StringToInt(lost_begin_end[0], &begin) && - base::StringToInt(lost_begin_end[1], &end)) - << "Wrong 'connection_lost' format."; - CHECK((begin == 0 && end == 0) || - (STAGE_WAITING_FOR_CODE_CONFIRMATION <= begin && begin <= end && - end <= STAGE_HOST_ENROLLMENT_ERROR)) - << "Wrong 'connection_lost' interval."; - connection_lost_begin_ = static_cast<Stage>(begin); - connection_lost_end_ = static_cast<Stage>(end); - } else { - connection_lost_begin_ = connection_lost_end_ = STAGE_NONE; - } - - if (!dict.count("discovery")) { - dict["discovery"] = - "F-Device_1~F-Device_5~F-Device_3~L-Device_3~L-Device_1~F-Device_1"; - } - base::StringPairs events; - CHECK( - base::SplitStringIntoKeyValuePairs(dict["discovery"], '-', '~', &events)) - << "Wrong 'discovery' format."; - DiscoveryScenario scenario; - for (const auto& event : events) { - const std::string& type = event.first; - const std::string& device_id = event.second; - CHECK(type == "F" || type == "L" || type == "N") - << "Wrong discovery event type."; - CHECK(!device_id.empty() || type == "N") << "Empty device ID."; - scenario.push_back(DiscoveryEvent( - type == "F" ? DEVICE_FOUND : type == "L" ? DEVICE_LOST : NOTHING_FOUND, - device_id)); - } - SetDiscoveryScenario(scenario); - - preset_confirmation_code_ = dict["code"]; - CHECK(preset_confirmation_code_.empty() || - (preset_confirmation_code_.length() == 6 && - preset_confirmation_code_.find_first_not_of("0123456789") == - std::string::npos)) - << "Wrong 'code' format."; -} - -void FakeControllerPairingController::SetShouldFailOnConnecting() { - should_fail_on_connecting_ = true; -} - -void FakeControllerPairingController::SetShouldLoseConnection(Stage stage_begin, - Stage stage_end) { - connection_lost_begin_ = stage_begin; - connection_lost_end_ = stage_end; -} - -void FakeControllerPairingController::SetEnrollmentShouldFail() { - enrollment_should_fail_ = true; -} - -void FakeControllerPairingController::SetDiscoveryScenario( - const DiscoveryScenario& discovery_scenario) { - discovery_scenario_ = discovery_scenario; - // Check that scenario is valid. - std::set<std::string> devices; - for (DiscoveryScenario::const_iterator event = discovery_scenario_.begin(); - event != discovery_scenario_.end(); - ++event) { - switch (event->first) { - case DEVICE_FOUND: { - devices.insert(event->second); - break; - } - case DEVICE_LOST: { - CHECK(devices.count(event->second)); - devices.erase(event->second); - break; - } - case NOTHING_FOUND: { - CHECK(++event == discovery_scenario_.end()); - return; - } - } - } -} - -void FakeControllerPairingController::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void FakeControllerPairingController::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -ControllerPairingController::Stage -FakeControllerPairingController::GetCurrentStage() { - return current_stage_; -} - -void FakeControllerPairingController::StartPairing() { - CHECK(current_stage_ == STAGE_NONE); - ChangeStage(STAGE_DEVICES_DISCOVERY); -} - -ControllerPairingController::DeviceIdList -FakeControllerPairingController::GetDiscoveredDevices() { - CHECK(current_stage_ == STAGE_DEVICES_DISCOVERY); - return DeviceIdList(discovered_devices_.begin(), discovered_devices_.end()); -} - -void FakeControllerPairingController::ChooseDeviceForPairing( - const std::string& device_id) { - CHECK(current_stage_ == STAGE_DEVICES_DISCOVERY); - CHECK(discovered_devices_.count(device_id)); - choosen_device_ = device_id; - ChangeStage(STAGE_ESTABLISHING_CONNECTION); -} - -void FakeControllerPairingController::RepeatDiscovery() { - CHECK(current_stage_ == STAGE_DEVICE_NOT_FOUND || - current_stage_ == STAGE_ESTABLISHING_CONNECTION_ERROR || - current_stage_ == STAGE_HOST_ENROLLMENT_ERROR); - ChangeStage(STAGE_DEVICES_DISCOVERY); -} - -std::string FakeControllerPairingController::GetConfirmationCode() { - CHECK(current_stage_ == STAGE_WAITING_FOR_CODE_CONFIRMATION); - if (confirmation_code_.empty()) { - if (preset_confirmation_code_.empty()) { - for (int i = 0; i < 6; ++i) - confirmation_code_.push_back(base::RandInt('0', '9')); - } else { - confirmation_code_ = preset_confirmation_code_; - } - } - return confirmation_code_; -} - -void FakeControllerPairingController::SetConfirmationCodeIsCorrect( - bool correct) { - CHECK(current_stage_ == STAGE_WAITING_FOR_CODE_CONFIRMATION); - if (correct) - ChangeStage(STAGE_HOST_UPDATE_IN_PROGRESS); - else - ChangeStage(STAGE_DEVICES_DISCOVERY); -} - -void FakeControllerPairingController::SetHostNetwork( - const std::string& onc_spec) {} - -void FakeControllerPairingController::SetHostConfiguration( - bool accepted_eula, - const std::string& lang, - const std::string& timezone, - bool send_reports, - const std::string& keyboard_layout) { -} - -void FakeControllerPairingController::OnAuthenticationDone( - const std::string& domain, - const std::string& auth_token) { - CHECK(current_stage_ == STAGE_WAITING_FOR_CREDENTIALS); - ChangeStage(STAGE_HOST_ENROLLMENT_IN_PROGRESS); -} - -void FakeControllerPairingController::StartSession() { - CHECK(current_stage_ == STAGE_HOST_ENROLLMENT_SUCCESS); - ChangeStage(STAGE_FINISHED); -} - -void FakeControllerPairingController::ChangeStage(Stage new_stage) { - if (current_stage_ == new_stage) - return; - current_stage_ = new_stage; - for (Observer& observer : observers_) - observer.PairingStageChanged(new_stage); -} - -void FakeControllerPairingController::ChangeStageLater(Stage new_stage) { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&FakeControllerPairingController::ChangeStage, - base::Unretained(this), new_stage), - async_duration_); -} - -void FakeControllerPairingController::ExecuteDiscoveryEvent( - size_t event_position) { - if (current_stage_ != STAGE_DEVICES_DISCOVERY) - return; - CHECK(event_position < discovery_scenario_.size()); - const DiscoveryEvent& event = discovery_scenario_[event_position]; - switch (event.first) { - case DEVICE_FOUND: { - DeviceFound(event.second); - break; - } - case DEVICE_LOST: { - DeviceLost(event.second); - break; - } - case NOTHING_FOUND: { - ChangeStage(STAGE_DEVICE_NOT_FOUND); - break; - } - } - if (++event_position == discovery_scenario_.size()) { - return; - } - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&FakeControllerPairingController::ExecuteDiscoveryEvent, - base::Unretained(this), event_position), - async_duration_); -} - -void FakeControllerPairingController::DeviceFound( - const std::string& device_id) { - CHECK(current_stage_ == STAGE_DEVICES_DISCOVERY); - discovered_devices_.insert(device_id); - for (Observer& observer : observers_) - observer.DiscoveredDevicesListChanged(); -} - -void FakeControllerPairingController::DeviceLost(const std::string& device_id) { - CHECK(current_stage_ == STAGE_DEVICES_DISCOVERY); - discovered_devices_.erase(device_id); - for (Observer& observer : observers_) - observer.DiscoveredDevicesListChanged(); -} - -void FakeControllerPairingController::PairingStageChanged(Stage new_stage) { - Stage next_stage = STAGE_NONE; - switch (new_stage) { - case STAGE_DEVICES_DISCOVERY: { - discovered_devices_.clear(); - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce( - &FakeControllerPairingController::ExecuteDiscoveryEvent, - base::Unretained(this), 0), - async_duration_); - break; - } - case STAGE_ESTABLISHING_CONNECTION: { - if (should_fail_on_connecting_) { - next_stage = STAGE_ESTABLISHING_CONNECTION_ERROR; - should_fail_on_connecting_ = false; - } else { - confirmation_code_.clear(); - next_stage = STAGE_WAITING_FOR_CODE_CONFIRMATION; - } - break; - } - case STAGE_HOST_UPDATE_IN_PROGRESS: { - next_stage = STAGE_WAITING_FOR_CREDENTIALS; - break; - } - case STAGE_HOST_ENROLLMENT_IN_PROGRESS: { - if (enrollment_should_fail_) { - enrollment_should_fail_ = false; - next_stage = STAGE_HOST_ENROLLMENT_ERROR; - } else { - next_stage = STAGE_HOST_ENROLLMENT_SUCCESS; - } - break; - } - case STAGE_HOST_CONNECTION_LOST: { - next_stage = connection_lost_end_; - connection_lost_end_ = STAGE_NONE; - break; - } - default: - break; - } - if (new_stage == connection_lost_begin_) { - connection_lost_begin_ = STAGE_NONE; - next_stage = STAGE_HOST_CONNECTION_LOST; - } - if (next_stage != STAGE_NONE) - ChangeStageLater(next_stage); -} - -void FakeControllerPairingController::DiscoveredDevicesListChanged() { -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/fake_controller_pairing_controller.h b/components/pairing/fake_controller_pairing_controller.h deleted file mode 100644 index 7de4eff..0000000 --- a/components/pairing/fake_controller_pairing_controller.h +++ /dev/null
@@ -1,118 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_FAKE_CONTROLLER_PAIRING_CONTROLLER_H_ -#define COMPONENTS_PAIRING_FAKE_CONTROLLER_PAIRING_CONTROLLER_H_ - -#include <stddef.h> - -#include <set> -#include <utility> - -#include "base/macros.h" -#include "base/observer_list.h" -#include "base/time/time.h" -#include "components/pairing/controller_pairing_controller.h" - -namespace pairing_chromeos { - -class FakeControllerPairingController - : public ControllerPairingController, - public ControllerPairingController::Observer { - public: - typedef ControllerPairingController::Observer Observer; - - enum DiscoveryEventType { DEVICE_FOUND, DEVICE_LOST, NOTHING_FOUND }; - - typedef std::pair<DiscoveryEventType, std::string> DiscoveryEvent; - typedef std::vector<DiscoveryEvent> DiscoveryScenario; - - // Config is a coma separated list of key-value pairs separated by colon. - // Supported options: - // * async_duration - integer. Default: 3000. - // * fail_connecting - {0,1}. Default: 0. - // * connection_lost - integer-integer. Default: 0-0. - // * fail_enrollment - {0,1}. Default: 0. - // * discovery - {F,L,N}-string(~{F,L,N}-string)*. Default: - // F-Device_1~F-Device_5~F-Device_3~L-Device_3~L-Device_1~F-Device_1 - // * code - 6 digits or empty string. Default: empty string. If strings is - // empty, random code is generated. - explicit FakeControllerPairingController(const std::string& config); - ~FakeControllerPairingController() override; - - // Applies given |config| to controller. - void ApplyConfig(const std::string& config); - - // Sets delay for asynchronous operations. like device searching or host - // enrollment. Default value is 3 seconds. - void set_async_duration(base::TimeDelta async_duration) { - async_duration_ = async_duration; - } - - // Causing an error on |STAGE_ESTABLISHING_CONNECTION| stage once. - void SetShouldFailOnConnecting(); - - // Causing a connection loss on |stage_begin| and a connection recovery - // on |stage_end| once. - void SetShouldLoseConnection(Stage stage_begin, Stage stage_end); - - // Makes host enrollment to fail once. - void SetEnrollmentShouldFail(); - - // Sets devices discovery scenario for |STAGE_DEVICES_DESCOVERY| stage. - // Events are executed with interval of |async_duration_|. - // For default scenario refer to implementation. - void SetDiscoveryScenario(const DiscoveryScenario& discovery_scenario); - - // Overridden from ControllerPairingController: - void AddObserver(Observer* observer) override; - void RemoveObserver(Observer* observer) override; - Stage GetCurrentStage() override; - void StartPairing() override; - DeviceIdList GetDiscoveredDevices() override; - void ChooseDeviceForPairing(const std::string& device_id) override; - void RepeatDiscovery() override; - std::string GetConfirmationCode() override; - void SetConfirmationCodeIsCorrect(bool correct) override; - void SetHostNetwork(const std::string& onc_spec) override; - void SetHostConfiguration(bool accepted_eula, - const std::string& lang, - const std::string& timezone, - bool send_reports, - const std::string& keyboard_layout) override; - void OnAuthenticationDone(const std::string& domain, - const std::string& auth_token) override; - void StartSession() override; - - private: - void ChangeStage(Stage new_stage); - void ChangeStageLater(Stage new_stage); - void ExecuteDiscoveryEvent(size_t event_position); - void DeviceFound(const std::string& device_id); - void DeviceLost(const std::string& device_id); - - // Overridden from ui::ControllerPairingController::Observer: - void PairingStageChanged(Stage new_stage) override; - void DiscoveredDevicesListChanged() override; - - base::ObserverList<ControllerPairingController::Observer>::Unchecked - observers_; - Stage current_stage_; - std::string confirmation_code_; - std::string preset_confirmation_code_; - base::TimeDelta async_duration_; - DiscoveryScenario discovery_scenario_; - std::set<std::string> discovered_devices_; - std::string choosen_device_; - bool should_fail_on_connecting_; - Stage connection_lost_begin_; - Stage connection_lost_end_; - bool enrollment_should_fail_; - - DISALLOW_COPY_AND_ASSIGN(FakeControllerPairingController); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_FAKE_CONTROLLER_PAIRING_CONTROLLER_H_
diff --git a/components/pairing/fake_host_pairing_controller.cc b/components/pairing/fake_host_pairing_controller.cc deleted file mode 100644 index fef253cb5..0000000 --- a/components/pairing/fake_host_pairing_controller.cc +++ /dev/null
@@ -1,191 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/fake_host_pairing_controller.h" - -#include <stddef.h> - -#include <map> -#include <vector> - -#include "base/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/rand_util.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/threading/thread_task_runner_handle.h" - -namespace { - -const int kDefaultAsyncDurationMs = 3000; -const size_t kCodeLength = 6; - -} // namespace - -namespace pairing_chromeos { - -FakeHostPairingController::FakeHostPairingController(const std::string& config) - : current_stage_(STAGE_NONE), - enrollment_should_fail_(false), - start_after_update_(false) { - ApplyConfig(config); - AddObserver(this); -} - -FakeHostPairingController::~FakeHostPairingController() { - RemoveObserver(this); -} - -void FakeHostPairingController::ApplyConfig(const std::string& config) { - base::StringPairs kv_pairs; - CHECK(base::SplitStringIntoKeyValuePairs(config, ':', ',', &kv_pairs)) - << "Wrong config format."; - std::map<std::string, std::string> dict(kv_pairs.begin(), kv_pairs.end()); - - if (dict.count("async_duration")) { - int ms = 0; - CHECK(base::StringToInt(dict["async_duration"], &ms)) - << "Wrong 'async_duration' format."; - async_duration_ = base::TimeDelta::FromMilliseconds(ms); - } else { - async_duration_ = - base::TimeDelta::FromMilliseconds(kDefaultAsyncDurationMs); - } - - start_after_update_ = dict["start_after_update"] == "1"; - - enrollment_should_fail_ = dict["fail_enrollment"] == "1"; - - if (dict.count("code")) { - confirmation_code_ = dict["code"]; - } else { - confirmation_code_.clear(); - for (size_t i = 0; i < kCodeLength; ++i) - confirmation_code_.push_back(base::RandInt('0', '9')); - } - CHECK(confirmation_code_.length() == kCodeLength && - confirmation_code_.find_first_not_of("0123456789") == std::string::npos) - << "Wrong 'code' format."; - - device_name_ = - dict.count("device_name") ? dict["device_name"] : "Chromebox-01"; - - enrollment_domain_ = dict.count("domain") ? dict["domain"] : "example.com"; -} - -void FakeHostPairingController::ChangeStage(Stage new_stage) { - if (current_stage_ == new_stage) - return; - current_stage_ = new_stage; - for (Observer& observer : observers_) - observer.PairingStageChanged(new_stage); -} - -void FakeHostPairingController::ChangeStageLater(Stage new_stage) { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&FakeHostPairingController::ChangeStage, - base::Unretained(this), new_stage), - async_duration_); -} - -void FakeHostPairingController::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void FakeHostPairingController::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -HostPairingController::Stage FakeHostPairingController::GetCurrentStage() { - return current_stage_; -} - -void FakeHostPairingController::StartPairing() { - CHECK(current_stage_ == STAGE_NONE); - if (start_after_update_) { - ChangeStage(STAGE_WAITING_FOR_CONTROLLER_AFTER_UPDATE); - } else { - ChangeStage(STAGE_WAITING_FOR_CONTROLLER); - } -} - -std::string FakeHostPairingController::GetDeviceName() { - return device_name_; -} - -std::string FakeHostPairingController::GetConfirmationCode() { - CHECK(current_stage_ == STAGE_WAITING_FOR_CODE_CONFIRMATION); - return confirmation_code_; -} - -std::string FakeHostPairingController::GetEnrollmentDomain() { - return enrollment_domain_; -} - -void FakeHostPairingController::OnNetworkConnectivityChanged( - Connectivity connectivity_status) { -} - -void FakeHostPairingController::OnUpdateStatusChanged( - UpdateStatus update_status) { -} - -void FakeHostPairingController::OnEnrollmentStatusChanged( - EnrollmentStatus enrollment_status) { -} - -void FakeHostPairingController::SetPermanentId( - const std::string& permanent_id) { -} - -void FakeHostPairingController::SetErrorCodeAndMessage( - int error_code, - const std::string& error_message) {} - -void FakeHostPairingController::Reset() { -} - -void FakeHostPairingController::PairingStageChanged(Stage new_stage) { - switch (new_stage) { - case STAGE_WAITING_FOR_CONTROLLER: { - ChangeStageLater(STAGE_WAITING_FOR_CODE_CONFIRMATION); - break; - } - case STAGE_WAITING_FOR_CODE_CONFIRMATION: { - ChangeStageLater(STAGE_WAITING_FOR_CONTROLLER_AFTER_UPDATE); - break; - } - case STAGE_WAITING_FOR_CONTROLLER_AFTER_UPDATE: { - ChangeStageLater(STAGE_WAITING_FOR_CREDENTIALS); - break; - } - case STAGE_WAITING_FOR_CREDENTIALS: { - ChangeStageLater(STAGE_ENROLLING); - break; - } - case STAGE_ENROLLING: { - if (enrollment_should_fail_) { - enrollment_should_fail_ = false; - ChangeStageLater(STAGE_ENROLLMENT_ERROR); - } else { - ChangeStageLater(STAGE_ENROLLMENT_SUCCESS); - } - break; - } - case STAGE_ENROLLMENT_ERROR: { - ChangeStageLater(STAGE_WAITING_FOR_CONTROLLER_AFTER_UPDATE); - break; - } - case STAGE_ENROLLMENT_SUCCESS: { - ChangeStageLater(STAGE_FINISHED); - break; - } - default: { break; } - } -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/fake_host_pairing_controller.h b/components/pairing/fake_host_pairing_controller.h deleted file mode 100644 index 6f54a847..0000000 --- a/components/pairing/fake_host_pairing_controller.h +++ /dev/null
@@ -1,78 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_FAKE_HOST_PAIRING_CONTROLLER_H_ -#define COMPONENTS_PAIRING_FAKE_HOST_PAIRING_CONTROLLER_H_ - -#include "base/macros.h" -#include "base/observer_list.h" -#include "base/time/time.h" -#include "components/pairing/host_pairing_controller.h" - -namespace pairing_chromeos { - -class FakeHostPairingController - : public HostPairingController, - public HostPairingController::Observer { - public: - typedef HostPairingController::Observer Observer; - - // Config is a comma separated list of key-value pairs separated by colon. - // Supported options: - // * async_duration - integer. Default: 3000. - // * start_after_update - {0,1}. Default: 0. - // * fail_enrollment - {0,1}. Default: 0. - // * code - 6 digits or empty string. Default: empty string. If strings is - // empty, random code is generated. - // * device_name - string. Default: "Chromebox-01". - // * domain - string. Default: "example.com". - explicit FakeHostPairingController(const std::string& config); - ~FakeHostPairingController() override; - - // Applies given |config| to flow. - void ApplyConfig(const std::string& config); - - private: - void ChangeStage(Stage new_stage); - void ChangeStageLater(Stage new_stage); - - // HostPairingController: - void AddObserver(Observer* observer) override; - void RemoveObserver(Observer* observer) override; - Stage GetCurrentStage() override; - void StartPairing() override; - std::string GetDeviceName() override; - std::string GetConfirmationCode() override; - std::string GetEnrollmentDomain() override; - void OnNetworkConnectivityChanged(Connectivity connectivity_status) override; - void OnUpdateStatusChanged(UpdateStatus update_status) override; - void OnEnrollmentStatusChanged(EnrollmentStatus enrollment_status) override; - void SetPermanentId(const std::string& permanent_id) override; - void SetErrorCodeAndMessage(int error_code, - const std::string& error_message) override; - void Reset() override; - - // HostPairingController::Observer: - void PairingStageChanged(Stage new_stage) override; - - base::ObserverList<Observer>::Unchecked observers_; - Stage current_stage_; - std::string device_name_; - std::string confirmation_code_; - base::TimeDelta async_duration_; - - // If this flag is true error happens on |STAGE_ENROLLING| once. - bool enrollment_should_fail_; - - // Controller starts its work like if update and reboot already happened. - bool start_after_update_; - - std::string enrollment_domain_; - - DISALLOW_COPY_AND_ASSIGN(FakeHostPairingController); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_FAKE_HOST_PAIRING_CONTROLLER_H_
diff --git a/components/pairing/host_pairing_controller.cc b/components/pairing/host_pairing_controller.cc deleted file mode 100644 index be240c9d..0000000 --- a/components/pairing/host_pairing_controller.cc +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/host_pairing_controller.h" - -namespace pairing_chromeos { - -HostPairingController::HostPairingController() {} - -HostPairingController::~HostPairingController() {} - -HostPairingController::Observer::Observer() {} -HostPairingController::Observer::~Observer() {} - -} // namespace pairing_chromeos
diff --git a/components/pairing/host_pairing_controller.h b/components/pairing/host_pairing_controller.h deleted file mode 100644 index 4e6b612..0000000 --- a/components/pairing/host_pairing_controller.h +++ /dev/null
@@ -1,141 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_HOST_PAIRING_CONTROLLER_H_ -#define COMPONENTS_PAIRING_HOST_PAIRING_CONTROLLER_H_ - -#include <string> - -#include "base/macros.h" - -namespace pairing_chromeos { - -class HostPairingController { - public: - enum Stage { - STAGE_NONE, - STAGE_INITIALIZATION_ERROR, - STAGE_WAITING_FOR_CONTROLLER, - STAGE_WAITING_FOR_CODE_CONFIRMATION, - STAGE_CONTROLLER_CONNECTION_ERROR, - STAGE_SETUP_BASIC_CONFIGURATION, - STAGE_SETUP_NETWORK_ERROR, - STAGE_WAITING_FOR_CONTROLLER_AFTER_UPDATE, - STAGE_WAITING_FOR_CREDENTIALS, - STAGE_ENROLLING, - STAGE_ENROLLMENT_ERROR, - STAGE_ENROLLMENT_SUCCESS, - STAGE_FINISHED - }; - - enum Connectivity { - CONNECTIVITY_UNTESTED, - CONNECTIVITY_NONE, - CONNECTIVITY_LIMITED, - CONNECTIVITY_CONNECTING, - CONNECTIVITY_CONNECTED, - }; - - enum UpdateStatus { - UPDATE_STATUS_UNKNOWN, - UPDATE_STATUS_UPDATING, - UPDATE_STATUS_REBOOTING, - UPDATE_STATUS_UPDATED, - }; - - enum EnrollmentStatus { - ENROLLMENT_STATUS_UNKNOWN, - ENROLLMENT_STATUS_ENROLLING, - ENROLLMENT_STATUS_FAILURE, - ENROLLMENT_STATUS_SUCCESS, - }; - - enum class ErrorCode : int { - ERROR_NONE = 0, - NETWORK_ERROR, - AUTH_ERROR, - ENROLL_ERROR, - OTHER_ERROR, - }; - - class Observer { - public: - Observer(); - virtual ~Observer(); - - // Called when pairing has moved on from one stage to another. - virtual void PairingStageChanged(Stage new_stage) = 0; - - // Called when the controller has sent a configuration to apply. - virtual void ConfigureHostRequested(bool accepted_eula, - const std::string& lang, - const std::string& timezone, - bool send_reports, - const std::string& keyboard_layout) {} - - // Called when the controller has sent a network to add. - virtual void AddNetworkRequested(const std::string& onc_spec) {} - - // Called when the controller has provided an |auth_token| for enrollment. - virtual void EnrollHostRequested(const std::string& auth_token) {} - - // Called when the controller has sent a reboot request. This will happen - // when the host enrollment fails. - virtual void RebootHostRequested() {} - - private: - DISALLOW_COPY_AND_ASSIGN(Observer); - }; - - HostPairingController(); - virtual ~HostPairingController(); - - // Returns current stage of pairing process. - virtual Stage GetCurrentStage() = 0; - - // Starts pairing process. Can be called only on |STAGE_NONE| stage. - virtual void StartPairing() = 0; - - // Returns device name. - virtual std::string GetDeviceName() = 0; - - // Returns 6-digit confirmation code. Can be called only on - // |STAGE_WAITING_FOR_CODE_CONFIRMATION| stage. - virtual std::string GetConfirmationCode() = 0; - - // Returns an enrollment domain name. Can be called on stage - // |STAGE_ENROLLMENT| and later. - virtual std::string GetEnrollmentDomain() = 0; - - // Notify that the network connectivity status has changed. - virtual void OnNetworkConnectivityChanged( - Connectivity connectivity_status) = 0; - - // Notify that the update status has changed. - virtual void OnUpdateStatusChanged(UpdateStatus update_status) = 0; - - // Notify that enrollment status has changed. - // Can be called on stage |STAGE_WAITING_FOR_CREDENTIALS|. - virtual void OnEnrollmentStatusChanged( - EnrollmentStatus enrollment_status) = 0; - - // Set the permanent id assigned during enrollment. - virtual void SetPermanentId(const std::string& permanent_id) = 0; - - virtual void SetErrorCodeAndMessage(int error_code, - const std::string& error_message) = 0; - - // Reset the controller. - virtual void Reset() = 0; - - virtual void AddObserver(Observer* observer) = 0; - virtual void RemoveObserver(Observer* observer) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(HostPairingController); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_HOST_PAIRING_CONTROLLER_H_
diff --git a/components/pairing/message_buffer.cc b/components/pairing/message_buffer.cc deleted file mode 100644 index 3cfe95d..0000000 --- a/components/pairing/message_buffer.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/message_buffer.h" - -#include "net/base/io_buffer.h" - -namespace pairing_chromeos { - -MessageBuffer::MessageBuffer() - : buffer_offset_(0), - total_buffer_size_(0) { -} - -MessageBuffer::~MessageBuffer() {} - -int MessageBuffer::AvailableBytes() { - return total_buffer_size_ - buffer_offset_; -} - -void MessageBuffer::ReadBytes(char* buffer, int size) { - CHECK_LE(size, AvailableBytes()); - - int offset = 0; - while (offset < size) { - scoped_refptr<net::IOBuffer> io_buffer = pending_data_.front().first; - int io_buffer_size = pending_data_.front().second; - - CHECK_GT(io_buffer_size, buffer_offset_); - int copy_size = std::min(size - offset, io_buffer_size - buffer_offset_); - memcpy(&buffer[offset], &io_buffer->data()[buffer_offset_], copy_size); - - offset += copy_size; - buffer_offset_ += copy_size; - - CHECK_LE(buffer_offset_, io_buffer_size); - if (buffer_offset_ == io_buffer_size) { - CHECK_GE(total_buffer_size_, io_buffer_size); - total_buffer_size_ -= io_buffer_size; - pending_data_.pop_front(); - buffer_offset_ = 0; - } - } - CHECK_EQ(offset, size); -} - -void MessageBuffer::AddIOBuffer(scoped_refptr<net::IOBuffer> io_buffer, - int size) { - if (size == 0) - return; - pending_data_.push_back(std::make_pair(io_buffer, size)); - total_buffer_size_ += size; -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/message_buffer.h b/components/pairing/message_buffer.h deleted file mode 100644 index 74a18224f..0000000 --- a/components/pairing/message_buffer.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_MESSAGE_BUFFER_H_ -#define COMPONENTS_PAIRING_MESSAGE_BUFFER_H_ - -#include "base/containers/circular_deque.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" - -namespace net { -class IOBuffer; -} - -namespace pairing_chromeos { - -// A MessageBuffer is a simple wrapper around an ordered set of buffers received -// from a socket. It keeps track of the amount of unread data, and allows data -// to be retreived that was split across buffers in a single chunk. -class MessageBuffer { - public: - MessageBuffer(); - ~MessageBuffer(); - - // Returns the number of bytes currently received, but not yet read. - int AvailableBytes(); - - // Read |size| bytes into |buffer|. |size| must be smaller than or equal to - // the current number of available bytes. - void ReadBytes(char* buffer, int size); - - // Add the data from an IOBuffer. A reference to the IOBuffer will be - // maintained until it is drained. - void AddIOBuffer(scoped_refptr<net::IOBuffer> io_buffer, int size); - - private: - // Offset of the next byte to be read from the current IOBuffer. - int buffer_offset_; - // Total number of bytes in IOBuffers in |pending_data_|, including bytes that - // have already been read. - int total_buffer_size_; - base::circular_deque<std::pair<scoped_refptr<net::IOBuffer>, int>> - pending_data_; - - DISALLOW_COPY_AND_ASSIGN(MessageBuffer); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_MESSAGE_BUFFER_H_
diff --git a/components/pairing/message_buffer_unittest.cc b/components/pairing/message_buffer_unittest.cc deleted file mode 100644 index e2d41229..0000000 --- a/components/pairing/message_buffer_unittest.cc +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/message_buffer.h" - -#include "net/base/io_buffer.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace pairing_chromeos { - -typedef testing::Test MessageBufferTest; - -TEST_F(MessageBufferTest, BasicReadWrite) { - MessageBuffer message_buffer; - scoped_refptr<net::IOBuffer> io_buffer = - base::MakeRefCounted<net::IOBuffer>(3); - io_buffer->data()[0] = 3; - io_buffer->data()[1] = 1; - io_buffer->data()[2] = 4; - - message_buffer.AddIOBuffer(io_buffer, 3); - - EXPECT_EQ(message_buffer.AvailableBytes(), 3); - char data = 0; - message_buffer.ReadBytes(&data, 1); - EXPECT_EQ(data, 3); - EXPECT_EQ(message_buffer.AvailableBytes(), 2); - message_buffer.ReadBytes(&data, 1); - EXPECT_EQ(data, 1); - EXPECT_EQ(message_buffer.AvailableBytes(), 1); - message_buffer.ReadBytes(&data, 1); - EXPECT_EQ(data, 4); - EXPECT_EQ(message_buffer.AvailableBytes(), 0); -} - -TEST_F(MessageBufferTest, SplitBuffer) { - MessageBuffer message_buffer; - scoped_refptr<net::IOBuffer> io_buffer0 = - base::MakeRefCounted<net::IOBuffer>(1); - io_buffer0->data()[0] = 3; - - scoped_refptr<net::IOBuffer> io_buffer1 = - base::MakeRefCounted<net::IOBuffer>(2); - io_buffer1->data()[0] = 1; - io_buffer1->data()[1] = 4; - - message_buffer.AddIOBuffer(io_buffer0, 1); - message_buffer.AddIOBuffer(io_buffer1, 2); - - EXPECT_EQ(message_buffer.AvailableBytes(), 3); - char data[3]; - message_buffer.ReadBytes(data, 3); - EXPECT_EQ(message_buffer.AvailableBytes(), 0); - EXPECT_EQ(data[0], 3); - EXPECT_EQ(data[1], 1); - EXPECT_EQ(data[2], 4); -} - -TEST_F(MessageBufferTest, EmptyBuffer) { - MessageBuffer message_buffer; - scoped_refptr<net::IOBuffer> io_buffer0 = - base::MakeRefCounted<net::IOBuffer>(1); - io_buffer0->data()[0] = 3; - - scoped_refptr<net::IOBuffer> io_buffer1 = - base::MakeRefCounted<net::IOBuffer>(0); - scoped_refptr<net::IOBuffer> io_buffer2 = - base::MakeRefCounted<net::IOBuffer>(2); - io_buffer2->data()[0] = 1; - io_buffer2->data()[1] = 4; - - message_buffer.AddIOBuffer(io_buffer0, 1); - message_buffer.AddIOBuffer(io_buffer1, 0); - message_buffer.AddIOBuffer(io_buffer2, 2); - - EXPECT_EQ(message_buffer.AvailableBytes(), 3); - char data = 0; - message_buffer.ReadBytes(&data, 1); - EXPECT_EQ(data, 3); - EXPECT_EQ(message_buffer.AvailableBytes(), 2); - message_buffer.ReadBytes(&data, 1); - EXPECT_EQ(data, 1); - EXPECT_EQ(message_buffer.AvailableBytes(), 1); - message_buffer.ReadBytes(&data, 1); - EXPECT_EQ(data, 4); - EXPECT_EQ(message_buffer.AvailableBytes(), 0); -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/pairing_api.proto b/components/pairing/pairing_api.proto deleted file mode 100644 index 76c7032..0000000 --- a/components/pairing/pairing_api.proto +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Protocol buffer definitions for Syncable FileSystem. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package pairing_api; - -message HostStatusParameters { - enum Connectivity { - CONNECTIVITY_UNTESTED = 0; - CONNECTIVITY_NONE = 1; - CONNECTIVITY_LIMITED = 2; - CONNECTIVITY_CONNECTING = 3; - CONNECTIVITY_CONNECTED = 4; - } - - enum UpdateStatus { - UPDATE_STATUS_UNKNOWN = 0; - UPDATE_STATUS_UPDATING = 1; - UPDATE_STATUS_REBOOTING = 2; - UPDATE_STATUS_UPDATED = 3; - } - - enum EnrollmentStatus { - ENROLLMENT_STATUS_UNKNOWN = 0; - ENROLLMENT_STATUS_ENROLLING = 1; - ENROLLMENT_STATUS_FAILURE = 2; - ENROLLMENT_STATUS_SUCCESS = 3; - } - - optional string domain = 1; - optional Connectivity connectivity = 2; - optional UpdateStatus update_status = 3; - optional EnrollmentStatus enrollment_status = 4; - repeated string paired_controllers = 5; - optional string permanent_id = 6; -} - -message HostStatus { - optional int32 api_version = 1; - optional HostStatusParameters parameters = 2; -} - -message ConfigureHostParameters { - optional bool accepted_eula = 1; - optional string lang = 2; - optional string timezone = 3; - optional bool send_reports = 4; - optional string keyboard_layout = 5; -} - -message ConfigureHost { - optional int32 api_version = 1; - optional ConfigureHostParameters parameters = 2; -} - -message PairDevicesParameters { - optional string controller_access_token = 1; - optional string admin_access_token = 2; - optional string enrolling_domain = 3; -} - -message PairDevices { - optional int32 api_version = 1; - optional PairDevicesParameters parameters = 2; -} - -message CompleteSetupParameters { - optional bool add_another = 1; -} - -message CompleteSetup { - optional int32 api_version = 1; - optional CompleteSetupParameters parameters = 2; -} - -message ErrorParameters { - optional int32 code = 1; - optional string description = 2; -} - -message Error { - optional int32 api_version = 1; - optional ErrorParameters parameters = 2; -} - -message AddNetworkParameters { - optional string onc_spec = 1; -} - -message AddNetwork { - optional int32 api_version = 1; - optional AddNetworkParameters parameters = 2; -} - -message Reboot { - optional int32 api_version = 1; - optional bool reboot = 2 [default = true]; -}
diff --git a/components/pairing/proto_decoder.cc b/components/pairing/proto_decoder.cc deleted file mode 100644 index 83bb7ac..0000000 --- a/components/pairing/proto_decoder.cc +++ /dev/null
@@ -1,230 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/proto_decoder.h" - -#include "components/pairing/pairing_api.pb.h" -#include "net/base/io_buffer.h" - -namespace { -enum { - MESSAGE_NONE, - MESSAGE_HOST_STATUS, - MESSAGE_CONFIGURE_HOST, - MESSAGE_PAIR_DEVICES, - MESSAGE_COMPLETE_SETUP, - MESSAGE_ERROR, - MESSAGE_ADD_NETWORK, - MESSAGE_REBOOT, - NUM_MESSAGES, -}; -} - -namespace pairing_chromeos { - -ProtoDecoder::ProtoDecoder(Observer* observer) - : observer_(observer), - next_message_type_(MESSAGE_NONE), - next_message_size_(0) { - DCHECK(observer_); -} - -ProtoDecoder::~ProtoDecoder() {} - -bool ProtoDecoder::DecodeIOBuffer(int size, - ProtoDecoder::IOBufferRefPtr io_buffer) { - // Update the message buffer. - message_buffer_.AddIOBuffer(io_buffer, size); - - // If there is no current message, the next byte is the message type. - if (next_message_type_ == MESSAGE_NONE) { - if (message_buffer_.AvailableBytes() < static_cast<int>(sizeof(uint8_t))) - return true; - - uint8_t message_type = MESSAGE_NONE; - message_buffer_.ReadBytes(reinterpret_cast<char*>(&message_type), - sizeof(message_type)); - - if (message_type == MESSAGE_NONE || message_type >= NUM_MESSAGES) { - LOG(ERROR) << "Unknown message type received: " << message_type; - return false; - } - next_message_type_ = message_type; - } - - // If the message size isn't set, the next two bytes are the message size. - if (next_message_size_ == 0) { - if (message_buffer_.AvailableBytes() < static_cast<int>(sizeof(uint16_t))) - return true; - - // The size is sent in network byte order. - uint8_t high_byte = 0; - message_buffer_.ReadBytes(reinterpret_cast<char*>(&high_byte), - sizeof(high_byte)); - uint8_t low_byte = 0; - message_buffer_.ReadBytes(reinterpret_cast<char*>(&low_byte), - sizeof(low_byte)); - - next_message_size_ = (high_byte << 8) + low_byte; - } - - // If the whole proto buffer is not yet available, return early. - if (message_buffer_.AvailableBytes() < next_message_size_) - return true; - - std::vector<char> buffer(next_message_size_); - message_buffer_.ReadBytes(&buffer[0], next_message_size_); - - switch (next_message_type_) { - case MESSAGE_HOST_STATUS: { - pairing_api::HostStatus message; - message.ParseFromArray(&buffer[0], buffer.size()); - observer_->OnHostStatusMessage(message); - } - break; - case MESSAGE_CONFIGURE_HOST: { - pairing_api::ConfigureHost message; - message.ParseFromArray(&buffer[0], buffer.size()); - observer_->OnConfigureHostMessage(message); - } - break; - case MESSAGE_PAIR_DEVICES: { - pairing_api::PairDevices message; - message.ParseFromArray(&buffer[0], buffer.size()); - observer_->OnPairDevicesMessage(message); - } - break; - case MESSAGE_COMPLETE_SETUP: { - pairing_api::CompleteSetup message; - message.ParseFromArray(&buffer[0], buffer.size()); - observer_->OnCompleteSetupMessage(message); - } - break; - case MESSAGE_ERROR: { - pairing_api::Error message; - message.ParseFromArray(&buffer[0], buffer.size()); - observer_->OnErrorMessage(message); - } - break; - case MESSAGE_ADD_NETWORK: { - pairing_api::AddNetwork message; - message.ParseFromArray(&buffer[0], buffer.size()); - observer_->OnAddNetworkMessage(message); - } - break; - case MESSAGE_REBOOT: { - pairing_api::Reboot message; - message.ParseFromArray(&buffer[0], buffer.size()); - observer_->OnRebootMessage(message); - } - break; - - default: - LOG(WARNING) << "Skipping unknown message type: " << next_message_type_; - break; - } - - // Reset the message data. - next_message_type_ = MESSAGE_NONE; - next_message_size_ = 0; - - return true; -} - -ProtoDecoder::IOBufferRefPtr ProtoDecoder::SendHostStatus( - const pairing_api::HostStatus& message, int* size) { - std::string serialized_proto; - if (!message.SerializeToString(&serialized_proto)) - NOTREACHED(); - - return SendMessage(MESSAGE_HOST_STATUS, serialized_proto, size); -} - -ProtoDecoder::IOBufferRefPtr ProtoDecoder::SendHostNetwork( - const pairing_api::AddNetwork& message, - int* size) { - std::string serialized_proto; - if (!message.SerializeToString(&serialized_proto)) - NOTREACHED(); - - return SendMessage(MESSAGE_ADD_NETWORK, serialized_proto, size); -} - -ProtoDecoder::IOBufferRefPtr ProtoDecoder::SendConfigureHost( - const pairing_api::ConfigureHost& message, int* size) { - std::string serialized_proto; - if (!message.SerializeToString(&serialized_proto)) - NOTREACHED(); - - return SendMessage(MESSAGE_CONFIGURE_HOST, serialized_proto, size); -} - -ProtoDecoder::IOBufferRefPtr ProtoDecoder::SendPairDevices( - const pairing_api::PairDevices& message, int* size) { - std::string serialized_proto; - if (!message.SerializeToString(&serialized_proto)) - NOTREACHED(); - - return SendMessage(MESSAGE_PAIR_DEVICES, serialized_proto, size); -} - -ProtoDecoder::IOBufferRefPtr ProtoDecoder::SendCompleteSetup( - const pairing_api::CompleteSetup& message, int* size) { - std::string serialized_proto; - if (!message.SerializeToString(&serialized_proto)) - NOTREACHED(); - - return SendMessage(MESSAGE_COMPLETE_SETUP, serialized_proto, size); -} - -ProtoDecoder::IOBufferRefPtr ProtoDecoder::SendError( - const pairing_api::Error& message, int* size) { - std::string serialized_proto; - if (!message.SerializeToString(&serialized_proto)) - NOTREACHED(); - - return SendMessage(MESSAGE_ERROR, serialized_proto, size); -} - -ProtoDecoder::IOBufferRefPtr ProtoDecoder::SendRebootHost( - const pairing_api::Reboot& message, - int* size) { - std::string serialized_proto; - if (!message.SerializeToString(&serialized_proto)) - NOTREACHED(); - - return SendMessage(MESSAGE_REBOOT, serialized_proto, size); -} - -ProtoDecoder::IOBufferRefPtr ProtoDecoder::SendMessage( - uint8_t message_type, - const std::string& message, - int* size) { - uint16_t message_size = message.size(); - - *size = sizeof(message_type) + sizeof(message_size) + message.size(); - IOBufferRefPtr io_buffer = base::MakeRefCounted<net::IOBuffer>(*size); - - // Write the message type. - int offset = 0; - memcpy(&io_buffer->data()[offset], &message_type, sizeof(message_type)); - offset += sizeof(message_type); - - // Network byte order. - // Write the high byte of the size. - uint8_t data = (message_size >> 8) & 0xFF; - memcpy(&io_buffer->data()[offset], &data, sizeof(data)); - offset += sizeof(data); - // Write the low byte of the size. - data = message_size & 0xFF; - memcpy(&io_buffer->data()[offset], &data, sizeof(data)); - offset += sizeof(data); - - // Write the actual message. - memcpy(&io_buffer->data()[offset], message.data(), message.size()); - - return io_buffer; -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/proto_decoder.h b/components/pairing/proto_decoder.h deleted file mode 100644 index 0ad7b0fe..0000000 --- a/components/pairing/proto_decoder.h +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_PROTO_DECODER_H_ -#define COMPONENTS_PAIRING_PROTO_DECODER_H_ - -#include <stdint.h> - -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "components/pairing/message_buffer.h" - -namespace net { -class IOBuffer; -} - -namespace pairing_api { -class AddNetwork; -class CompleteSetup; -class ConfigureHost; -class Error; -class HostStatus; -class PairDevices; -class Reboot; -} // namespace pairing_api - -namespace pairing_chromeos { - -// A ProtoDecoder collects data from a series of IOBuffers and decodes Proto -// buffers from the data. The decoded messages are then forwarded to an -// observer. -class ProtoDecoder { - public: - typedef scoped_refptr<net::IOBuffer> IOBufferRefPtr; - class Observer { - public: - virtual ~Observer() {} - - virtual void OnHostStatusMessage( - const pairing_api::HostStatus& message) = 0; - virtual void OnConfigureHostMessage( - const pairing_api::ConfigureHost& message) = 0; - virtual void OnPairDevicesMessage( - const pairing_api::PairDevices& message) = 0; - virtual void OnCompleteSetupMessage( - const pairing_api::CompleteSetup& message) = 0; - virtual void OnErrorMessage( - const pairing_api::Error& message) = 0; - virtual void OnAddNetworkMessage( - const pairing_api::AddNetwork& message) = 0; - virtual void OnRebootMessage(const pairing_api::Reboot& message) = 0; - - protected: - Observer() {} - - private: - DISALLOW_COPY_AND_ASSIGN(Observer); - }; - - explicit ProtoDecoder(Observer* observer); - ~ProtoDecoder(); - - // Decodes the data from an io_buffer, and sends out events for any complete - // messages. - bool DecodeIOBuffer(int size, IOBufferRefPtr io_buffer); - - // Convenience functions for serializing messages into an IOBuffer. - static IOBufferRefPtr SendHostStatus(const pairing_api::HostStatus& message, - int* size); - static IOBufferRefPtr SendHostNetwork(const pairing_api::AddNetwork& message, - int* size); - static IOBufferRefPtr SendConfigureHost( - const pairing_api::ConfigureHost& message, int* size); - static IOBufferRefPtr SendPairDevices(const pairing_api::PairDevices& message, - int* size); - static IOBufferRefPtr SendCompleteSetup( - const pairing_api::CompleteSetup& message, int* size); - static IOBufferRefPtr SendError(const pairing_api::Error& message, int* size); - static IOBufferRefPtr SendRebootHost(const pairing_api::Reboot& message, - int* size); - - private: - static IOBufferRefPtr SendMessage(uint8_t message_type, - const std::string& message, - int* size); - - Observer* observer_; - MessageBuffer message_buffer_; - int next_message_type_; - int next_message_size_; - - DISALLOW_COPY_AND_ASSIGN(ProtoDecoder); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_PROTO_DECODER_H_
diff --git a/components/pairing/shark_connection_listener.cc b/components/pairing/shark_connection_listener.cc deleted file mode 100644 index d49113e..0000000 --- a/components/pairing/shark_connection_listener.cc +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/pairing/shark_connection_listener.h" - -#include <utility> - -#include "base/logging.h" -#include "base/threading/thread_restrictions.h" -#include "components/pairing/bluetooth_host_pairing_controller.h" -#include "services/service_manager/public/cpp/connector.h" - -namespace pairing_chromeos { - -SharkConnectionListener::SharkConnectionListener( - service_manager::Connector* connector, - OnConnectedCallback callback) - : callback_(callback) { - controller_.reset(new BluetoothHostPairingController(connector)); - controller_->AddObserver(this); - controller_->StartPairing(); -} - -SharkConnectionListener::~SharkConnectionListener() { - if (controller_.get()) - controller_->RemoveObserver(this); -} - -void SharkConnectionListener::ResetController() { - if (controller_.get()) { - controller_->RemoveObserver(this); - controller_->Reset(); - } -} - -BluetoothHostPairingController* -SharkConnectionListener::GetControllerForTesting() { - return static_cast<BluetoothHostPairingController*>(controller_.get()); -} - -void SharkConnectionListener::PairingStageChanged(Stage new_stage) { - if (new_stage == HostPairingController::STAGE_WAITING_FOR_CODE_CONFIRMATION - // Code confirmation stage can be skipped if devices were paired before. - || new_stage == HostPairingController::STAGE_SETUP_BASIC_CONFIGURATION) { - controller_->RemoveObserver(this); - callback_.Run(std::move(controller_)); - callback_.Reset(); - } else if (new_stage != HostPairingController::STAGE_WAITING_FOR_CONTROLLER) { - LOG(ERROR) << "Unexpected stage " << new_stage; - } -} - -} // namespace pairing_chromeos
diff --git a/components/pairing/shark_connection_listener.h b/components/pairing/shark_connection_listener.h deleted file mode 100644 index 4ee63156..0000000 --- a/components/pairing/shark_connection_listener.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_PAIRING_SHARK_CONNECTION_LISTENER_H_ -#define COMPONENTS_PAIRING_SHARK_CONNECTION_LISTENER_H_ - -#include <memory> -#include <string> - -#include "base/callback.h" -#include "base/macros.h" -#include "components/pairing/host_pairing_controller.h" - -namespace service_manager { -class Connector; -} - -namespace pairing_chromeos { - -class BluetoothHostPairingController; - -// Listens for incoming connection from shark controller. If connection -// is established, invokes callback passing HostPairingController -// as an argument. -class SharkConnectionListener : public HostPairingController::Observer { - public: - using OnConnectedCallback = - base::Callback<void(std::unique_ptr<HostPairingController>)>; - - SharkConnectionListener(service_manager::Connector* connector, - OnConnectedCallback callback); - ~SharkConnectionListener() override; - - void ResetController(); - - // This function is used for testing. - BluetoothHostPairingController* GetControllerForTesting(); - - private: - typedef HostPairingController::Stage Stage; - - // HostPairingController::Observer overrides: - void PairingStageChanged(Stage new_stage) override; - - OnConnectedCallback callback_; - std::unique_ptr<HostPairingController> controller_; - - DISALLOW_COPY_AND_ASSIGN(SharkConnectionListener); -}; - -} // namespace pairing_chromeos - -#endif // COMPONENTS_PAIRING_SHARK_CONNECTION_LISTENER_H_
diff --git a/components/payments/core/test_payment_request_delegate.h b/components/payments/core/test_payment_request_delegate.h index a7d3ed3a..b0555b1 100644 --- a/components/payments/core/test_payment_request_delegate.h +++ b/components/payments/core/test_payment_request_delegate.h
@@ -7,8 +7,8 @@ #include <string> -#include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" +#include "base/task/single_thread_task_executor.h" #include "components/autofill/core/browser/payments/full_card_request.h" #include "components/autofill/core/browser/payments/payments_client.h" #include "components/autofill/core/browser/test_address_normalizer.h" @@ -54,7 +54,7 @@ void CompleteFullCardRequest(); private: - base::MessageLoop loop_; + base::SingleThreadTaskExecutor main_task_executor_; autofill::PersonalDataManager* personal_data_manager_; std::string locale_; const GURL last_committed_url_;
diff --git a/components/policy/BUILD.gn b/components/policy/BUILD.gn index a791d14..0087025 100644 --- a/components/policy/BUILD.gn +++ b/components/policy/BUILD.gn
@@ -4,6 +4,7 @@ import("//build/config/chrome_build.gni") import("//build/config/features.gni") +import("//build/config/mac/base_rules.gni") import("//build/toolchain/toolchain.gni") import("//components/policy/resources/policy_templates.gni") import("//third_party/protobuf/proto_library.gni") @@ -373,32 +374,10 @@ ] } } else if (gen_policy_templates_mac && is_mac) { - action("convert_mcx_plist") { - script = "//build/config/mac/xcrun.py" - sources = [ - "$policy_templates_base_dir/mac/app-Manifest.plist", - ] - inputs = [ - script, - ] - outputs = [ - "$target_gen_dir/$chrome_mac_bundle_id.manifest", - ] - - if (use_system_xcode) { - args = [] - } else { - args = [ - "--developer_dir", - hermetic_xcode_path, - ] - } - args += [ - "plutil", - "-convert", - "xml1", - ] + rebase_path(sources, root_out_dir) + [ "-o" ] + - rebase_path(outputs, root_out_dir) + convert_plist("convert_mcx_plist") { + source = "$policy_templates_base_dir/mac/app-Manifest.plist" + output = "$target_gen_dir/$chrome_mac_bundle_id.manifest" + format = "xml1" deps = [ ":policy_templates",
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 8879c62..7337ce3e 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -15286,13 +15286,14 @@ 'dynamic_refresh': False, 'per_profile': False, }, - 'supported_on': ['chrome_os:74-'], + 'supported_on': ['chrome_os:76-'], 'caption': '''Force device reboot when user sign out''', 'tags': ['system-security'], 'desc': ''' This policy, when set to ArcSession, forces the device to reboot when a user sign out if Android has started. When set to Always, it forces the device to reboot on every user sign out. If left unset, it has no effect and no reboot is forced on user sign out. The same applies if set to Never. + This policy has effect only for unaffiliated users. ''', }, {
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 74f26da..a1b05e5 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -759,7 +759,7 @@ // Optional. Replaces |frame_| with selection if needed. Will call |on_ready| // when completed. void CopySelectionIfNeeded(const WebPreferences& preferences, - const base::Closure& on_ready); + base::OnceClosure on_ready); // Prepares frame for printing. void StartPrinting(); @@ -808,7 +808,7 @@ gfx::Size prev_view_size_; gfx::Size prev_scroll_offset_; int expected_pages_count_ = 0; - base::Closure on_ready_; + base::OnceClosure on_ready_; const bool should_print_backgrounds_; const bool should_print_selection_only_; bool is_printing_started_ = false; @@ -896,8 +896,8 @@ void PrepareFrameAndViewForPrint::CopySelectionIfNeeded( const WebPreferences& preferences, - const base::Closure& on_ready) { - on_ready_ = on_ready; + base::OnceClosure on_ready) { + on_ready_ = std::move(on_ready); if (should_print_selection_only_) { CopySelection(preferences); } else { @@ -994,7 +994,8 @@ } void PrepareFrameAndViewForPrint::CallOnReady() { - return on_ready_.Run(); // Can delete |this|. + if (on_ready_) + std::move(on_ready_).Run(); // Can delete |this|. } void PrepareFrameAndViewForPrint::RestoreSize() { @@ -1087,10 +1088,8 @@ void PrintRenderFrameHelper::DidFinishLoad() { is_loading_ = false; - if (!on_stop_loading_closure_.is_null()) { - on_stop_loading_closure_.Run(); - on_stop_loading_closure_.Reset(); - } + if (!on_stop_loading_closure_.is_null()) + std::move(on_stop_loading_closure_).Run(); } void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { @@ -1299,8 +1298,8 @@ print_preview_context_.source_node(), ignore_css_margins_); prep_frame_view_->CopySelectionIfNeeded( render_frame()->GetWebkitPreferences(), - base::Bind(&PrintRenderFrameHelper::OnFramePreparedForPreviewDocument, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&PrintRenderFrameHelper::OnFramePreparedForPreviewDocument, + weak_ptr_factory_.GetWeakPtr())); } void PrintRenderFrameHelper::OnFramePreparedForPreviewDocument() { @@ -2033,8 +2032,8 @@ print_pages_params_->pages.empty()); prep_frame_view_->CopySelectionIfNeeded( render_frame()->GetWebkitPreferences(), - base::Bind(&PrintRenderFrameHelper::OnFramePreparedForPrintPages, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&PrintRenderFrameHelper::OnFramePreparedForPrintPages, + weak_ptr_factory_.GetWeakPtr())); return true; } @@ -2170,8 +2169,8 @@ // |is_modifiable| value until they are fully loaded, which occurs when // DidStopLoading() is called. Defer showing the preview until then. on_stop_loading_closure_ = - base::Bind(&PrintRenderFrameHelper::ShowScriptedPrintPreview, - weak_ptr_factory_.GetWeakPtr()); + base::BindOnce(&PrintRenderFrameHelper::ShowScriptedPrintPreview, + weak_ptr_factory_.GetWeakPtr()); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, @@ -2194,8 +2193,8 @@ // print a PDF document. if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) { on_stop_loading_closure_ = - base::Bind(&PrintRenderFrameHelper::RequestPrintPreview, - weak_ptr_factory_.GetWeakPtr(), type); + base::BindOnce(&PrintRenderFrameHelper::RequestPrintPreview, + weak_ptr_factory_.GetWeakPtr(), type); return; } @@ -2210,8 +2209,8 @@ case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE: { if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) { on_stop_loading_closure_ = - base::Bind(&PrintRenderFrameHelper::RequestPrintPreview, - weak_ptr_factory_.GetWeakPtr(), type); + base::BindOnce(&PrintRenderFrameHelper::RequestPrintPreview, + weak_ptr_factory_.GetWeakPtr(), type); return; }
diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 1e27775..ebe927e 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h
@@ -536,7 +536,7 @@ // hangs because RequestPrintPreview is called before DidStopLoading() is // called. This is a store for the RequestPrintPreview() call and its // parameters so that it can be invoked after DidStopLoading. - base::Closure on_stop_loading_closure_; + base::OnceClosure on_stop_loading_closure_; base::WeakPtrFactory<PrintRenderFrameHelper> weak_ptr_factory_;
diff --git a/components/signin/core/browser/about_signin_internals.cc b/components/signin/core/browser/about_signin_internals.cc index b3e4d98..6b5716b 100644 --- a/components/signin/core/browser/about_signin_internals.cc +++ b/components/signin/core/browser/about_signin_internals.cc
@@ -63,7 +63,8 @@ } std::string GetTimeStr(base::Time time) { - return base::UTF16ToUTF8(base::TimeFormatShortDateAndTime(time)); + return base::UTF16ToUTF8( + base::TimeFormatWithPattern(time, "yyyy-MM-dd HH:mm:ss X")); } base::ListValue* AddSection(base::ListValue* parent_list, @@ -159,10 +160,12 @@ } #endif // !defined (OS_CHROMEOS) +// It's quite unfortunate that |time| is saved in prefs as a string instead of +// base::Time because any change of the format would create inconsistency. void SetPref(PrefService* prefs, signin_internals_util::TimedSigninStatusField field, - const std::string& time, - const std::string& value) { + const std::string& value, + const std::string& time) { std::string value_pref = SigninStatusFieldToString(field) + ".value"; std::string time_pref = SigninStatusFieldToString(field) + ".time"; prefs->SetString(value_pref, value); @@ -171,8 +174,8 @@ void GetPref(PrefService* prefs, signin_internals_util::TimedSigninStatusField field, - std::string* time, - std::string* value) { + std::string* value, + std::string* time) { std::string value_pref = SigninStatusFieldToString(field) + ".value"; std::string time_pref = SigninStatusFieldToString(field) + ".time"; *value = prefs->GetString(value_pref); @@ -271,8 +274,7 @@ field_index < signin_status_.timed_signin_fields.size()); base::Time now = base::Time::NowFromSystemTime(); - std::string time_as_str = - base::UTF16ToUTF8(base::TimeFormatShortDateAndTime(now)); + std::string time_as_str = GetTimeStr(now); TimedSigninStatusValue timed_value(value, time_as_str); signin_status_.timed_signin_fields[field_index] = timed_value; @@ -301,7 +303,7 @@ i < signin_internals_util::TIMED_FIELDS_END; ++i) { std::string time_str; std::string value_str; - GetPref(pref_service, i, &time_str, &value_str); + GetPref(pref_service, i, &value_str, &time_str); TimedSigninStatusValue value(value_str, time_str); signin_status_ .timed_signin_fields[i - signin_internals_util::TIMED_FIELDS_BEGIN] = @@ -684,15 +686,8 @@ if (cookie_requests_delay > base::TimeDelta()) { base::Time next_retry_time = base::Time::NowFromSystemTime() + cookie_requests_delay; - - std::string next_retry_time_as_str = - base::UTF16ToUTF8( - base::TimeFormatShortDateAndTime(next_retry_time)); - - AddSectionEntry(detailed_info, - "Cookie Manager Next Retry", - next_retry_time_as_str, - ""); + AddSectionEntry(detailed_info, "Cookie Manager Next Retry", + GetTimeStr(next_retry_time), ""); } base::TimeDelta token_requests_delay = @@ -702,15 +697,8 @@ if (token_requests_delay > base::TimeDelta()) { base::Time next_retry_time = base::Time::NowFromSystemTime() + token_requests_delay; - - std::string next_retry_time_as_str = - base::UTF16ToUTF8( - base::TimeFormatShortDateAndTime(next_retry_time)); - - AddSectionEntry(detailed_info, - "Token Service Next Retry", - next_retry_time_as_str, - ""); + AddSectionEntry(detailed_info, "Token Service Next Retry", + GetTimeStr(next_retry_time), ""); } #endif // !defined(OS_CHROMEOS)
diff --git a/components/sync/model_impl/client_tag_based_model_type_processor.cc b/components/sync/model_impl/client_tag_based_model_type_processor.cc index 8541725..465c3cbc 100644 --- a/components/sync/model_impl/client_tag_based_model_type_processor.cc +++ b/components/sync/model_impl/client_tag_based_model_type_processor.cc
@@ -184,6 +184,15 @@ // |model_type_state_| and the one received from sync. This indicates that // the stored metadata are invalid (e.g. has been manipulated) and don't // belong to the current syncing client. + if (model_type_state_.progress_marker().data_type_id() != + GetSpecificsFieldNumberFromModelType(type_)) { + // This is not strongly typed because historically, + // ModelTypeToHistogramInt() defines quite a different order from the + // type_ enum. + UMA_HISTOGRAM_ENUMERATION("Sync.PersistedModelTypeIdMismatch", + ModelTypeToHistogramInt(type_), + static_cast<int>(ModelType::NUM_ENTRIES)); + } ClearMetadataAndResetState(); // The model is still ready to sync (with the same |bridge_|) - replay
diff --git a/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc b/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc index b989632..83b7b67 100644 --- a/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc +++ b/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc
@@ -2272,7 +2272,11 @@ type_processor()->ModelReadyToSync(std::move(metadata_batch)); ASSERT_TRUE(type_processor()->IsModelReadyToSyncForTest()); + base::HistogramTester histogram_tester; OnSyncStarting(); + histogram_tester.ExpectBucketCount( + "Sync.PersistedModelTypeIdMismatch", + /*bucket=*/ModelTypeToHistogramInt(GetModelType()), /*count=*/1); // Model should still be ready to sync. ASSERT_TRUE(type_processor()->IsModelReadyToSyncForTest());
diff --git a/components/viz/demo/demo_main.cc b/components/viz/demo/demo_main.cc index 7438a9cf..b095759 100644 --- a/components/viz/demo/demo_main.cc +++ b/components/viz/demo/demo_main.cc
@@ -6,8 +6,8 @@ #include "base/command_line.h" #include "base/i18n/icu_util.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/threading/thread.h" #include "build/build_config.h" @@ -49,7 +49,8 @@ private: // The exit manager is in charge of calling the dtors of singleton objects. base::AtExitManager exit_manager_; - base::MessageLoopForUI message_loop_; + base::SingleThreadTaskExecutor main_task_executor_{ + base::MessagePump::Type::UI}; DISALLOW_COPY_AND_ASSIGN(InitBase); }; @@ -60,7 +61,7 @@ InitMojo() : thread_("Mojo thread") { mojo::core::Init(); thread_.StartWithOptions( - base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); + base::Thread::Options(base::MessagePump::Type::IO, 0)); ipc_support_ = std::make_unique<mojo::core::ScopedIPCSupport>( thread_.task_runner(), mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN);
diff --git a/components/viz/service/display_embedder/skia_output_device.cc b/components/viz/service/display_embedder/skia_output_device.cc index 8693fbb3..ce44e46 100644 --- a/components/viz/service/display_embedder/skia_output_device.cc +++ b/components/viz/service/display_embedder/skia_output_device.cc
@@ -28,6 +28,8 @@ return FinishSwapBuffers(gfx::SwapResult::SWAP_FAILED); } +void SkiaOutputDevice::SetDrawRectangle(const gfx::Rect& draw_rectangle) {} + void SkiaOutputDevice::StartSwapBuffers( base::Optional<BufferPresentedCallback> feedback) { DCHECK(!feedback_);
diff --git a/components/viz/service/display_embedder/skia_output_device.h b/components/viz/service/display_embedder/skia_output_device.h index a19cecc..0c49d762 100644 --- a/components/viz/service/display_embedder/skia_output_device.h +++ b/components/viz/service/display_embedder/skia_output_device.h
@@ -52,6 +52,10 @@ virtual gfx::SwapResponse PostSubBuffer(const gfx::Rect& rect, const GrBackendSemaphore& semaphore, BufferPresentedCallback feedback); + + // Set the rectangle that will be drawn into on the surface. + virtual void SetDrawRectangle(const gfx::Rect& draw_rectangle); + const OutputSurface::Capabilities& capabilities() const { return capabilities_; }
diff --git a/components/viz/service/display_embedder/skia_output_device_gl.cc b/components/viz/service/display_embedder/skia_output_device_gl.cc index f7c162e0..9b2c814c 100644 --- a/components/viz/service/display_embedder/skia_output_device_gl.cc +++ b/components/viz/service/display_embedder/skia_output_device_gl.cc
@@ -6,6 +6,8 @@ #include <utility> +#include "base/bind_helpers.h" +#include "components/viz/service/gl/gpu_service_impl.h" #include "gpu/command_buffer/common/swap_buffers_complete_params.h" #include "gpu/command_buffer/service/feature_info.h" #include "gpu/command_buffer/service/gl_utils.h" @@ -20,20 +22,24 @@ #include "ui/gl/gl_context.h" #include "ui/gl/gl_surface.h" #include "ui/gl/gl_version_info.h" - namespace viz { SkiaOutputDeviceGL::SkiaOutputDeviceGL( gpu::SurfaceHandle surface_handle, + GpuServiceImpl* gpu_service, scoped_refptr<gpu::gles2::FeatureInfo> feature_info, const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback) : SkiaOutputDevice(false /*need_swap_semaphore */, did_swap_buffer_complete_callback), surface_handle_(surface_handle), + gpu_service_(gpu_service), feature_info_(feature_info) { DCHECK(surface_handle_); gl_surface_ = gpu::ImageTransportSurface::CreateNativeSurface( - nullptr, surface_handle_, gl::GLSurfaceFormat()); + weak_ptr_factory_.GetWeakPtr(), surface_handle_, gl::GLSurfaceFormat()); +#if !defined(OS_WIN) + ALLOW_UNUSED_LOCAL(gpu_service_); +#endif } void SkiaOutputDeviceGL::Initialize(GrContext* gr_context, @@ -120,6 +126,10 @@ rect.x(), rect.y(), rect.width(), rect.height(), std::move(feedback))); } +void SkiaOutputDeviceGL::SetDrawRectangle(const gfx::Rect& draw_rectangle) { + gl_surface_->SetDrawRectangle(draw_rectangle); +} + void SkiaOutputDeviceGL::EnsureBackbuffer() { gl_surface_->SetBackbufferAllocation(true); } @@ -128,4 +138,36 @@ gl_surface_->SetBackbufferAllocation(false); } +#if defined(OS_WIN) +void SkiaOutputDeviceGL::DidCreateAcceleratedSurfaceChildWindow( + gpu::SurfaceHandle parent_window, + gpu::SurfaceHandle child_window) { + gpu_service_->SendCreatedChildWindow(parent_window, child_window); +} +#endif + +const gpu::gles2::FeatureInfo* SkiaOutputDeviceGL::GetFeatureInfo() const { + return feature_info_.get(); +} + +const gpu::GpuPreferences& SkiaOutputDeviceGL::GetGpuPreferences() const { + return gpu_preferences_; +} + +void SkiaOutputDeviceGL::DidSwapBuffersComplete( + gpu::SwapBuffersCompleteParams params) { + // TODO(kylechar): Check if this is necessary. +} + +void SkiaOutputDeviceGL::BufferPresented( + const gfx::PresentationFeedback& feedback) { + // TODO(kylechar): Check if this is necessary. +} + +GpuVSyncCallback SkiaOutputDeviceGL::GetGpuVSyncCallback() { + // TODO(sunnyps): Implement GpuVSync with SkiaRenderer. + NOTIMPLEMENTED(); + return base::DoNothing::Repeatedly<base::TimeTicks, base::TimeDelta>(); +} + } // namespace viz
diff --git a/components/viz/service/display_embedder/skia_output_device_gl.h b/components/viz/service/display_embedder/skia_output_device_gl.h index 0c528d7..cb2b58a 100644 --- a/components/viz/service/display_embedder/skia_output_device_gl.h +++ b/components/viz/service/display_embedder/skia_output_device_gl.h
@@ -9,9 +9,12 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "build/build_config.h" #include "components/viz/service/display_embedder/skia_output_device.h" #include "gpu/config/gpu_preferences.h" #include "gpu/ipc/common/surface_handle.h" +#include "gpu/ipc/service/image_transport_surface_delegate.h" class GrContext; @@ -27,11 +30,14 @@ } // namespace gpu namespace viz { +class GpuServiceImpl; -class SkiaOutputDeviceGL final : public SkiaOutputDevice { +class SkiaOutputDeviceGL final : public SkiaOutputDevice, + public gpu::ImageTransportSurfaceDelegate { public: SkiaOutputDeviceGL( gpu::SurfaceHandle surface_handle, + GpuServiceImpl* gpu_service, scoped_refptr<gpu::gles2::FeatureInfo> feature_info, const DidSwapBufferCompleteCallback& did_swap_buffer_complete_callback); ~SkiaOutputDeviceGL() override; @@ -53,11 +59,25 @@ gfx::SwapResponse PostSubBuffer(const gfx::Rect& rect, const GrBackendSemaphore& semaphore, BufferPresentedCallback feedback) override; + void SetDrawRectangle(const gfx::Rect& draw_rectangle) override; void EnsureBackbuffer() override; void DiscardBackbuffer() override; + // gpu::ImageTransportSurfaceDelegate implementation: +#if defined(OS_WIN) + void DidCreateAcceleratedSurfaceChildWindow( + gpu::SurfaceHandle parent_window, + gpu::SurfaceHandle child_window) override; +#endif + const gpu::gles2::FeatureInfo* GetFeatureInfo() const override; + const gpu::GpuPreferences& GetGpuPreferences() const override; + void DidSwapBuffersComplete(gpu::SwapBuffersCompleteParams params) override; + void BufferPresented(const gfx::PresentationFeedback& feedback) override; + GpuVSyncCallback GetGpuVSyncCallback() override; + private: const gpu::SurfaceHandle surface_handle_; + GpuServiceImpl* const gpu_service_; scoped_refptr<gpu::gles2::FeatureInfo> feature_info_; gpu::GpuPreferences gpu_preferences_; @@ -66,6 +86,8 @@ bool supports_alpha_ = false; + base::WeakPtrFactory<SkiaOutputDeviceGL> weak_ptr_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(SkiaOutputDeviceGL); };
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.cc b/components/viz/service/display_embedder/skia_output_surface_impl.cc index 258aa5b..ebc449c 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl.cc
@@ -126,6 +126,15 @@ event.Wait(); } +void SkiaOutputSurfaceImpl::SetDrawRectangle(const gfx::Rect& draw_rectangle) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + + auto callback = + base::BindOnce(&SkiaOutputSurfaceImplOnGpu::SetDrawRectangle, + base::Unretained(impl_on_gpu_.get()), draw_rectangle); + ScheduleGpuTask(std::move(callback), {}); +} + void SkiaOutputSurfaceImpl::EnsureBackbuffer() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // impl_on_gpu_ is released on the GPU thread by a posted task from
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.h b/components/viz/service/display_embedder/skia_output_surface_impl.h index 4508b92..af2ba3a 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl.h
@@ -50,6 +50,7 @@ // OutputSurface implementation: void BindToClient(OutputSurfaceClient* client) override; + void SetDrawRectangle(const gfx::Rect& draw_rectangle) override; void EnsureBackbuffer() override; void DiscardBackbuffer() override; void Reshape(const gfx::Size& size,
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc index f496528..5588fba 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc
@@ -1055,6 +1055,11 @@ } } +void SkiaOutputSurfaceImplOnGpu::SetDrawRectangle( + const gfx::Rect& draw_rectangle) { + output_device_->SetDrawRectangle(draw_rectangle); +} + sk_sp<GrContextThreadSafeProxy> SkiaOutputSurfaceImplOnGpu::GetGrContextThreadSafeProxy() { return gr_context()->threadSafeProxy(); @@ -1084,7 +1089,8 @@ std::unique_ptr<SkiaOutputDeviceGL> onscreen_device; if (surface_handle_) { onscreen_device = std::make_unique<SkiaOutputDeviceGL>( - surface_handle_, feature_info_, did_swap_buffer_complete_callback_); + surface_handle_, gpu_service_, feature_info_, + did_swap_buffer_complete_callback_); gl_surface_ = onscreen_device->gl_surface(); } else { gl_surface_ = gl::init::CreateOffscreenGLSurface(gfx::Size());
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h index 6f13012..5ac0548 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h
@@ -133,6 +133,8 @@ std::vector<GrBackendSemaphore>* end_semaphores); void EndAccessImages(const std::vector<ImageContext*>& image_contexts); + void SetDrawRectangle(const gfx::Rect& draw_rectangle); + sk_sp<GrContextThreadSafeProxy> GetGrContextThreadSafeProxy(); const gl::GLVersionInfo* gl_version_info() const { return gl_version_info_; }
diff --git a/components/viz/service/gl/gpu_service_impl.h b/components/viz/service/gl/gpu_service_impl.h index f6714eb..304d0ea8 100644 --- a/components/viz/service/gl/gpu_service_impl.h +++ b/components/viz/service/gl/gpu_service_impl.h
@@ -162,6 +162,24 @@ void ThrowJavaException() override; void Stop(StopCallback callback) override; + // gpu::GpuChannelManagerDelegate: + void DidCreateContextSuccessfully() override; + void DidCreateOffscreenContext(const GURL& active_url) override; + void DidDestroyChannel(int client_id) override; + void DidDestroyOffscreenContext(const GURL& active_url) override; + void DidLoseContext(bool offscreen, + gpu::error::ContextLostReason reason, + const GURL& active_url) override; + void StoreShaderToDisk(int client_id, + const std::string& key, + const std::string& shader) override; + void MaybeExitOnContextLost() override; + bool IsExiting() const override; +#if defined(OS_WIN) + void SendCreatedChildWindow(gpu::SurfaceHandle parent_window, + gpu::SurfaceHandle child_window) override; +#endif + bool is_initialized() const { return !!gpu_host_; } media::MediaGpuChannelManager* media_gpu_channel_manager() { @@ -236,23 +254,6 @@ void UpdateGpuInfoPlatform(base::OnceClosure on_gpu_info_updated); - // gpu::GpuChannelManagerDelegate: - void DidCreateContextSuccessfully() override; - void DidCreateOffscreenContext(const GURL& active_url) override; - void DidDestroyChannel(int client_id) override; - void DidDestroyOffscreenContext(const GURL& active_url) override; - void DidLoseContext(bool offscreen, - gpu::error::ContextLostReason reason, - const GURL& active_url) override; - void StoreShaderToDisk(int client_id, - const std::string& key, - const std::string& shader) override; - void MaybeExitOnContextLost() override; - bool IsExiting() const override; -#if defined(OS_WIN) - void SendCreatedChildWindow(gpu::SurfaceHandle parent_window, - gpu::SurfaceHandle child_window) override; -#endif #if defined(OS_CHROMEOS) void CreateArcVideoDecodeAcceleratorOnMainThread(
diff --git a/content/browser/accessibility/accessibility_event_recorder_uia_win.cc b/content/browser/accessibility/accessibility_event_recorder_uia_win.cc index 06458b6..ac57093 100644 --- a/content/browser/accessibility/accessibility_event_recorder_uia_win.cc +++ b/content/browser/accessibility/accessibility_event_recorder_uia_win.cc
@@ -395,8 +395,16 @@ return S_OK; } - std::string log = base::StringPrintf("%s %s", event_str.c_str(), - GetSenderInfo(sender).c_str()); + // Remove duplicate menuclosed events with no event data. + // The "duplicates" are benign. UIA currently duplicates *all* events for + // in-process listeners, and the event-recorder tries to eliminate the + // duplicates... but since the recorder sometimes isn't able to retrieve + // the role, the duplicate-elimination logic doesn't see them as + // duplicates in this case. + std::string sender_info = + event_id == UIA_MenuClosedEventId ? "" : GetSenderInfo(sender); + std::string log = + base::StringPrintf("%s %s", event_str.c_str(), sender_info.c_str()); owner_->OnEvent(log); } }
diff --git a/content/browser/android/java/java_bridge_thread.cc b/content/browser/android/java/java_bridge_thread.cc index 8919e96..e062be7 100644 --- a/content/browser/android/java/java_bridge_thread.cc +++ b/content/browser/android/java/java_bridge_thread.cc
@@ -33,15 +33,12 @@ // static bool JavaBridgeThread::CurrentlyOn() { - return g_background_thread.Get() - .message_loop() - ->task_runner() - ->BelongsToCurrentThread(); + return g_background_thread.Get().task_runner()->BelongsToCurrentThread(); } // static scoped_refptr<base::SingleThreadTaskRunner> JavaBridgeThread::GetTaskRunner() { - return g_background_thread.Get().message_loop()->task_runner(); + return g_background_thread.Get().task_runner(); } } // namespace content
diff --git a/content/browser/android/launcher_thread.cc b/content/browser/android/launcher_thread.cc index 995bc5a..0995ec2 100644 --- a/content/browser/android/launcher_thread.cc +++ b/content/browser/android/launcher_thread.cc
@@ -13,8 +13,8 @@ base::LazyInstance<LauncherThread>::Leaky g_launcher_thread; } -base::MessageLoop* LauncherThread::GetMessageLoop() { - return g_launcher_thread.Get().java_handler_thread_.message_loop(); +scoped_refptr<base::SingleThreadTaskRunner> LauncherThread::GetTaskRunner() { + return g_launcher_thread.Get().java_handler_thread_.task_runner(); } LauncherThread::LauncherThread()
diff --git a/content/browser/android/launcher_thread.h b/content/browser/android/launcher_thread.h index 02233fc..bd18c4f 100644 --- a/content/browser/android/launcher_thread.h +++ b/content/browser/android/launcher_thread.h
@@ -9,10 +9,6 @@ #include "base/lazy_instance.h" -namespace base { -class MessageLoop; -} - namespace content { namespace android { @@ -20,7 +16,7 @@ // native code, but accessed through BrowserThread(Impl) instead. class LauncherThread { public: - static base::MessageLoop* GetMessageLoop(); + static scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(); private: friend base::LazyInstanceTraitsBase<LauncherThread>;
diff --git a/content/browser/child_process_launcher_helper.cc b/content/browser/child_process_launcher_helper.cc index 8cbede7e..6081cbe 100644 --- a/content/browser/child_process_launcher_helper.cc +++ b/content/browser/child_process_launcher_helper.cc
@@ -224,8 +224,7 @@ // use-after-free if anything tries to access objects deleted by // AtExitManager, such as non-leaky LazyInstance. static base::NoDestructor<scoped_refptr<base::SingleThreadTaskRunner>> - launcher_task_runner( - android::LauncherThread::GetMessageLoop()->task_runner()); + launcher_task_runner(android::LauncherThread::GetTaskRunner()); return (*launcher_task_runner).get(); #else // defined(OS_ANDROID) // TODO(http://crbug.com/820200): Investigate whether we could use
diff --git a/content/browser/frame_host/render_frame_message_filter.cc b/content/browser/frame_host/render_frame_message_filter.cc index 3bdd59c..8702473 100644 --- a/content/browser/frame_host/render_frame_message_filter.cc +++ b/content/browser/frame_host/render_frame_message_filter.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/debug/alias.h" +#include "base/feature_list.h" #include "base/macros.h" #include "base/strings/string_util.h" #include "base/syslog_logging.h" @@ -38,6 +39,7 @@ #include "content/public/browser/download_manager.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_constants.h" +#include "content/public/common/content_features.h" #include "gpu/GLES2/gl2extchromium.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "mojo/public/cpp/system/message_pipe.h" @@ -222,36 +224,43 @@ bool log_unspecified_treated_as_lax_metric = false; bool log_none_insecure_metric = false; + bool emit_messages = + base::FeatureList::IsEnabled(features::kCookieDeprecationMessages); + for (const auto& cookie_with_status : deprecated_cookies) { if (cookie_with_status.status == net::CanonicalCookie::CookieInclusionStatus:: EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX) { log_unspecified_treated_as_lax_metric = true; - render_frame_host->AddMessageToConsole( - blink::mojom::ConsoleMessageLevel::kWarning, - "[Deprecation] A cookie associated with a cross-site resource at " + - url.possibly_invalid_spec() + - " was set without the `SameSite` attribute. " - "Starting in M77, Chrome will only deliver cookies with " - "cross-site requests if they are set with `SameSite=None`. You " - "can review cookies in developer tools under " - "Application>Storage>Cookies and see more details at " - "https://www.chromestatus.com/feature/5088147346030592."); + if (emit_messages) { + render_frame_host->AddMessageToConsole( + blink::mojom::ConsoleMessageLevel::kWarning, + "[Deprecation] A cookie associated with a cross-site resource at " + + url.possibly_invalid_spec() + + " was set without the `SameSite` attribute. " + "A future release of Chrome will only deliver cookies with " + "cross-site requests if they are set with `SameSite=None`. You " + "can review cookies in developer tools under " + "Application>Storage>Cookies and see more details at " + "https://www.chromestatus.com/feature/5088147346030592."); + } } if (cookie_with_status.status == net::CanonicalCookie::CookieInclusionStatus:: EXCLUDE_SAMESITE_NONE_INSECURE) { log_none_insecure_metric = true; - render_frame_host->AddMessageToConsole( - blink::mojom::ConsoleMessageLevel::kWarning, - "[Deprecation] A cookie associated with a resource at " + - url.possibly_invalid_spec() + - " was set with `SameSite=None` but without `Secure`. " - "Starting in M80, Chrome will only deliver cookies marked " - "`SameSite=None` if they are also marked `Secure`. You " - "can review cookies in developer tools under " - "Application>Storage>Cookies and see more details at " - "https://www.chromestatus.com/feature/5633521622188032."); + if (emit_messages) { + render_frame_host->AddMessageToConsole( + blink::mojom::ConsoleMessageLevel::kWarning, + "[Deprecation] A cookie associated with a resource at " + + url.possibly_invalid_spec() + + " was set with `SameSite=None` but without `Secure`. " + "A future release of Chrome will only deliver cookies marked " + "`SameSite=None` if they are also marked `Secure`. You " + "can review cookies in developer tools under " + "Application>Storage>Cookies and see more details at " + "https://www.chromestatus.com/feature/5633521622188032."); + } } }
diff --git a/content/browser/network_service_client.cc b/content/browser/network_service_client.cc index 0e060f99..f988069 100644 --- a/content/browser/network_service_client.cc +++ b/content/browser/network_service_client.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/feature_list.h" #include "base/optional.h" #include "base/task/post_task.h" #include "base/threading/sequence_bound.h" @@ -29,6 +30,7 @@ #include "content/public/browser/login_delegate.h" #include "content/public/browser/network_service_instance.h" #include "content/public/browser/resource_request_info.h" +#include "content/public/common/content_features.h" #include "content/public/common/network_service_util.h" #include "content/public/common/resource_type.h" #include "mojo/public/cpp/bindings/strong_binding.h" @@ -456,6 +458,9 @@ bool samesite_treated_as_lax_cookies = false; bool samesite_none_insecure_cookies = false; + bool emit_messages = + base::FeatureList::IsEnabled(features::kCookieDeprecationMessages); + for (const net::CookieWithStatus& excluded_cookie : excluded_cookies) { std::string cookie_url = net::cookie_util::CookieOriginToURL(excluded_cookie.cookie.Domain(), @@ -467,31 +472,36 @@ EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX) { samesite_treated_as_lax_cookies = true; - frame->AddMessageToConsole( - blink::mojom::ConsoleMessageLevel::kWarning, - "[Deprecation] A cookie associated with a cross-site resource at " + - cookie_url + - " was set without the `SameSite` attribute. " - "Starting in M77, Chrome will only deliver cookies with " - "cross-site requests if they are set with `SameSite=None`. You " - "can review cookies in developer tools under " - "Application>Storage>Cookies and see more details at " - "https://www.chromestatus.com/feature/5088147346030592."); + if (emit_messages) { + frame->AddMessageToConsole( + blink::mojom::ConsoleMessageLevel::kWarning, + "[Deprecation] A cookie associated with a cross-site resource at " + + cookie_url + + " was set without the `SameSite` attribute. " + "A future release of Chrome will only deliver cookies with " + "cross-site requests if they are set with `SameSite=None`. You " + "can review cookies in developer tools under " + "Application>Storage>Cookies and see more details at " + "https://www.chromestatus.com/feature/5088147346030592."); + } } if (excluded_cookie.status == net::CanonicalCookie::CookieInclusionStatus:: EXCLUDE_SAMESITE_NONE_INSECURE) { samesite_none_insecure_cookies = true; - frame->AddMessageToConsole( - blink::mojom::ConsoleMessageLevel::kWarning, - "[Deprecation] A cookie associated with a resource at " + cookie_url + - " was set with `SameSite=None` but without `Secure`. " - "Starting in M80, Chrome will only deliver cookies marked " - "`SameSite=None` if they are also marked `Secure`. You " - "can review cookies in developer tools under " - "Application>Storage>Cookies and see more details at " - "https://www.chromestatus.com/feature/5633521622188032."); + if (emit_messages) { + frame->AddMessageToConsole( + blink::mojom::ConsoleMessageLevel::kWarning, + "[Deprecation] A cookie associated with a resource at " + + cookie_url + + " was set with `SameSite=None` but without `Secure`. " + "A future release of Chrome will only deliver cookies marked " + "`SameSite=None` if they are also marked `Secure`. You " + "can review cookies in developer tools under " + "Application>Storage>Cookies and see more details at " + "https://www.chromestatus.com/feature/5633521622188032."); + } } }
diff --git a/content/browser/scheduler/browser_io_task_environment.cc b/content/browser/scheduler/browser_io_task_environment.cc index ef8542d1..f899b38 100644 --- a/content/browser/scheduler/browser_io_task_environment.cc +++ b/content/browser/scheduler/browser_io_task_environment.cc
@@ -17,7 +17,7 @@ BrowserIOTaskEnvironment::BrowserIOTaskEnvironment() : sequence_manager_(CreateUnboundSequenceManager( SequenceManager::Settings::Builder() - .SetMessagePumpType(base::MessageLoop::TYPE_IO) + .SetMessagePumpType(base::MessagePump::Type::IO) .Build())) { Init(sequence_manager_.get()); }
diff --git a/content/browser/scheduler/browser_task_executor.cc b/content/browser/scheduler/browser_task_executor.cc index 71fa381..353d009 100644 --- a/content/browser/scheduler/browser_task_executor.cc +++ b/content/browser/scheduler/browser_task_executor.cc
@@ -275,7 +275,7 @@ } base::Thread::Options options; - options.message_loop_type = base::MessageLoop::TYPE_IO; + options.message_loop_type = base::MessagePump::Type::IO; options.task_environment = g_browser_task_executor->browser_io_task_environment_.release(); #if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(USE_OZONE)
diff --git a/content/browser/scheduler/browser_ui_thread_scheduler.cc b/content/browser/scheduler/browser_ui_thread_scheduler.cc index ca438a9c..da0b5cd 100644 --- a/content/browser/scheduler/browser_ui_thread_scheduler.cc +++ b/content/browser/scheduler/browser_ui_thread_scheduler.cc
@@ -38,7 +38,7 @@ : owned_sequence_manager_( base::sequence_manager::CreateUnboundSequenceManager( base::sequence_manager::SequenceManager::Settings::Builder() - .SetMessagePumpType(base::MessageLoop::TYPE_UI) + .SetMessagePumpType(base::MessagePump::Type::UI) .Build())), task_queues_(BrowserThread::UI, owned_sequence_manager_.get(),
diff --git a/content/browser/tracing/perfetto_file_tracer.cc b/content/browser/tracing/perfetto_file_tracer.cc index a9744ab4..2f2f3f7 100644 --- a/content/browser/tracing/perfetto_file_tracer.cc +++ b/content/browser/tracing/perfetto_file_tracer.cc
@@ -19,7 +19,7 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/tracing/public/cpp/perfetto/perfetto_config.h" #include "services/tracing/public/mojom/constants.mojom.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/protos/perfetto/config/trace_config.pb.h" namespace content {
diff --git a/content/gpu/gpu_main.cc b/content/gpu/gpu_main.cc index f0d320c..635e8f93 100644 --- a/content/gpu/gpu_main.cc +++ b/content/gpu/gpu_main.cc
@@ -235,8 +235,8 @@ logging::SetLogMessageHandler(GpuProcessLogMessageHandler); // We are experiencing what appear to be memory-stomp issues in the GPU - // process. These issues seem to be impacting the message loop and listeners - // registered to it. Create the message loop on the heap to guard against + // process. These issues seem to be impacting the task executor and listeners + // registered to it. Create the task executor on the heap to guard against // this. // TODO(ericrk): Revisit this once we assess its impact on crbug.com/662802 // and crbug.com/609252.
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 35fbcc09..54815fb 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -117,6 +117,11 @@ const base::Feature kCompositeOpaqueScrollers{"CompositeOpaqueScrollers", base::FEATURE_ENABLED_BY_DEFAULT}; +// Show messages in the DevTools console about upcoming deprecations +// that would affect sent/received cookies. +const base::Feature kCookieDeprecationMessages{ + "CookieDeprecationMessages", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables crash reporting via Reporting API. // https://www.w3.org/TR/reporting/#crash-report const base::Feature kCrashReporting{"CrashReporting",
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index ad4041e..eceeec34 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -37,6 +37,7 @@ CONTENT_EXPORT extern const base::Feature kCanvas2DImageChromium; CONTENT_EXPORT extern const base::Feature kCompositeOpaqueFixedPosition; CONTENT_EXPORT extern const base::Feature kCompositeOpaqueScrollers; +CONTENT_EXPORT extern const base::Feature kCookieDeprecationMessages; CONTENT_EXPORT extern const base::Feature kCrashReporting; CONTENT_EXPORT extern const base::Feature kDataSaverHoldback; CONTENT_EXPORT extern const base::Feature kDesktopCaptureChangeSource;
diff --git a/content/renderer/categorized_worker_pool.cc b/content/renderer/categorized_worker_pool.cc index ce1db96..c13116f 100644 --- a/content/renderer/categorized_worker_pool.cc +++ b/content/renderer/categorized_worker_pool.cc
@@ -123,7 +123,10 @@ private: ~CategorizedWorkerPoolSequencedTaskRunner() override { - task_graph_runner_->WaitForTasksToFinishRunning(namespace_token_); + { + base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; + task_graph_runner_->WaitForTasksToFinishRunning(namespace_token_); + } task_graph_runner_->CollectCompletedTasks(namespace_token_, &completed_tasks_); } @@ -196,7 +199,11 @@ } void CategorizedWorkerPool::Shutdown() { - WaitForTasksToFinishRunning(namespace_token_); + { + base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; + WaitForTasksToFinishRunning(namespace_token_); + } + CollectCompletedTasks(namespace_token_, &completed_tasks_); // Shutdown raster threads. { @@ -335,8 +342,6 @@ { base::AutoLock lock(lock_); - // http://crbug.com/902823 - base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; auto* task_namespace = work_queue_.GetNamespaceForToken(token);
diff --git a/content/renderer/input/widget_input_handler_manager.cc b/content/renderer/input/widget_input_handler_manager.cc index 1b4e45a..098ecd5f 100644 --- a/content/renderer/input/widget_input_handler_manager.cc +++ b/content/renderer/input/widget_input_handler_manager.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/logging.h" +#include "base/metrics/histogram_macros.h" #include "content/common/input_messages.h" #include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/ime_event_guard.h" @@ -330,6 +331,14 @@ return; } + if (!(have_emitted_uma_ || + event->web_event->GetType() == WebInputEvent::Type::kMouseMove || + event->web_event->GetType() == WebInputEvent::Type::kPointerMove)) { + UMA_HISTOGRAM_ENUMERATION("PaintHolding.InputTiming", + current_lifecycle_state_); + have_emitted_uma_ = true; + } + // If TimeTicks is not consistent across processes we cannot use the event's // platform timestamp in this process. Instead use the time that the event is // received as the event's timestamp. @@ -446,6 +455,16 @@ #endif } +void WidgetInputHandlerManager::MarkBeginMainFrame() { + if (current_lifecycle_state_ == InitialInputTiming::kBeforeLifecycle) + current_lifecycle_state_ = InitialInputTiming::kBeforeCommit; +} + +void WidgetInputHandlerManager::MarkCompositorCommit() { + if (current_lifecycle_state_ == InitialInputTiming::kBeforeCommit) + current_lifecycle_state_ = InitialInputTiming::kAfterCommit; +} + void WidgetInputHandlerManager::InitOnInputHandlingThread( const base::WeakPtr<cc::InputHandler>& input_handler, bool smooth_scroll_enabled,
diff --git a/content/renderer/input/widget_input_handler_manager.h b/content/renderer/input/widget_input_handler_manager.h index 9da9944..a98ce998 100644 --- a/content/renderer/input/widget_input_handler_manager.h +++ b/content/renderer/input/widget_input_handler_manager.h
@@ -37,6 +37,16 @@ : public base::RefCountedThreadSafe<WidgetInputHandlerManager>, public ui::InputHandlerProxyClient, public base::SupportsWeakPtr<WidgetInputHandlerManager> { + enum class InitialInputTiming { + // Input comes before lifecycle update + kBeforeLifecycle = 0, + // Input is before commit + kBeforeCommit = 1, + // Input comes only after commit + kAfterCommit = 2, + kMaxValue = kAfterCommit + }; + public: static scoped_refptr<WidgetInputHandlerManager> Create( base::WeakPtr<RenderWidget> render_widget, @@ -98,6 +108,12 @@ void FallbackCursorModeLockCursor(bool left, bool right, bool up, bool down); void FallbackCursorModeSetCursorVisibility(bool visible); + // Called to inform us of a lifecycle update + void MarkBeginMainFrame(); + + // Called to inform us of a lifecycle update + void MarkCompositorCommit(); + protected: friend class base::RefCountedThreadSafe<WidgetInputHandlerManager>; ~WidgetInputHandlerManager() override; @@ -175,6 +191,15 @@ // WebWidget (Popups, Plugins). bool uses_input_handler_ = false; + // State tracking which lifecycle and commit events we have seen + InitialInputTiming current_lifecycle_state_ = + InitialInputTiming::kBeforeLifecycle; + + // Control of UMA. We emit one UMA metric per instantiation telling us + // whether any non-move input arrived before we starting updating the page or + // displaying content to the user. + bool have_emitted_uma_ = false; + #if defined(OS_ANDROID) std::unique_ptr<SynchronousCompositorProxyRegistry> synchronous_compositor_registry_;
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index f46d82f..8f1951e 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -1094,11 +1094,16 @@ !!compositor_deps_->GetCompositorImplThreadTaskRunner(); if (input_event_queue_) { base::Optional<ScopedUkmRafAlignedInputTimer> ukm_timer; - if (record_main_frame_metrics) + if (record_main_frame_metrics) { ukm_timer.emplace(GetWebWidget()); + } input_event_queue_->DispatchRafAlignedInput(frame_time); } + // The input handler wants to know about the main frame for metric purposes + DCHECK(widget_input_handler_manager_); + widget_input_handler_manager_->MarkBeginMainFrame(); + GetWebWidget()->BeginFrame(frame_time, record_main_frame_metrics); } @@ -1173,6 +1178,10 @@ // tab_capture_performancetest.cc. TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame"); + // The input handler wants to know about the commit for metric purposes + DCHECK(widget_input_handler_manager_); + widget_input_handler_manager_->MarkCompositorCommit(); + for (auto& observer : render_frames_) observer.DidCommitAndDrawCompositorFrame();
diff --git a/content/renderer/sandbox_mac_v2_unittest.mm b/content/renderer/sandbox_mac_v2_unittest.mm index 56beb45..bc63354 100644 --- a/content/renderer/sandbox_mac_v2_unittest.mm +++ b/content/renderer/sandbox_mac_v2_unittest.mm
@@ -159,11 +159,9 @@ 4096)); // Check that not all sysctls, including those that can get the MAC address, - // are allowed. See crbug.com/738129. Only 10.10+ supports sysctl filtering. - if (base::mac::IsAtLeastOS10_10()) { - struct ifaddrs* ifap; - CHECK_EQ(-1, getifaddrs(&ifap)); - } + // are allowed. See crbug.com/738129. + struct ifaddrs* ifap; + CHECK_EQ(-1, getifaddrs(&ifap)); std::vector<uint8_t> sysctl_data(4096); size_t data_size = sysctl_data.size();
diff --git a/content/test/data/accessibility/event/menu-opened-closed-expected-uia-win.txt b/content/test/data/accessibility/event/menu-opened-closed-expected-uia-win.txt index 17f4da3..183eeb84 100644 --- a/content/test/data/accessibility/event/menu-opened-closed-expected-uia-win.txt +++ b/content/test/data/accessibility/event/menu-opened-closed-expected-uia-win.txt
@@ -3,7 +3,5 @@ MenuOpened on role=menu === Start Continuation === MenuClosed -MenuClosed on role=menu === Start Continuation === -MenuClosed -MenuClosed on role=menu, name=menu \ No newline at end of file +MenuClosed \ No newline at end of file
diff --git a/content/utility/utility_main.cc b/content/utility/utility_main.cc index d0795c0c..fcea959 100644 --- a/content/utility/utility_main.cc +++ b/content/utility/utility_main.cc
@@ -63,7 +63,7 @@ }); #endif - // The main message loop of the utility process. + // The main task executor of the utility process. base::SingleThreadTaskExecutor main_thread_task_executor(message_pump_type); base::PlatformThread::SetName("CrUtilityMain");
diff --git a/device/bluetooth/bluetooth_adapter_factory.cc b/device/bluetooth/bluetooth_adapter_factory.cc index 76832d1..50ff691 100644 --- a/device/bluetooth/bluetooth_adapter_factory.cc +++ b/device/bluetooth/bluetooth_adapter_factory.cc
@@ -118,7 +118,7 @@ // consistent we consider Windows 8 as lacking Low Energy support. return base::win::GetVersion() >= base::win::Version::WIN10; #elif defined(OS_MACOSX) - return base::mac::IsAtLeastOS10_10(); + return true; #elif defined(OS_LINUX) return true; #else
diff --git a/device/bluetooth/bluetooth_adapter_mac.h b/device/bluetooth/bluetooth_adapter_mac.h index 290ace9..7d089c3 100644 --- a/device/bluetooth/bluetooth_adapter_mac.h +++ b/device/bluetooth/bluetooth_adapter_mac.h
@@ -105,12 +105,6 @@ // Registers that a new |device| has connected to the local host. void DeviceConnected(IOBluetoothDevice* device); - // We only use CoreBluetooth when OS X >= 10.10. This because the - // CBCentralManager destructor was found to crash on the mac-rel builder - // running 10.9.5. May also cause blued to crash on OS X 10.9.5 - // (crbug.com/506287). - static bool IsLowEnergyAvailable(); - // Creates a GATT connection by calling CoreBluetooth APIs. void CreateGattConnection(BluetoothLowEnergyDeviceMac* device_mac);
diff --git a/device/bluetooth/bluetooth_adapter_mac.mm b/device/bluetooth/bluetooth_adapter_mac.mm index fcf50dc..b6bea74 100644 --- a/device/bluetooth/bluetooth_adapter_mac.mm +++ b/device/bluetooth/bluetooth_adapter_mac.mm
@@ -129,29 +129,26 @@ device_paired_status_callback_( base::BindRepeating(&IsDeviceSystemPaired)), weak_ptr_factory_(this) { - if (IsLowEnergyAvailable()) { - low_energy_discovery_manager_.reset( - BluetoothLowEnergyDiscoveryManagerMac::Create(this)); - low_energy_central_manager_delegate_.reset( - [[BluetoothLowEnergyCentralManagerDelegate alloc] - initWithDiscoveryManager:low_energy_discovery_manager_.get() - andAdapter:this]); - low_energy_central_manager_.reset([[CBCentralManager alloc] - initWithDelegate:low_energy_central_manager_delegate_ - queue:dispatch_get_main_queue()]); - low_energy_discovery_manager_->SetCentralManager( - low_energy_central_manager_); + low_energy_discovery_manager_.reset( + BluetoothLowEnergyDiscoveryManagerMac::Create(this)); + low_energy_central_manager_delegate_.reset( + [[BluetoothLowEnergyCentralManagerDelegate alloc] + initWithDiscoveryManager:low_energy_discovery_manager_.get() + andAdapter:this]); + low_energy_central_manager_.reset([[CBCentralManager alloc] + initWithDelegate:low_energy_central_manager_delegate_ + queue:dispatch_get_main_queue()]); + low_energy_discovery_manager_->SetCentralManager(low_energy_central_manager_); - low_energy_advertisement_manager_.reset( - new BluetoothLowEnergyAdvertisementManagerMac()); - low_energy_peripheral_manager_delegate_.reset( - [[BluetoothLowEnergyPeripheralManagerDelegate alloc] - initWithAdvertisementManager:low_energy_advertisement_manager_.get() - andAdapter:this]); - low_energy_peripheral_manager_.reset([[CBPeripheralManager alloc] - initWithDelegate:low_energy_peripheral_manager_delegate_ - queue:dispatch_get_main_queue()]); - } + low_energy_advertisement_manager_.reset( + new BluetoothLowEnergyAdvertisementManagerMac()); + low_energy_peripheral_manager_delegate_.reset( + [[BluetoothLowEnergyPeripheralManagerDelegate alloc] + initWithAdvertisementManager:low_energy_advertisement_manager_.get() + andAdapter:this]); + low_energy_peripheral_manager_.reset([[CBPeripheralManager alloc] + initWithDelegate:low_energy_peripheral_manager_delegate_ + queue:dispatch_get_main_queue()]); DCHECK(classic_discovery_manager_); } @@ -197,13 +194,8 @@ } bool BluetoothAdapterMac::IsPresent() const { - bool is_present = !address_.empty(); - if (IsLowEnergyAvailable()) { - is_present = - is_present || (GetCBManagerState(low_energy_central_manager_) != - CBCentralManagerStateUnsupported); - } - return is_present; + return !address_.empty() || (GetCBManagerState(low_energy_central_manager_) != + CBCentralManagerStateUnsupported); } bool BluetoothAdapterMac::IsPowered() const { @@ -224,11 +216,8 @@ } bool BluetoothAdapterMac::IsDiscovering() const { - bool is_discovering = classic_discovery_manager_->IsDiscovering(); - if (IsLowEnergyAvailable()) - is_discovering = - is_discovering || low_energy_discovery_manager_->IsDiscovering(); - return is_discovering; + return classic_discovery_manager_->IsDiscovering() || + low_energy_discovery_manager_->IsDiscovering(); } std::unordered_map<BluetoothDevice*, BluetoothDevice::UUIDSet> @@ -313,11 +302,6 @@ ClassicDeviceAdded(device); } -// static -bool BluetoothAdapterMac::IsLowEnergyAvailable() { - return base::mac::IsAtLeastOS10_10(); -} - bool BluetoothAdapterMac::SetPoweredImpl(bool powered) { power_state_function_.Run(base::strict_cast<int>(powered)); return true; @@ -365,7 +349,6 @@ void BluetoothAdapterMac::SetCentralManagerForTesting( CBCentralManager* central_manager) { - CHECK(BluetoothAdapterMac::IsLowEnergyAvailable()); central_manager.delegate = low_energy_central_manager_delegate_; low_energy_central_manager_.reset(central_manager, base::scoped_policy::RETAIN); @@ -436,10 +419,7 @@ if (transport & BLUETOOTH_TRANSPORT_LE) { // Begin a low energy discovery session or update it if one is already // running. - if (IsLowEnergyAvailable()) { - low_energy_discovery_manager_->StartDiscovery( - BluetoothDevice::UUIDList()); - } + low_energy_discovery_manager_->StartDiscovery(BluetoothDevice::UUIDList()); } for (auto& observer : observers_) observer.AdapterDiscoveringChanged(this, true); @@ -480,11 +460,9 @@ } } if (transport & BLUETOOTH_TRANSPORT_LE) { - if (IsLowEnergyAvailable()) { - low_energy_discovery_manager_->StopDiscovery(); - for (const auto& device_id_object_pair : devices_) { - device_id_object_pair.second->ClearAdvertisementData(); - } + low_energy_discovery_manager_->StopDiscovery(); + for (const auto& device_id_object_pair : devices_) { + device_id_object_pair.second->ClearAdvertisementData(); } } @@ -521,9 +499,7 @@ if (transport & BLUETOOTH_TRANSPORT_LE) { // Begin a low energy discovery session or update it if one is already // running. - if (IsLowEnergyAvailable()) - low_energy_discovery_manager_->StartDiscovery( - BluetoothDevice::UUIDList()); + low_energy_discovery_manager_->StartDiscovery(BluetoothDevice::UUIDList()); } return true; } @@ -601,10 +577,6 @@ } bool BluetoothAdapterMac::IsLowEnergyPowered() const { - if (!IsLowEnergyAvailable()) { - return false; - } - return GetCBManagerState(low_energy_central_manager_) == CBCentralManagerStatePoweredOn; }
diff --git a/device/bluetooth/bluetooth_adapter_mac_unittest.mm b/device/bluetooth/bluetooth_adapter_mac_unittest.mm index fff3b1f0..bf68952 100644 --- a/device/bluetooth/bluetooth_adapter_mac_unittest.mm +++ b/device/bluetooth/bluetooth_adapter_mac_unittest.mm
@@ -159,10 +159,6 @@ } CBPeripheral* CreateMockPeripheral(const char* identifier) { - if (!BluetoothAdapterMac::IsLowEnergyAvailable()) { - LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; - return nil; - } base::scoped_nsobject<MockCBPeripheral> mock_peripheral( [[MockCBPeripheral alloc] initWithUTF8StringIdentifier:identifier]); return [[mock_peripheral peripheral] retain]; @@ -189,10 +185,6 @@ } bool SetMockCentralManager(CBCentralManagerState desired_state) { - if (!BluetoothAdapterMac::IsLowEnergyAvailable()) { - LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; - return false; - } mock_central_manager_.reset([[MockCentralManager alloc] init]); [mock_central_manager_ setState:desired_state]; CBCentralManager* centralManager =
diff --git a/device/bluetooth/bluetooth_low_energy_device_mac.mm b/device/bluetooth/bluetooth_low_energy_device_mac.mm index 8d9df35..5de8625 100644 --- a/device/bluetooth/bluetooth_low_energy_device_mac.mm +++ b/device/bluetooth/bluetooth_low_energy_device_mac.mm
@@ -42,7 +42,6 @@ peripheral_(peripheral, base::scoped_policy::RETAIN), connected_(false), discovery_pending_count_(0) { - DCHECK(BluetoothAdapterMac::IsLowEnergyAvailable()); DCHECK(peripheral_); peripheral_delegate_.reset([[BluetoothLowEnergyPeripheralDelegate alloc] initWithBluetoothLowEnergyDeviceMac:this]); @@ -400,7 +399,6 @@ // static std::string BluetoothLowEnergyDeviceMac::GetPeripheralIdentifier( CBPeripheral* peripheral) { - DCHECK(BluetoothAdapterMac::IsLowEnergyAvailable()); NSUUID* uuid = [peripheral identifier]; NSString* uuidString = [uuid UUIDString]; return base::SysNSStringToUTF8(uuidString);
diff --git a/device/bluetooth/bluetooth_low_energy_discovery_manager_mac.mm b/device/bluetooth/bluetooth_low_energy_discovery_manager_mac.mm index 650982b2..fde563b 100644 --- a/device/bluetooth/bluetooth_low_energy_discovery_manager_mac.mm +++ b/device/bluetooth/bluetooth_low_energy_discovery_manager_mac.mm
@@ -104,7 +104,6 @@ BluetoothLowEnergyDiscoveryManagerMac::BluetoothLowEnergyDiscoveryManagerMac( Observer* observer) : observer_(observer) { - DCHECK(BluetoothAdapterMac::IsLowEnergyAvailable()); discovering_ = false; }
diff --git a/device/bluetooth/test/bluetooth_test.h b/device/bluetooth/test/bluetooth_test.h index 9d342dd..2c74ff88 100644 --- a/device/bluetooth/test/bluetooth_test.h +++ b/device/bluetooth/test/bluetooth_test.h
@@ -154,7 +154,7 @@ // Then RunLoop().RunUntilIdle(). void StartLowEnergyDiscoverySessionExpectedToFail(); - // Check if Low Energy is available. On Mac, we require OS X >= 10.10. + // Check if Low Energy is available. virtual bool PlatformSupportsLowEnergy() = 0; // Initializes the BluetoothAdapter |adapter_| with the system adapter.
diff --git a/device/bluetooth/test/bluetooth_test_mac.mm b/device/bluetooth/test/bluetooth_test_mac.mm index fb26159..0f3fd0a 100644 --- a/device/bluetooth/test/bluetooth_test_mac.mm +++ b/device/bluetooth/test/bluetooth_test_mac.mm
@@ -105,7 +105,7 @@ void BluetoothTestMac::SetUp() {} bool BluetoothTestMac::PlatformSupportsLowEnergy() { - return BluetoothAdapterMac::IsLowEnergyAvailable(); + return true; } void BluetoothTestMac::InitWithDefaultAdapter() { @@ -119,13 +119,11 @@ .get(); adapter_ = adapter_mac_; - if (BluetoothAdapterMac::IsLowEnergyAvailable()) { - mock_central_manager_.reset( - new ScopedMockCentralManager([[MockCentralManager alloc] init])); - [mock_central_manager_->get() setBluetoothTestMac:this]; - [mock_central_manager_->get() setState:CBCentralManagerStateUnsupported]; - adapter_mac_->SetCentralManagerForTesting((id)mock_central_manager_->get()); - } + mock_central_manager_.reset( + new ScopedMockCentralManager([[MockCentralManager alloc] init])); + [mock_central_manager_->get() setBluetoothTestMac:this]; + [mock_central_manager_->get() setState:CBCentralManagerStateUnsupported]; + adapter_mac_->SetCentralManagerForTesting((id)mock_central_manager_->get()); } void BluetoothTestMac::InitWithFakeAdapter() { @@ -135,16 +133,13 @@ .get(); adapter_ = adapter_mac_; - if (BluetoothAdapterMac::IsLowEnergyAvailable()) { - mock_central_manager_.reset( - new ScopedMockCentralManager([[MockCentralManager alloc] init])); - mock_central_manager_->get().bluetoothTestMac = this; - [mock_central_manager_->get() setState:CBCentralManagerStatePoweredOn]; - adapter_mac_->SetCentralManagerForTesting((id)mock_central_manager_->get()); - adapter_mac_->SetPowerStateFunctionForTesting( - base::BindRepeating(&BluetoothTestMac::SetMockControllerPowerState, - base::Unretained(this))); - } + mock_central_manager_.reset( + new ScopedMockCentralManager([[MockCentralManager alloc] init])); + mock_central_manager_->get().bluetoothTestMac = this; + [mock_central_manager_->get() setState:CBCentralManagerStatePoweredOn]; + adapter_mac_->SetCentralManagerForTesting((id)mock_central_manager_->get()); + adapter_mac_->SetPowerStateFunctionForTesting(base::BindRepeating( + &BluetoothTestMac::SetMockControllerPowerState, base::Unretained(this))); } void BluetoothTestMac::ResetEventCounts() {
diff --git a/device/vr/openvr/openvr_gamepad_helper.cc b/device/vr/openvr/openvr_gamepad_helper.cc index f30034b..db0114ae 100644 --- a/device/vr/openvr/openvr_gamepad_helper.cc +++ b/device/vr/openvr/openvr_gamepad_helper.cc
@@ -78,14 +78,25 @@ button_data.x_axis = x_axis; button_data.y_axis = y_axis; vr::EVRButtonId button_id = GetAxisId(j); + + // Even if the button associated with the axis isn't supported, if we + // have valid axis data, we should still send that up. Since the spec + // expects buttons with axes, then we will add a dummy button to match + // the axes. GamepadButton button; if (TryGetGamepadButton(controller_state, supported_buttons, button_id, &button)) { button_data.touched = button.touched; button_data.pressed = button.pressed; button_data.value = button.value; - button_data_map[button_id] = button_data; + } else { + button_data.pressed = false; + button_data.value = 0.0; + button_data.touched = + (std::fabs(x_axis) > 0 || std::fabs(y_axis) > 0); } + + button_data_map[button_id] = button_data; } break; case vr::k_eControllerAxis_Trigger: { GamepadButton button;
diff --git a/docs/win_cross.md b/docs/win_cross.md index 7f1efb1..e0a20ec 100644 --- a/docs/win_cross.md +++ b/docs/win_cross.md
@@ -95,6 +95,9 @@ `mini_installer` target. Then, copy just `mini_installer.exe` over to the Windows box and run it to install the chrome you just built. +Note that the `mini_installer` doesn't include PDB files. PDB files are needed +to correctly symbolize stack traces (or if you want to attach a debugger). + ## Running tests on swarming You can run the Windows binaries you built on swarming, like so:
diff --git a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_embedder.cc b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_embedder.cc index 0820b76..31f32ff6 100644 --- a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_embedder.cc +++ b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_embedder.cc
@@ -225,8 +225,10 @@ !render_frame_host_->IsSandboxed(blink::WebSandboxFlags::kPlugins)) { return; } - // Notify the renderer to load an empty page instead. - GetContainerManager()->LoadEmptyPage(resource_url_); + if (render_frame_host_) { + // Notify the renderer to load an empty page instead. + GetContainerManager()->LoadEmptyPage(resource_url_); + } GetMimeHandlerViewEmbeddersMap()->erase(frame_tree_node_id_); }
diff --git a/extensions/common/extension_l10n_util.cc b/extensions/common/extension_l10n_util.cc index c967e10..ee2fa5b 100644 --- a/extensions/common/extension_l10n_util.cc +++ b/extensions/common/extension_l10n_util.cc
@@ -500,4 +500,8 @@ SetPreferredLocale(preferred_locale_.as_string()); } +const std::string& GetPreferredLocaleForTest() { + return GetPreferredLocale(); +} + } // namespace extension_l10n_util
diff --git a/extensions/common/extension_l10n_util.h b/extensions/common/extension_l10n_util.h index d82d83c..d1a155c 100644 --- a/extensions/common/extension_l10n_util.h +++ b/extensions/common/extension_l10n_util.h
@@ -134,6 +134,9 @@ base::StringPiece preferred_locale_; // The preferred locale at ctor time. }; +// Returns a locale like "en-CA". +const std::string& GetPreferredLocaleForTest(); + } // namespace extension_l10n_util #endif // EXTENSIONS_COMMON_EXTENSION_L10N_UTIL_H_
diff --git a/fuchsia/engine/context_provider_main.cc b/fuchsia/engine/context_provider_main.cc index d4b4675..9d2c532 100644 --- a/fuchsia/engine/context_provider_main.cc +++ b/fuchsia/engine/context_provider_main.cc
@@ -7,13 +7,14 @@ #include "base/fuchsia/scoped_service_binding.h" #include "base/fuchsia/service_directory.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "fuchsia/base/lifecycle_impl.h" #include "fuchsia/engine/context_provider_impl.h" int ContextProviderMain() { - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::fuchsia::ServiceDirectory* const directory = base::fuchsia::ServiceDirectory::GetDefault();
diff --git a/fuchsia/http/http_service_main.cc b/fuchsia/http/http_service_main.cc index 9c9724c7..81fbfc7 100644 --- a/fuchsia/http/http_service_main.cc +++ b/fuchsia/http/http_service_main.cc
@@ -7,8 +7,8 @@ #include "base/command_line.h" #include "base/fuchsia/scoped_service_binding.h" #include "base/fuchsia/service_directory.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "fuchsia/http/http_service_impl.h" @@ -16,7 +16,7 @@ // Instantiate various global structures. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("HTTP Service"); base::CommandLine::Init(argc, argv); - base::MessageLoopForIO loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::AtExitManager exit_manager; // Bind the parent-supplied ServiceDirectory-request to a directory and
diff --git a/fuchsia/runners/cast/main.cc b/fuchsia/runners/cast/main.cc index 77aa159..a4b791e 100644 --- a/fuchsia/runners/cast/main.cc +++ b/fuchsia/runners/cast/main.cc
@@ -4,12 +4,12 @@ #include "base/fuchsia/service_directory.h" #include "base/fuchsia/service_directory_client.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "fuchsia/runners/cast/cast_runner.h" int main(int argc, char** argv) { - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::RunLoop run_loop; CastRunner runner(base::fuchsia::ServiceDirectory::GetDefault(),
diff --git a/fuchsia/runners/web/main.cc b/fuchsia/runners/web/main.cc index 88e4b976..dd9ad4a 100644 --- a/fuchsia/runners/web/main.cc +++ b/fuchsia/runners/web/main.cc
@@ -3,12 +3,12 @@ // found in the LICENSE file. #include "base/fuchsia/service_directory.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "fuchsia/runners/common/web_content_runner.h" int main(int argc, char** argv) { - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::RunLoop run_loop; WebContentRunner runner(base::fuchsia::ServiceDirectory::GetDefault(),
diff --git a/google_apis/gcm/tools/mcs_probe.cc b/google_apis/gcm/tools/mcs_probe.cc index 338d08d..c566116 100644 --- a/google_apis/gcm/tools/mcs_probe.cc +++ b/google_apis/gcm/tools/mcs_probe.cc
@@ -22,9 +22,9 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" @@ -446,7 +446,7 @@ mojo::core::Init(); - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::ThreadPoolInstance::CreateAndStartWithDefaultParams("MCSProbe"); const base::CommandLine& command_line =
diff --git a/gpu/angle_perftests_main.cc b/gpu/angle_perftests_main.cc index 8c06477..4e9230b 100644 --- a/gpu/angle_perftests_main.cc +++ b/gpu/angle_perftests_main.cc
@@ -4,14 +4,14 @@ #include "base/bind.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" namespace { int RunHelper(base::TestSuite* test_suite) { - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); return test_suite->Run(); }
diff --git a/gpu/command_buffer/service/external_vk_image_gl_representation.cc b/gpu/command_buffer/service/external_vk_image_gl_representation.cc index e46de30..1c1155b 100644 --- a/gpu/command_buffer/service/external_vk_image_gl_representation.cc +++ b/gpu/command_buffer/service/external_vk_image_gl_representation.cc
@@ -12,11 +12,52 @@ #include "gpu/vulkan/vulkan_function_pointers.h" #include "gpu/vulkan/vulkan_implementation.h" +#define GL_LAYOUT_GENERAL_EXT 0x958D #define GL_LAYOUT_COLOR_ATTACHMENT_EXT 0x958E +#define GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT 0x958F +#define GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT 0x9590 +#define GL_LAYOUT_SHADER_READ_ONLY_EXT 0x9591 +#define GL_LAYOUT_TRANSFER_SRC_EXT 0x9592 +#define GL_LAYOUT_TRANSFER_DST_EXT 0x9593 +#define GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT 0x9530 +#define GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT 0x9531 + #define GL_HANDLE_TYPE_OPAQUE_FD_EXT 0x9586 namespace gpu { +namespace { + +GLenum ToGLImageLayout(VkImageLayout layout) { + switch (layout) { + case VK_IMAGE_LAYOUT_UNDEFINED: + return GL_NONE; + case VK_IMAGE_LAYOUT_GENERAL: + return GL_LAYOUT_GENERAL_EXT; + case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: + return GL_LAYOUT_COLOR_ATTACHMENT_EXT; + case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: + return GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT; + case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: + return GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT; + case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: + return GL_LAYOUT_SHADER_READ_ONLY_EXT; + case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: + return GL_LAYOUT_TRANSFER_SRC_EXT; + case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: + return GL_LAYOUT_TRANSFER_DST_EXT; + case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR: + return GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT; + case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR: + return GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT; + default: + NOTREACHED() << "Invalid image layout " << layout; + return GL_NONE; + } +} + +} // namespace + ExternalVkImageGlRepresentation::ExternalVkImageGlRepresentation( SharedImageManager* manager, SharedImageBacking* backing, @@ -54,7 +95,10 @@ for (auto& handle : handles) { GLuint gl_semaphore = ImportVkSemaphoreIntoGL(std::move(handle)); if (gl_semaphore) { - GLenum src_layout = GL_LAYOUT_COLOR_ATTACHMENT_EXT; + GrVkImageInfo info; + auto result = backing_impl()->backend_texture().getVkImageInfo(&info); + DCHECK(result); + GLenum src_layout = ToGLImageLayout(info.fImageLayout); api()->glWaitSemaphoreEXTFn(gl_semaphore, 0, nullptr, 1, &texture_service_id_, &src_layout); api()->glDeleteSemaphoresEXTFn(1, &gl_semaphore); @@ -114,7 +158,10 @@ return; } - GLenum dst_layout = GL_LAYOUT_COLOR_ATTACHMENT_EXT; + GrVkImageInfo info; + auto result = backing_impl()->backend_texture().getVkImageInfo(&info); + DCHECK(result); + GLenum dst_layout = ToGLImageLayout(info.fImageLayout); api()->glSignalSemaphoreEXTFn(gl_semaphore, 0, nullptr, 1, &texture_service_id_, &dst_layout); api()->glDeleteSemaphoresEXTFn(1, &gl_semaphore);
diff --git a/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.cc b/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.cc index a4fde280..4164571 100644 --- a/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.cc +++ b/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.cc
@@ -18,6 +18,7 @@ #include "base/command_line.h" #include "base/i18n/icu_util.h" #include "base/strings/string_split.h" +#include "base/task/single_thread_task_executor.h" #include "gpu/command_buffer/client/gles2_lib.h" #include "gpu/command_buffer/tests/gl_manager.h" #include "gpu/command_buffer/tests/gl_test_utils.h" @@ -45,7 +46,8 @@ command_line->AppendSwitchASCII(switches::kUseANGLE, gl::kANGLEImplementationNullName); base::FeatureList::InitializeInstance(std::string(), std::string()); - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor( + base::MessagePump::Type::IO); gpu::GLTestHelper::InitializeGLDefault(); ::gles2::Initialize(); }
diff --git a/gpu/gles2_conform_support/native/main.cc b/gpu/gles2_conform_support/native/main.cc index 672b212..7ec89bd 100644 --- a/gpu/gles2_conform_support/native/main.cc +++ b/gpu/gles2_conform_support/native/main.cc
@@ -8,13 +8,13 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #if defined(OS_MACOSX) #include "base/mac/scoped_nsautorelease_pool.h" #endif #if defined(OS_WIN) #include "base/strings/utf_string_conversions.h" #endif +#include "base/task/single_thread_task_executor.h" #include "ui/gl/gl_surface.h" extern "C" { @@ -28,7 +28,8 @@ int main(int argc, char *argv[]) { base::AtExitManager at_exit; base::CommandLine::Init(argc, argv); - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::CommandLine::StringVector args = base::CommandLine::ForCurrentProcess()->GetArgs();
diff --git a/gpu/ipc/common/gpu_memory_buffer_impl_test_template.h b/gpu/ipc/common/gpu_memory_buffer_impl_test_template.h index 21c2892..c8aa8afd 100644 --- a/gpu/ipc/common/gpu_memory_buffer_impl_test_template.h +++ b/gpu/ipc/common/gpu_memory_buffer_impl_test_template.h
@@ -14,7 +14,7 @@ #include <memory> #include "base/bind.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "build/build_config.h" #include "gpu/ipc/common/gpu_memory_buffer_support.h" #include "mojo/public/cpp/base/shared_memory_mojom_traits.h" @@ -248,7 +248,7 @@ } TYPED_TEST_P(GpuMemoryBufferImplTest, SerializeAndDeserialize) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; const gfx::Size kBufferSize(8, 8); const gfx::GpuMemoryBufferType kBufferType = TypeParam::kBufferType;
diff --git a/gpu/khronos_glcts_support/native/main.cc b/gpu/khronos_glcts_support/native/main.cc index fc6c14d..ba55e70 100644 --- a/gpu/khronos_glcts_support/native/main.cc +++ b/gpu/khronos_glcts_support/native/main.cc
@@ -6,7 +6,7 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "third_party/khronos_glcts/framework/common/tcuApp.hpp" #include "third_party/khronos_glcts/framework/common/tcuCommandLine.hpp" @@ -44,7 +44,8 @@ int main(int argc, char *argv[]) { base::AtExitManager at_exit; base::CommandLine::Init(argc, argv); - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); GTFMain(argc, argv);
diff --git a/gpu/vulkan/demo/main.cc b/gpu/vulkan/demo/main.cc index 35b66ef..7a3040e 100644 --- a/gpu/vulkan/demo/main.cc +++ b/gpu/vulkan/demo/main.cc
@@ -7,7 +7,7 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/debug/stack_trace.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/trace_event/trace_event.h" #include "components/tracing/common/trace_to_console.h" @@ -33,9 +33,10 @@ trace_config, base::trace_event::TraceLog::RECORDING_MODE); } - // Build UI thread message loop. This is used by platform + // Build UI thread task executor. This is used by platform // implementations for event polling & running background tasks. - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::ThreadPoolInstance::CreateAndStartWithDefaultParams("VulkanDemo"); gpu::VulkanDemo vulkan_demo;
diff --git a/headless/test/headless_protocol_browsertest.cc b/headless/test/headless_protocol_browsertest.cc index 503cba1..931fc0fe 100644 --- a/headless/test/headless_protocol_browsertest.cc +++ b/headless/test/headless_protocol_browsertest.cc
@@ -345,8 +345,11 @@ HEADLESS_PROTOCOL_COMPOSITOR_TEST( RendererOverrideTitleJsDisabled, "sanity/renderer-override-title-js-disabled.js") +// TODO(crbug.com/943636): rebaseline and re-enable once +// https://chromium-review.googlesource.com/c/v8/v8/+/1593307 is rolled into +// chromium. HEADLESS_PROTOCOL_COMPOSITOR_TEST( - RendererJavaScriptConsoleErrors, + DISABLED_RendererJavaScriptConsoleErrors, "sanity/renderer-javascript-console-errors.js") HEADLESS_PROTOCOL_COMPOSITOR_TEST(RendererDelayedCompletion, "sanity/renderer-delayed-completion.js")
diff --git a/ios/chrome/browser/metrics/ukm_egtest.mm b/ios/chrome/browser/metrics/ukm_egtest.mm index 0661e17..d64f6b5ea 100644 --- a/ios/chrome/browser/metrics/ukm_egtest.mm +++ b/ios/chrome/browser/metrics/ukm_egtest.mm
@@ -353,11 +353,16 @@ // Open Sync and Google services settings [ChromeEarlGreyUI tapSettingsMenuButton:GoogleServicesSettingsButton()]; // Toggle "Make searches and browsing better" switch off. - [[EarlGrey + + [[[EarlGrey selectElementWithMatcher:chrome_test_util::SettingsSwitchCell( @"betterSearchAndBrowsingItem_switch", YES)] + usingSearchAction:grey_scrollInDirection(kGREYDirectionDown, 200) + onElementWithMatcher:grey_accessibilityID( + @"google_services_settings_view_controller")] performAction:chrome_test_util::TurnSettingsSwitchOn(NO)]; + } else { // Open accounts settings, then sync settings. [[EarlGrey selectElementWithMatcher:SettingsAccountButton()]
diff --git a/ios/chrome/browser/ui/activity_services/activities/send_tab_to_self_activity.mm b/ios/chrome/browser/ui/activity_services/activities/send_tab_to_self_activity.mm index a38511f..d873db2 100644 --- a/ios/chrome/browser/ui/activity_services/activities/send_tab_to_self_activity.mm +++ b/ios/chrome/browser/ui/activity_services/activities/send_tab_to_self_activity.mm
@@ -85,25 +85,33 @@ } - (void)performActivity { - NSMutableArray<ContextMenuItem*>* targetActions = - [NSMutableArray arrayWithCapacity:[_sendTabToSelfTargets count]]; + // TODO(crbug.com/970284) once the modal dialog is created this will be + // removed. + BOOL useContextMenu = YES; + if (useContextMenu) { + NSMutableArray<ContextMenuItem*>* targetActions = + [NSMutableArray arrayWithCapacity:[_sendTabToSelfTargets count]]; - for (NSString* key in _sendTabToSelfTargets) { - NSString* deviceId = _sendTabToSelfTargets[key]; - // Retain |self| here since a |weakSelf| would be deallocated when - // displaying the target device sheet, as the ActivitySheet will be gone. - ProceduralBlock action = ^{ - SendTabToSelfCommand* command = - [[SendTabToSelfCommand alloc] initWithTargetDeviceId:deviceId]; - [self.dispatcher sendTabToSelf:command]; - }; - [targetActions addObject:[[ContextMenuItem alloc] initWithTitle:key - action:action]]; + for (NSString* key in _sendTabToSelfTargets) { + NSString* deviceId = _sendTabToSelfTargets[key]; + // Retain |self| here since a |weakSelf| would be deallocated when + // displaying the target device sheet, as the ActivitySheet will be gone. + ProceduralBlock action = ^{ + SendTabToSelfCommand* command = + [[SendTabToSelfCommand alloc] initWithTargetDeviceId:deviceId]; + [self.dispatcher sendTabToSelf:command]; + }; + [targetActions addObject:[[ContextMenuItem alloc] initWithTitle:key + action:action]]; + } + + NSString* title = l10n_util::GetNSStringF( + IDS_IOS_SHARE_MENU_SEND_TAB_TO_SELF_DEVICE_ACTION, + base::SysNSStringToUTF16(_title)); + [_presenter showActivityServiceContextMenu:title items:targetActions]; + } else { + [self.dispatcher showSendTabToSelfUI]; } - NSString* title = - l10n_util::GetNSStringF(IDS_IOS_SHARE_MENU_SEND_TAB_TO_SELF_DEVICE_ACTION, - base::SysNSStringToUTF16(_title)); - [_presenter showActivityServiceContextMenu:title items:targetActions]; [self activityDidFinish:YES]; }
diff --git a/ios/chrome/browser/ui/alert_view_controller/alert_view_controller_unittest.mm b/ios/chrome/browser/ui/alert_view_controller/alert_view_controller_unittest.mm index b6bec48..117bfe2 100644 --- a/ios/chrome/browser/ui/alert_view_controller/alert_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/alert_view_controller/alert_view_controller_unittest.mm
@@ -4,6 +4,7 @@ #import "ios/chrome/browser/ui/alert_view_controller/alert_view_controller.h" +#import "ios/chrome/browser/ui/alert_view_controller/alert_action.h" #include "testing/platform_test.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -27,3 +28,18 @@ } EXPECT_FALSE(weakAlert); } + +// Tests there are no circular references in an alert with actions. +TEST_F(AlertViewControllerTest, DeallocWithActions) { + __weak AlertViewController* weakAlert = nil; + @autoreleasepool { + AlertViewController* alert = [[AlertViewController alloc] init]; + AlertAction* action = [AlertAction actionWithTitle:@"OK" + style:UIAlertActionStyleDefault + handler:^(AlertAction* action){ + }]; + [alert setActions:@[ action ]]; + weakAlert = alert; + } + EXPECT_FALSE(weakAlert); +}
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm b/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm index fb0317c..680cabc 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm
@@ -311,6 +311,25 @@ } } ++ (void)setUp { + [super setUp]; + // If the previous run was manually stopped then the profile will be in the + // store and the test will fail. We clean it here for those cases. + ios::ChromeBrowserState* browserState = + chrome_test_util::GetOriginalBrowserState(); + autofill::PersonalDataManager* personalDataManager = + autofill::PersonalDataManagerFactory::GetForBrowserState(browserState); + for (const auto* profile : personalDataManager->GetProfiles()) { + personalDataManager->RemoveByGUID(profile->guid()); + } + GREYAssert(base::test::ios::WaitUntilConditionOrTimeout( + base::test::ios::kWaitForActionTimeout, + ^bool() { + return 0 == personalDataManager->GetProfiles().size(); + }), + @"Failed to clean profiles."); +} + - (void)setUp { [super setUp]; ios::ChromeBrowserState* browserState = @@ -435,6 +454,8 @@ performAction:chrome_test_util::TapWebElement(kFormElementCity)]; // Tap on the profiles icon. + [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()] + performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)]; [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] performAction:grey_tap()]; @@ -464,13 +485,15 @@ // Bring up the regular keyboard again. [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()] - performAction:chrome_test_util::TapWebElement(kFormElementName)]; + performAction:chrome_test_util::TapWebElement(kFormElementCity)]; // Wait for the accessory icon to appear. [GREYKeyboard waitForKeyboardToAppear]; // Verify the profiles icon is visible, and therefore also the input accessory // bar. + [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()] + performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)]; [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] assertWithMatcher:grey_sufficientlyVisible()]; } @@ -615,6 +638,8 @@ performAction:chrome_test_util::TapWebElement(kFormElementCity)]; // Verify the profiles icon is visible. + [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()] + performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)]; [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] assertWithMatcher:grey_sufficientlyVisible()]; @@ -628,6 +653,8 @@ performAction:chrome_test_util::TapWebElement(kFormElementCity)]; // Verify the profiles icon is visible. + [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()] + performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)]; [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] assertWithMatcher:grey_sufficientlyVisible()]; @@ -643,6 +670,8 @@ performAction:chrome_test_util::TapWebElement(kFormElementCity)]; // Verify the profiles icon is visible. + [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()] + performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)]; [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] assertWithMatcher:grey_sufficientlyVisible()]; @@ -669,6 +698,8 @@ performAction:chrome_test_util::TapWebElement(kFormElementCity)]; // This will fail if there is more than one profiles icon in the hierarchy. + [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()] + performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)]; [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] assertWithMatcher:grey_sufficientlyVisible()]; }
diff --git a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm index d6b79aa..b874905 100644 --- a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm
@@ -2472,7 +2472,10 @@ } [self updateToolbar]; - // Notify the WebState that it was displayed. + // TODO(crbug.com/971364): The webState is not necessarily added to the view + // hierarchy, even though the bookkeeping says that the WebState is visible. + // Do not DCHECK([webState->GetView() window]) here since this is a known + // issue. webState->WasShown(); } @@ -4309,6 +4312,10 @@ [_bookmarkInteractionController presentBookmarks]; } +- (void)showSendTabToSelfUI { + NOTIMPLEMENTED(); +} + - (void)requestDesktopSite { [self reloadWithUserAgentType:web::UserAgentType::DESKTOP]; }
diff --git a/ios/chrome/browser/ui/commands/browser_commands.h b/ios/chrome/browser/ui/commands/browser_commands.h index 4670412..25492a4 100644 --- a/ios/chrome/browser/ui/commands/browser_commands.h +++ b/ios/chrome/browser/ui/commands/browser_commands.h
@@ -91,6 +91,9 @@ // Shows the bookmarks manager. - (void)showBookmarksManager; +// Shows the dialog for sending the current tab between a user's devices. +- (void)showSendTabToSelfUI; + // Requests the "desktop" version of the current page in the active tab. - (void)requestDesktopSite;
diff --git a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_unity_egtest.mm b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_unity_egtest.mm index e073343..330c36e6 100644 --- a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_unity_egtest.mm +++ b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_unity_egtest.mm
@@ -132,10 +132,7 @@ // Tests signing in with one account, switching sync account to a second and // choosing to keep the browsing data separate during the switch. -// -// TODO(crbug.com/962843): This test is crashing due to a recent change in -// |page_placeholder_tab_helper.mm|. -- (void)DISABLED_testSignInSwitchAccountsAndKeepDataSeparate { +- (void)testSignInSwitchAccountsAndKeepDataSeparate { // The ChromeSigninView's activity indicator must be hidden as the import // data UI is presented on top of the activity indicator and Earl Grey cannot // interact with any UI while an animation is active.
diff --git a/ios/chrome/browser/web/browsing_egtest.mm b/ios/chrome/browser/web/browsing_egtest.mm index 8dfb938..0180141b 100644 --- a/ios/chrome/browser/web/browsing_egtest.mm +++ b/ios/chrome/browser/web/browsing_egtest.mm
@@ -16,7 +16,6 @@ #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #include "ios/chrome/test/scoped_block_popups_pref.h" @@ -100,17 +99,15 @@ web::test::SetUpHttpServer(std::move(provider)); GURL URL = ReloadResponseProvider::GetReloadTestUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL]); + [ChromeEarlGrey loadURL:URL]; std::string expectedBodyBeforeReload( ReloadResponseProvider::GetResponseBody(0 /* request number */)); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:expectedBodyBeforeReload]); + [ChromeEarlGrey waitForWebStateContainingText:expectedBodyBeforeReload]; [ChromeEarlGreyUI reload]; std::string expectedBodyAfterReload( ReloadResponseProvider::GetResponseBody(1 /* request_number */)); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:expectedBodyAfterReload]); + [ChromeEarlGrey waitForWebStateContainingText:expectedBodyAfterReload]; } // Tests that a tab's title is based on the URL when no other information is @@ -124,7 +121,7 @@ const GURL destinationURL = web::test::HttpServer::MakeUrl( "http://ios/testing/data/http_server_files/destination.html"); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:destinationURL]); + [ChromeEarlGrey loadURL:destinationURL]; // Add 3 for the "://" which is not considered part of the scheme std::string URLWithoutScheme = @@ -144,7 +141,7 @@ const GURL destinationURL = web::test::HttpServer::MakeUrl( "http://ios/testing/data/http_server_files/testpage.pdf"); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:destinationURL]); + [ChromeEarlGrey loadURL:destinationURL]; // Add 3 for the "://" which is not considered part of the scheme std::string URLWithoutScheme = @@ -165,7 +162,7 @@ "data:text/html;charset=utf-8,<script>document.title = " "\"%s\"</script>", kPageTitle)); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL]); + [ChromeEarlGrey loadURL:URL]; [[EarlGrey selectElementWithMatcher:TabWithTitle(kPageTitle)] assertWithMatcher:grey_sufficientlyVisible()]; @@ -191,11 +188,11 @@ ScopedBlockPopupsPref prefSetter(CONTENT_SETTING_ALLOW, GetOriginalBrowserState()); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey loadURL:URL]; + [ChromeEarlGrey waitForMainTabCount:1]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey tapWebStateElementWithID:@"link"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:@"link"]; + [ChromeEarlGrey waitForMainTabCount:2]; // Verify the new tab was opened with the expected URL. [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] @@ -221,12 +218,12 @@ ScopedBlockPopupsPref prefSetter(CONTENT_SETTING_ALLOW, GetOriginalBrowserState()); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey loadURL:URL]; + [ChromeEarlGrey waitForMainTabCount:1]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey tapWebStateElementWithID:@"link"]); + [ChromeEarlGrey tapWebStateElementWithID:@"link"]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey waitForMainTabCount:2]; // Verify the new tab was opened with the expected URL. const std::string omniboxText = @@ -264,11 +261,11 @@ ScopedBlockPopupsPref prefSetter(CONTENT_SETTING_ALLOW, GetOriginalBrowserState()); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey loadURL:URL]; + [ChromeEarlGrey waitForMainTabCount:1]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey tapWebStateElementWithID:@"link"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:@"link"]; + [ChromeEarlGrey waitForMainTabCount:2]; // Verify the new tab was opened with the expected URL. [[EarlGrey selectElementWithMatcher:OmniboxText(anchorURL.GetContent())] @@ -303,11 +300,11 @@ ScopedBlockPopupsPref prefSetter(CONTENT_SETTING_ALLOW, GetOriginalBrowserState()); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey loadURL:URL]; + [ChromeEarlGrey waitForMainTabCount:1]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey tapWebStateElementWithID:@"link"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:@"link"]; + [ChromeEarlGrey waitForMainTabCount:2]; // Verify the new tab was opened with the expected URL. [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] @@ -329,16 +326,14 @@ responses[destURL] = "You've arrived!"; web::test::SetUpSimpleHttpServer(responses); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey tapWebStateElementWithID:@"link"]); + [ChromeEarlGrey loadURL:URL]; + [ChromeEarlGrey tapWebStateElementWithID:@"link"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destURL.GetContent())] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); - - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"Link"]); + [ChromeEarlGrey goBack]; + [ChromeEarlGrey waitForWebStateContainingText:"Link"]; if (web::GetWebClient()->IsSlimNavigationManagerEnabled()) { // Using partial match for Omnibox text because the displayed URL is now // "http://origin/#" due to the link click. This is consistent with all @@ -373,23 +368,22 @@ web::test::SetUpSimpleHttpServer(responses); // Assert that test is starting with one tab. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForIncognitoTabCount:0]); + [ChromeEarlGrey waitForMainTabCount:1]; + [ChromeEarlGrey waitForIncognitoTabCount:0]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL]); + [ChromeEarlGrey loadURL:URL]; // Tap on chrome://version link. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey tapWebStateElementWithID:@"link"]); + [ChromeEarlGrey tapWebStateElementWithID:@"link"]; // Verify that page did not change by checking its URL and message printed by // onclick event. [[EarlGrey selectElementWithMatcher:OmniboxText("chrome://version")] assertWithMatcher:grey_nil()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"Hello world!"]); + [ChromeEarlGrey waitForWebStateContainingText:"Hello world!"]; // Verify that no new tabs were open which could load chrome://version. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey waitForMainTabCount:1]; } // Tests that evaluating user JavaScript that causes navigation correctly @@ -410,7 +404,7 @@ // Load the first page and run JS (using the codepath that user-entered JS in // the omnibox would take, not page-triggered) that should navigate. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:startURL]); + [ChromeEarlGrey loadURL:startURL]; NSString* script = [NSString stringWithFormat:@"javascript:window.location='%s'", @@ -420,12 +414,12 @@ [[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"Go")] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForPageToFinishLoading]); + [ChromeEarlGrey waitForPageToFinishLoading]; [[EarlGrey selectElementWithMatcher:OmniboxText(targetURL.GetContent())] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); + [ChromeEarlGrey goBack]; [[EarlGrey selectElementWithMatcher:OmniboxText(startURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -447,20 +441,19 @@ responses[secondURL] = secondResponse; web::test::SetUpSimpleHttpServer(responses); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:firstURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:secondURL]); + [ChromeEarlGrey loadURL:firstURL]; + [ChromeEarlGrey loadURL:secondURL]; // Execute some JavaScript in the omnibox. [ChromeEarlGreyUI focusOmniboxAndType:@"javascript:document.write('foo')\n"]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"foo"]); + [ChromeEarlGrey waitForWebStateContainingText:"foo"]; // Verify that the JavaScript did not affect history by going back and then // forward again. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); + [ChromeEarlGrey goBack]; [[EarlGrey selectElementWithMatcher:OmniboxText(firstURL.GetContent())] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goForward]); + [ChromeEarlGrey goForward]; [[EarlGrey selectElementWithMatcher:OmniboxText(secondURL.GetContent())] assertWithMatcher:grey_notNil()]; }
diff --git a/ios/chrome/browser/web/browsing_prevent_default_egtest.mm b/ios/chrome/browser/web/browsing_prevent_default_egtest.mm index 45e90ab4..f13262b6 100644 --- a/ios/chrome/browser/web/browsing_prevent_default_egtest.mm +++ b/ios/chrome/browser/web/browsing_prevent_default_egtest.mm
@@ -10,7 +10,6 @@ #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #include "ios/chrome/test/scoped_block_popups_pref.h" @@ -54,20 +53,19 @@ web::test::SetUpFileBasedHttpServer(); const GURL testURL = GetTestUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:testURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey loadURL:testURL]; + [ChromeEarlGrey waitForMainTabCount:1]; // Tap on the test link and wait for the page to display "Click done", as an // indicator that the element was tapped. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey + [ChromeEarlGrey tapWebStateElementWithID: [NSString stringWithCString:linkID.c_str() - encoding:[NSString defaultCStringEncoding]]]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"Click done"]); + encoding:[NSString defaultCStringEncoding]]]; + [ChromeEarlGrey waitForWebStateContainingText:"Click done"]; // Check that no navigation occurred and no new tabs were opened. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey waitForMainTabCount:1]; const GURL& currentURL = chrome_test_util::GetCurrentWebState()->GetVisibleURL(); GREYAssert(currentURL == testURL, @"Page navigated unexpectedly %s", @@ -96,12 +94,11 @@ web::test::SetUpFileBasedHttpServer(); const GURL testURL = GetTestUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:testURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey loadURL:testURL]; + [ChromeEarlGrey waitForMainTabCount:1]; // Tap on the test link. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"overrides-window-open"]); + [ChromeEarlGrey tapWebStateElementWithID:@"overrides-window-open"]; // Check that the tab navigated to about:blank and no new tabs were opened. [[GREYCondition @@ -111,7 +108,7 @@ chrome_test_util::GetCurrentWebState()->GetVisibleURL(); return currentURL == url::kAboutBlankURL; }] waitWithTimeout:kConditionTimeout]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey waitForMainTabCount:1]; } @end
diff --git a/ios/chrome/browser/web/cache_egtest.mm b/ios/chrome/browser/web/cache_egtest.mm index c66a31c..bf2723a 100644 --- a/ios/chrome/browser/web/cache_egtest.mm +++ b/ios/chrome/browser/web/cache_egtest.mm
@@ -12,7 +12,6 @@ #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #include "ios/chrome/test/scoped_block_popups_pref.h" @@ -131,32 +130,27 @@ HttpServer::MakeUrl(kCacheTestFirstPageURL); // 1st hit to server. Verify that the server has the correct hit count. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:cacheTestFirstPageURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 1"]); + [ChromeEarlGrey loadURL:cacheTestFirstPageURL]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 1"]; // Navigate to another page. 2nd hit to server. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey + [ChromeEarlGrey tapWebStateElementWithID:[NSString - stringWithUTF8String:kCacheTestLinkID]]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 2"]); + stringWithUTF8String:kCacheTestLinkID]]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 2"]; // Navigate back. This should not hit the server. Verify the page has been // loaded from cache. The serverHitCounter will remain the same. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 1"]); + [ChromeEarlGrey goBack]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 1"]; // Reload page. 3rd hit to server. Verify that page reload causes the // hitCounter to show updated value. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey reload]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 3"]); + [ChromeEarlGrey reload]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 3"]; // Verify that page reload causes Cache-Control value to be sent with request. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"cacheControl: max-age=0"]); + [ChromeEarlGrey waitForWebStateContainingText:"cacheControl: max-age=0"]; } // Tests caching behavior when opening new tab. New tab should not use the @@ -170,30 +164,25 @@ HttpServer::MakeUrl(kCacheTestThirdPageURL); // 1st hit to server. Verify title and hitCount. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:cacheTestFirstPageURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"First Page"]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 1"]); + [ChromeEarlGrey loadURL:cacheTestFirstPageURL]; + [ChromeEarlGrey waitForWebStateContainingText:"First Page"]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 1"]; // 2nd hit to server. Verify hitCount. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:cacheTestThirdPageURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 2"]); + [ChromeEarlGrey loadURL:cacheTestThirdPageURL]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 2"]; // Open the first page in a new tab. Verify that cache was not used. Must // first allow popups. ScopedBlockPopupsPref prefSetter(CONTENT_SETTING_ALLOW, GetOriginalBrowserState()); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey + [ChromeEarlGrey tapWebStateElementWithID:[NSString - stringWithUTF8String:kCacheTestLinkID]]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForPageToFinishLoading]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"First Page"]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 3"]); + stringWithUTF8String:kCacheTestLinkID]]; + [ChromeEarlGrey waitForMainTabCount:2]; + [ChromeEarlGrey waitForPageToFinishLoading]; + [ChromeEarlGrey waitForWebStateContainingText:"First Page"]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 3"]; } // Tests that cache is not used when selecting omnibox suggested website, even @@ -214,11 +203,9 @@ HttpServer::MakeUrl(kCacheTestFirstPageURL); // 1st hit to server. Verify title and hitCount. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:cacheTestFirstPageURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"First Page"]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 1"]); + [ChromeEarlGrey loadURL:cacheTestFirstPageURL]; + [ChromeEarlGrey waitForWebStateContainingText:"First Page"]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 1"]; // Type a search into omnnibox and select the first suggestion (second row) [ChromeEarlGreyUI focusOmniboxAndType:@"cachetestfirstpage"]; @@ -227,10 +214,8 @@ performAction:grey_tap()]; // Verify title and hitCount. Cache should not be used. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"First Page"]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 2"]); + [ChromeEarlGrey waitForWebStateContainingText:"First Page"]; + [ChromeEarlGrey waitForWebStateContainingText:"serverHitCounter: 2"]; } @end
diff --git a/ios/chrome/browser/web/child_window_open_by_dom_egtest.mm b/ios/chrome/browser/web/child_window_open_by_dom_egtest.mm index 7d841bfe..64f90b9a 100644 --- a/ios/chrome/browser/web/child_window_open_by_dom_egtest.mm +++ b/ios/chrome/browser/web/child_window_open_by_dom_egtest.mm
@@ -5,7 +5,6 @@ #include "base/strings/sys_string_conversions.h" #include "components/content_settings/core/common/content_settings.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/testing/earl_grey/earl_grey_test.h" @@ -53,14 +52,12 @@ #endif + (void)setUpHelper { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey setContentSettings:CONTENT_SETTING_ALLOW]); + [ChromeEarlGrey setContentSettings:CONTENT_SETTING_ALLOW]; web::test::SetUpFileBasedHttpServer(); } + (void)tearDown { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey setContentSettings:CONTENT_SETTING_DEFAULT]); + [ChromeEarlGrey setContentSettings:CONTENT_SETTING_DEFAULT]; [super tearDown]; } @@ -69,79 +66,65 @@ // Open the test page. There should only be one tab open. const char kChildWindowTestURL[] = "http://ios/testing/data/http_server_files/window_proxy.html"; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey loadURL:HttpServer::MakeUrl(kChildWindowTestURL)]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:(base::SysNSStringToUTF8( - kNamedWindowLink))]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey loadURL:HttpServer::MakeUrl(kChildWindowTestURL)]; + [ChromeEarlGrey waitForWebStateContainingText:(base::SysNSStringToUTF8( + kNamedWindowLink))]; + [ChromeEarlGrey waitForMainTabCount:1]; } // Tests that multiple calls to window.open() with the same window name returns // the same window object. - (void)test2ChildWindowsWithName { // Open two windows with the same name. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kNamedWindowLink]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:kNamedWindowLink]; + [ChromeEarlGrey waitForMainTabCount:2]; [ChromeEarlGrey selectTabAtIndex:0]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kNamedWindowLink]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:kNamedWindowLink]; + [ChromeEarlGrey waitForMainTabCount:2]; [ChromeEarlGrey selectTabAtIndex:0]; // Check that they're the same window. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"compareNamedWindows"]); + [ChromeEarlGrey tapWebStateElementWithID:@"compareNamedWindows"]; const char kWindowsEqualText[] = "named windows equal: true"; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindowsEqualText]); + [ChromeEarlGrey waitForWebStateContainingText:kWindowsEqualText]; } // Tests that multiple calls to window.open() with no window name passed in // returns a unique window object each time. - (void)test2ChildWindowsWithoutName { // Open two unnamed windows. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kUnnamedWindowLink]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:kUnnamedWindowLink]; + [ChromeEarlGrey waitForMainTabCount:2]; [ChromeEarlGrey selectTabAtIndex:0]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kUnnamedWindowLink]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:3]); + [ChromeEarlGrey tapWebStateElementWithID:kUnnamedWindowLink]; + [ChromeEarlGrey waitForMainTabCount:3]; [ChromeEarlGrey selectTabAtIndex:0]; // Check that they aren't the same window object. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"compareUnnamedWindows"]); + [ChromeEarlGrey tapWebStateElementWithID:@"compareUnnamedWindows"]; std::string kWindowsEqualText = "unnamed windows equal: false"; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindowsEqualText]); + [ChromeEarlGrey waitForWebStateContainingText:kWindowsEqualText]; } // Tests that calling window.open() with a name returns a different window // object than a subsequent call to window.open() without a name. - (void)testChildWindowsWithAndWithoutName { // Open a named window. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kNamedWindowLink]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:kNamedWindowLink]; + [ChromeEarlGrey waitForMainTabCount:2]; [ChromeEarlGrey selectTabAtIndex:0]; // Open an unnamed window. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kUnnamedWindowLink]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:3]); + [ChromeEarlGrey tapWebStateElementWithID:kUnnamedWindowLink]; + [ChromeEarlGrey waitForMainTabCount:3]; [ChromeEarlGrey selectTabAtIndex:0]; // Check that they aren't the same window object. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"compareNamedAndUnnamedWindows"]); + [ChromeEarlGrey tapWebStateElementWithID:@"compareNamedAndUnnamedWindows"]; const char kWindowsEqualText[] = "named and unnamed equal: false"; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindowsEqualText]); + [ChromeEarlGrey waitForWebStateContainingText:kWindowsEqualText]; } // Tests that window.closed is correctly set to true when the corresponding tab @@ -150,103 +133,79 @@ // results in window.closed being set to true for all references to the window // object for that tab. - (void)testWindowClosedWithName { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"openWindowWithName"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:@"openWindowWithName"]; + [ChromeEarlGrey waitForMainTabCount:2]; [ChromeEarlGrey selectTabAtIndex:0]; // Check that named window 1 is opened and named window 2 isn't. const char kCheckWindow1Link[] = "checkNamedWindow1Closed"; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kCheckWindow1Link]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey + [ChromeEarlGrey waitForWebStateContainingText:kCheckWindow1Link]; + [ChromeEarlGrey tapWebStateElementWithID:[NSString - stringWithUTF8String:kCheckWindow1Link]]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow1Open]); + stringWithUTF8String:kCheckWindow1Link]]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow1Open]; NSString* kCheckWindow2Link = @"checkNamedWindow2Closed"; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow2NeverOpen]); + [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow2NeverOpen]; // Open another window with the same name. Check that named window 2 is now // opened. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"openWindowWithName"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:@"openWindowWithName"]; + [ChromeEarlGrey waitForMainTabCount:2]; [ChromeEarlGrey selectTabAtIndex:0]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow2Open]); + [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow2Open]; // Close the opened window. Check that named window 1 and 2 are both closed. [ChromeEarlGrey closeTabAtIndex:1]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey + [ChromeEarlGrey waitForMainTabCount:1]; + [ChromeEarlGrey tapWebStateElementWithID:[NSString - stringWithUTF8String:kCheckWindow1Link]]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow1Closed]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow2Closed]); + stringWithUTF8String:kCheckWindow1Link]]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow1Closed]; + [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow2Closed]; } // Tests that closing a tab will set window.closed to true for only // corresponding window object and not for any other window objects. - (void)testWindowClosedWithoutName { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"openWindowNoName"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID:@"openWindowNoName"]; + [ChromeEarlGrey waitForMainTabCount:2]; [ChromeEarlGrey selectTabAtIndex:0]; // Check that unnamed window 1 is opened and unnamed window 2 isn't. const char kCheckWindow1Link[] = "checkUnnamedWindow1Closed"; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kCheckWindow1Link]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey + [ChromeEarlGrey waitForWebStateContainingText:kCheckWindow1Link]; + [ChromeEarlGrey tapWebStateElementWithID:[NSString - stringWithUTF8String:kCheckWindow1Link]]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow1Open]); + stringWithUTF8String:kCheckWindow1Link]]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow1Open]; NSString* kCheckWindow2Link = @"checkUnnamedWindow2Closed"; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow2NeverOpen]); + [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow2NeverOpen]; // Open another unnamed window. Check that unnamed window 2 is now opened. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"openWindowNoName"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:3]); + [ChromeEarlGrey tapWebStateElementWithID:@"openWindowNoName"]; + [ChromeEarlGrey waitForMainTabCount:3]; [ChromeEarlGrey selectTabAtIndex:0]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow2Open]); + [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow2Open]; // Close the first opened window. Check that unnamed window 1 is closed and // unnamed window 2 is still open. [ChromeEarlGrey closeTabAtIndex:1]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey + [ChromeEarlGrey tapWebStateElementWithID:[NSString - stringWithUTF8String:kCheckWindow1Link]]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow1Closed]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow2Open]); + stringWithUTF8String:kCheckWindow1Link]]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow1Closed]; + [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow2Open]; // Close the second opened window. Check that unnamed window 2 is closed. [ChromeEarlGrey closeTabAtIndex:1]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kWindow2Closed]); + [ChromeEarlGrey tapWebStateElementWithID:kCheckWindow2Link]; + [ChromeEarlGrey waitForWebStateContainingText:kWindow2Closed]; } @end
diff --git a/ios/chrome/browser/web/error_page_egtest.mm b/ios/chrome/browser/web/error_page_egtest.mm index 3fab31f..45db8bc 100644 --- a/ios/chrome/browser/web/error_page_egtest.mm +++ b/ios/chrome/browser/web/error_page_egtest.mm
@@ -7,7 +7,6 @@ #include "base/bind.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/testing/earl_grey/earl_grey_test.h" #include "ios/testing/embedded_test_server_handlers.h" @@ -53,32 +52,26 @@ - (void)testReloadErrorPage { // No response leads to ERR_CONNECTION_CLOSED error. self.serverRespondsWithContent = NO; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey loadURL:self.testServer->GetURL("/echo-query?foo")]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:GetErrorMessage()]); + [ChromeEarlGrey loadURL:self.testServer->GetURL("/echo-query?foo")]; + [ChromeEarlGrey waitForWebStateContainingText:GetErrorMessage()]; // Reload the page, which should load without errors. self.serverRespondsWithContent = YES; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey reload]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"foo"]); + [ChromeEarlGrey reload]; + [ChromeEarlGrey waitForWebStateContainingText:"foo"]; } // Sucessfully loads the page, stops the server and reloads the page. - (void)testReloadPageAfterServerIsDown { // Sucessfully load the page. self.serverRespondsWithContent = YES; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey loadURL:self.testServer->GetURL("/echo-query?foo")]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"foo"]); + [ChromeEarlGrey loadURL:self.testServer->GetURL("/echo-query?foo")]; + [ChromeEarlGrey waitForWebStateContainingText:"foo"]; // Reload the page, no response leads to ERR_CONNECTION_CLOSED error. self.serverRespondsWithContent = NO; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey reload]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:GetErrorMessage()]); + [ChromeEarlGrey reload]; + [ChromeEarlGrey waitForWebStateContainingText:GetErrorMessage()]; } @end
diff --git a/ios/chrome/browser/web/forms_egtest.mm b/ios/chrome/browser/web/forms_egtest.mm index 7fe0bb0..86d32006 100644 --- a/ios/chrome/browser/web/forms_egtest.mm +++ b/ios/chrome/browser/web/forms_egtest.mm
@@ -15,7 +15,6 @@ #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/chrome/test/scoped_eg_synchronization_disabler.h" @@ -209,11 +208,9 @@ [self setUpFormTestSimpleHttpServer]; const GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetFormUrl()]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey loadURL:GetFormUrl()]; + [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]; + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; @@ -224,7 +221,7 @@ } else { // Legacy navigation manager presents repost confirmation dialog after // loading stops. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey reload]); + [ChromeEarlGrey reload]; } { @@ -243,8 +240,7 @@ [self confirmResendWarning]; } - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -255,17 +251,15 @@ [self setUpFormTestSimpleHttpServer]; const GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetFormUrl()]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey loadURL:GetFormUrl()]; + [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]; + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; // Go to a new page and go back and check that the data is reposted. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetGenericUrl()]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); + [ChromeEarlGrey loadURL:GetGenericUrl()]; + [ChromeEarlGrey goBack]; // WKBasedNavigationManager doesn't triggere repost on |goForward| due to // WKWebView's back-forward cache. Force reload to trigger repost. Not using @@ -291,8 +285,7 @@ [self confirmResendWarning]; } - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -303,16 +296,14 @@ [self setUpFormTestSimpleHttpServer]; const GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetFormUrl()]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey loadURL:GetFormUrl()]; + [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]; + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goForward]); + [ChromeEarlGrey goBack]; + [ChromeEarlGrey goForward]; // WKBasedNavigationManager doesn't triggere repost on |goForward| due to // WKWebView's back-forward cache. Force reload to trigger repost. Not using @@ -338,8 +329,7 @@ [self confirmResendWarning]; } - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -350,22 +340,20 @@ [self setUpFormTestSimpleHttpServer]; const GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetFormUrl()]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey loadURL:GetFormUrl()]; + [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]; + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; // Go to a new page and go back to destination through back history. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetGenericUrl()]); + [ChromeEarlGrey loadURL:GetGenericUrl()]; [self openBackHistory]; [self waitForTabHistoryView]; id<GREYMatcher> historyItem = grey_text( base::SysUTF16ToNSString(web::GetDisplayTitleForUrl(destinationURL))); [[EarlGrey selectElementWithMatcher:historyItem] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForPageToFinishLoading]); + [ChromeEarlGrey waitForPageToFinishLoading]; // Back-forward navigation with WKBasedNavigationManager is served from // WKWebView's app-cache, so it won't trigger repost warning. @@ -373,8 +361,7 @@ [self confirmResendWarning]; } - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -384,16 +371,14 @@ [self setUpFormTestSimpleHttpServer]; const GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetFormUrl()]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey loadURL:GetFormUrl()]; + [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]; + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goForward]); + [ChromeEarlGrey goBack]; + [ChromeEarlGrey goForward]; // WKBasedNavigationManager doesn't triggere repost on |goForward| due to // WKWebView's back-forward cache. Force reload to trigger repost. Not using @@ -420,16 +405,15 @@ performAction:grey_tap()]; } - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForPageToFinishLoading]); + [ChromeEarlGrey waitForPageToFinishLoading]; // Expected behavior is different between the two navigation manager // implementations. if (!web::GetWebClient()->IsSlimNavigationManagerEnabled()) { // LegacyNavigationManager displays repost on |goBack|. So after cancelling, // web view should show form URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - waitForWebStateContainingText:(base::SysNSStringToUTF8( - kSubmitButtonLabel))]); + [ChromeEarlGrey waitForWebStateContainingText:(base::SysNSStringToUTF8( + kSubmitButtonLabel))]; [[EarlGrey selectElementWithMatcher:OmniboxText(GetFormUrl().GetContent())] assertWithMatcher:grey_notNil()]; [[EarlGrey selectElementWithMatcher:chrome_test_util::ForwardButton()] @@ -437,8 +421,7 @@ } else { // WKBasedNavigationManager displays repost on |reload|. So after // cancelling, web view should show |destinationURL|. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; @@ -452,11 +435,9 @@ [self setUpFormTestSimpleHttpServer]; const GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetFormUrl()]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey loadURL:GetFormUrl()]; + [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]; + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; @@ -467,7 +448,7 @@ } else { // Legacy navigation manager presents repost confirmation dialog after // loading stops. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey reload]); + [ChromeEarlGrey reload]; } // When slim navigation manager is enabled, synchronization must be disabled @@ -483,14 +464,13 @@ } // Repost confirmation box should be visible. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - waitForSufficientlyVisibleElementWithMatcher:ResendPostButtonMatcher()]); + [ChromeEarlGrey + waitForSufficientlyVisibleElementWithMatcher:ResendPostButtonMatcher()]; // Starting a new navigation while the repost dialog is presented should not // crash. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetGenericUrl()]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kGenericText]); + [ChromeEarlGrey loadURL:GetGenericUrl()]; + [ChromeEarlGrey waitForWebStateContainingText:kGenericText]; // Repost dialog should not be visible anymore. [[EarlGrey selectElementWithMatcher:ResendPostButtonMatcher()] @@ -503,19 +483,16 @@ [self setUpFormTestSimpleHttpServer]; GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetFormUrl()]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]); + [ChromeEarlGrey loadURL:GetFormUrl()]; + [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]; + [ChromeEarlGrey waitForWebStateContainingText:kDestinationText]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; // Go back and verify the browser navigates to the original URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:(base::SysNSStringToUTF8( - kSubmitButtonLabel))]); + [ChromeEarlGrey goBack]; + [ChromeEarlGrey waitForWebStateContainingText:(base::SysNSStringToUTF8( + kSubmitButtonLabel))]; [[EarlGrey selectElementWithMatcher:OmniboxText(GetFormUrl().GetContent())] assertWithMatcher:grey_notNil()]; } @@ -525,25 +502,23 @@ web::test::SetUpHttpServer(std::make_unique<TestFormResponseProvider>()); const GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetRedirectFormUrl()]); + [ChromeEarlGrey loadURL:GetRedirectFormUrl()]; // Submit the form, which redirects before printing the data. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]); + [ChromeEarlGrey tapWebStateElementWithID:kSubmitButtonLabel]; // Check that the redirect changes the POST to a GET. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"GET"]); + [ChromeEarlGrey waitForWebStateContainingText:"GET"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey reload]); + [ChromeEarlGrey reload]; // Check that the popup did not show [[EarlGrey selectElementWithMatcher:ResendPostButtonMatcher()] assertWithMatcher:grey_nil()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"GET"]); + + [ChromeEarlGrey waitForWebStateContainingText:"GET"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -562,25 +537,23 @@ const GURL formURL = GetFormPostOnSamePageUrl(); // Open the first URL so it's in history. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetGenericUrl()]); + [ChromeEarlGrey loadURL:GetGenericUrl()]; // Open the second URL, tap the button, and verify the browser navigates to // the expected URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:formURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"button"]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"POST"]); + [ChromeEarlGrey loadURL:formURL]; + [ChromeEarlGrey tapWebStateElementWithID:@"button"]; + [ChromeEarlGrey waitForWebStateContainingText:"POST"]; [[EarlGrey selectElementWithMatcher:OmniboxText(formURL.GetContent())] assertWithMatcher:grey_notNil()]; // Go back once and verify the browser navigates to the form URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); + [ChromeEarlGrey goBack]; [[EarlGrey selectElementWithMatcher:OmniboxText(formURL.GetContent())] assertWithMatcher:grey_notNil()]; // Go back a second time and verify the browser navigates to the first URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); + [ChromeEarlGrey goBack]; [[EarlGrey selectElementWithMatcher:OmniboxText(GetGenericUrl().GetContent())] assertWithMatcher:grey_notNil()]; } @@ -592,17 +565,16 @@ [self setUpFormTestSimpleHttpServer]; const GURL destinationURL = GetDestinationUrl(); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GetFormUrl()]); + [ChromeEarlGrey loadURL:GetFormUrl()]; [self submitFormUsingKeyboardGoButtonWithInputID:"textfield"]; // Verify that the browser navigates to the expected URL. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"bar!"]); + [ChromeEarlGrey waitForWebStateContainingText:"bar!"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; // Go back and verify that the browser navigates to the original URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); + [ChromeEarlGrey goBack]; [[EarlGrey selectElementWithMatcher:OmniboxText(GetFormUrl().GetContent())] assertWithMatcher:grey_notNil()]; }
diff --git a/ios/chrome/browser/web/http_auth_egtest.mm b/ios/chrome/browser/web/http_auth_egtest.mm index 29994642..e8509fe 100644 --- a/ios/chrome/browser/web/http_auth_egtest.mm +++ b/ios/chrome/browser/web/http_auth_egtest.mm
@@ -12,7 +12,6 @@ #include "ios/chrome/browser/ui/util/ui_util.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/web/public/test/http_server/http_auth_response_provider.h" @@ -86,7 +85,7 @@ GURL URL = web::test::HttpServer::MakeUrl("http://good-auth"); web::test::SetUpHttpServer(std::make_unique<web::HttpAuthResponseProvider>( URL, "GoodRealm", "gooduser", "goodpass")); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL waitForCompletion:NO]); + [ChromeEarlGrey loadURL:URL waitForCompletion:NO]; WaitForHttpAuthDialog(); // Enter valid username and password. @@ -97,8 +96,7 @@ [[EarlGrey selectElementWithMatcher:LoginButton()] performAction:grey_tap()]; const std::string pageText = web::HttpAuthResponseProvider::page_text(); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:pageText]); + [ChromeEarlGrey waitForWebStateContainingText:pageText]; } // Tests Basic HTTP Authentication with incorrect username and password. @@ -113,7 +111,7 @@ GURL URL = web::test::HttpServer::MakeUrl("http://bad-auth"); web::test::SetUpHttpServer(std::make_unique<web::HttpAuthResponseProvider>( URL, "BadRealm", "baduser", "badpass")); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL waitForCompletion:NO]); + [ChromeEarlGrey loadURL:URL waitForCompletion:NO]; WaitForHttpAuthDialog(); // Enter invalid username and password. @@ -139,7 +137,7 @@ GURL URL = web::test::HttpServer::MakeUrl("http://cancel-auth"); web::test::SetUpHttpServer(std::make_unique<web::HttpAuthResponseProvider>( URL, "CancellingRealm", "", "")); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL waitForCompletion:NO]); + [ChromeEarlGrey loadURL:URL waitForCompletion:NO]; WaitForHttpAuthDialog(); [[EarlGrey selectElementWithMatcher:chrome_test_util::CancelButton()]
diff --git a/ios/chrome/browser/web/js_print_egtest.mm b/ios/chrome/browser/web/js_print_egtest.mm index bdca7a1..0d5cdafa 100644 --- a/ios/chrome/browser/web/js_print_egtest.mm +++ b/ios/chrome/browser/web/js_print_egtest.mm
@@ -7,7 +7,6 @@ #include <map> #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/testing/earl_grey/disabled_test_macros.h" @@ -46,11 +45,10 @@ "value='Print Page' />"; web::test::SetUpSimpleHttpServer(responses); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:testURL]); + [ChromeEarlGrey loadURL:testURL]; // Tap print button. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"printButton"]); + [ChromeEarlGrey tapWebStateElementWithID:@"printButton"]; // Test if print dialog appeared. [[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"Printer Options")]
diff --git a/ios/chrome/browser/web/navigation_egtest.mm b/ios/chrome/browser/web/navigation_egtest.mm index cd5146f..288bb226 100644 --- a/ios/chrome/browser/web/navigation_egtest.mm +++ b/ios/chrome/browser/web/navigation_egtest.mm
@@ -10,7 +10,6 @@ #import "ios/chrome/browser/ui/util/uikit_ui_util.h" #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #include "ios/net/url_test_util.h" @@ -155,19 +154,16 @@ // Load the history test page and ensure that its onload text is visible. const GURL windowHistoryURL = self.testServer->GetURL(kWindowHistoryGoTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:windowHistoryURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey loadURL:windowHistoryURL]; + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; // Tap on the window.history.go() button. This will clear |kOnLoadText|, so // the subsequent check for |kOnLoadText| will only pass if a reload has // occurred. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kGoNoParameterID]); + [ChromeEarlGrey tapWebStateElementWithID:kGoNoParameterID]; // Verify that the onload text is reset. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; } // Tests reloading the current page via history.go(0). @@ -176,19 +172,16 @@ // Load the history test page and ensure that its onload text is visible. const GURL windowHistoryURL = self.testServer->GetURL(kWindowHistoryGoTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:windowHistoryURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey loadURL:windowHistoryURL]; + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; // Tap on the window.history.go() button. This will clear |kOnLoadText|, so // the subsequent check for |kOnLoadText| will only pass if a reload has // occurred. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kGoZeroID]); + [ChromeEarlGrey tapWebStateElementWithID:kGoZeroID]; // Verify that the onload text is reset. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; } // Tests that calling window.history.go() with an offset that is out of bounds @@ -198,24 +191,20 @@ // Load the history test page and ensure that its onload text is visible. const GURL windowHistoryURL = self.testServer->GetURL(kWindowHistoryGoTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:windowHistoryURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey loadURL:windowHistoryURL]; + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; // Tap on the window.history.go(2) button. This will clear all div text, so // the subsequent check for |kNoOpText| will only pass if no navigations have // occurred. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey tapWebStateElementWithID:kGoTwoID]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kNoOpText]); + [ChromeEarlGrey tapWebStateElementWithID:kGoTwoID]; + [ChromeEarlGrey waitForWebStateContainingText:kNoOpText]; // Tap on the window.history.go(-2) button. This will clear all div text, so // the subsequent check for |kNoOpText| will only pass if no navigations have // occurred. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kGoBackTwoID]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kNoOpText]); + [ChromeEarlGrey tapWebStateElementWithID:kGoBackTwoID]; + [ChromeEarlGrey waitForWebStateContainingText:kNoOpText]; } // Tests going back and forward via history.go(). @@ -227,25 +216,21 @@ const GURL fourthURL = self.testServer->GetURL("/history.html"); // Load 4 pages. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:firstURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:secondURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:thirdURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:fourthURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"onload"]); + [ChromeEarlGrey loadURL:firstURL]; + [ChromeEarlGrey loadURL:secondURL]; + [ChromeEarlGrey loadURL:thirdURL]; + [ChromeEarlGrey loadURL:fourthURL]; + [ChromeEarlGrey waitForWebStateContainingText:"onload"]; // Tap button to go back 3 pages. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"goBack3"]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey tapWebStateElementWithID:@"goBack3"]; + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; [[EarlGrey selectElementWithMatcher:OmniboxText(firstURL.GetContent())] assertWithMatcher:grey_notNil()]; // Tap button to go forward 2 pages. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey tapWebStateElementWithID:kGoTwoID]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"pony"]); + [ChromeEarlGrey tapWebStateElementWithID:kGoTwoID]; + [ChromeEarlGrey waitForWebStateContainingText:"pony"]; [[EarlGrey selectElementWithMatcher:OmniboxText(thirdURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -257,24 +242,20 @@ // Load the history test page and ensure that its onload text is visible. const GURL windowHistoryURL = self.testServer->GetURL(kWindowHistoryGoTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:windowHistoryURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey loadURL:windowHistoryURL]; + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; const GURL sampleURL = self.testServer->GetURL(kSimpleFileBasedTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:sampleURL]); + [ChromeEarlGrey loadURL:sampleURL]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:windowHistoryURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey loadURL:windowHistoryURL]; + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; // Tap the window.history.go(-2) button. This will clear the current page's // |kOnLoadText|, so the subsequent check will only pass if another load // occurs. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kGoBackTwoID]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey tapWebStateElementWithID:kGoBackTwoID]; + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; } #pragma mark window.history.[back/forward] operations @@ -284,17 +265,15 @@ GREYAssertTrue(self.testServer->Start(), @"Test server failed to start."); // Navigate to a URL. const GURL firstURL = self.testServer->GetURL(kSimpleFileBasedTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:firstURL]); + [ChromeEarlGrey loadURL:firstURL]; // Navigate to an HTML page with a back button. const GURL secondURL = self.testServer->GetURL(kWindowHistoryGoTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:secondURL]); + [ChromeEarlGrey loadURL:secondURL]; // Tap the back button in the HTML and verify the first URL is loaded. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kGoBackID]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"pony"]); + [ChromeEarlGrey tapWebStateElementWithID:kGoBackID]; + [ChromeEarlGrey waitForWebStateContainingText:"pony"]; [[EarlGrey selectElementWithMatcher:OmniboxText(firstURL.GetContent())] assertWithMatcher:grey_notNil()]; @@ -310,25 +289,22 @@ GREYAssertTrue(self.testServer->Start(), @"Test server failed to start."); // Navigate to an HTML page with a forward button. const GURL firstURL = self.testServer->GetURL(kWindowHistoryGoTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:firstURL]); + [ChromeEarlGrey loadURL:firstURL]; // Navigate to some other page. const GURL secondURL = self.testServer->GetURL(kSimpleFileBasedTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:secondURL]); + [ChromeEarlGrey loadURL:secondURL]; // Tap the back button in the toolbar and verify the page with forward button // is loaded. [[EarlGrey selectElementWithMatcher:BackButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]); + [ChromeEarlGrey waitForWebStateContainingText:kOnLoadText]; [[EarlGrey selectElementWithMatcher:OmniboxText(firstURL.GetContent())] assertWithMatcher:grey_notNil()]; // Tap the forward button in the HTML and verify the second URL is loaded. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kGoForwardID]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"pony"]); + [ChromeEarlGrey tapWebStateElementWithID:kGoForwardID]; + [ChromeEarlGrey waitForWebStateContainingText:"pony"]; [[EarlGrey selectElementWithMatcher:OmniboxText(secondURL.GetContent())] assertWithMatcher:grey_notNil()]; @@ -344,21 +320,19 @@ - (void)testHistoryBackAndForwardAroundNTP { GREYAssertTrue(self.testServer->Start(), @"Test server failed to start."); const GURL testURL = self.testServer->GetURL(kSimpleFileBasedTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:testURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"pony"]); + [ChromeEarlGrey loadURL:testURL]; + [ChromeEarlGrey waitForWebStateContainingText:"pony"]; // Tap the back button and verify NTP is loaded. [[EarlGrey selectElementWithMatcher:BackButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForPageToFinishLoading]); + [ChromeEarlGrey waitForPageToFinishLoading]; [[EarlGrey selectElementWithMatcher:ContentSuggestionCollectionView()] assertWithMatcher:grey_notNil()]; // Tap the forward button and verify test page is loaded. [[EarlGrey selectElementWithMatcher:ForwardButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"pony"]); + [ChromeEarlGrey waitForWebStateContainingText:"pony"]; } #pragma mark window.location.hash operations @@ -373,11 +347,10 @@ const GURL hashChangedWithHistoryURL = self.testServer->GetURL(kHashChangedWithHistoryURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:page1URL]); + [ChromeEarlGrey loadURL:page1URL]; // Click link to update location.hash and go to new URL (same page). - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithHistoryLabel]); + [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithHistoryLabel]; // Navigate back to original URL. This should fire a hashchange event. std::string backHashChangeContent = "backHashChange"; @@ -387,8 +360,7 @@ net::GetContentAndFragmentForUrl(page1URL); [[EarlGrey selectElementWithMatcher:OmniboxText(page1OmniboxText)] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:backHashChangeContent]); + [ChromeEarlGrey waitForWebStateContainingText:backHashChangeContent]; // Navigate forward to the new URL. This should fire a hashchange event. std::string forwardHashChangeContent = "forwardHashChange"; @@ -400,15 +372,13 @@ [[EarlGrey selectElementWithMatcher:OmniboxText(hashChangedWithHistoryOmniboxText)] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:forwardHashChangeContent]); + [ChromeEarlGrey waitForWebStateContainingText:forwardHashChangeContent]; // Load a hash URL directly. This shouldn't fire a hashchange event. std::string hashChangeContent = "FAIL_loadUrlHashChange"; [self addHashChangeListenerWithContent:hashChangeContent]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:hashChangedWithHistoryURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateNotContainingText:hashChangeContent]); + [ChromeEarlGrey loadURL:hashChangedWithHistoryURL]; + [ChromeEarlGrey waitForWebStateNotContainingText:hashChangeContent]; } // Loads a URL and replaces its location, then updates its location.hash @@ -423,11 +393,10 @@ const GURL hashChangedWithoutHistoryURL = self.testServer->GetURL(kHashChangedWithoutHistoryURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:page1URL]); + [ChromeEarlGrey loadURL:page1URL]; // Tap link to replace the location value. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithoutHistoryLabel]); + [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithoutHistoryLabel]; const std::string hashChangedWithoutHistoryOmniboxText = net::GetContentAndFragmentForUrl(hashChangedWithoutHistoryURL); [[EarlGrey selectElementWithMatcher:OmniboxText( @@ -435,8 +404,7 @@ assertWithMatcher:grey_notNil()]; // Tap link to update the location.hash with a new value. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithHistoryLabel]); + [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithHistoryLabel]; const std::string hashChangedWithHistoryOmniboxText = net::GetContentAndFragmentForUrl(hashChangedWithHistoryURL); [[EarlGrey @@ -461,11 +429,10 @@ const GURL hashChangedWithHistoryURL = self.testServer->GetURL(kHashChangedWithHistoryURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:page1URL]); + [ChromeEarlGrey loadURL:page1URL]; // Tap link to update location.hash with a new value. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithHistoryLabel]); + [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithHistoryLabel]; const std::string hashChangedWithHistoryOmniboxText = net::GetContentAndFragmentForUrl(hashChangedWithHistoryURL); [[EarlGrey @@ -473,8 +440,7 @@ assertWithMatcher:grey_notNil()]; // Tap link to update location.hash with the same value. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithHistoryLabel]); + [ChromeEarlGrey tapWebStateElementWithID:kHashChangeWithHistoryLabel]; // Tap back once to return to original URL. [[EarlGrey selectElementWithMatcher:BackButton()] performAction:grey_tap()]; @@ -504,8 +470,8 @@ const GURL originURL = self.testServer->GetURL(kRedirectWindowURL); const GURL destinationURL = self.testServer->GetURL(kDestinationURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:initialURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:originURL]); + [ChromeEarlGrey loadURL:initialURL]; + [ChromeEarlGrey loadURL:originURL]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; @@ -563,29 +529,26 @@ // Load index, tap on redirect link, and assert that the page is redirected // to the proper destination. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:indexURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey + [ChromeEarlGrey loadURL:indexURL]; + [ChromeEarlGrey tapWebStateElementWithID: [NSString stringWithCString:redirectLabel.c_str() - encoding:[NSString defaultCStringEncoding]]]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"You've arrived"]); + encoding:[NSString defaultCStringEncoding]]]; + [ChromeEarlGrey waitForWebStateContainingText:"You've arrived"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; // Navigate to a new URL, navigate back and assert that the resulting page is // the proper destination. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:lastURL]); + [ChromeEarlGrey loadURL:lastURL]; [[EarlGrey selectElementWithMatcher:BackButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"You've arrived"]); + [ChromeEarlGrey waitForWebStateContainingText:"You've arrived"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; // Navigate back and assert that the resulting page is the initial index. [[EarlGrey selectElementWithMatcher:BackButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:redirectLabel]); + [ChromeEarlGrey waitForWebStateContainingText:redirectLabel]; [[EarlGrey selectElementWithMatcher:OmniboxText(indexURL.GetContent())] assertWithMatcher:grey_notNil()]; @@ -593,8 +556,7 @@ // destination. [[EarlGrey selectElementWithMatcher:ForwardButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"You've arrived"]); + [ChromeEarlGrey waitForWebStateContainingText:"You've arrived"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -604,19 +566,17 @@ - (void)testRestoreHistoryToWebUIAndNavigateForward { GREYAssertTrue(self.testServer->Start(), @"Test server failed to start."); const GURL destinationURL = self.testServer->GetURL(kSimpleFileBasedTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GURL("chrome://version")]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:destinationURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); + [ChromeEarlGrey loadURL:GURL("chrome://version")]; + [ChromeEarlGrey loadURL:destinationURL]; + [ChromeEarlGrey goBack]; GREYAssert(PurgeCachedWebViewPages(), @"History not restored"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"Revision"]); + [ChromeEarlGrey waitForWebStateContainingText:"Revision"]; [[EarlGrey selectElementWithMatcher:OmniboxText("chrome://version")] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goForward]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"pony"]); + [ChromeEarlGrey goForward]; + [ChromeEarlGrey waitForWebStateContainingText:"pony"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -626,14 +586,13 @@ - (void)testRestoreHistoryToNTPAndNavigateForward { GREYAssertTrue(self.testServer->Start(), @"Test server failed to start."); const GURL destinationURL = self.testServer->GetURL(kSimpleFileBasedTestURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:destinationURL]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goBack]); + [ChromeEarlGrey loadURL:destinationURL]; + [ChromeEarlGrey goBack]; GREYAssert(PurgeCachedWebViewPages(), @"History not restored"); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey goForward]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"pony"]); + [ChromeEarlGrey goForward]; + [ChromeEarlGrey waitForWebStateContainingText:"pony"]; [[EarlGrey selectElementWithMatcher:OmniboxText(destinationURL.GetContent())] assertWithMatcher:grey_notNil()]; }
diff --git a/ios/chrome/browser/web/page_placeholder_tab_helper.mm b/ios/chrome/browser/web/page_placeholder_tab_helper.mm index 6990eade..9da95c5 100644 --- a/ios/chrome/browser/web/page_placeholder_tab_helper.mm +++ b/ios/chrome/browser/web/page_placeholder_tab_helper.mm
@@ -79,7 +79,11 @@ } void PagePlaceholderTabHelper::AddPlaceholder() { - if (displaying_placeholder_) + // WebState::WasShown() and WebState::IsVisible() are bookkeeping mechanisms + // that do not guarantee the WebState's view is in the view hierarchy. + // TODO(crbug.com/971364): Do not DCHECK([webState->GetView() window]) here + // since this is a known issue. + if (displaying_placeholder_ || ![web_state_->GetView() window]) return; displaying_placeholder_ = true; @@ -115,6 +119,8 @@ void PagePlaceholderTabHelper::DisplaySnapshotImage(UIImage* snapshot) { DCHECK(web_state_->IsVisible()) << "The WebState must be visible to display a page placeholder."; + DCHECK([web_state_->GetView() window]) + << "The WebState's view must be in the main window's view hierarchy."; UIView* web_state_view = web_state_->GetView(); NamedGuide* guide = [NamedGuide guideWithName:kContentAreaGuide view:web_state_view];
diff --git a/ios/chrome/browser/web/page_placeholder_tab_helper_unittest.mm b/ios/chrome/browser/web/page_placeholder_tab_helper_unittest.mm index 1a240b2..0db1eeb 100644 --- a/ios/chrome/browser/web/page_placeholder_tab_helper_unittest.mm +++ b/ios/chrome/browser/web/page_placeholder_tab_helper_unittest.mm
@@ -12,6 +12,7 @@ #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" #import "ios/chrome/browser/snapshots/snapshot_tab_helper.h" #import "ios/chrome/browser/ui/util/named_guide.h" +#import "ios/chrome/test/scoped_key_window.h" #import "ios/web/public/test/fakes/test_web_state.h" #include "ios/web/public/test/test_web_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" @@ -37,6 +38,8 @@ web_state_view_.backgroundColor = [UIColor blueColor]; web_state_->SetView(web_state_view_); + [scoped_key_window_.Get() addSubview:web_state_view_]; + // The Content Area named guide should be available. NamedGuide* guide = [[NamedGuide alloc] initWithName:kContentAreaGuide]; [web_state_view_ addLayoutGuide:guide]; @@ -53,6 +56,7 @@ } web::TestWebThreadBundle thread_bundle_; + ScopedKeyWindow scoped_key_window_; std::unique_ptr<ios::ChromeBrowserState> browser_state_; std::unique_ptr<web::TestWebState> web_state_; UIView* web_state_view_ = nil;
diff --git a/ios/chrome/browser/web/progress_indicator_egtest.mm b/ios/chrome/browser/web/progress_indicator_egtest.mm index 6f37db7..54434c9f 100644 --- a/ios/chrome/browser/web/progress_indicator_egtest.mm +++ b/ios/chrome/browser/web/progress_indicator_egtest.mm
@@ -17,7 +17,6 @@ #include "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/third_party/material_components_ios/src/components/ProgressView/src/MaterialProgressView.h" #include "ios/web/public/test/http_server/html_response_provider.h" @@ -186,12 +185,10 @@ web::test::SetUpHttpServer(std::move(uniqueInfinitePendingProvider)); // The page being loaded never completes, so call the LoadUrl helper that // does not wait for the page to complete loading. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:infinitePendingURL - waitForCompletion:NO]); + [ChromeEarlGrey loadURL:infinitePendingURL waitForCompletion:NO]; // Wait until the page is half loaded. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kPageText]); + [ChromeEarlGrey waitForWebStateContainingText:kPageText]; // Verify progress view visible and halfway progress. [[EarlGrey selectElementWithMatcher:ProgressViewWithProgress(0.5)] @@ -225,15 +222,13 @@ web::test::AddResponseProvider(std::move(uniqueInfinitePendingProvider)); // Load form first. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:formURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kFormPageText]); + [ChromeEarlGrey loadURL:formURL]; + [ChromeEarlGrey waitForWebStateContainingText:kFormPageText]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey submitWebStateFormWithID:kFormID]); + [ChromeEarlGrey submitWebStateFormWithID:kFormID]; // Wait until the page is half loaded. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kPageText]); + [ChromeEarlGrey waitForWebStateContainingText:kPageText]; // Verify progress view visible and halfway progress. [[EarlGrey selectElementWithMatcher:ProgressViewWithProgress(0.5)] @@ -258,16 +253,14 @@ responses[simplePageURL] = kPageText; web::test::SetUpSimpleHttpServer(responses); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:formURL]); + [ChromeEarlGrey loadURL:formURL]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kFormPageText]); + [ChromeEarlGrey waitForWebStateContainingText:kFormPageText]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey submitWebStateFormWithID:kFormID]); + [ChromeEarlGrey submitWebStateFormWithID:kFormID]; // Verify the new page has been loaded. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kPageText]); + [ChromeEarlGrey waitForWebStateContainingText:kPageText]; // Verify progress view is not visible. [[EarlGrey selectElementWithMatcher:ProgressView()] @@ -287,13 +280,12 @@ responses[formURL] = [self formPageHTMLWithSuppressedSubmitEvent]; web::test::SetUpSimpleHttpServer(responses); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:formURL]); + [ChromeEarlGrey loadURL:formURL]; // Verify the form page has been loaded. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kFormPageText]); + [ChromeEarlGrey waitForWebStateContainingText:kFormPageText]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey submitWebStateFormWithID:kFormID]); + [ChromeEarlGrey submitWebStateFormWithID:kFormID]; // Verify progress view is not visible. [[EarlGrey selectElementWithMatcher:grey_kindOfClass([MDCProgressView class])]
diff --git a/ios/chrome/browser/web/push_and_replace_state_navigation_egtest.mm b/ios/chrome/browser/web/push_and_replace_state_navigation_egtest.mm index 0ac2bd8..592c687 100644 --- a/ios/chrome/browser/web/push_and_replace_state_navigation_egtest.mm +++ b/ios/chrome/browser/web/push_and_replace_state_navigation_egtest.mm
@@ -10,7 +10,6 @@ #include "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #include "ios/net/url_test_util.h" @@ -64,24 +63,20 @@ const std::string pushStatePathSpaceOmniboxText = net::GetContentAndFragmentForUrl(pushStatePathSpaceURL); web::test::SetUpFileBasedHttpServer(); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey loadURL:web::test::HttpServer::MakeUrl(kHistoryTestUrl)]); + [ChromeEarlGrey loadURL:web::test::HttpServer::MakeUrl(kHistoryTestUrl)]; // Push 3 URLs. Verify that the URL changed and the status was updated. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashWithObject"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashWithObject"]; [self assertStatusText:@"pushStateHashWithObject" withOmniboxText:pushStateHashWithObjectOmniboxText pageLoaded:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStateRootPath"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStateRootPath"]; [self assertStatusText:@"pushStateRootPath" withOmniboxText:pushStateRootPathOmniboxText pageLoaded:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStatePathSpace"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStatePathSpace"]; [self assertStatusText:@"pushStatePathSpace" withOmniboxText:pushStatePathSpaceOmniboxText pageLoaded:NO]; @@ -98,8 +93,7 @@ withOmniboxText:pushStateHashWithObjectOmniboxText pageLoaded:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"goBack"]); + [ChromeEarlGrey tapWebStateElementWithID:@"goBack"]; const GURL historyTestURL = web::test::HttpServer::MakeUrl(kHistoryTestUrl); [self assertStatusText:nil withOmniboxText:net::GetContentAndFragmentForUrl(historyTestURL) @@ -107,8 +101,7 @@ // Go forward 2 pages and check that the page doesn't load and the status text // is updated by the popstate event. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"goForward2"]); + [ChromeEarlGrey tapWebStateElementWithID:@"goForward2"]; [self assertStatusText:@"pushStateRootPath" withOmniboxText:pushStateRootPathOmniboxText pageLoaded:NO]; @@ -120,17 +113,15 @@ const GURL initialURL = web::test::HttpServer::MakeUrl(kNonPushedUrl); const std::string initialOmniboxText = net::GetContentAndFragmentForUrl(initialURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:initialURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey loadURL:web::test::HttpServer::MakeUrl(kHistoryTestUrl)]); + [ChromeEarlGrey loadURL:initialURL]; + [ChromeEarlGrey loadURL:web::test::HttpServer::MakeUrl(kHistoryTestUrl)]; // Replace the URL and go back then forward. const GURL replaceStateHashWithObjectURL = web::test::HttpServer::MakeUrl(kReplaceStateHashWithObjectURL); const std::string replaceStateHashWithObjectOmniboxText = net::GetContentAndFragmentForUrl(replaceStateHashWithObjectURL); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"replaceStateHashWithObject"]); + [ChromeEarlGrey tapWebStateElementWithID:@"replaceStateHashWithObject"]; [self assertStatusText:@"replaceStateHashWithObject" withOmniboxText:replaceStateHashWithObjectOmniboxText pageLoaded:NO]; @@ -154,8 +145,7 @@ web::test::HttpServer::MakeUrl(kPushStateHashStringURL); const std::string pushStateHashStringOmniboxText = net::GetContentAndFragmentForUrl(pushStateHashStringURL); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashString"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashString"]; [self assertStatusText:@"pushStateHashString" withOmniboxText:pushStateHashStringOmniboxText pageLoaded:NO]; @@ -164,8 +154,7 @@ web::test::HttpServer::MakeUrl(kReplaceStateHashStringURL); const std::string replaceStateHashStringOmniboxText = net::GetContentAndFragmentForUrl(replaceStateHashStringURL); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"replaceStateHashString"]); + [ChromeEarlGrey tapWebStateElementWithID:@"replaceStateHashString"]; [self assertStatusText:@"replaceStateHashString" withOmniboxText:replaceStateHashStringOmniboxText pageLoaded:NO]; @@ -174,8 +163,7 @@ web::test::HttpServer::MakeUrl(kPushStatePathURL); const std::string pushStatePathOmniboxText = net::GetContentAndFragmentForUrl(pushStatePathURL); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStatePath"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStatePath"]; [self assertStatusText:@"pushStatePath" withOmniboxText:pushStatePathOmniboxText pageLoaded:NO]; @@ -184,8 +172,7 @@ web::test::HttpServer::MakeUrl(kReplaceStateRootPathSpaceURL); const std::string replaceStateRootPathSpaceOmniboxText = net::GetContentAndFragmentForUrl(replaceStateRootPathSpaceURL); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"replaceStateRootPathSpace"]); + [ChromeEarlGrey tapWebStateElementWithID:@"replaceStateRootPathSpace"]; [self assertStatusText:@"replaceStateRootPathSpace" withOmniboxText:replaceStateRootPathSpaceOmniboxText pageLoaded:NO]; @@ -201,8 +188,7 @@ pageLoaded:NO]; // Go forward and check URL. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"goForward2"]); + [ChromeEarlGrey tapWebStateElementWithID:@"goForward2"]; [self assertStatusText:@"replaceStateRootPathSpace" withOmniboxText:replaceStateRootPathSpaceOmniboxText pageLoaded:NO]; @@ -213,7 +199,7 @@ GURL nonPushedURL = web::test::HttpServer::MakeUrl(kNonPushedUrl); web::test::SetUpFileBasedHttpServer(); const GURL historyTestURL = web::test::HttpServer::MakeUrl(kHistoryTestUrl); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:historyTestURL]); + [ChromeEarlGrey loadURL:historyTestURL]; const std::string historyTestOmniboxText = net::GetContentAndFragmentForUrl(historyTestURL); @@ -222,24 +208,21 @@ web::test::HttpServer::MakeUrl(kPushStateHashStringURL); const std::string pushStateHashStringOmniboxText = net::GetContentAndFragmentForUrl(pushStateHashStringURL); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashString"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashString"]; [self assertStatusText:@"pushStateHashString" withOmniboxText:pushStateHashStringOmniboxText pageLoaded:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashString"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashString"]; [self assertStatusText:@"pushStateHashString" withOmniboxText:pushStateHashStringOmniboxText pageLoaded:NO]; // Load a non-pushed URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:nonPushedURL]); + [ChromeEarlGrey loadURL:nonPushedURL]; // Load history.html and push another URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:historyTestURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashString"]); + [ChromeEarlGrey loadURL:historyTestURL]; + [ChromeEarlGrey tapWebStateElementWithID:@"pushStateHashString"]; [self assertStatusText:@"pushStateHashString" withOmniboxText:pushStateHashStringOmniboxText pageLoaded:NO]; @@ -270,16 +253,14 @@ pageLoaded:NO]; // Go forward 4 entries at once (to third #string) and verify page did load. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"goForward4"]); + [ChromeEarlGrey tapWebStateElementWithID:@"goForward4"]; [self assertStatusText:nil withOmniboxText:pushStateHashStringOmniboxText pageLoaded:expectOnLoad]; // Go back 4 entries at once (to first #string) and verify page did load. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"goBack4"]); + [ChromeEarlGrey tapWebStateElementWithID:@"goBack4"]; [self assertStatusText:nil withOmniboxText:pushStateHashStringOmniboxText @@ -306,33 +287,27 @@ NSString* pushStateUnicode2Status = @"pushStateUnicode2∢"; web::test::SetUpFileBasedHttpServer(); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey loadURL:web::test::HttpServer::MakeUrl(kHistoryTestUrl)]); + [ChromeEarlGrey loadURL:web::test::HttpServer::MakeUrl(kHistoryTestUrl)]; // Do 2 push states with unicode characters. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStateUnicode"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStateUnicode"]; [[EarlGrey selectElementWithMatcher:chrome_test_util::OmniboxText(pushStateUnicode)] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:pushStateUnicodeLabel]); + [ChromeEarlGrey waitForWebStateContainingText:pushStateUnicodeLabel]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStateUnicode2"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStateUnicode2"]; [[EarlGrey selectElementWithMatcher:chrome_test_util::OmniboxText(pushStateUnicode2)] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:pushStateUnicode2Label]); + [ChromeEarlGrey waitForWebStateContainingText:pushStateUnicode2Label]; // Do a push state without a unicode character. const GURL pushStatePathURL = web::test::HttpServer::MakeUrl(kPushStatePathURL); const std::string pushStatePathOmniboxText = net::GetContentAndFragmentForUrl(pushStatePathURL); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushStatePath"]); + [ChromeEarlGrey tapWebStateElementWithID:@"pushStatePath"]; [self assertStatusText:@"pushStatePath" withOmniboxText:pushStatePathOmniboxText @@ -380,15 +355,13 @@ [NSString stringWithFormat:simplePage, baseTag, pushAndReplaceButtons]); web::test::SetUpSimpleHttpServer(responses); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:originURL]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"pushState"]); + [ChromeEarlGrey loadURL:originURL]; + [ChromeEarlGrey tapWebStateElementWithID:@"pushState"]; [[EarlGrey selectElementWithMatcher:chrome_test_util::OmniboxText( pushResultOmniboxText)] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"replaceState"]); + [ChromeEarlGrey tapWebStateElementWithID:@"replaceState"]; [[EarlGrey selectElementWithMatcher:chrome_test_util::OmniboxText( replaceResultOmniboxText)] assertWithMatcher:grey_notNil()]; @@ -403,17 +376,15 @@ withOmniboxText:(const std::string&)omniboxText pageLoaded:(BOOL)pageLoaded { if (pageLoaded) { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"onload"]); + [ChromeEarlGrey waitForWebStateContainingText:"onload"]; } else { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateNotContainingText:"onload"]); + [ChromeEarlGrey waitForWebStateNotContainingText:"onload"]; } if (status != nil) { NSString* statusLabel = [NSString stringWithFormat:@"Action: %@", status]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - waitForWebStateContainingText:base::SysNSStringToUTF8(statusLabel)]); + [ChromeEarlGrey + waitForWebStateContainingText:base::SysNSStringToUTF8(statusLabel)]; } [[EarlGrey
diff --git a/ios/chrome/browser/web/sad_tab_tab_helper_unittest.mm b/ios/chrome/browser/web/sad_tab_tab_helper_unittest.mm index 9079f926..ddea3cc 100644 --- a/ios/chrome/browser/web/sad_tab_tab_helper_unittest.mm +++ b/ios/chrome/browser/web/sad_tab_tab_helper_unittest.mm
@@ -11,8 +11,10 @@ #include "ios/chrome/browser/chrome_url_constants.h" #import "ios/chrome/browser/ntp/new_tab_page_tab_helper.h" #import "ios/chrome/browser/ntp/new_tab_page_tab_helper_delegate.h" +#import "ios/chrome/browser/ui/util/named_guide.h" #import "ios/chrome/browser/web/page_placeholder_tab_helper.h" #import "ios/chrome/browser/web/sad_tab_tab_helper_delegate.h" +#import "ios/chrome/test/scoped_key_window.h" #import "ios/web/public/test/fakes/fake_navigation_context.h" #import "ios/web/public/test/fakes/test_navigation_manager.h" #import "ios/web/public/test/fakes/test_web_state.h" @@ -66,6 +68,16 @@ sad_tab_delegate_([[SadTabTabHelperTestDelegate alloc] init]) { browser_state_ = TestChromeBrowserState::Builder().Build(); + // Create view that is added to the window. + CGRect frame = {CGPointZero, CGSizeMake(400, 300)}; + web_state_view_ = [[UIView alloc] initWithFrame:frame]; + web_state_.SetView(web_state_view_); + [scoped_key_window_.Get() addSubview:web_state_view_]; + + // The Content Area named guide should be available. + NamedGuide* guide = [[NamedGuide alloc] initWithName:kContentAreaGuide]; + [web_state_view_ addLayoutGuide:guide]; + SadTabTabHelper::CreateForWebState(&web_state_); tab_helper()->SetDelegate(sad_tab_delegate_); PagePlaceholderTabHelper::CreateForWebState(&web_state_); @@ -87,6 +99,8 @@ ~SadTabTabHelperTest() override { [application_ stopMocking]; } base::test::ScopedTaskEnvironment environment_; + ScopedKeyWindow scoped_key_window_; + UIView* web_state_view_; std::unique_ptr<ios::ChromeBrowserState> browser_state_; web::TestWebState web_state_; web::TestNavigationManager* navigation_manager_;
diff --git a/ios/chrome/browser/web/stop_loading_egtest.mm b/ios/chrome/browser/web/stop_loading_egtest.mm index e4a07861..20236e9 100644 --- a/ios/chrome/browser/web/stop_loading_egtest.mm +++ b/ios/chrome/browser/web/stop_loading_egtest.mm
@@ -11,7 +11,6 @@ #include "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/chrome/test/scoped_eg_synchronization_disabler.h" @@ -99,11 +98,9 @@ // TODO(crbug.com/960508): Investigate why test fails on iPad if // synchronization is enabled. ScopedSynchronizationDisabler disabler; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:infinitePendingURL - waitForCompletion:NO]); + [ChromeEarlGrey loadURL:infinitePendingURL waitForCompletion:NO]; } else { - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:infinitePendingURL - waitForCompletion:NO]); + [ChromeEarlGrey loadURL:infinitePendingURL waitForCompletion:NO]; } if (IsIPadIdiom()) { @@ -116,8 +113,7 @@ } // Wait until the page is half loaded. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kPageText]); + [ChromeEarlGrey waitForWebStateContainingText:kPageText]; // On iPhone Stop/Reload button is a part of tools menu, so open it. if (!IsIPadIdiom()) {
diff --git a/ios/chrome/browser/web/tab_order_egtest.mm b/ios/chrome/browser/web/tab_order_egtest.mm index 93c5922..9707782 100644 --- a/ios/chrome/browser/web/tab_order_egtest.mm +++ b/ios/chrome/browser/web/tab_order_egtest.mm
@@ -9,7 +9,6 @@ #import "ios/chrome/test/app/tab_test_util.h" #import "ios/chrome/test/earl_grey/chrome_actions.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/web/public/test/earl_grey/web_view_matchers.h" @@ -58,9 +57,8 @@ const GURL URL1 = self.testServer->GetURL(kLinksTestURL1); // Create a tab that will act as the parent tab. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL1]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kLinksTestURL1Text]); + [ChromeEarlGrey loadURL:URL1]; + [ChromeEarlGrey waitForWebStateContainingText:kLinksTestURL1Text]; Tab* parentTab = chrome_test_util::GetCurrentTab(); // Child tab should be inserted after the parent. @@ -70,7 +68,7 @@ true /* menu should appear */)]; [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2U]); + [ChromeEarlGrey waitForMainTabCount:2U]; Tab* childTab1 = chrome_test_util::GetNextTab(); // New child tab should be inserted AFTER |childTab1|. @@ -80,7 +78,7 @@ true /* menu should appear */)]; [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:3U]); + [ChromeEarlGrey waitForMainTabCount:3U]; GREYAssertEqual(childTab1, chrome_test_util::GetNextTab(), @"Unexpected next tab"); @@ -88,15 +86,13 @@ // grouping with the current child tabs. Total number of tabs should not // change. const GURL URL2 = self.testServer->GetURL(kLinksTestURL2); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL2]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kLinksTestURL2Text]); + [ChromeEarlGrey loadURL:URL2]; + [ChromeEarlGrey waitForWebStateContainingText:kLinksTestURL2Text]; GREYAssertEqual(3U, [ChromeEarlGrey mainTabCount], @"Unexpected number of tabs"); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:URL1]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kLinksTestURL1Text]); + [ChromeEarlGrey loadURL:URL1]; + [ChromeEarlGrey waitForWebStateContainingText:kLinksTestURL1Text]; GREYAssertEqual(3U, [ChromeEarlGrey mainTabCount], @"Unexpected number of tabs"); @@ -107,7 +103,7 @@ true /* menu should appear */)]; [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:4U]); + [ChromeEarlGrey waitForMainTabCount:4U]; Tab* childTab3 = chrome_test_util::GetNextTab(); GREYAssertNotEqual(childTab1, childTab3, @"Unexpected next tab"); @@ -118,7 +114,7 @@ true /* menu should appear */)]; [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:5U]); + [ChromeEarlGrey waitForMainTabCount:5U]; GREYAssertEqual(childTab3, chrome_test_util::GetNextTab(), @"Unexpected next tab"); @@ -129,8 +125,8 @@ // Add a non-owned tab. It should be added at the end and marked as the // current tab. Next tab should wrap back to index 0, the original parent tab. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey openNewTab]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:6U]); + [ChromeEarlGrey openNewTab]; + [ChromeEarlGrey waitForMainTabCount:6U]; GREYAssertEqual(parentTab, chrome_test_util::GetNextTab(), @"Unexpected next tab");
diff --git a/ios/chrome/browser/web/visible_url_egtest.mm b/ios/chrome/browser/web/visible_url_egtest.mm index 8f9b250..2a13c4cc 100644 --- a/ios/chrome/browser/web/visible_url_egtest.mm +++ b/ios/chrome/browser/web/visible_url_egtest.mm
@@ -16,7 +16,6 @@ #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/web/common/features.h" @@ -149,8 +148,8 @@ _responseProvider = unique_provider.get(); web::test::SetUpHttpServer(std::move(unique_provider)); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:_testURL1]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:_testURL2]); + [ChromeEarlGrey loadURL:_testURL1]; + [ChromeEarlGrey loadURL:_testURL2]; } - (void)tearDown { @@ -175,8 +174,7 @@ // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [self setServerPaused:YES]; // Tap the back button in the toolbar and verify that URL2 (committed URL) is @@ -190,16 +188,14 @@ // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] assertWithMatcher:grey_notNil()]; // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [self setServerPaused:YES]; // Tap the forward button in the toolbar and verify that URL1 (committed URL) @@ -213,8 +209,7 @@ // Make server respond so URL2 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL2.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -229,8 +224,7 @@ // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [self setServerPaused:YES]; // Re-enable synchronization here to synchronize EarlGrey LongPress and Tap @@ -258,8 +252,7 @@ // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -274,8 +267,7 @@ // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [self setServerPaused:YES]; // Tap the back button, stop pending navigation and reload. @@ -297,8 +289,7 @@ // Make server respond and verify that page2 was reloaded, not page1. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL2.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -313,14 +304,13 @@ // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [self setServerPaused:YES]; // Tap the back button on the page and verify that URL2 (committed URL) is // displayed even though URL1 is a pending URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:base::SysUTF8ToNSString(kGoBackLink)]); + [ChromeEarlGrey + tapWebStateElementWithID:base::SysUTF8ToNSString(kGoBackLink)]; GREYAssert([self waitForServerToReceiveRequestWithURL:_testURL1], @"Last request URL: %@", self.lastRequestURLSpec); [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL2.GetContent())] @@ -328,22 +318,20 @@ // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] assertWithMatcher:grey_notNil()]; // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [self setServerPaused:YES]; // Tap the forward button on the page and verify that URL1 (committed URL) // is displayed even though URL2 is a pending URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:base::SysUTF8ToNSString(kGoForwardLink)]); + [ChromeEarlGrey + tapWebStateElementWithID:base::SysUTF8ToNSString(kGoForwardLink)]; GREYAssert([self waitForServerToReceiveRequestWithURL:_testURL2], @"Last request URL: %@", self.lastRequestURLSpec); [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] @@ -351,8 +339,7 @@ // Make server respond so URL2 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL2.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -367,14 +354,13 @@ // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [self setServerPaused:YES]; // Tap the go negative delta button on the page and verify that URL2 // (committed URL) is displayed even though URL1 is a pending URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:base::SysUTF8ToNSString(kGoNegativeDeltaLink)]); + [ChromeEarlGrey + tapWebStateElementWithID:base::SysUTF8ToNSString(kGoNegativeDeltaLink)]; GREYAssert([self waitForServerToReceiveRequestWithURL:_testURL1], @"Last request URL: %@", self.lastRequestURLSpec); [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL2.GetContent())] @@ -382,22 +368,20 @@ // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] assertWithMatcher:grey_notNil()]; // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [self setServerPaused:YES]; // Tap go positive delta button on the page and verify that URL1 (committed // URL) is displayed even though URL2 is a pending URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:base::SysUTF8ToNSString(kGoPositiveDeltaLink)]); + [ChromeEarlGrey + tapWebStateElementWithID:base::SysUTF8ToNSString(kGoPositiveDeltaLink)]; GREYAssert([self waitForServerToReceiveRequestWithURL:_testURL2], @"Last request URL: %@", self.lastRequestURLSpec); [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] @@ -405,8 +389,7 @@ // Make server respond so URL2 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL2.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -421,8 +404,7 @@ // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [self setServerPaused:YES]; // Start reloading the page. @@ -448,8 +430,7 @@ // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -472,13 +453,11 @@ // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [self setServerPaused:YES]; // Start renderer initiated navigation. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:base::SysUTF8ToNSString(kPage3Link)]); + [ChromeEarlGrey tapWebStateElementWithID:base::SysUTF8ToNSString(kPage3Link)]; // Do not wait until renderer-initiated navigation is finished, tap the back // button in the toolbar and verify that URL2 (committed URL) is displayed @@ -492,8 +471,7 @@ // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -509,8 +487,7 @@ // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage2]; [self setServerPaused:YES]; // Tap the back button in the toolbar and verify that URL2 (committed URL) is @@ -523,15 +500,13 @@ assertWithMatcher:grey_notNil()]; // Interrupt back navigation with renderer initiated navigation. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:base::SysUTF8ToNSString(kPage3Link)]); + [ChromeEarlGrey tapWebStateElementWithID:base::SysUTF8ToNSString(kPage3Link)]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL2.GetContent())] assertWithMatcher:grey_notNil()]; // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage3]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage3]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL3.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -544,13 +519,12 @@ EARL_GREY_TEST_DISABLED(@"Test disabled on SlimNavigationManager."); // Create 3rd entry in the history, to be able to go back twice. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:_testURL3]); + [ChromeEarlGrey loadURL:_testURL3]; // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage3]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage3]; [self setServerPaused:YES]; // Tap the back button twice in the toolbar and verify that URL3 (committed @@ -567,8 +541,7 @@ // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] assertWithMatcher:grey_notNil()]; } @@ -582,23 +555,21 @@ // Create 3rd entry in the history, to be able to go back twice. GURL URL(kChromeUIVersionURL); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:GURL(kChromeUIVersionURL)]); + [ChromeEarlGrey loadURL:GURL(kChromeUIVersionURL)]; // Tap the back button twice in the toolbar and wait for URL 1 to load. [[EarlGrey selectElementWithMatcher:chrome_test_util::BackButton()] performAction:grey_tap()]; [[EarlGrey selectElementWithMatcher:chrome_test_util::BackButton()] performAction:grey_tap()]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; // Quickly navigate forward twice and wait for kChromeUIVersionURL to load. [chrome_test_util::BrowserCommandDispatcherForMainBVC() goForward]; [chrome_test_util::BrowserCommandDispatcherForMainBVC() goForward]; const std::string version = version_info::GetVersionNumber(); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:version]); + [ChromeEarlGrey waitForWebStateContainingText:version]; // Make sure that kChromeUIVersionURL URL is displayed in the omnibox. std::string expectedText = base::UTF16ToUTF8(web::GetDisplayTitleForUrl(URL)); @@ -614,21 +585,20 @@ EARL_GREY_TEST_DISABLED(@"Test disabled on SlimNavigationManager."); // Create 3rd entry in the history, to be able to go back twice. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey loadURL:_testURL3]); + [ChromeEarlGrey loadURL:_testURL3]; // Purge web view caches and pause the server to make sure that tests can // verify omnibox state before server starts responding. GREYAssert(PurgeCachedWebViewPages(), @"Pages were not purged"); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage3]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage3]; [self setServerPaused:YES]; // Tap the back button twice on the page and verify that URL3 (committed URL) // is displayed even though URL1 is a pending URL. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:base::SysUTF8ToNSString(kGoBackLink)]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:base::SysUTF8ToNSString(kGoBackLink)]); + [ChromeEarlGrey + tapWebStateElementWithID:base::SysUTF8ToNSString(kGoBackLink)]; + [ChromeEarlGrey + tapWebStateElementWithID:base::SysUTF8ToNSString(kGoBackLink)]; // Server will receive only one request either for |_testURL2| or for // |_testURL1| depending on load timing and then will pause. So there is no // need to wait for particular request. @@ -638,8 +608,7 @@ // Make server respond so URL1 becomes committed. [self setServerPaused:NO]; // TODO(crbug.com/866406): fix the test to have documented behavior. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]); + [ChromeEarlGrey waitForWebStateContainingText:kTestPage1]; [[EarlGrey selectElementWithMatcher:OmniboxText(_testURL1.GetContent())] assertWithMatcher:grey_notNil()]; }
diff --git a/ios/chrome/browser/web/window_open_by_dom_egtest.mm b/ios/chrome/browser/web/window_open_by_dom_egtest.mm index 3ca6334..ec4103c5 100644 --- a/ios/chrome/browser/web/window_open_by_dom_egtest.mm +++ b/ios/chrome/browser/web/window_open_by_dom_egtest.mm
@@ -13,7 +13,6 @@ #include "ios/chrome/grit/ios_strings.h" #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" -#import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" #include "ios/net/url_test_util.h" @@ -55,34 +54,29 @@ + (void)setUp { [super setUp]; - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey setContentSettings:CONTENT_SETTING_ALLOW]); + [ChromeEarlGrey setContentSettings:CONTENT_SETTING_ALLOW]; web::test::SetUpFileBasedHttpServer(); } + (void)tearDown { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey setContentSettings:CONTENT_SETTING_DEFAULT]); + [ChromeEarlGrey setContentSettings:CONTENT_SETTING_DEFAULT]; [super tearDown]; } - (void)setUp { [super setUp]; // Open the test page. There should only be one tab open. - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey loadURL:HttpServer::MakeUrl(kTestURL)]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"Expected result"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey loadURL:HttpServer::MakeUrl(kTestURL)]; + [ChromeEarlGrey waitForWebStateContainingText:"Expected result"]; + [ChromeEarlGrey waitForMainTabCount:1]; } // Tests that opening a link with target=_blank which then immediately closes // itself works. - (void)testLinkWithBlankTargetWithImmediateClose { - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID: - @"webScenarioWindowOpenBlankTargetWithImmediateClose"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey tapWebStateElementWithID: + @"webScenarioWindowOpenBlankTargetWithImmediateClose"]; + [ChromeEarlGrey waitForMainTabCount:1]; } // Tests that sessionStorage content is available for windows opened by DOM via @@ -95,9 +89,8 @@ GetCurrentWebState(), [ElementSelector selectorWithElementID:ID])]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey waitForWebStateContainingText:"Expected result"]); + [ChromeEarlGrey waitForMainTabCount:2]; + [ChromeEarlGrey waitForWebStateContainingText:"Expected result"]; id value = [ChromeEarlGrey executeJavaScript:@"sessionStorage.getItem('key');"]; @@ -111,19 +104,17 @@ performAction:web::WebViewTapElement( GetCurrentWebState(), [ElementSelector selectorWithElementID:ID])]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey waitForMainTabCount:2]; } // Tests executing script that clicks a link with target="_blank". - (void)testLinkWithBlankTargetWithoutUserGesture { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey setContentSettings:CONTENT_SETTING_BLOCK]); + [ChromeEarlGrey setContentSettings:CONTENT_SETTING_BLOCK]; [ChromeEarlGrey executeJavaScript:@"document.getElementById('" @"webScenarioWindowOpenRegularLink').click()"]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - waitForSufficientlyVisibleElementWithMatcher:PopupBlocker()]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey waitForSufficientlyVisibleElementWithMatcher:PopupBlocker()]; + [ChromeEarlGrey waitForMainTabCount:1]; } // Tests a link with target="_blank" multiple times. @@ -135,29 +126,28 @@ test_page_web_state, [ElementSelector selectorWithElementID:ID]); [[EarlGrey selectElementWithMatcher:test_page_matcher] performAction:link_tap]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey openNewTab]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:3]); + [ChromeEarlGrey waitForMainTabCount:2]; + [ChromeEarlGrey openNewTab]; + [ChromeEarlGrey waitForMainTabCount:3]; [ChromeEarlGrey selectTabAtIndex:0]; [[EarlGrey selectElementWithMatcher:test_page_matcher] performAction:link_tap]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:4]); + [ChromeEarlGrey waitForMainTabCount:4]; } // Tests a window.open by assigning to window.location. - (void)testWindowOpenAndAssignToHref { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID: - @"webScenarioWindowOpenTabWithAssignmentToHref"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenTabWithAssignmentToHref"]; + [ChromeEarlGrey waitForMainTabCount:2]; } // Tests that opening a window and calling window.location.assign works. - (void)testWindowOpenAndCallLocationAssign { // Open a child tab. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioWindowOpenAndCallLocationAssign"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenAndCallLocationAssign"]; + [ChromeEarlGrey waitForMainTabCount:2]; // Ensure that the resulting tab is updated as expected. const GURL targetURL = @@ -172,9 +162,9 @@ // completes and causes a navigation. (Reduced test case from actual site.) - (void)testWindowOpenAndSetLocation { // Open a child tab. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioWindowOpenAndSetLocation"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenAndSetLocation"]; + [ChromeEarlGrey waitForMainTabCount:2]; // Ensure that the resulting tab is updated as expected. const GURL targetURL = @@ -187,9 +177,9 @@ // Tests a button that invokes window.open() with "_blank" target parameter. - (void)testWindowOpenWithBlankTarget { - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioWindowOpenWithBlankTarget"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenWithBlankTarget"]; + [ChromeEarlGrey waitForMainTabCount:2]; } // Tests that opening a window with target=_blank which closes itself after 1 @@ -200,33 +190,32 @@ performAction:web::WebViewTapElement( GetCurrentWebState(), [ElementSelector selectorWithElementID:ID])]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey waitForMainTabCount:2]; base::test::ios::SpinRunLoopWithMinDelay(base::TimeDelta::FromSecondsD(1)); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey waitForMainTabCount:1]; } // Tests a window.open used in a <button onClick> element. - (void)testWindowOpenWithButtonOnClick { - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioWindowOpenWithButtonOnClick"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenWithButtonOnClick"]; + [ChromeEarlGrey waitForMainTabCount:2]; } // Tests a button that invokes window.open with an empty target parameter. - (void)testWindowOpenWithEmptyTarget { - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioWindowOpenWithEmptyTarget"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenWithEmptyTarget"]; + [ChromeEarlGrey waitForMainTabCount:2]; } // Tests that the correct URL is displayed for a child window opened with the // script window.open('', '').location.replace('about:blank#hash'). // This is a regression test for crbug.com/866142. - (void)testLocationReplaceInWindowOpenWithEmptyTarget { - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID: - @"webScenarioLocationReplaceInWindowOpenWithEmptyTarget"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey tapWebStateElementWithID: + @"webScenarioLocationReplaceInWindowOpenWithEmptyTarget"]; + [ChromeEarlGrey waitForMainTabCount:2]; // WebKit doesn't parse 'about:blank#hash' as about:blank with URL fragment. // Instead, it percent encodes '#hash' and considers 'blank%23hash' as the // resource identifier. Nevertheless, the '#' is significant in triggering the @@ -238,25 +227,25 @@ // Tests a link with JavaScript in the href. + (void)testWindowOpenWithJavaScriptInHref { - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioWindowOpenWithJavaScriptInHref"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenWithJavaScriptInHref"]; + [ChromeEarlGrey waitForMainTabCount:2]; } // Tests a window.open by running Meta-Refresh. - (void)testWindowOpenWithMetaRefresh { - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioWindowOpenWithMetaRefresh"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenWithMetaRefresh"]; + [ChromeEarlGrey waitForMainTabCount:2]; } // Tests that a link with an onclick that opens a tab and calls preventDefault // opens the tab, but doesn't navigate the main tab. - (void)testWindowOpenWithPreventDefaultLink { // Open a child tab. - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioWindowOpenWithPreventDefaultLink"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioWindowOpenWithPreventDefaultLink"]; + [ChromeEarlGrey waitForMainTabCount:2]; // Ensure that the starting tab hasn't navigated. [ChromeEarlGrey closeCurrentTab]; @@ -267,21 +256,19 @@ // Tests that closing the current window using DOM fails. - (void)testCloseWindowNotOpenByDOM { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey tapWebStateElementWithID:@"webScenarioWindowClose"]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:1]); + [ChromeEarlGrey tapWebStateElementWithID:@"webScenarioWindowClose"]; + [ChromeEarlGrey waitForMainTabCount:1]; } // Tests that popup blocking works when a popup is injected into a window before // its initial load is committed. - (void)testBlockPopupInjectedIntoOpenedWindow { - CHROME_EG_ASSERT_NO_ERROR( - [ChromeEarlGrey setContentSettings:CONTENT_SETTING_BLOCK]); - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey - tapWebStateElementWithID:@"webScenarioOpenWindowAndInjectPopup"]); + [ChromeEarlGrey setContentSettings:CONTENT_SETTING_BLOCK]; + [ChromeEarlGrey + tapWebStateElementWithID:@"webScenarioOpenWindowAndInjectPopup"]; [[EarlGrey selectElementWithMatcher:PopupBlocker()] assertWithMatcher:grey_notNil()]; - CHROME_EG_ASSERT_NO_ERROR([ChromeEarlGrey waitForMainTabCount:2]); + [ChromeEarlGrey waitForMainTabCount:2]; } @end
diff --git a/ios/public/provider/chrome/browser/signin/chrome_identity_service.h b/ios/public/provider/chrome/browser/signin/chrome_identity_service.h index afcf72f58..b12eddb 100644 --- a/ios/public/provider/chrome/browser/signin/chrome_identity_service.h +++ b/ios/public/provider/chrome/browser/signin/chrome_identity_service.h
@@ -25,6 +25,7 @@ @class UIApplication; @class UIImage; @class UINavigationController; +@class UIViewController; namespace ios { @@ -52,6 +53,11 @@ // the device is blocked. typedef void (^MDMStatusCallback)(bool is_blocked); +// Callback to dismiss Web and App settings details view. No-op, if this block +// is more than once. +// |animated| the view will be dismissed with animation if the value is YES. +typedef void (^DismissWebAndAppSettingDetailsControllerBlock)(BOOL animated); + // Opaque type representing the MDM (Mobile Device Management) status of the // device. Checking for equality is guaranteed to be valid. typedef int MDMDeviceStatus; @@ -110,6 +116,13 @@ ChromeIdentity* identity, id<ChromeIdentityBrowserOpener> browser_opener); + // Not implemented yet. Please use CreateWebAndAppSettingDetailsController(). + // See: crbug.com/905680. + virtual DismissWebAndAppSettingDetailsControllerBlock + PresentWebAndAppSettingDetailsController(ChromeIdentity* identity, + UIViewController* viewController, + BOOL animated); + // Returns a new ChromeIdentityInteractionManager with |delegate| as its // delegate. virtual ChromeIdentityInteractionManager*
diff --git a/ios/public/provider/chrome/browser/signin/chrome_identity_service.mm b/ios/public/provider/chrome/browser/signin/chrome_identity_service.mm index a6f1f58..d90db5d8 100644 --- a/ios/public/provider/chrome/browser/signin/chrome_identity_service.mm +++ b/ios/public/provider/chrome/browser/signin/chrome_identity_service.mm
@@ -40,6 +40,14 @@ return nil; } +DismissWebAndAppSettingDetailsControllerBlock +ChromeIdentityService::PresentWebAndAppSettingDetailsController( + ChromeIdentity* identity, + UIViewController* viewController, + BOOL animated) { + return nil; +} + ChromeIdentityInteractionManager* ChromeIdentityService::CreateChromeIdentityInteractionManager( ios::ChromeBrowserState* browser_state,
diff --git a/ios/web/init/ios_global_state.mm b/ios/web/init/ios_global_state.mm index f0a4b53..a8bb7df5 100644 --- a/ios/web/init/ios_global_state.mm +++ b/ios/web/init/ios_global_state.mm
@@ -7,8 +7,8 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/memory/ptr_util.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_current.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/initialization_util.h" #include "net/base/network_change_notifier.h" @@ -19,7 +19,7 @@ namespace { base::AtExitManager* g_exit_manager = nullptr; -base::MessageLoopForUI* g_message_loop = nullptr; +base::SingleThreadTaskExecutor* g_task_executor = nullptr; net::NetworkChangeNotifier* g_network_change_notifer = nullptr; } // namespace @@ -38,21 +38,21 @@ }); } -void BuildMessageLoop() { +void BuildSingleThreadTaskExecutor() { static dispatch_once_t once_token; dispatch_once(&once_token, ^{ - // Create a MessageLoop if one does not already exist for the current - // thread. + // Create a SingleThreadTaskExecutor if one does not already exist for the + // current thread. if (!base::MessageLoopCurrent::Get()) { - g_message_loop = new base::MessageLoopForUI(); + g_task_executor = + new base::SingleThreadTaskExecutor(base::MessagePump::Type::UI); } - base::MessageLoopCurrentForUI::Get()->Attach(); }); } -void DestroyMessageLoop() { - delete g_message_loop; - g_message_loop = nullptr; +void DestroySingleThreadTaskExecutor() { + delete g_task_executor; + g_task_executor = nullptr; } void CreateNetworkChangeNotifier() { @@ -86,8 +86,8 @@ g_exit_manager = nullptr; } -base::MessageLoop* GetMainThreadMessageLoop() { - return g_message_loop; +base::SingleThreadTaskExecutor* GetMainThreadTaskExecutor() { + return g_task_executor; } } // namespace ios_global_state
diff --git a/ios/web/init/web_main_loop.h b/ios/web/init/web_main_loop.h index 6e46617..13c8fe8 100644 --- a/ios/web/init/web_main_loop.h +++ b/ios/web/init/web_main_loop.h
@@ -64,9 +64,10 @@ bool created_threads_; // Members initialized in |MainMessageLoopStart()| --------------------------- - // The MessageLoop and NetworkChangeNotifier are not owned by the WebMainLoop - // but still need to be destroyed in correct order so use ScopedClosureRunner. - base::ScopedClosureRunner destroy_message_loop_; + // The SingleThreadTaskExecutor and NetworkChangeNotifier are not owned by the + // WebMainLoop but still need to be destroyed in correct order so use + // ScopedClosureRunner. + base::ScopedClosureRunner destroy_task_executor_; std::unique_ptr<base::PowerMonitor> power_monitor_; base::ScopedClosureRunner destroy_network_change_notifier_;
diff --git a/ios/web/init/web_main_loop.mm b/ios/web/init/web_main_loop.mm index 4ff9439..f158cf4 100644 --- a/ios/web/init/web_main_loop.mm +++ b/ios/web/init/web_main_loop.mm
@@ -11,13 +11,13 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/metrics/histogram_macros.h" #include "base/path_service.h" #include "base/power_monitor/power_monitor.h" #include "base/power_monitor/power_monitor_device_source.h" #include "base/process/process_metrics.h" #include "base/task/post_task.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/threading/thread_restrictions.h" #import "ios/web/net/cookie_notification_bridge.h" @@ -45,9 +45,10 @@ WebMainLoop::WebMainLoop() : result_code_(0), created_threads_(false), - destroy_message_loop_(base::Bind(&ios_global_state::DestroyMessageLoop)), + destroy_task_executor_( + base::BindOnce(&ios_global_state::DestroySingleThreadTaskExecutor)), destroy_network_change_notifier_( - base::Bind(&ios_global_state::DestroyNetworkChangeNotifier)) { + base::BindOnce(&ios_global_state::DestroyNetworkChangeNotifier)) { DCHECK(!g_current_web_main_loop); g_current_web_main_loop = this; } @@ -73,7 +74,7 @@ parts_->PreMainMessageLoopStart(); } - ios_global_state::BuildMessageLoop(); + ios_global_state::BuildSingleThreadTaskExecutor(); InitializeMainThread(); @@ -121,7 +122,7 @@ ios_global_state::StartThreadPool(); base::Thread::Options io_message_loop_options; - io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO; + io_message_loop_options.message_loop_type = base::MessagePump::Type::IO; io_thread_ = std::make_unique<WebSubThread>(WebThread::IO); if (!io_thread_->StartWithOptions(io_message_loop_options)) LOG(FATAL) << "Failed to start WebThread::IO"; @@ -205,7 +206,7 @@ DCHECK(base::ThreadTaskRunnerHandle::IsSet()); main_thread_.reset(new WebThreadImpl( WebThread::UI, - ios_global_state::GetMainThreadMessageLoop()->task_runner())); + ios_global_state::GetMainThreadTaskExecutor()->task_runner())); } int WebMainLoop::WebThreadsStarted() {
diff --git a/ios/web/navigation/BUILD.gn b/ios/web/navigation/BUILD.gn index 3980511d..0be37f14 100644 --- a/ios/web/navigation/BUILD.gn +++ b/ios/web/navigation/BUILD.gn
@@ -46,6 +46,9 @@ "crw_session_controller+private_constructors.h", "crw_session_controller.h", "crw_session_controller.mm", + "crw_web_view_navigation_observer.h", + "crw_web_view_navigation_observer.mm", + "crw_web_view_navigation_observer_delegate.h", "crw_wk_navigation_handler.h", "crw_wk_navigation_handler.mm", "crw_wk_navigation_states.h",
diff --git a/ios/web/navigation/crw_web_view_navigation_observer.h b/ios/web/navigation/crw_web_view_navigation_observer.h new file mode 100644 index 0000000..7ecebee --- /dev/null +++ b/ios/web/navigation/crw_web_view_navigation_observer.h
@@ -0,0 +1,23 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_WEB_NAVIGATION_CRW_WEB_VIEW_NAVIGATION_OBSERVER_H_ +#define IOS_WEB_NAVIGATION_CRW_WEB_VIEW_NAVIGATION_OBSERVER_H_ + +#import <WebKit/WebKit.h> + +@protocol CRWWebViewNavigationObserverDelegate; + +// Observes the navigation-related events of a WebView, making sure that the +// different navigaiton events are taken into account. +@interface CRWWebViewNavigationObserver : NSObject + +@property(nonatomic, weak) id<CRWWebViewNavigationObserverDelegate> delegate; + +// The webView to observe. +@property(nonatomic, weak) WKWebView* webView; + +@end + +#endif // IOS_WEB_NAVIGATION_CRW_WEB_VIEW_NAVIGATION_OBSERVER_H_
diff --git a/ios/web/navigation/crw_web_view_navigation_observer.mm b/ios/web/navigation/crw_web_view_navigation_observer.mm new file mode 100644 index 0000000..696990a0 --- /dev/null +++ b/ios/web/navigation/crw_web_view_navigation_observer.mm
@@ -0,0 +1,224 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/web/navigation/crw_web_view_navigation_observer.h" + +#include "base/logging.h" +#include "base/strings/sys_string_conversions.h" +#import "ios/net/http_response_headers_util.h" +#include "ios/web/common/features.h" +#include "ios/web/common/url_util.h" +#import "ios/web/navigation/crw_navigation_item_holder.h" +#import "ios/web/navigation/crw_pending_navigation_info.h" +#import "ios/web/navigation/crw_web_view_navigation_observer_delegate.h" +#import "ios/web/navigation/crw_wk_navigation_handler.h" +#import "ios/web/navigation/crw_wk_navigation_states.h" +#import "ios/web/navigation/navigation_context_impl.h" +#import "ios/web/navigation/wk_navigation_util.h" +#import "ios/web/public/web_client.h" +#import "ios/web/web_state/web_state_impl.h" +#import "ios/web/web_view/wk_web_view_util.h" +#import "net/base/mac/url_conversions.h" +#include "url/gurl.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +using web::NavigationManagerImpl; + +using web::wk_navigation_util::IsRestoreSessionUrl; +using web::wk_navigation_util::IsPlaceholderUrl; + +@interface CRWWebViewNavigationObserver () + +// Dictionary where keys are the names of WKWebView properties and values are +// selector names which should be called when a corresponding property has +// changed. e.g. @{ @"URL" : @"webViewURLDidChange" } means that +// -[self webViewURLDidChange] must be called every time when WKWebView.URL is +// changed. +@property(weak, nonatomic, readonly) NSDictionary* WKWebViewObservers; + +@property(nonatomic, assign, readonly) web::WebStateImpl* webStateImpl; + +// The WKNavigationDelegate handler class. +@property(nonatomic, readonly, strong) + CRWWKNavigationHandler* navigationHandler; + +// The actual URL of the document object (i.e., the last committed URL). +@property(nonatomic, readonly) const GURL& documentURL; + +// The NavigationManagerImpl associated with the web state. +@property(nonatomic, readonly) NavigationManagerImpl* navigationManagerImpl; + +@end + +@implementation CRWWebViewNavigationObserver + +#pragma mark - Property + +- (void)setWebView:(WKWebView*)webView { + for (NSString* keyPath in self.WKWebViewObservers) { + [_webView removeObserver:self forKeyPath:keyPath]; + } + + _webView = webView; + + for (NSString* keyPath in self.WKWebViewObservers) { + [_webView addObserver:self forKeyPath:keyPath options:0 context:nullptr]; + } +} + +- (NSDictionary*)WKWebViewObservers { + return @{ + @"estimatedProgress" : @"webViewEstimatedProgressDidChange", + @"loading" : @"webViewLoadingStateDidChange", + @"canGoForward" : @"webViewBackForwardStateDidChange", + @"canGoBack" : @"webViewBackForwardStateDidChange" + }; +} + +- (NavigationManagerImpl*)navigationManagerImpl { + return self.webStateImpl ? &(self.webStateImpl->GetNavigationManagerImpl()) + : nil; +} + +- (web::WebStateImpl*)webStateImpl { + return [self.delegate webStateImplForNavigationObserver:self]; +} + +- (CRWWKNavigationHandler*)navigationHandler { + return [self.delegate navigationHandlerForNavigationObserver:self]; +} + +- (const GURL&)documentURL { + return [self.delegate documentURLForNavigationObserver:self]; +} + +#pragma mark - KVO Observation + +- (void)observeValueForKeyPath:(NSString*)keyPath + ofObject:(id)object + change:(NSDictionary*)change + context:(void*)context { + NSString* dispatcherSelectorName = self.WKWebViewObservers[keyPath]; + DCHECK(dispatcherSelectorName); + if (dispatcherSelectorName) { + // With ARC memory management, it is not known what a method called + // via a selector will return. If a method returns a retained value + // (e.g. NS_RETURNS_RETAINED) that returned object will leak as ARC is + // unable to property insert the correct release calls for it. + // All selectors used here return void and take no parameters so it's safe + // to call a function mapping to the method implementation manually. + SEL selector = NSSelectorFromString(dispatcherSelectorName); + IMP methodImplementation = [self methodForSelector:selector]; + if (methodImplementation) { + void (*methodCallFunction)(id, SEL) = + reinterpret_cast<void (*)(id, SEL)>(methodImplementation); + methodCallFunction(self, selector); + } + } +} + +// Called when WKWebView estimatedProgress has been changed. +- (void)webViewEstimatedProgressDidChange { + if (![self.delegate webViewIsBeingDestroyed:self]) { + self.webStateImpl->SendChangeLoadProgress(self.webView.estimatedProgress); + } +} + +// Called when WKWebView loading state has been changed. +- (void)webViewLoadingStateDidChange { + if (self.webView.loading) + return; + + GURL webViewURL = net::GURLWithNSURL(self.webView.URL); + + if (![self.navigationHandler isCurrentNavigationBackForward]) + return; + + web::NavigationContextImpl* existingContext = [self.navigationHandler + contextForPendingMainFrameNavigationWithURL:webViewURL]; + + // When traversing history restored from a previous session, WKWebView does + // not fire 'pageshow', 'onload', 'popstate' or any of the + // WKNavigationDelegate callbacks for back/forward navigation from an about: + // scheme placeholder URL to another entry or if either of the redirect fails + // to load (e.g. in airplane mode). Loading state KVO is the only observable + // event in this scenario, so force a reload to trigger redirect from + // restore_session.html to the restored URL. + bool previousURLHasAboutScheme = + self.documentURL.SchemeIs(url::kAboutScheme) || + IsPlaceholderUrl(self.documentURL) || + web::GetWebClient()->IsAppSpecificURL(self.documentURL); + bool is_back_forward_navigation = + existingContext && + (existingContext->GetPageTransition() & ui::PAGE_TRANSITION_FORWARD_BACK); + if (web::GetWebClient()->IsSlimNavigationManagerEnabled() && + IsRestoreSessionUrl(webViewURL)) { + if (previousURLHasAboutScheme || is_back_forward_navigation) { + [self.webView reload]; + self.navigationHandler.navigationState = + web::WKNavigationState::REQUESTED; + return; + } + } + + // For failed navigations, WKWebView will sometimes revert to the previous URL + // before committing the current navigation or resetting the web view's + // |isLoading| property to NO. If this is the first navigation for the web + // view, this will result in an empty URL. + BOOL navigationWasCommitted = self.navigationHandler.navigationState != + web::WKNavigationState::REQUESTED; + if (!navigationWasCommitted && + (webViewURL.is_empty() || webViewURL == self.documentURL)) { + return; + } + + if (!navigationWasCommitted && + !self.navigationHandler.pendingNavigationInfo.cancelled) { + // A fast back-forward navigation does not call |didCommitNavigation:|, so + // signal page change explicitly. + DCHECK_EQ(self.documentURL.GetOrigin(), webViewURL.GetOrigin()); + BOOL isSameDocumentNavigation = + [self.delegate navigationObserver:self + isURLChangeSameDocumentNavigation:webViewURL]; + + [self.delegate navigationObserver:self + didChangeDocumentURL:webViewURL + forContext:existingContext]; + if (!existingContext) { + // This URL was not seen before, so register new load request. + [self.delegate navigationObserver:self + didLoadNewURL:webViewURL + forSameDocumentNavigation:isSameDocumentNavigation]; + } else { + // Same document navigation does not contain response headers. + net::HttpResponseHeaders* headers = + isSameDocumentNavigation + ? nullptr + : self.webStateImpl->GetHttpResponseHeaders(); + existingContext->SetResponseHeaders(headers); + existingContext->SetIsSameDocument(isSameDocumentNavigation); + existingContext->SetHasCommitted(!isSameDocumentNavigation); + self.webStateImpl->OnNavigationStarted(existingContext); + [self.delegate navigationObserver:self + didChangePageWithContext:existingContext]; + self.webStateImpl->OnNavigationFinished(existingContext); + } + } + + [self.delegate navigationObserverDidChangeSSLStatus:self]; + [self.delegate navigationObserver:self didFinishNavigation:existingContext]; +} + +// Called when WKWebView canGoForward/canGoBack state has been changed. +- (void)webViewBackForwardStateDidChange { + // Don't trigger for LegacyNavigationManager because its back/foward state + // doesn't always match that of WKWebView. + if (web::GetWebClient()->IsSlimNavigationManagerEnabled()) + self.webStateImpl->OnBackForwardStateChanged(); +} + +@end
diff --git a/ios/web/navigation/crw_web_view_navigation_observer_delegate.h b/ios/web/navigation/crw_web_view_navigation_observer_delegate.h new file mode 100644 index 0000000..1ffd9f7 --- /dev/null +++ b/ios/web/navigation/crw_web_view_navigation_observer_delegate.h
@@ -0,0 +1,68 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_WEB_NAVIGATION_CRW_WEB_VIEW_NAVIGATION_OBSERVER_DELEGATE_H_ +#define IOS_WEB_NAVIGATION_CRW_WEB_VIEW_NAVIGATION_OBSERVER_DELEGATE_H_ + +@class CRWWebViewNavigationObserver; +@class CRWWKNavigationHandler; +class GURL; +namespace web { +class NavigationContextImpl; +class WebStateImpl; +} + +// Delegate for the NavigationObserver. +@protocol CRWWebViewNavigationObserverDelegate + +// Whether the the web view is being closed. +- (BOOL)webViewIsBeingDestroyed: + (CRWWebViewNavigationObserver*)navigationObserver; + +// The WebState. +- (web::WebStateImpl*)webStateImplForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver; + +// The navigation handler +- (CRWWKNavigationHandler*)navigationHandlerForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver; + +// The actual URL of the document object. +- (const GURL&)documentURLForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver; + +// Notifies the delegate that the SSL status of the web view changed. +- (void)navigationObserverDidChangeSSLStatus: + (CRWWebViewNavigationObserver*)navigationObserver; + +// Notifies the delegate that the navigation has finished. Navigation is +// considered complete when the document has finished loading, or when other +// page load mechanics are completed on a non-document-changing URL change. +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didFinishNavigation:(web::NavigationContextImpl*)context; + +// Notifies the delegate that the URL of the document object changed. +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didChangeDocumentURL:(const GURL&)documentURL + forContext:(web::NavigationContextImpl*)context; + +// Called when the web page has changed document and/or URL, and so the page +// navigation should be reported. |context| contains information about the +// navigation that triggered the document/URL change. +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didChangePageWithContext:(web::NavigationContextImpl*)context; + +// Notifies the delegate that the webView has started a new navigation to +// |webViewURL| and whether it |isSameDocumentNavigation|. +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didLoadNewURL:(const GURL&)webViewURL + forSameDocumentNavigation:(BOOL)isSameDocumentNavigation; + +// Returns whether the navigation to |URL| is a navigation in the same document. +- (BOOL)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + isURLChangeSameDocumentNavigation:(const GURL&)URL; + +@end + +#endif // IOS_WEB_NAVIGATION_CRW_WEB_VIEW_NAVIGATION_OBSERVER_DELEGATE_H_
diff --git a/ios/web/navigation/crw_wk_navigation_handler.mm b/ios/web/navigation/crw_wk_navigation_handler.mm index a69f5ad..3d7b6d78 100644 --- a/ios/web/navigation/crw_wk_navigation_handler.mm +++ b/ios/web/navigation/crw_wk_navigation_handler.mm
@@ -58,8 +58,24 @@ // Cache holds errors only for pending navigations, so the actual number of // stored errors is not expected to be high. const web::CertVerificationErrorsCacheType::size_type kMaxCertErrorsCount = 100; + +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum class OutOfSyncURLAction { + kNoAction = 0, + kGoBack = 1, + kGoForward = 2, + kMaxValue = kGoForward, +}; + +void ReportOutOfSyncURLInDidStartProvisionalNavigation( + OutOfSyncURLAction action) { + UMA_HISTOGRAM_ENUMERATION( + "WebController.BackForwardListOutOfSyncInProvisionalNavigation", action); } +} // namespace + @interface CRWWKNavigationHandler () { // Used to poll for a SafeBrowsing warning being displayed. This is created in // |decidePolicyForNavigationAction| and destroyed once any of the following @@ -534,13 +550,37 @@ return; } - if (!context->IsPlaceholderNavigation() && - context->GetUrl() != webViewURL) { - // Update last seen URL because it may be changed by WKWebView (f.e. by - // performing characters escaping). + if (!context->IsPlaceholderNavigation() && !IsWKInternalUrl(webViewURL)) { web::NavigationItem* item = web::GetItemWithUniqueID(self.navigationManagerImpl, context); - if (!IsWKInternalUrl(webViewURL)) { + if (item) { + web::WKBackForwardListItemHolder* itemHolder = + web::WKBackForwardListItemHolder::FromNavigationItem(item); + if (itemHolder->navigation_type() == WKNavigationTypeBackForward && + ![webView.backForwardList.currentItem.URL isEqual:webView.URL]) { + // Sometimes on back/forward navigation, the backforward list is out + // of sync with the webView. Go back or forward to fix it. See + // crbug.com/968539. + if ([webView.backForwardList.backItem.URL isEqual:webView.URL]) { + ReportOutOfSyncURLInDidStartProvisionalNavigation( + OutOfSyncURLAction::kGoBack); + [webView goBack]; + return; + } + if ([webView.backForwardList.forwardItem.URL isEqual:webView.URL]) { + ReportOutOfSyncURLInDidStartProvisionalNavigation( + OutOfSyncURLAction::kGoForward); + [webView goForward]; + return; + } + ReportOutOfSyncURLInDidStartProvisionalNavigation( + OutOfSyncURLAction::kNoAction); + } + } + + if (context->GetUrl() != webViewURL) { + // Update last seen URL because it may be changed by WKWebView (f.e. + // by performing characters escaping). if (item) { // Item may not exist if navigation was stopped (see // crbug.com/969915). @@ -549,6 +589,7 @@ context->SetUrl(webViewURL); } } + self.webStateImpl->OnNavigationStarted(context); return; }
diff --git a/ios/web/public/init/ios_global_state.h b/ios/web/public/init/ios_global_state.h index 69ca3a9..6f13d91 100644 --- a/ios/web/public/init/ios_global_state.h +++ b/ios/web/public/init/ios_global_state.h
@@ -8,7 +8,7 @@ #include "base/task/thread_pool/thread_pool.h" namespace base { -class MessageLoop; +class SingleThreadTaskExecutor; } namespace ios_global_state { @@ -38,13 +38,13 @@ // call. void Create(const CreateParams& create_params); -// Creates a message loop for the UI thread and attaches it. It is safe to call +// Creates a task executor for the UI thread and attaches it. It is safe to call // this method more than once, the initialization will only be performed once. -void BuildMessageLoop(); +void BuildSingleThreadTaskExecutor(); -// Destroys the message loop create by BuildMessageLoop. It is safe to call -// multiple time. -void DestroyMessageLoop(); +// Destroys the message loop create by BuildSingleThreadTaskExecutor. It is safe +// to call multiple times. +void DestroySingleThreadTaskExecutor(); // Creates a network change notifier. It is safe to call this method more than // once, the initialization will only be performed once. @@ -65,8 +65,8 @@ // AtExitManager will be destroyed on the first call. void DestroyAtExitManager(); -// Returns message loop for the UI thread. -base::MessageLoop* GetMainThreadMessageLoop(); +// Returns SingleThreadTaskExecutor for the UI thread. +base::SingleThreadTaskExecutor* GetMainThreadTaskExecutor(); } // namespace ios_global_state
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index cff9892..de9a7561 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -55,6 +55,8 @@ #import "ios/web/js_messaging/web_frames_manager_impl.h" #import "ios/web/navigation/crw_navigation_item_holder.h" #import "ios/web/navigation/crw_pending_navigation_info.h" +#import "ios/web/navigation/crw_web_view_navigation_observer.h" +#import "ios/web/navigation/crw_web_view_navigation_observer_delegate.h" #import "ios/web/navigation/crw_wk_navigation_handler.h" #import "ios/web/navigation/crw_wk_navigation_states.h" #include "ios/web/navigation/error_retry_state_machine.h" @@ -192,10 +194,11 @@ CRWSSLStatusUpdaterDataSource, CRWSSLStatusUpdaterDelegate, CRWWebControllerContainerViewDelegate, + CRWWebViewNavigationObserverDelegate, CRWWebViewScrollViewProxyObserver, - WKNavigationDelegate, CRWWKNavigationHandlerDelegate, - CRWWKUIHandlerDelegate> { + CRWWKUIHandlerDelegate, + WKNavigationDelegate> { // The view used to display content. Must outlive |_webViewProxy|. The // container view should be accessed through this property rather than // |self.view| from within this class, as |self.view| triggers creation while @@ -263,6 +266,10 @@ @property(nonatomic, readwrite) web::PageDisplayState pageDisplayState; @property(nonatomic, strong) CRWLegacyNativeContentController* legacyNativeController; + +@property(nonatomic, strong, readonly) + CRWWebViewNavigationObserver* webViewNavigationObserver; + // Dictionary where keys are the names of WKWebView properties and values are // selector names which should be called when a corresponding property has // changed. e.g. @{ @"URL" : @"webViewURLDidChange" } means that @@ -449,6 +456,9 @@ _UIHandler = [[CRWWKUIHandler alloc] init]; _UIHandler.delegate = self; + + _webViewNavigationObserver = [[CRWWebViewNavigationObserver alloc] init]; + _webViewNavigationObserver.delegate = self; } return self; } @@ -575,6 +585,7 @@ for (NSString* keyPath in self.WKWebViewObservers) { [_webView addObserver:self forKeyPath:keyPath options:0 context:nullptr]; } + self.webViewNavigationObserver.webView = _webView; _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures; [self setDocumentURL:_defaultURL context:nullptr]; @@ -625,13 +636,9 @@ - (NSDictionary*)WKWebViewObservers { return @{ @"serverTrust" : @"webViewSecurityFeaturesDidChange", - @"estimatedProgress" : @"webViewEstimatedProgressDidChange", @"hasOnlySecureContent" : @"webViewSecurityFeaturesDidChange", @"title" : @"webViewTitleDidChange", - @"loading" : @"webViewLoadingStateDidChange", @"URL" : @"webViewURLDidChange", - @"canGoForward" : @"webViewBackForwardStateDidChange", - @"canGoBack" : @"webViewBackForwardStateDidChange" }; } @@ -3135,13 +3142,6 @@ } } -// Called when WKWebView estimatedProgress has been changed. -- (void)webViewEstimatedProgressDidChange { - if (!_isBeingDestroyed) { - self.webStateImpl->SendChangeLoadProgress(self.webView.estimatedProgress); - } -} - // Called when WKWebView certificateChain or hasOnlySecureContent property has // changed. - (void)webViewSecurityFeaturesDidChange { @@ -3154,102 +3154,6 @@ [self updateSSLStatusForCurrentNavigationItem]; } -// Called when WKWebView loading state has been changed. -- (void)webViewLoadingStateDidChange { - if (self.webView.loading) - return; - - GURL webViewURL = net::GURLWithNSURL(self.webView.URL); - - if (![self.navigationHandler isCurrentNavigationBackForward]) - return; - - web::NavigationContextImpl* existingContext = [self.navigationHandler - contextForPendingMainFrameNavigationWithURL:webViewURL]; - - // When traversing history restored from a previous session, WKWebView does - // not fire 'pageshow', 'onload', 'popstate' or any of the - // WKNavigationDelegate callbacks for back/forward navigation from an about: - // scheme placeholder URL to another entry or if either of the redirect fails - // to load (e.g. in airplane mode). Loading state KVO is the only observable - // event in this scenario, so force a reload to trigger redirect from - // restore_session.html to the restored URL. - bool previousURLHasAboutScheme = - _documentURL.SchemeIs(url::kAboutScheme) || - IsPlaceholderUrl(_documentURL) || - web::GetWebClient()->IsAppSpecificURL(_documentURL); - bool is_back_forward_navigation = - existingContext && - (existingContext->GetPageTransition() & ui::PAGE_TRANSITION_FORWARD_BACK); - if (web::GetWebClient()->IsSlimNavigationManagerEnabled() && - IsRestoreSessionUrl(webViewURL)) { - if (previousURLHasAboutScheme || is_back_forward_navigation) { - [self.webView reload]; - self.navigationHandler.navigationState = - web::WKNavigationState::REQUESTED; - return; - } - } - - // For failed navigations, WKWebView will sometimes revert to the previous URL - // before committing the current navigation or resetting the web view's - // |isLoading| property to NO. If this is the first navigation for the web - // view, this will result in an empty URL. - BOOL navigationWasCommitted = self.navigationHandler.navigationState != - web::WKNavigationState::REQUESTED; - if (!navigationWasCommitted && - (webViewURL.is_empty() || webViewURL == _documentURL)) { - return; - } - - if (!navigationWasCommitted && - !self.navigationHandler.pendingNavigationInfo.cancelled) { - // A fast back-forward navigation does not call |didCommitNavigation:|, so - // signal page change explicitly. - DCHECK_EQ(_documentURL.GetOrigin(), webViewURL.GetOrigin()); - BOOL isSameDocumentNavigation = - [self isKVOChangePotentialSameDocumentNavigationToURL:webViewURL]; - - [self setDocumentURL:webViewURL context:existingContext]; - if (!existingContext) { - // This URL was not seen before, so register new load request. - std::unique_ptr<web::NavigationContextImpl> newContext = - [self registerLoadRequestForURL:webViewURL - sameDocumentNavigation:isSameDocumentNavigation - hasUserGesture:NO - rendererInitiated:YES - placeholderNavigation:IsPlaceholderUrl(webViewURL)]; - [self.navigationHandler webPageChangedWithContext:newContext.get() - webView:self.webView]; - newContext->SetHasCommitted(!isSameDocumentNavigation); - self.webStateImpl->OnNavigationFinished(newContext.get()); - // TODO(crbug.com/792515): It is OK, but very brittle, to call - // |didFinishNavigation:| here because the gating condition is mutually - // exclusive with the condition below. Refactor this method after - // deprecating self.navigationHandler.pendingNavigationInfo. - if (newContext->GetWKNavigationType() == WKNavigationTypeBackForward) { - [self didFinishNavigation:newContext.get()]; - } - } else { - // Same document navigation does not contain response headers. - net::HttpResponseHeaders* headers = - isSameDocumentNavigation - ? nullptr - : self.webStateImpl->GetHttpResponseHeaders(); - existingContext->SetResponseHeaders(headers); - existingContext->SetIsSameDocument(isSameDocumentNavigation); - existingContext->SetHasCommitted(!isSameDocumentNavigation); - self.webStateImpl->OnNavigationStarted(existingContext); - [self.navigationHandler webPageChangedWithContext:existingContext - webView:self.webView]; - self.webStateImpl->OnNavigationFinished(existingContext); - } - } - - [self updateSSLStatusForCurrentNavigationItem]; - [self didFinishNavigation:existingContext]; -} - // Called when WKWebView title has been changed. - (void)webViewTitleDidChange { // WKWebView's title becomes empty when the web process dies; ignore that @@ -3275,14 +3179,6 @@ } } -// Called when WKWebView canGoForward/canGoBack state has been changed. -- (void)webViewBackForwardStateDidChange { - // Don't trigger for LegacyNavigationManager because its back/foward state - // doesn't always match that of WKWebView. - if (web::GetWebClient()->IsSlimNavigationManagerEnabled()) - self.webStateImpl->OnBackForwardStateChanged(); -} - // Called when WKWebView URL has been changed. - (void)webViewURLDidChange { // TODO(stuartmorgan): Determine if there are any cases where this still @@ -3557,6 +3453,77 @@ } } +#pragma mark - CRWWebViewNavigationObserverDelegate + +- (BOOL)webViewIsBeingDestroyed: + (CRWWebViewNavigationObserver*)navigationObserver { + return _isBeingDestroyed; +} + +- (web::WebStateImpl*)webStateImplForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver { + return self.webStateImpl; +} + +- (CRWWKNavigationHandler*)navigationHandlerForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver { + return self.navigationHandler; +} + +- (const GURL&)documentURLForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver { + return _documentURL; +} + +- (void)navigationObserverDidChangeSSLStatus: + (CRWWebViewNavigationObserver*)navigationObserver { + [self updateSSLStatusForCurrentNavigationItem]; +} + +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didFinishNavigation:(web::NavigationContextImpl*)context { + [self didFinishNavigation:context]; +} + +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didChangeDocumentURL:(const GURL&)documentURL + forContext:(web::NavigationContextImpl*)context { + [self setDocumentURL:documentURL context:context]; +} + +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didChangePageWithContext:(web::NavigationContextImpl*)context { + [self.navigationHandler webPageChangedWithContext:context + webView:self.webView]; +} + +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didLoadNewURL:(const GURL&)webViewURL + forSameDocumentNavigation:(BOOL)isSameDocumentNavigation { + std::unique_ptr<web::NavigationContextImpl> newContext = + [self registerLoadRequestForURL:webViewURL + sameDocumentNavigation:isSameDocumentNavigation + hasUserGesture:NO + rendererInitiated:YES + placeholderNavigation:IsPlaceholderUrl(webViewURL)]; + [self.navigationHandler webPageChangedWithContext:newContext.get() + webView:self.webView]; + newContext->SetHasCommitted(!isSameDocumentNavigation); + self.webStateImpl->OnNavigationFinished(newContext.get()); + // TODO(crbug.com/792515): It is OK, but very brittle, to call + // |didFinishNavigation:| here because the gating condition is mutually + // exclusive with the condition below. Refactor this method after + // deprecating self.navigationHandler.pendingNavigationInfo. + if (newContext->GetWKNavigationType() == WKNavigationTypeBackForward) { + [self didFinishNavigation:newContext.get()]; + } +} + +- (BOOL)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + isURLChangeSameDocumentNavigation:(const GURL&)URL { + return [self isKVOChangePotentialSameDocumentNavigationToURL:URL]; +} + #pragma mark - CRWWKNavigationHandlerDelegate - (BOOL)navigationHandlerWebViewBeingDestroyed:
diff --git a/ios/web/web_state/ui/crw_web_controller_unittest.mm b/ios/web/web_state/ui/crw_web_controller_unittest.mm index e5393593..9826e21 100644 --- a/ios/web/web_state/ui/crw_web_controller_unittest.mm +++ b/ios/web/web_state/ui/crw_web_controller_unittest.mm
@@ -220,11 +220,11 @@ OCMStub([result customUserAgent]); OCMStub([static_cast<WKWebView*>(result) loadRequest:OCMOCK_ANY]); OCMStub([result setFrame:GetExpectedWebViewFrame()]); - OCMStub([result addObserver:web_controller() + OCMStub([result addObserver:OCMOCK_ANY forKeyPath:OCMOCK_ANY options:0 context:nullptr]); - OCMStub([result removeObserver:web_controller() forKeyPath:OCMOCK_ANY]); + OCMStub([result removeObserver:OCMOCK_ANY forKeyPath:OCMOCK_ANY]); OCMStub([result evaluateJavaScript:OCMOCK_ANY completionHandler:OCMOCK_ANY]); OCMStub([result allowsBackForwardNavigationGestures]);
diff --git a/ipc/ipc_perftest_util.h b/ipc/ipc_perftest_util.h index 3c9ceeb..7e1f804 100644 --- a/ipc/ipc_perftest_util.h +++ b/ipc/ipc_perftest_util.h
@@ -10,9 +10,9 @@ #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/process/process_metrics.h" #include "base/single_thread_task_runner.h" +#include "base/task/single_thread_task_executor.h" #include "build/build_config.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_listener.h" @@ -89,7 +89,7 @@ int Run(MojoHandle handle); private: - base::MessageLoop main_message_loop_; + base::SingleThreadTaskExecutor main_task_executor_; std::unique_ptr<ChannelReflectorListener> listener_; std::unique_ptr<Channel> channel_; mojo::ScopedMessagePipeHandle handle_;
diff --git a/media/audio/mac/coreaudio_dispatch_override.cc b/media/audio/mac/coreaudio_dispatch_override.cc index 34d1ad2..2e555e1 100644 --- a/media/audio/mac/coreaudio_dispatch_override.cc +++ b/media/audio/mac/coreaudio_dispatch_override.cc
@@ -139,12 +139,6 @@ DCHECK_EQ(g_pause_resume_queue, nullptr); - if (!base::mac::IsAtLeastOS10_10()) { - LogInitResult(RESULT_NOT_SUPPORTED); - return false; - } - - // This function should be available in macOS > 10.10. if (dyld_dynamic_interpose == nullptr) { LOG(ERROR) << "Unable to resolve dyld_dynamic_interpose()"; LogInitResult(RESULT_DYNAMIC_INTERPOSE_NOT_FOUND);
diff --git a/media/cast/test/receiver.cc b/media/cast/test/receiver.cc index 120e179..e3cd07b 100644 --- a/media/cast/test/receiver.cc +++ b/media/cast/test/receiver.cc
@@ -21,10 +21,10 @@ #include "base/containers/circular_deque.h" #include "base/logging.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/default_tick_clock.h" @@ -555,7 +555,7 @@ base::AtExitManager at_exit; base::CommandLine::Init(argc, argv); InitLogging(logging::LoggingSettings()); - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; scoped_refptr<media::cast::CastEnvironment> cast_environment( new media::cast::StandaloneCastEnvironment);
diff --git a/media/cast/test/sender.cc b/media/cast/test/sender.cc index 44860e1..2e730378 100644 --- a/media/cast/test/sender.cc +++ b/media/cast/test/sender.cc
@@ -17,11 +17,11 @@ #include "base/files/file_path.h" #include "base/json/json_writer.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread.h" #include "base/time/default_tick_clock.h" #include "base/values.h" @@ -210,7 +210,7 @@ audio_thread.Start(); video_thread.Start(); - base::MessageLoopForIO io_message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); // Default parameters. base::CommandLine* cmd = base::CommandLine::ForCurrentProcess(); @@ -239,7 +239,7 @@ // Running transport on the main thread. scoped_refptr<media::cast::CastEnvironment> cast_environment( new media::cast::CastEnvironment( - base::DefaultTickClock::GetInstance(), io_message_loop.task_runner(), + base::DefaultTickClock::GetInstance(), io_task_executor.task_runner(), audio_thread.task_runner(), video_thread.task_runner())); // SendProcess initialization. @@ -267,9 +267,9 @@ cast_environment->Clock(), base::TimeDelta::FromSeconds(1), std::make_unique<TransportClient>(cast_environment->logger()), std::make_unique<media::cast::UdpTransportImpl>( - io_message_loop.task_runner(), net::IPEndPoint(), remote_endpoint, - base::Bind(&UpdateCastTransportStatus)), - io_message_loop.task_runner()); + io_task_executor.task_runner(), net::IPEndPoint(), + remote_endpoint, base::Bind(&UpdateCastTransportStatus)), + io_task_executor.task_runner()); // Set up event subscribers. std::unique_ptr<media::cast::EncodingEventSubscriber> video_event_subscriber; @@ -313,7 +313,7 @@ } const int logging_duration_seconds = 10; - io_message_loop.task_runner()->PostDelayedTask( + io_task_executor.task_runner()->PostDelayedTask( FROM_HERE, base::BindOnce(&WriteLogsToFileAndDestroySubscribers, cast_environment, std::move(video_event_subscriber), @@ -321,7 +321,7 @@ std::move(video_log_file), std::move(audio_log_file)), base::TimeDelta::FromSeconds(logging_duration_seconds)); - io_message_loop.task_runner()->PostDelayedTask( + io_task_executor.task_runner()->PostDelayedTask( FROM_HERE, base::BindOnce(&WriteStatsAndDestroySubscribers, cast_environment, std::move(video_stats_subscriber), @@ -332,7 +332,7 @@ // CastSender initialization. std::unique_ptr<media::cast::CastSender> cast_sender = media::cast::CastSender::Create(cast_environment, transport_sender.get()); - io_message_loop.task_runner()->PostTask( + io_task_executor.task_runner()->PostTask( FROM_HERE, base::BindOnce(&media::cast::CastSender::InitializeVideo, base::Unretained(cast_sender.get()), @@ -341,7 +341,7 @@ media::cast::CreateDefaultVideoEncodeAcceleratorCallback(), media::cast::CreateDefaultVideoEncodeMemoryCallback())); base::RunLoop().Run(); // Wait for video initialization. - io_message_loop.task_runner()->PostTask( + io_task_executor.task_runner()->PostTask( FROM_HERE, base::BindOnce(&media::cast::CastSender::InitializeAudio, base::Unretained(cast_sender.get()), audio_config,
diff --git a/media/cast/test/utility/udp_proxy_main.cc b/media/cast/test/utility/udp_proxy_main.cc index 759f7845..d0da3bb 100644 --- a/media/cast/test/utility/udp_proxy_main.cc +++ b/media/cast/test/utility/udp_proxy_main.cc
@@ -13,9 +13,9 @@ #include "base/command_line.h" #include "base/containers/circular_deque.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread_task_runner_handle.h" #include "media/cast/test/utility/udp_proxy.h" #include "net/base/ip_address.h" @@ -209,7 +209,7 @@ media::cast::test::UDPProxy::Create(local_endpoint, remote_endpoint, std::move(in_pipe), std::move(out_pipe), NULL)); - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; counter->last_printout = base::TimeTicks::Now(); CheckByteCounters(); base::RunLoop().Run();
diff --git a/media/gpu/BUILD.gn b/media/gpu/BUILD.gn index bb118ad..83d778d 100644 --- a/media/gpu/BUILD.gn +++ b/media/gpu/BUILD.gn
@@ -111,6 +111,8 @@ "android/device_info.h", "android/image_reader_gl_owner.cc", "android/image_reader_gl_owner.h", + "android/maybe_render_early_manager.cc", + "android/maybe_render_early_manager.h", "android/media_codec_video_decoder.cc", "android/media_codec_video_decoder.h", "android/promotion_hint_aggregator.h", @@ -118,6 +120,8 @@ "android/promotion_hint_aggregator_impl.h", "android/shared_image_video.cc", "android/shared_image_video.h", + "android/shared_image_video_provider.cc", + "android/shared_image_video_provider.h", "android/surface_chooser_helper.cc", "android/surface_chooser_helper.h", "android/surface_texture_gl_owner.cc", @@ -447,6 +451,7 @@ "android/fake_codec_allocator.cc", "android/fake_codec_allocator.h", "android/image_reader_gl_owner_unittest.cc", + "android/maybe_render_early_manager_unittest.cc", "android/media_codec_video_decoder_unittest.cc", "android/mock_abstract_texture.cc", "android/mock_abstract_texture.h",
diff --git a/media/gpu/android/codec_image.cc b/media/gpu/android/codec_image.cc index 7628758..5c753a5 100644 --- a/media/gpu/android/codec_image.cc +++ b/media/gpu/android/codec_image.cc
@@ -41,20 +41,24 @@ } // namespace -CodecImage::CodecImage( - std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner, - PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb) - : phase_(Phase::kInCodec), - output_buffer_(std::move(output_buffer)), - texture_owner_(std::move(texture_owner)), - promotion_hint_cb_(std::move(promotion_hint_cb)) {} +CodecImage::CodecImage() = default; CodecImage::~CodecImage() { if (destruction_cb_) std::move(destruction_cb_).Run(this); } +void CodecImage::Initialize( + std::unique_ptr<CodecOutputBuffer> output_buffer, + scoped_refptr<TextureOwner> texture_owner, + PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb) { + DCHECK(output_buffer); + phase_ = Phase::kInCodec; + output_buffer_ = std::move(output_buffer); + texture_owner_ = std::move(texture_owner); + promotion_hint_cb_ = std::move(promotion_hint_cb); +} + void CodecImage::SetDestructionCb(DestructionCb destruction_cb) { destruction_cb_ = std::move(destruction_cb); } @@ -281,4 +285,13 @@ return texture_owner_->GetAHardwareBuffer(); } +CodecImageHolder::CodecImageHolder( + scoped_refptr<base::SequencedTaskRunner> task_runner, + scoped_refptr<CodecImage> codec_image) + : base::RefCountedDeleteOnSequence<CodecImageHolder>( + std::move(task_runner)), + codec_image_(std::move(codec_image)) {} + +CodecImageHolder::~CodecImageHolder() = default; + } // namespace media
diff --git a/media/gpu/android/codec_image.h b/media/gpu/android/codec_image.h index f5fa91a..bb539473bf 100644 --- a/media/gpu/android/codec_image.h +++ b/media/gpu/android/codec_image.h
@@ -11,6 +11,7 @@ #include "base/callback.h" #include "base/macros.h" +#include "base/memory/ref_counted_delete_on_sequence.h" #include "gpu/command_buffer/service/gl_stream_texture_image.h" #include "media/gpu/android/codec_wrapper.h" #include "media/gpu/android/promotion_hint_aggregator.h" @@ -33,9 +34,16 @@ // since CodecImageGroup calls the same cb for multiple images. using DestructionCb = base::RepeatingCallback<void(CodecImage*)>; - CodecImage(std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner, - PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb); + CodecImage(); + + // (Re-)Initialize this CodecImage to use |output_buffer| et. al. + // + // May be called on a random thread, but only if the CodecImage is otherwise + // not in use. + void Initialize( + std::unique_ptr<CodecOutputBuffer> output_buffer, + scoped_refptr<TextureOwner> texture_owner, + PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb); void SetDestructionCb(DestructionCb destruction_cb); @@ -132,7 +140,7 @@ bool RenderToOverlay(); // The phase of the image buffer's lifecycle. - Phase phase_; + Phase phase_ = Phase::kInvalidated; // The buffer backing this image. std::unique_ptr<CodecOutputBuffer> output_buffer_; @@ -153,6 +161,30 @@ DISALLOW_COPY_AND_ASSIGN(CodecImage); }; +// Temporary helper class to prevent touching a non-threadsafe-ref-counted +// CodecImage off the gpu main thread, while still holding a reference to it. +// Passing a raw pointer around isn't safe, since stub destruction could still +// destroy the consumers of the codec image. +class MEDIA_GPU_EXPORT CodecImageHolder + : public base::RefCountedDeleteOnSequence<CodecImageHolder> { + public: + CodecImageHolder(scoped_refptr<base::SequencedTaskRunner> task_runner, + scoped_refptr<CodecImage> codec_image); + + // Safe from any thread. + CodecImage* codec_image_raw() const { return codec_image_.get(); } + + private: + virtual ~CodecImageHolder(); + + friend class base::RefCountedDeleteOnSequence<CodecImageHolder>; + friend class base::DeleteHelper<CodecImageHolder>; + + scoped_refptr<CodecImage> codec_image_; + + DISALLOW_COPY_AND_ASSIGN(CodecImageHolder); +}; + } // namespace media #endif // MEDIA_GPU_ANDROID_CODEC_IMAGE_H_
diff --git a/media/gpu/android/codec_image_group_unittest.cc b/media/gpu/android/codec_image_group_unittest.cc index 813d8f8..663cecf 100644 --- a/media/gpu/android/codec_image_group_unittest.cc +++ b/media/gpu/android/codec_image_group_unittest.cc
@@ -43,10 +43,7 @@ // CodecImage with a mocked ReleaseCodecBuffer. class MockCodecImage : public CodecImage { public: - MockCodecImage() - : CodecImage(nullptr, - nullptr, - PromotionHintAggregator::NotifyPromotionHintCB()) {} + MockCodecImage() = default; MOCK_METHOD0(ReleaseCodecBuffer, void());
diff --git a/media/gpu/android/codec_image_unittest.cc b/media/gpu/android/codec_image_unittest.cc index 7d68c6d6..96f8edd 100644 --- a/media/gpu/android/codec_image_unittest.cc +++ b/media/gpu/android/codec_image_unittest.cc
@@ -81,7 +81,8 @@ CodecImage::DestructionCb destruction_cb = base::DoNothing()) { std::unique_ptr<CodecOutputBuffer> buffer; wrapper_->DequeueOutputBuffer(nullptr, nullptr, &buffer); - scoped_refptr<CodecImage> image = new CodecImage( + scoped_refptr<CodecImage> image = new CodecImage(); + image->Initialize( std::move(buffer), kind == kTextureOwner ? texture_owner_ : nullptr, base::BindRepeating(&PromotionHintReceiver::OnPromotionHint, base::Unretained(&promotion_hint_receiver_)));
diff --git a/media/gpu/android/maybe_render_early_manager.cc b/media/gpu/android/maybe_render_early_manager.cc new file mode 100644 index 0000000..fcec8fa --- /dev/null +++ b/media/gpu/android/maybe_render_early_manager.cc
@@ -0,0 +1,110 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "media/gpu/android/maybe_render_early_manager.h" + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/threading/sequence_bound.h" +#include "media/gpu/android/codec_image_group.h" +#include "media/gpu/android/codec_surface_bundle.h" + +namespace media { + +// GPU-thread side of the default MaybeRenderEarlyManager. This handles doing +// the actual rendering. +class GpuMaybeRenderEarlyImpl { + public: + GpuMaybeRenderEarlyImpl() : weak_factory_(this) {} + ~GpuMaybeRenderEarlyImpl() = default; + + void SetCodecImageGroup(scoped_refptr<CodecImageGroup> image_group) { + image_group_ = std::move(image_group); + image_group_->SetDestructionCb( + base::BindRepeating(&GpuMaybeRenderEarlyImpl::OnImageDestructed, + weak_factory_.GetWeakPtr())); + } + + void AddCodecImage(scoped_refptr<CodecImageHolder> codec_image_holder) { + images_.push_back(codec_image_holder->codec_image_raw()); + // Add |image| to our current image group. This makes sure that any overlay + // lasts as long as the images. For TextureOwner, it doesn't do much. + image_group_->AddCodecImage(codec_image_holder->codec_image_raw()); + } + + void MaybeRenderEarly() { internal::MaybeRenderEarly(&images_); } + + private: + void OnImageDestructed(CodecImage* image) { + base::Erase(images_, image); + internal::MaybeRenderEarly(&images_); + } + + // Outstanding images that should be considered for early rendering. + std::vector<CodecImage*> images_; + + // Current image group to which new images (frames) will be added. We'll + // replace this when SetImageGroup() is called. + scoped_refptr<CodecImageGroup> image_group_; + + base::WeakPtrFactory<GpuMaybeRenderEarlyImpl> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(GpuMaybeRenderEarlyImpl); +}; + +// Default implementation of MaybeRenderEarlyManager. Lives on whatever thread +// you like, but will hop to the gpu thread to do real work. +class MaybeRenderEarlyManagerImpl : public MaybeRenderEarlyManager { + public: + MaybeRenderEarlyManagerImpl( + scoped_refptr<base::SequencedTaskRunner> gpu_task_runner) + : gpu_task_runner_(gpu_task_runner), + gpu_impl_(std::move(gpu_task_runner)) {} + ~MaybeRenderEarlyManagerImpl() override = default; + + void SetSurfaceBundle( + scoped_refptr<CodecSurfaceBundle> surface_bundle) override { + // Start a new image group. Note that there's no reason that we can't have + // more than one group per surface bundle; it's okay if we're called + // multiple times with the same surface bundle. It just helps to combine + // the callbacks if we don't, especially since AndroidOverlay doesn't know + // how to remove destruction callbacks. That's one reason why we don't just + // make the CodecImage register itself. The other is that the threading is + // easier if we do it this way, since the image group is constructed on the + // proper thread to talk to the overlay. + auto image_group = base::MakeRefCounted<CodecImageGroup>( + gpu_task_runner_, std::move(surface_bundle)); + + // Give the image group to |gpu_impl_|. Note that we don't drop our ref to + // |image_group| on this thread. It can only be constructed here. + gpu_impl_.Post(FROM_HERE, &GpuMaybeRenderEarlyImpl::SetCodecImageGroup, + std::move(image_group)); + } + + void AddCodecImage( + scoped_refptr<CodecImageHolder> codec_image_holder) override { + gpu_impl_.Post(FROM_HERE, &GpuMaybeRenderEarlyImpl::AddCodecImage, + std::move(codec_image_holder)); + } + + void MaybeRenderEarly() override { + gpu_impl_.Post(FROM_HERE, &GpuMaybeRenderEarlyImpl::MaybeRenderEarly); + } + + private: + scoped_refptr<base::SequencedTaskRunner> gpu_task_runner_; + + // Gpu-side. + base::SequenceBound<GpuMaybeRenderEarlyImpl> gpu_impl_; + + DISALLOW_COPY_AND_ASSIGN(MaybeRenderEarlyManagerImpl); +}; + +// static +std::unique_ptr<MaybeRenderEarlyManager> MaybeRenderEarlyManager::Create( + scoped_refptr<base::SequencedTaskRunner> task_runner) { + return std::make_unique<MaybeRenderEarlyManagerImpl>(std::move(task_runner)); +} + +} // namespace media
diff --git a/media/gpu/android/maybe_render_early_manager.h b/media/gpu/android/maybe_render_early_manager.h new file mode 100644 index 0000000..4911c3bd --- /dev/null +++ b/media/gpu/android/maybe_render_early_manager.h
@@ -0,0 +1,97 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MEDIA_GPU_ANDROID_MAYBE_RENDER_EARLY_MANAGER_H_ +#define MEDIA_GPU_ANDROID_MAYBE_RENDER_EARLY_MANAGER_H_ + +#include <memory> +#include <vector> + +#include "base/memory/scoped_refptr.h" +#include "base/optional.h" +#include "base/sequenced_task_runner.h" +#include "media/gpu/media_gpu_export.h" + +namespace media { +class CodecImageHolder; +class CodecSurfaceBundle; + +// Manager for rendering images speculatively. Tries to advance images to the +// back buffer, then to the front buffer, once those slots are unoccupied. +class MEDIA_GPU_EXPORT MaybeRenderEarlyManager { + public: + MaybeRenderEarlyManager() = default; + virtual ~MaybeRenderEarlyManager() = default; + + // Sets the surface bundle that future images will use. + virtual void SetSurfaceBundle( + scoped_refptr<CodecSurfaceBundle> surface_bundle) = 0; + + // Adds |codec_image_holder| and tries to render early. + // + // Note that CodecImage should be some other abstraction that handles + // front / backbuffer rendering. However, for now, CodecImage does that. + virtual void AddCodecImage( + scoped_refptr<CodecImageHolder> codec_image_holder) = 0; + + // Try to render codec images early. It's okay if no work can be done. + virtual void MaybeRenderEarly() = 0; + + // Create a default instance that uses |gpu_task_runner| to render early. + // Note that the returned object should be accessed from the thread that + // created it. + static std::unique_ptr<MaybeRenderEarlyManager> Create( + scoped_refptr<base::SequencedTaskRunner> gpu_task_runner); + + DISALLOW_COPY_AND_ASSIGN(MaybeRenderEarlyManager); +}; + +namespace internal { + +// Tries to render CodecImages to their backing surfaces when it's valid to do +// so. This lets us release codec buffers back to their codecs as soon as +// possible so that decoding can progress smoothly. +// Templated on the image type for testing. +template <typename Image> +void MEDIA_GPU_EXPORT MaybeRenderEarly(std::vector<Image*>* image_vector_ptr) { + auto& images = *image_vector_ptr; + if (images.empty()) + return; + + // Find the latest image rendered to the front buffer (if any). + base::Optional<size_t> front_buffer_index; + for (int i = images.size() - 1; i >= 0; --i) { + if (images[i]->was_rendered_to_front_buffer()) { + front_buffer_index = i; + break; + } + } + + // If there's no image in the front buffer we can safely render one. + if (!front_buffer_index.has_value()) { + // Iterate until we successfully render one to skip over invalidated images. + for (size_t i = 0; i < images.size(); ++i) { + if (images[i]->RenderToFrontBuffer()) { + front_buffer_index = i; + break; + } + } + // If we couldn't render anything there's nothing more to do. + if (!front_buffer_index.has_value()) + return; + } + + // Try to render the image following the front buffer to the back buffer. + size_t back_buffer_index = *front_buffer_index + 1; + if (back_buffer_index < images.size() && + images[back_buffer_index]->is_texture_owner_backed()) { + images[back_buffer_index]->RenderToTextureOwnerBackBuffer(); + } +} + +} // namespace internal + +} // namespace media + +#endif // MEDIA_GPU_ANDROID_MAYBE_RENDER_EARLY_MANAGER_H_
diff --git a/media/gpu/android/maybe_render_early_manager_unittest.cc b/media/gpu/android/maybe_render_early_manager_unittest.cc new file mode 100644 index 0000000..65d5a92 --- /dev/null +++ b/media/gpu/android/maybe_render_early_manager_unittest.cc
@@ -0,0 +1,102 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "media/gpu/android/video_frame_factory_impl.h" + +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace media { + +using testing::NiceMock; +using testing::Return; + +// The dimensions for specifying MockImage behavior. +enum ImageKind { kTextureOwner, kOverlay }; +enum Phase { kInCodec, kInFrontBuffer, kInvalidated }; +enum Expectation { kRenderToFrontBuffer, kRenderToBackBuffer, kNone }; + +// A mock image with the same interface as CodecImage. +struct MockImage { + MockImage(ImageKind kind, Phase phase, Expectation expectation) { + ON_CALL(*this, is_texture_owner_backed()) + .WillByDefault(Return(kind == kTextureOwner)); + + ON_CALL(*this, was_rendered_to_front_buffer()) + .WillByDefault(Return(phase == kInFrontBuffer)); + + if (expectation == kRenderToFrontBuffer) { + EXPECT_CALL(*this, RenderToFrontBuffer()) + .WillOnce(Return(phase != kInvalidated)); + } else { + EXPECT_CALL(*this, RenderToFrontBuffer()).Times(0); + } + + if (expectation == kRenderToBackBuffer) { + EXPECT_CALL(*this, RenderToTextureOwnerBackBuffer()) + .WillOnce(Return(phase != kInvalidated)); + } else { + EXPECT_CALL(*this, RenderToTextureOwnerBackBuffer()).Times(0); + } + } + + MOCK_METHOD0(was_rendered_to_front_buffer, bool()); + MOCK_METHOD0(is_texture_owner_backed, bool()); + MOCK_METHOD0(RenderToFrontBuffer, bool()); + MOCK_METHOD0(RenderToTextureOwnerBackBuffer, bool()); +}; + +class MaybeRenderEarlyTest : public testing::Test { + public: + MaybeRenderEarlyTest() = default; + ~MaybeRenderEarlyTest() override = default; + + void AddImage(ImageKind kind, Phase phase, Expectation expectation) { + owned_images_.push_back( + std::make_unique<NiceMock<MockImage>>(kind, phase, expectation)); + images_.push_back(owned_images_.back().get()); + } + + std::vector<std::unique_ptr<NiceMock<MockImage>>> owned_images_; + std::vector<MockImage*> images_; +}; + +TEST_F(MaybeRenderEarlyTest, EmptyVector) { + internal::MaybeRenderEarly(&images_); +} + +TEST_F(MaybeRenderEarlyTest, SingleUnrenderedSTImageIsRendered) { + AddImage(kTextureOwner, kInCodec, Expectation::kRenderToFrontBuffer); + internal::MaybeRenderEarly(&images_); +} + +TEST_F(MaybeRenderEarlyTest, SingleUnrenderedOverlayImageIsRendered) { + AddImage(kOverlay, kInCodec, Expectation::kRenderToFrontBuffer); + internal::MaybeRenderEarly(&images_); +} + +TEST_F(MaybeRenderEarlyTest, InvalidatedImagesAreSkippedOver) { + AddImage(kTextureOwner, kInvalidated, Expectation::kRenderToFrontBuffer); + AddImage(kTextureOwner, kInvalidated, Expectation::kRenderToFrontBuffer); + AddImage(kTextureOwner, kInCodec, Expectation::kRenderToFrontBuffer); + internal::MaybeRenderEarly(&images_); +} + +// This also serves as a test that Overlay images are not back buffer rendered. +TEST_F(MaybeRenderEarlyTest, NoFrontBufferRenderingIfAlreadyPopulated) { + AddImage(kOverlay, kInFrontBuffer, Expectation::kNone); + AddImage(kOverlay, kInCodec, Expectation::kNone); + internal::MaybeRenderEarly(&images_); +} + +TEST_F(MaybeRenderEarlyTest, + ImageFollowingLatestFrontBufferIsBackBufferRendered) { + AddImage(kTextureOwner, kInCodec, Expectation::kNone); + AddImage(kTextureOwner, kInFrontBuffer, Expectation::kNone); + AddImage(kTextureOwner, kInCodec, Expectation::kRenderToBackBuffer); + AddImage(kTextureOwner, kInCodec, Expectation::kNone); + internal::MaybeRenderEarly(&images_); +} + +} // namespace media
diff --git a/media/gpu/android/shared_image_video_provider.cc b/media/gpu/android/shared_image_video_provider.cc new file mode 100644 index 0000000..445acd0 --- /dev/null +++ b/media/gpu/android/shared_image_video_provider.cc
@@ -0,0 +1,18 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "media/gpu/android/shared_image_video_provider.h" + +namespace media { + +SharedImageVideoProvider::ImageSpec::ImageSpec(const gfx::Size& our_size) + : size(our_size) {} +SharedImageVideoProvider::ImageSpec::ImageSpec(const ImageSpec&) = default; +SharedImageVideoProvider::ImageSpec::~ImageSpec() = default; + +SharedImageVideoProvider::ImageRecord::ImageRecord() = default; +SharedImageVideoProvider::ImageRecord::ImageRecord(ImageRecord&&) = default; +SharedImageVideoProvider::ImageRecord::~ImageRecord() = default; + +} // namespace media
diff --git a/media/gpu/android/shared_image_video_provider.h b/media/gpu/android/shared_image_video_provider.h new file mode 100644 index 0000000..69a9eed --- /dev/null +++ b/media/gpu/android/shared_image_video_provider.h
@@ -0,0 +1,88 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MEDIA_GPU_ANDROID_SHARED_IMAGE_VIDEO_PROVIDER_H_ +#define MEDIA_GPU_ANDROID_SHARED_IMAGE_VIDEO_PROVIDER_H_ + +#include "base/callback.h" +#include "gpu/command_buffer/service/mailbox_manager.h" +#include "gpu/ipc/common/vulkan_ycbcr_info.h" +#include "media/gpu/android/codec_image_group.h" +#include "media/gpu/android/promotion_hint_aggregator.h" +#include "media/gpu/media_gpu_export.h" +#include "ui/gfx/geometry/size.h" + +namespace gpu { +struct SyncToken; +} // namespace gpu + +namespace media { + +// Provider class for shared images. +class MEDIA_GPU_EXPORT SharedImageVideoProvider { + public: + // Description of the underlying properties of the shared image. + struct ImageSpec { + ImageSpec(const gfx::Size& size); + ImageSpec(const ImageSpec&); + ~ImageSpec(); + + // Size of the underlying texture. + gfx::Size size; + + // TODO: Include other properties, if they matter, like texture format. + + bool operator==(const ImageSpec&); + }; + + using ReleaseCB = base::OnceCallback<void(const gpu::SyncToken&)>; + + // Description of the image that's being provided to the client. + struct ImageRecord { + ImageRecord(); + ImageRecord(ImageRecord&&); + ~ImageRecord(); + + // Mailbox to which this shared image is bound. + gpu::Mailbox mailbox; + + // Sampler conversion information which is used in vulkan context. + base::Optional<gpu::VulkanYCbCrInfo> ycbcr_info; + + // Release callback. When this is called (or dropped), the image will be + // considered to be unused. + ReleaseCB release_cb; + + // CodecImage that one can use for MaybeRenderEarly. + scoped_refptr<CodecImageHolder> codec_image_holder; + + private: + DISALLOW_COPY_AND_ASSIGN(ImageRecord); + }; + + SharedImageVideoProvider() = default; + virtual ~SharedImageVideoProvider() = default; + + using ImageReadyCB = base::OnceCallback<void(ImageRecord)>; + + // Call |cb| when we have a shared image that matches |spec|. We may call + // |cb| back before returning, or we might post it for later. + // |output_buffer|, |texture_owner|, and |promotion_hint_cb| probably should + // not be provided to the provider, but need to be refactored a bit first. + // They will be used to configure the SharedImageVideo to display the buffer + // on the given texture, and return promotion hints. + virtual void RequestImage( + ImageReadyCB cb, + const ImageSpec& spec, + std::unique_ptr<CodecOutputBuffer> output_buffer, + scoped_refptr<TextureOwner> texture_owner, + PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(SharedImageVideoProvider); +}; + +} // namespace media + +#endif // MEDIA_GPU_ANDROID_SHARED_IMAGE_VIDEO_PROVIDER_H_
diff --git a/media/gpu/android/video_frame_factory_impl.cc b/media/gpu/android/video_frame_factory_impl.cc index c94ac66..6f1a89f 100644 --- a/media/gpu/android/video_frame_factory_impl.cc +++ b/media/gpu/android/video_frame_factory_impl.cc
@@ -17,6 +17,7 @@ #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/task_runner_util.h" +#include "base/threading/sequence_bound.h" #include "gpu/command_buffer/common/constants.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/service/mailbox_manager.h" @@ -32,6 +33,7 @@ #include "media/gpu/android/codec_image.h" #include "media/gpu/android/codec_image_group.h" #include "media/gpu/android/codec_wrapper.h" +#include "media/gpu/android/maybe_render_early_manager.h" #include "media/gpu/android/shared_image_video.h" #include "media/gpu/command_buffer_helper.h" #include "mojo/public/cpp/bindings/callback_helpers.h" @@ -82,40 +84,104 @@ void ContextStateResultUMA(gpu::ContextResult result) { UMA_HISTOGRAM_ENUMERATION( - "Media.GpuVideoFrameFactory.SharedContextStateResult", result); + "Media.GpuSharedImageVideoFactory.SharedContextStateResult", result); } } // namespace using gpu::gles2::AbstractTexture; +// TODO(liberato): This should be in its own file. However, for now, it's here +// so that we don't have to move GpuSharedImageFactory with it, since the latter +// is an implementation detail. This makes the diffs much easier to review. +// Moving it can be done separately with no other code changes. +class DirectSharedImageVideoProvider : public SharedImageVideoProvider { + public: + DirectSharedImageVideoProvider( + scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner, + VideoFrameFactory::OverlayMode overlay_mode, + VideoFrameFactory::GetStubCb get_stub_cb, + VideoFrameFactory::InitCb init_cb) + : gpu_factory_(gpu_task_runner), gpu_task_runner_(gpu_task_runner) { + gpu_factory_.Post(FROM_HERE, &GpuSharedImageVideoFactory::Initialize, + overlay_mode, std::move(get_stub_cb), + BindToCurrentLoop(std::move(init_cb))); + } + + // TODO(liberato): add a thread hop to create the default texture owner, but + // not as part of this class. just post something from VideoFrameFactory. + void Initialize(VideoFrameFactory::OverlayMode overlay_mode, + VideoFrameFactory::GetStubCb get_stub_cb) {} + + void RequestImage(ImageReadyCB cb, + const ImageSpec& spec, + std::unique_ptr<CodecOutputBuffer> output_buffer, + scoped_refptr<TextureOwner> texture_owner, + PromotionHintAggregator::NotifyPromotionHintCB + promotion_hint_cb) override { + auto image_ready_cb = BindToCurrentLoop( + base::BindOnce(&DirectSharedImageVideoProvider::OnImageReady, + std::move(cb), std::move(output_buffer), texture_owner, + std::move(promotion_hint_cb), gpu_task_runner_)); + + // It's unclear that we should handle the image group, but since CodecImages + // have to be registered on it, we do. If the CodecImage is ever re-used, + // then part of that re-use would be to call the (then mis-named) + // destruction cb to remove it from the group. + // + // Also note that CodecImage shouldn't be the thing that's added to the + // group anyway. The thing that owns buffer management is all we really + // care about, and that doesn't have anything to do with GLImage. + + gpu_factory_.Post(FROM_HERE, &GpuSharedImageVideoFactory::CreateImage, + std::move(image_ready_cb), spec, + std::move(texture_owner)); + } + + static void OnImageReady( + ImageReadyCB cb, + std::unique_ptr<CodecOutputBuffer> output_buffer, + scoped_refptr<TextureOwner> texture_owner, + PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb, + scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner, + ImageRecord record) { + // It's okay to access |codec_image| here, since it's not used anywhere. + // We could let |cb| do this, but, in the long term, we want our caller to + // provide the output buffer / etc. to us, so we can hide how we use it. + record.codec_image_holder->codec_image_raw()->Initialize( + std::move(output_buffer), std::move(texture_owner), + std::move(promotion_hint_cb)); + + std::move(cb).Run(std::move(record)); + } + + base::SequenceBound<GpuSharedImageVideoFactory> gpu_factory_; + scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner_; +}; + VideoFrameFactoryImpl::VideoFrameFactoryImpl( scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner, GetStubCb get_stub_cb, - const gpu::GpuPreferences& gpu_preferences) + const gpu::GpuPreferences& gpu_preferences, + std::unique_ptr<MaybeRenderEarlyManager> mre_manager) : gpu_task_runner_(std::move(gpu_task_runner)), get_stub_cb_(std::move(get_stub_cb)), enable_threaded_texture_mailboxes_( - gpu_preferences.enable_threaded_texture_mailboxes) {} + gpu_preferences.enable_threaded_texture_mailboxes), + mre_manager_(std::move(mre_manager)), + weak_factory_(this) {} VideoFrameFactoryImpl::~VideoFrameFactoryImpl() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (gpu_video_frame_factory_) - gpu_task_runner_->DeleteSoon(FROM_HERE, gpu_video_frame_factory_.release()); } void VideoFrameFactoryImpl::Initialize(OverlayMode overlay_mode, InitCb init_cb) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!gpu_video_frame_factory_); + DCHECK(!image_provider_); overlay_mode_ = overlay_mode; - gpu_video_frame_factory_ = std::make_unique<GpuVideoFrameFactory>(); - base::PostTaskAndReplyWithResult( - gpu_task_runner_.get(), FROM_HERE, - base::Bind(&GpuVideoFrameFactory::Initialize, - base::Unretained(gpu_video_frame_factory_.get()), overlay_mode, - get_stub_cb_), - std::move(init_cb)); + image_provider_ = std::make_unique<DirectSharedImageVideoProvider>( + gpu_task_runner_, overlay_mode, get_stub_cb_, std::move(init_cb)); } void VideoFrameFactoryImpl::SetSurfaceBundle( @@ -125,27 +191,21 @@ // Clear everything, just so we're not holding a reference. texture_owner_ = nullptr; } else { - // If |surface_bundle| is using a TextureOwner, then get it. + // If |surface_bundle| is using a TextureOwner, then get it. Note that the + // only reason we need this is for legacy mailbox support; we send it to + // the SharedImageVideoProvider so that (eventually) it can get the service + // id from the owner for the legacy mailbox texture. Otherwise, this would + // be a lot simpler. texture_owner_ = surface_bundle->overlay() ? nullptr : surface_bundle->texture_owner(); - // Start a new image group. Note that there's no reason that we can't have - // more than one group per surface bundle; it's okay if we're called - // mulitiple times with the same surface bundle. It just helps to combine - // the callbacks if we don't, especially since AndroidOverlay doesn't know - // how to remove destruction callbacks. That's one reason why we don't just - // make the CodecImage register itself. The other is that the threading is - // easier if we do it this way, since the image group is constructed on the - // proper thread to talk to the overlay. - image_group = - base::MakeRefCounted<CodecImageGroup>(gpu_task_runner_, surface_bundle); - } + // TODO(liberato): When we enable pooling, do we need to clear the pool + // here because the CodecImageGroup has changed? It's unclear, since the + // CodecImage shouldn't be in any group once we re-use it, so maybe it's + // fine to take no action. - gpu_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&GpuVideoFrameFactory::SetImageGroup, - base::Unretained(gpu_video_frame_factory_.get()), - std::move(image_group))); + mre_manager_->SetSurfaceBundle(std::move(surface_bundle)); + } } void VideoFrameFactoryImpl::CreateVideoFrame( @@ -170,22 +230,22 @@ return; } - auto image_ready_cb = base::BindOnce( - &VideoFrameFactoryImpl::OnImageReady, std::move(output_cb), timestamp, - coded_size, natural_size, texture_owner_, pixel_format, overlay_mode_, - enable_threaded_texture_mailboxes_); + SharedImageVideoProvider::ImageSpec spec(coded_size); - gpu_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&GpuVideoFrameFactory::CreateImage, - base::Unretained(gpu_video_frame_factory_.get()), - base::Passed(&output_buffer), texture_owner_, - std::move(promotion_hint_cb), std::move(image_ready_cb), - base::ThreadTaskRunnerHandle::Get())); + auto image_ready_cb = base::BindOnce( + &VideoFrameFactoryImpl::OnImageReady, weak_factory_.GetWeakPtr(), + std::move(output_cb), timestamp, coded_size, natural_size, texture_owner_, + pixel_format, overlay_mode_, enable_threaded_texture_mailboxes_, + gpu_task_runner_); + + image_provider_->RequestImage(std::move(image_ready_cb), spec, + std::move(output_buffer), texture_owner_, + std::move(promotion_hint_cb)); } // static void VideoFrameFactoryImpl::OnImageReady( + base::WeakPtr<VideoFrameFactoryImpl> thiz, OnceOutputCb output_cb, base::TimeDelta timestamp, gfx::Size coded_size, @@ -194,14 +254,20 @@ VideoPixelFormat pixel_format, OverlayMode overlay_mode, bool enable_threaded_texture_mailboxes, - gpu::Mailbox mailbox, - VideoFrame::ReleaseMailboxCB release_cb, - base::Optional<gpu::VulkanYCbCrInfo> ycbcr_info) { + scoped_refptr<base::SequencedTaskRunner> gpu_task_runner, + SharedImageVideoProvider::ImageRecord record) { TRACE_EVENT0("media", "VideoVideoFrameFactoryImpl::OnVideoFrameImageReady"); + if (!thiz) + return; + + // Send the CodecImage (via holder, since we can't touch the refcount here) to + // the MaybeRenderEarlyManager. + thiz->mre_manager()->AddCodecImage(std::move(record.codec_image_holder)); + gpu::MailboxHolder mailbox_holders[VideoFrame::kMaxPlanes]; - mailbox_holders[0] = - gpu::MailboxHolder(mailbox, gpu::SyncToken(), GL_TEXTURE_EXTERNAL_OES); + mailbox_holders[0] = gpu::MailboxHolder(record.mailbox, gpu::SyncToken(), + GL_TEXTURE_EXTERNAL_OES); // TODO(liberato): We should set the promotion hint cb here on the image. We // should also set the output buffer params; we shouldn't send the output @@ -221,7 +287,7 @@ pixel_format, mailbox_holders, VideoFrame::ReleaseMailboxCB(), coded_size, visible_rect, natural_size, timestamp); - frame->set_ycbcr_info(ycbcr_info); + frame->set_ycbcr_info(record.ycbcr_info); // If, for some reason, we failed to create a frame, then fail. Note that we // don't need to call |release_cb|; dropping it is okay since the api says so. if (!frame) { @@ -261,7 +327,7 @@ frame->metadata()->SetBoolean(VideoFrameMetadata::TEXTURE_OWNER, !!texture_owner); - frame->SetReleaseMailboxCB(std::move(release_cb)); + frame->SetReleaseMailboxCB(std::move(record.release_cb)); // Note that we don't want to handle the CodecImageGroup here. It needs to be // accessed on the gpu thread. Once we move to pooling, only the initial @@ -279,23 +345,26 @@ std::move(closure)); } -GpuVideoFrameFactory::GpuVideoFrameFactory() : weak_factory_(this) { +GpuSharedImageVideoFactory::GpuSharedImageVideoFactory() : weak_factory_(this) { DETACH_FROM_THREAD(thread_checker_); } -GpuVideoFrameFactory::~GpuVideoFrameFactory() { +GpuSharedImageVideoFactory::~GpuSharedImageVideoFactory() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (stub_) stub_->RemoveDestructionObserver(this); } -scoped_refptr<TextureOwner> GpuVideoFrameFactory::Initialize( +void GpuSharedImageVideoFactory::Initialize( VideoFrameFactoryImpl::OverlayMode overlay_mode, - VideoFrameFactoryImpl::GetStubCb get_stub_cb) { + VideoFrameFactoryImpl::GetStubCb get_stub_cb, + VideoFrameFactory::InitCb init_cb) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); stub_ = get_stub_cb.Run(); - if (!MakeContextCurrent(stub_)) - return nullptr; + if (!MakeContextCurrent(stub_)) { + std::move(init_cb).Run(nullptr); + return; + } stub_->AddDestructionObserver(this); decoder_helper_ = GLES2DecoderHelper::Create(stub_->decoder_context()); @@ -303,9 +372,10 @@ gpu::ContextResult result; auto shared_context = GetSharedContext(stub_, &result); if (!shared_context) { - LOG(ERROR) << "GpuVideoFrameFactory: Unable to get a shared context."; + LOG(ERROR) << "GpuSharedImageVideoFactory: Unable to get a shared context."; ContextStateResultUMA(result); - return nullptr; + std::move(init_cb).Run(nullptr); + return; } // Make the shared context current. @@ -314,35 +384,32 @@ if (!shared_context->IsCurrent(nullptr)) { result = gpu::ContextResult::kTransientFailure; LOG(ERROR) - << "GpuVideoFrameFactory: Unable to make shared context current."; + << "GpuSharedImageVideoFactory: Unable to make shared context current."; ContextStateResultUMA(result); - return nullptr; + std::move(init_cb).Run(nullptr); + return; } - return TextureOwner::Create(TextureOwner::CreateTexture(shared_context.get()), - GetTextureOwnerMode(overlay_mode)); + std::move(init_cb).Run( + TextureOwner::Create(TextureOwner::CreateTexture(shared_context.get()), + GetTextureOwnerMode(overlay_mode))); } -void GpuVideoFrameFactory::CreateImage( - std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner_, - PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb, - VideoFrameFactoryImpl::ImageReadyCB image_ready_cb, - scoped_refptr<base::SingleThreadTaskRunner> task_runner) { +void GpuSharedImageVideoFactory::CreateImage( + FactoryImageReadyCB image_ready_cb, + const SharedImageVideoProvider::ImageSpec& spec, + scoped_refptr<TextureOwner> texture_owner) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // Generate a shared image mailbox. auto mailbox = gpu::Mailbox::GenerateForSharedImage(); + auto codec_image = base::MakeRefCounted<CodecImage>(); bool success = - CreateImageInternal(std::move(output_buffer), std::move(texture_owner_), - mailbox, std::move(promotion_hint_cb)); - TRACE_EVENT0("media", "GpuVideoFrameFactory::CreateVideoFrame"); + CreateImageInternal(spec, std::move(texture_owner), mailbox, codec_image); + TRACE_EVENT0("media", "GpuSharedImageVideoFactory::CreateVideoFrame"); if (!success) return; - // Try to render this frame if possible. - internal::MaybeRenderEarly(&images_); - // This callback destroys the shared image when video frame is // released/destroyed. This callback has a weak pointer to the shared image // stub because shared image stub could be destroyed before video frame. In @@ -357,16 +424,26 @@ auto release_cb = mojo::WrapCallbackWithDefaultInvokeIfNotRun( BindToCurrentLoop(std::move(destroy_shared_image)), gpu::SyncToken()); - task_runner->PostTask(FROM_HERE, - base::BindOnce(std::move(image_ready_cb), mailbox, - std::move(release_cb), ycbcr_info_)); + SharedImageVideoProvider::ImageRecord record; + record.mailbox = mailbox; + record.release_cb = std::move(release_cb); + record.ycbcr_info = ycbcr_info_; + // Since |codec_image|'s ref holders can be destroyed by stub destruction, we + // create a ref to it for the MaybeRenderEarlyManager. This is a hack; we + // should not be sending the CodecImage at all. The MaybeRenderEarlyManager + // should work with some other object that happens to be used by CodecImage, + // and non-GL things, to hold the output buffer, etc. + record.codec_image_holder = base::MakeRefCounted<CodecImageHolder>( + base::SequencedTaskRunnerHandle::Get(), std::move(codec_image)); + + std::move(image_ready_cb).Run(std::move(record)); } -bool GpuVideoFrameFactory::CreateImageInternal( - std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner_, +bool GpuSharedImageVideoFactory::CreateImageInternal( + const SharedImageVideoProvider::ImageSpec& spec, + scoped_refptr<TextureOwner> texture_owner, gpu::Mailbox mailbox, - PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb) { + scoped_refptr<CodecImage> image) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!MakeContextCurrent(stub_)) return false; @@ -378,19 +455,14 @@ if (!texture_manager) return false; - gfx::Size size = output_buffer->size(); + const auto& size = spec.size; // Create a Texture and a CodecImage to back it. + // TODO(liberato): Once legacy mailbox support is removed, we don't need to + // create this texture. So, we won't need |texture_owner| either. std::unique_ptr<AbstractTexture> texture = decoder_helper_->CreateTexture( GL_TEXTURE_EXTERNAL_OES, GL_RGBA, size.width(), size.height(), GL_RGBA, GL_UNSIGNED_BYTE); - auto image = base::MakeRefCounted<CodecImage>( - std::move(output_buffer), texture_owner_, std::move(promotion_hint_cb)); - images_.push_back(image.get()); - - // Add |image| to our current image group. This makes sure that any overlay - // lasts as long as the images. For TextureOwner, it doesn't do much. - image_group_->AddCodecImage(image.get()); // Attach the image to the texture. // Either way, we expect this to be UNBOUND (i.e., decoder-managed). For @@ -404,13 +476,13 @@ // somebody tries to sample from it. Be sure that promotion hints still // work properly, though -- they might require a stream texture image. GLuint texture_owner_service_id = - texture_owner_ ? texture_owner_->GetTextureId() : 0; + texture_owner ? texture_owner->GetTextureId() : 0; texture->BindStreamTextureImage(image.get(), texture_owner_service_id); gpu::ContextResult result; auto shared_context = GetSharedContext(stub_, &result); if (!shared_context) { - LOG(ERROR) << "GpuVideoFrameFactory: Unable to get a shared context."; + LOG(ERROR) << "GpuSharedImageVideoFactory: Unable to get a shared context."; ContextStateResultUMA(result); return false; } @@ -439,28 +511,11 @@ return true; } -void GpuVideoFrameFactory::OnWillDestroyStub(bool have_context) { +void GpuSharedImageVideoFactory::OnWillDestroyStub(bool have_context) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(stub_); stub_ = nullptr; decoder_helper_ = nullptr; } -void GpuVideoFrameFactory::OnImageDestructed(CodecImage* image) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - base::Erase(images_, image); - internal::MaybeRenderEarly(&images_); -} - -void GpuVideoFrameFactory::SetImageGroup( - scoped_refptr<CodecImageGroup> image_group) { - image_group_ = std::move(image_group); - - if (!image_group_) - return; - - image_group_->SetDestructionCb(base::BindRepeating( - &GpuVideoFrameFactory::OnImageDestructed, weak_factory_.GetWeakPtr())); -} - } // namespace media
diff --git a/media/gpu/android/video_frame_factory_impl.h b/media/gpu/android/video_frame_factory_impl.h index b099cdb..1fa62c4 100644 --- a/media/gpu/android/video_frame_factory_impl.h +++ b/media/gpu/android/video_frame_factory_impl.h
@@ -7,6 +7,7 @@ #include <memory> +#include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/single_thread_task_runner.h" #include "gpu/command_buffer/service/abstract_texture.h" @@ -18,6 +19,8 @@ #include "media/base/video_frame.h" #include "media/gpu/android/codec_image.h" #include "media/gpu/android/codec_wrapper.h" +#include "media/gpu/android/maybe_render_early_manager.h" +#include "media/gpu/android/shared_image_video_provider.h" #include "media/gpu/android/surface_texture_gl_owner.h" #include "media/gpu/android/video_frame_factory.h" #include "media/gpu/gles2_decoder_helper.h" @@ -26,7 +29,7 @@ namespace media { class CodecImageGroup; -class GpuVideoFrameFactory; +class MaybeRenderEarlyManager; // VideoFrameFactoryImpl creates CodecOutputBuffer backed VideoFrames and tries // to eagerly render them to their surface to release the buffers back to the @@ -40,14 +43,14 @@ // cleaned up properly. The release callback may be called from any thread. using ImageReadyCB = base::OnceCallback<void(gpu::Mailbox mailbox, - VideoFrame::ReleaseMailboxCB release_cb, - base::Optional<gpu::VulkanYCbCrInfo> ycbcr_info)>; + VideoFrame::ReleaseMailboxCB release_cb)>; // |get_stub_cb| will be run on |gpu_task_runner|. VideoFrameFactoryImpl( scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner, GetStubCb get_stub_cb, - const gpu::GpuPreferences& gpu_preferences); + const gpu::GpuPreferences& gpu_preferences, + std::unique_ptr<MaybeRenderEarlyManager> mre_manager); ~VideoFrameFactoryImpl() override; void Initialize(OverlayMode overlay_mode, InitCb init_cb) override; @@ -73,20 +76,22 @@ // // Second, this way we don't care about the lifetime of |this|; |output_cb| // can worry about it. - static void OnImageReady(OnceOutputCb output_cb, - base::TimeDelta timestamp, - gfx::Size coded_size, - gfx::Size natural_size, - scoped_refptr<TextureOwner> texture_owner, - VideoPixelFormat pixel_format, - OverlayMode overlay_mode, - bool enable_threaded_texture_mailboxes, - gpu::Mailbox mailbox, - VideoFrame::ReleaseMailboxCB release_cb, - base::Optional<gpu::VulkanYCbCrInfo> ycbcr_info); + static void OnImageReady( + base::WeakPtr<VideoFrameFactoryImpl> thiz, + OnceOutputCb output_cb, + base::TimeDelta timestamp, + gfx::Size coded_size, + gfx::Size natural_size, + scoped_refptr<TextureOwner> texture_owner, + VideoPixelFormat pixel_format, + OverlayMode overlay_mode, + bool enable_threaded_texture_mailboxes, + scoped_refptr<base::SequencedTaskRunner> gpu_task_runner, + SharedImageVideoProvider::ImageRecord record); - // The gpu thread side of the implementation. - std::unique_ptr<GpuVideoFrameFactory> gpu_video_frame_factory_; + MaybeRenderEarlyManager* mre_manager() const { return mre_manager_.get(); } + + std::unique_ptr<SharedImageVideoProvider> image_provider_; scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner_; GetStubCb get_stub_cb_; @@ -98,113 +103,75 @@ // Is the sync mailbox manager enabled? bool enable_threaded_texture_mailboxes_ = false; + // Current group that new CodecImages should belong to. Do not use this on + // our thread; everything must be posted to the gpu main thread, including + // destruction of it. + scoped_refptr<CodecImageGroup> image_group_; + + std::unique_ptr<MaybeRenderEarlyManager> mre_manager_; + SEQUENCE_CHECKER(sequence_checker_); + + base::WeakPtrFactory<VideoFrameFactoryImpl> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(VideoFrameFactoryImpl); }; -// GpuVideoFrameFactory is an implementation detail of VideoFrameFactoryImpl. It -// may be created on any thread but only accessed on the gpu thread thereafter. -class GpuVideoFrameFactory +// GpuSharedImageVideoFactory creates SharedImageVideo objects. It must be run +// on the gpu main thread. +// +// GpuSharedImageVideoFactory is an implementation detail of +// DirectSharedImageVideoProvider. It really should be split out into its own +// file from here, but in the interest of making CL diffs more readable, that +// is left for later. +class GpuSharedImageVideoFactory : public gpu::CommandBufferStub::DestructionObserver { public: - GpuVideoFrameFactory(); - ~GpuVideoFrameFactory() override; + GpuSharedImageVideoFactory(); + ~GpuSharedImageVideoFactory() override; - scoped_refptr<TextureOwner> Initialize( - VideoFrameFactory::OverlayMode overlay_mode, - VideoFrameFactory::GetStubCb get_stub_cb); + // TODO(liberato): Now that this is used as part of an image provider, it + // doesn't really make sense for it to call back with a TextureOwner. That + // should be handled by VideoFrameFactoryImpl if it wants. + void Initialize(VideoFrameFactory::OverlayMode overlay_mode, + VideoFrameFactory::GetStubCb get_stub_cb, + VideoFrameFactory::InitCb init_cb); - // Creates a SharedImage for |output_buffer|, and returns it via the callback. - void CreateImage( - std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner, - PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb, - VideoFrameFactoryImpl::ImageReadyCB image_ready_cb, - scoped_refptr<base::SingleThreadTaskRunner> task_runner); + // Similar to SharedImageVideoProvider::ImageReadyCB, but provides additional + // details for the provider that's using us. + using FactoryImageReadyCB = SharedImageVideoProvider::ImageReadyCB; - // Set our image group. Must be called before the first call to - // CreateVideoFrame occurs. - void SetImageGroup(scoped_refptr<CodecImageGroup> image_group); + // Creates a SharedImage for |spec|, and returns it via the callback. + // TODO(liberato): |texture_owner| is only needed to get the service id, to + // create the per-frame texture. All of that is only needed for legacy + // mailbox support, where we have to have one texture per CodecImage. + void CreateImage(FactoryImageReadyCB cb, + const SharedImageVideoProvider::ImageSpec& spec, + scoped_refptr<TextureOwner> texture_owner); private: // Creates a SharedImage for |mailbox|, and returns success or failure. - bool CreateImageInternal( - std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner, - gpu::Mailbox mailbox, - PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb); + bool CreateImageInternal(const SharedImageVideoProvider::ImageSpec& spec, + scoped_refptr<TextureOwner> texture_owner, + gpu::Mailbox mailbox, + scoped_refptr<CodecImage> image); void OnWillDestroyStub(bool have_context) override; - // Removes |image| from |images_|. - void OnImageDestructed(CodecImage* image); - - // Outstanding images that should be considered for early rendering. - std::vector<CodecImage*> images_; - gpu::CommandBufferStub* stub_ = nullptr; // A helper for creating textures. Only valid while |stub_| is valid. std::unique_ptr<GLES2DecoderHelper> decoder_helper_; - // Current image group to which new images (frames) will be added. We'll - // replace this when SetImageGroup() is called. - scoped_refptr<CodecImageGroup> image_group_; - // Sampler conversion information which is used in vulkan context. This is // constant for all the frames in a video and hence we cache it. base::Optional<gpu::VulkanYCbCrInfo> ycbcr_info_; THREAD_CHECKER(thread_checker_); - base::WeakPtrFactory<GpuVideoFrameFactory> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(GpuVideoFrameFactory); + base::WeakPtrFactory<GpuSharedImageVideoFactory> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(GpuSharedImageVideoFactory); }; -namespace internal { - -// Tries to render CodecImages to their backing surfaces when it's valid to do -// so. This lets us release codec buffers back to their codecs as soon as -// possible so that decoding can progress smoothly. -// Templated on the image type for testing. -template <typename Image> -void MEDIA_GPU_EXPORT MaybeRenderEarly(std::vector<Image*>* image_vector_ptr) { - auto& images = *image_vector_ptr; - if (images.empty()) - return; - - // Find the latest image rendered to the front buffer (if any). - base::Optional<size_t> front_buffer_index; - for (int i = images.size() - 1; i >= 0; --i) { - if (images[i]->was_rendered_to_front_buffer()) { - front_buffer_index = i; - break; - } - } - - // If there's no image in the front buffer we can safely render one. - if (!front_buffer_index) { - // Iterate until we successfully render one to skip over invalidated images. - for (size_t i = 0; i < images.size(); ++i) { - if (images[i]->RenderToFrontBuffer()) { - front_buffer_index = i; - break; - } - } - // If we couldn't render anything there's nothing more to do. - if (!front_buffer_index) - return; - } - - // Try to render the image following the front buffer to the back buffer. - size_t back_buffer_index = *front_buffer_index + 1; - if (back_buffer_index < images.size() && - images[back_buffer_index]->is_texture_owner_backed()) { - images[back_buffer_index]->RenderToTextureOwnerBackBuffer(); - } -} - -} // namespace internal - } // namespace media #endif // MEDIA_GPU_ANDROID_VIDEO_FRAME_FACTORY_IMPL_
diff --git a/media/gpu/android/video_frame_factory_impl_unittest.cc b/media/gpu/android/video_frame_factory_impl_unittest.cc index 11fb25a3..c9ba386e 100644 --- a/media/gpu/android/video_frame_factory_impl_unittest.cc +++ b/media/gpu/android/video_frame_factory_impl_unittest.cc
@@ -4,99 +4,47 @@ #include "media/gpu/android/video_frame_factory_impl.h" +#include "base/bind.h" +#include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" +#include "base/threading/thread_task_runner_handle.h" +#include "gpu/config/gpu_preferences.h" +#include "media/gpu/android/maybe_render_early_manager.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +namespace gpu { +class CommandBufferStub; +} // namespace gpu + namespace media { -using testing::NiceMock; -using testing::Return; - -// The dimensions for specifying MockImage behavior. -enum ImageKind { kTextureOwner, kOverlay }; -enum Phase { kInCodec, kInFrontBuffer, kInvalidated }; -enum Expectation { kRenderToFrontBuffer, kRenderToBackBuffer, kNone }; - -// A mock image with the same interface as CodecImage. -struct MockImage { - MockImage(ImageKind kind, Phase phase, Expectation expectation) { - ON_CALL(*this, is_texture_owner_backed()) - .WillByDefault(Return(kind == kTextureOwner)); - - ON_CALL(*this, was_rendered_to_front_buffer()) - .WillByDefault(Return(phase == kInFrontBuffer)); - - if (expectation == kRenderToFrontBuffer) { - EXPECT_CALL(*this, RenderToFrontBuffer()) - .WillOnce(Return(phase != kInvalidated)); - } else { - EXPECT_CALL(*this, RenderToFrontBuffer()).Times(0); - } - - if (expectation == kRenderToBackBuffer) { - EXPECT_CALL(*this, RenderToTextureOwnerBackBuffer()) - .WillOnce(Return(phase != kInvalidated)); - } else { - EXPECT_CALL(*this, RenderToTextureOwnerBackBuffer()).Times(0); - } - } - - MOCK_METHOD0(was_rendered_to_front_buffer, bool()); - MOCK_METHOD0(is_texture_owner_backed, bool()); - MOCK_METHOD0(RenderToFrontBuffer, bool()); - MOCK_METHOD0(RenderToTextureOwnerBackBuffer, bool()); +struct MockMaybeRenderEarlyManager : public MaybeRenderEarlyManager { + MOCK_METHOD1(SetSurfaceBundle, void(scoped_refptr<CodecSurfaceBundle>)); + MOCK_METHOD1(AddCodecImage, void(scoped_refptr<CodecImageHolder>)); + MOCK_METHOD0(MaybeRenderEarly, void()); }; -class MaybeRenderEarlyTest : public testing::Test { +class VideoFrameFactoryImplTest : public testing::Test { public: - MaybeRenderEarlyTest() = default; - ~MaybeRenderEarlyTest() override = default; + VideoFrameFactoryImplTest() + : task_runner_(base::ThreadTaskRunnerHandle::Get()) {} + ~VideoFrameFactoryImplTest() override = default; - void AddImage(ImageKind kind, Phase phase, Expectation expectation) { - owned_images_.push_back( - std::make_unique<NiceMock<MockImage>>(kind, phase, expectation)); - images_.push_back(owned_images_.back().get()); - } + base::test::ScopedTaskEnvironment scoped_task_environment_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - std::vector<std::unique_ptr<NiceMock<MockImage>>> owned_images_; - std::vector<MockImage*> images_; + gpu::GpuPreferences gpu_preferences_; }; -TEST_F(MaybeRenderEarlyTest, EmptyVector) { - internal::MaybeRenderEarly(&images_); -} - -TEST_F(MaybeRenderEarlyTest, SingleUnrenderedSTImageIsRendered) { - AddImage(kTextureOwner, kInCodec, Expectation::kRenderToFrontBuffer); - internal::MaybeRenderEarly(&images_); -} - -TEST_F(MaybeRenderEarlyTest, SingleUnrenderedOverlayImageIsRendered) { - AddImage(kOverlay, kInCodec, Expectation::kRenderToFrontBuffer); - internal::MaybeRenderEarly(&images_); -} - -TEST_F(MaybeRenderEarlyTest, InvalidatedImagesAreSkippedOver) { - AddImage(kTextureOwner, kInvalidated, Expectation::kRenderToFrontBuffer); - AddImage(kTextureOwner, kInvalidated, Expectation::kRenderToFrontBuffer); - AddImage(kTextureOwner, kInCodec, Expectation::kRenderToFrontBuffer); - internal::MaybeRenderEarly(&images_); -} - -// This also serves as a test that Overlay images are not back buffer rendered. -TEST_F(MaybeRenderEarlyTest, NoFrontBufferRenderingIfAlreadyPopulated) { - AddImage(kOverlay, kInFrontBuffer, Expectation::kNone); - AddImage(kOverlay, kInCodec, Expectation::kNone); - internal::MaybeRenderEarly(&images_); -} - -TEST_F(MaybeRenderEarlyTest, - ImageFollowingLatestFrontBufferIsBackBufferRendered) { - AddImage(kTextureOwner, kInCodec, Expectation::kNone); - AddImage(kTextureOwner, kInFrontBuffer, Expectation::kNone); - AddImage(kTextureOwner, kInCodec, Expectation::kRenderToBackBuffer); - AddImage(kTextureOwner, kInCodec, Expectation::kNone); - internal::MaybeRenderEarly(&images_); +TEST_F(VideoFrameFactoryImplTest, CreateDoesntCrash) { + // Placeholder test until we pull out the SharedImageVideoProvider. + auto get_stub_cb = + base::BindRepeating([]() -> gpu::CommandBufferStub* { return nullptr; }); + std::unique_ptr<VideoFrameFactoryImpl> impl = + std::make_unique<VideoFrameFactoryImpl>( + task_runner_, get_stub_cb, gpu_preferences_, + std::make_unique<MockMaybeRenderEarlyManager>()); } } // namespace media
diff --git a/media/mojo/services/gpu_mojo_media_client.cc b/media/mojo/services/gpu_mojo_media_client.cc index 21c0633..053ea8a5 100644 --- a/media/mojo/services/gpu_mojo_media_client.cc +++ b/media/mojo/services/gpu_mojo_media_client.cc
@@ -30,6 +30,7 @@ #include "media/filters/android/media_codec_audio_decoder.h" #include "media/gpu/android/android_video_surface_chooser_impl.h" #include "media/gpu/android/codec_allocator.h" +#include "media/gpu/android/maybe_render_early_manager.h" #include "media/gpu/android/media_codec_video_decoder.h" #include "media/gpu/android/video_frame_factory_impl.h" #include "media/mojo/interfaces/media_drm_storage.mojom.h" @@ -197,7 +198,8 @@ DeviceInfo::GetInstance()->IsSetOutputSurfaceSupported()), android_overlay_factory_cb_, std::move(request_overlay_info_cb), std::make_unique<VideoFrameFactoryImpl>( - gpu_task_runner_, std::move(get_stub_cb), gpu_preferences_)); + gpu_task_runner_, std::move(get_stub_cb), gpu_preferences_, + MaybeRenderEarlyManager::Create(gpu_task_runner_))); #elif defined(OS_CHROMEOS) || defined(OS_MACOSX) || defined(OS_WIN) || \ defined(OS_LINUX) video_decoder = VdaVideoDecoder::Create(
diff --git a/mojo/core/channel_mac_fuzzer.cc b/mojo/core/channel_mac_fuzzer.cc index e45e6bb..924b9d1f 100644 --- a/mojo/core/channel_mac_fuzzer.cc +++ b/mojo/core/channel_mac_fuzzer.cc
@@ -30,12 +30,12 @@ } scoped_refptr<base::TaskRunner> io_task_runner() { - return message_loop_.task_runner(); + return io_task_executor_.task_runner(); } private: base::test::ScopedFeatureList feature_list_; - base::MessageLoopForIO message_loop_; + base::SingleThreadTaskExecutor io_task_executor_{base::MessagePump::Type::IO}; }; class FakeChannelDelegate : public mojo::core::Channel::Delegate {
diff --git a/mojo/public/cpp/bindings/lib/sequence_local_sync_event_watcher.cc b/mojo/public/cpp/bindings/lib/sequence_local_sync_event_watcher.cc index 6543802..01baeec 100644 --- a/mojo/public/cpp/bindings/lib/sequence_local_sync_event_watcher.cc +++ b/mojo/public/cpp/bindings/lib/sequence_local_sync_event_watcher.cc
@@ -18,6 +18,7 @@ #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/sequence_local_storage_slot.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "mojo/public/cpp/bindings/sync_event_watcher.h" namespace mojo { @@ -105,7 +106,11 @@ if (registered_watchers_.empty()) { // If no more watchers are registered, clear our sequence-local storage. // Deletes |this|. - GetStorageSlot().reset(); + // Check if the current task runner is valid before doing this to avoid + // races at shutdown when other objects use SequenceLocalStorageSlot and + // indirectly call to here. + if (base::SequencedTaskRunnerHandle::IsSet()) + GetStorageSlot().reset(); } }
diff --git a/mojo/public/java/system/javatests/mojo_test_rule.cc b/mojo/public/java/system/javatests/mojo_test_rule.cc index be37af1..4ac9fc9 100644 --- a/mojo/public/java/system/javatests/mojo_test_rule.cc +++ b/mojo/public/java/system/javatests/mojo_test_rule.cc
@@ -8,9 +8,9 @@ #include "base/bind.h" #include "base/location.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/task/single_thread_task_executor.h" #include "base/test/test_support_android.h" #include "base/threading/thread_task_runner_handle.h" #include "jni/MojoTestRule_jni.h" @@ -24,7 +24,7 @@ TestEnvironment() {} base::ShadowingAtExitManager at_exit; - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; }; } // namespace
diff --git a/mojo/public/tools/fuzzers/mojo_fuzzer_message_dump.cc b/mojo/public/tools/fuzzers/mojo_fuzzer_message_dump.cc index 15b156f1..2ba5ad9 100644 --- a/mojo/public/tools/fuzzers/mojo_fuzzer_message_dump.cc +++ b/mojo/public/tools/fuzzers/mojo_fuzzer_message_dump.cc
@@ -258,7 +258,7 @@ } std::string output_directory(argv[1]); - /* Dump the messages from a MessageLoop, and wait for it to finish. */ + /* Dump the messages from a TaskExecutor, and wait for it to finish. */ env->main_thread_task_executor.task_runner()->PostTask( FROM_HERE, base::BindOnce(&DumpMessages, output_directory)); base::RunLoop().RunUntilIdle();
diff --git a/mojo/public/tools/fuzzers/mojo_parse_message_fuzzer.cc b/mojo/public/tools/fuzzers/mojo_parse_message_fuzzer.cc index 6495250..9cd9232 100644 --- a/mojo/public/tools/fuzzers/mojo_parse_message_fuzzer.cc +++ b/mojo/public/tools/fuzzers/mojo_parse_message_fuzzer.cc
@@ -52,7 +52,7 @@ // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { static Environment* env = new Environment(); - /* Pass the data along to run on a MessageLoop, and wait for it to finish. */ + /* Pass the data along to run on a TaskExecutor, and wait for it to finish. */ base::RunLoop run; env->main_thread_task_executor.task_runner()->PostTask( FROM_HERE, base::BindOnce(&FuzzMessage, data, size, &run));
diff --git a/mojo/public/tools/fuzzers/mojo_parse_message_proto_fuzzer.cc b/mojo/public/tools/fuzzers/mojo_parse_message_proto_fuzzer.cc index b12f448..0ec55a8c 100644 --- a/mojo/public/tools/fuzzers/mojo_parse_message_proto_fuzzer.cc +++ b/mojo/public/tools/fuzzers/mojo_parse_message_proto_fuzzer.cc
@@ -6,8 +6,8 @@ // multiple messages per run. #include "base/bind.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "mojo/core/embedder/embedder.h" #include "mojo/public/cpp/bindings/binding.h" @@ -47,14 +47,14 @@ // ThreadPool, because Mojo messages must be sent and processed from // TaskRunners. struct Environment { - Environment() : message_loop(base::MessageLoop::TYPE_UI) { + Environment() : main_task_executor(base::MessagePump::Type::UI) { base::ThreadPoolInstance::CreateAndStartWithDefaultParams( "MojoParseMessageFuzzerProcess"); mojo::core::Init(); } - // Message loop to send and handle messages on. - base::MessageLoop message_loop; + // Task executor to send and handle messages on. + base::SingleThreadTaskExecutor main_task_executor; // Suppress mojo validation failure logs. mojo::internal::ScopedSuppressValidationErrorLoggingForTests log_suppression; @@ -62,9 +62,10 @@ DEFINE_PROTO_FUZZER(const MojoFuzzerMessages& mojo_fuzzer_messages) { static Environment* env = new Environment(); - // Pass the data along to run on a MessageLoop, and wait for it to finish. + // Pass the data along to run on a SingleThreadTaskExecutor, and wait for it + // to finish. base::RunLoop run; - env->message_loop.task_runner()->PostTask( + env->main_task_executor.task_runner()->PostTask( FROM_HERE, base::BindOnce(&FuzzMessage, mojo_fuzzer_messages, &run)); run.Run(); }
diff --git a/net/quic/platform/impl/quic_system_event_loop_impl.h b/net/quic/platform/impl/quic_system_event_loop_impl.h index e4654c59..05439c22 100644 --- a/net/quic/platform/impl/quic_system_event_loop_impl.h +++ b/net/quic/platform/impl/quic_system_event_loop_impl.h
@@ -5,8 +5,8 @@ #ifndef NET_QUIC_PLATFORM_IMPL_QUIC_SYSTEM_EVENT_LOOP_IMPL_H_ #define NET_QUIC_PLATFORM_IMPL_QUIC_SYSTEM_EVENT_LOOP_IMPL_H_ -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" inline void QuicRunSystemEventLoopIterationImpl() { @@ -20,7 +20,7 @@ } private: - base::MessageLoopForIO message_loop_; + base::SingleThreadTaskExecutor io_task_executor_{base::MessagePump::Type::IO}; }; #endif // NET_QUIC_PLATFORM_IMPL_QUIC_SYSTEM_EVENT_LOOP_IMPL_H_
diff --git a/net/test/embedded_test_server/embedded_test_server.cc b/net/test/embedded_test_server/embedded_test_server.cc index 4a3bc753..b24b44f5 100644 --- a/net/test/embedded_test_server/embedded_test_server.cc +++ b/net/test/embedded_test_server/embedded_test_server.cc
@@ -11,13 +11,13 @@ #include "base/files/file_util.h" #include "base/location.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_current.h" #include "base/path_service.h" #include "base/process/process_metrics.h" #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "crypto/rsa_private_key.h" @@ -175,7 +175,7 @@ DCHECK(!io_thread_.get()) << "Server must not be started while server is running"; base::Thread::Options thread_options; - thread_options.message_loop_type = base::MessageLoop::TYPE_IO; + thread_options.message_loop_type = base::MessagePump::Type::IO; io_thread_ = std::make_unique<base::Thread>("EmbeddedTestServer IO Thread"); CHECK(io_thread_->StartWithOptions(thread_options)); CHECK(io_thread_->WaitUntilThreadStarted()); @@ -502,14 +502,14 @@ // base::ThreadTaskRunnerHandle::Get() to return a task runner for posting // the reply task. However, in order to make EmbeddedTestServer universally // usable, it needs to cope with the situation where it's running on a thread - // on which a message loop is not (yet) available or as has been destroyed + // on which a task executor is not (yet) available or as has been destroyed // already. // - // To handle this situation, create temporary message loop to support the - // PostTaskAndReply operation if the current thread has no message loop. - std::unique_ptr<base::MessageLoop> temporary_loop; + // To handle this situation, create temporary task executor to support the + // PostTaskAndReply operation if the current thread has no task executor. + std::unique_ptr<base::SingleThreadTaskExecutor> temporary_loop; if (!base::MessageLoopCurrent::Get()) - temporary_loop = std::make_unique<base::MessageLoop>(); + temporary_loop = std::make_unique<base::SingleThreadTaskExecutor>(); base::RunLoop run_loop; if (!io_thread_->task_runner()->PostTaskAndReply(FROM_HERE, closure,
diff --git a/net/tools/cachetool/cachetool.cc b/net/tools/cachetool/cachetool.cc index 2e57733..7592203 100644 --- a/net/tools/cachetool/cachetool.cc +++ b/net/tools/cachetool/cachetool.cc
@@ -12,12 +12,12 @@ #include "base/format_macros.h" #include "base/hash/md5.h" #include "base/logging.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" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "net/base/io_buffer.h" #include "net/base/test_completion_callback.h" @@ -667,7 +667,7 @@ int main(int argc, char* argv[]) { base::AtExitManager at_exit_manager; - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::CommandLine::Init(argc, argv); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
diff --git a/net/tools/crash_cache/crash_cache.cc b/net/tools/crash_cache/crash_cache.cc index e90f6c5..4b01e3b 100644 --- a/net/tools/crash_cache/crash_cache.cc +++ b/net/tools/crash_cache/crash_cache.cc
@@ -13,7 +13,6 @@ #include "base/command_line.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/process/kill.h" #include "base/process/launch.h" @@ -21,6 +20,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread.h" #include "net/base/net_errors.h" #include "net/base/net_export.h" @@ -327,7 +327,7 @@ // Main function on the child process. int SlaveCode(const base::FilePath& path, RankCrashes action) { - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::FilePath full_path; if (!CreateTargetFolder(path, action, &full_path)) { @@ -337,7 +337,7 @@ base::Thread cache_thread("CacheThread"); if (!cache_thread.StartWithOptions( - base::Thread::Options(base::MessageLoop::TYPE_IO, 0))) + base::Thread::Options(base::MessagePump::Type::IO, 0))) return GENERIC; if (action <= disk_cache::INSERT_ONE_3)
diff --git a/net/tools/dump_cache/dump_files.cc b/net/tools/dump_cache/dump_files.cc index 6ff0c87c..6f68ee1 100644 --- a/net/tools/dump_cache/dump_files.cc +++ b/net/tools/dump_cache/dump_files.cc
@@ -20,9 +20,9 @@ #include "base/files/file_util.h" #include "base/format_macros.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" +#include "base/task/single_thread_task_executor.h" #include "net/disk_cache/blockfile/block_files.h" #include "net/disk_cache/blockfile/disk_format.h" #include "net/disk_cache/blockfile/mapped_file.h" @@ -61,8 +61,8 @@ // Dumps the contents of the Stats record. void DumpStats(const base::FilePath& path, disk_cache::CacheAddr addr) { - // We need a message loop, although we really don't run any task. - base::MessageLoopForIO loop; + // We need a task executor, although we really don't run any task. + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); disk_cache::BlockFiles block_files(path); if (!block_files.Init(false)) { @@ -445,8 +445,8 @@ if (!print_csv) DumpIndexHeader(input_path.Append(kIndexName), nullptr); - // We need a message loop, although we really don't run any task. - base::MessageLoopForIO loop; + // We need a task executor, although we really don't run any task. + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); CacheDumper dumper(input_path); if (!dumper.Init()) return -1; @@ -481,8 +481,8 @@ if (!ReadHeader(index_name, reinterpret_cast<char*>(&header), sizeof(header))) return -1; - // We need a message loop, although we really don't run any task. - base::MessageLoopForIO loop; + // We need a task executor, although we really don't run any task. + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); CacheDumper dumper(input_path); if (!dumper.Init()) return -1; @@ -534,8 +534,8 @@ if (!ReadHeader(index_name, reinterpret_cast<char*>(&header), sizeof(header))) return -1; - // We need a message loop, although we really don't run any task. - base::MessageLoopForIO loop; + // We need a task executor, although we really don't run any task. + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); CacheDumper dumper(input_path); if (!dumper.Init()) return -1;
diff --git a/net/tools/net_watcher/net_watcher.cc b/net/tools/net_watcher/net_watcher.cc index 024085e..09c55c5 100644 --- a/net/tools/net_watcher/net_watcher.cc +++ b/net/tools/net_watcher/net_watcher.cc
@@ -20,9 +20,9 @@ #include "base/json/json_writer.h" #include "base/logging.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_split.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/values.h" #include "build/build_config.h" @@ -154,8 +154,8 @@ logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR; logging::InitLogging(settings); - // Just make the main message loop the network loop. - base::MessageLoopForIO network_loop; + // Just make the main task executor the network loop. + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::ThreadPoolInstance::CreateAndStartWithDefaultParams("NetWatcher"); @@ -184,7 +184,7 @@ // Use the network loop as the file loop also. std::unique_ptr<net::ProxyConfigService> proxy_config_service( net::ProxyResolutionService::CreateSystemProxyConfigService( - network_loop.task_runner())); + io_task_executor.task_runner())); // Uses |network_change_notifier|. net::NetworkChangeNotifier::AddIPAddressObserver(&net_watcher);
diff --git a/net/tools/quic/quic_simple_server_bin.cc b/net/tools/quic/quic_simple_server_bin.cc index c166e3b7..8d371ba4 100644 --- a/net/tools/quic/quic_simple_server_bin.cc +++ b/net/tools/quic/quic_simple_server_bin.cc
@@ -10,9 +10,9 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" @@ -50,7 +50,7 @@ int main(int argc, char* argv[]) { base::ThreadPoolInstance::CreateAndStartWithDefaultParams("quic_server"); base::AtExitManager exit_manager; - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::CommandLine::Init(argc, argv); base::CommandLine* line = base::CommandLine::ForCurrentProcess();
diff --git a/net/tools/quic/synchronous_host_resolver.cc b/net/tools/quic/synchronous_host_resolver.cc index 9428d707..1f8a16fd 100644 --- a/net/tools/quic/synchronous_host_resolver.cc +++ b/net/tools/quic/synchronous_host_resolver.cc
@@ -12,10 +12,10 @@ #include "base/location.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop.h" #include "base/optional.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/simple_thread.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/host_port_pair.h" @@ -57,7 +57,7 @@ ResolverThread::~ResolverThread() = default; void ResolverThread::Run() { - base::MessageLoopForIO loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); net::NetLog net_log; net::HostResolver::ManagerOptions options;
diff --git a/net/tools/stress_cache/stress_cache.cc b/net/tools/stress_cache/stress_cache.cc index e385777..ff485cf4 100644 --- a/net/tools/stress_cache/stress_cache.cc +++ b/net/tools/stress_cache/stress_cache.cc
@@ -25,7 +25,6 @@ #include "base/files/file_path.h" #include "base/location.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/process/process.h" @@ -34,6 +33,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/platform_thread.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" @@ -306,7 +306,7 @@ base::Thread cache_thread("CacheThread"); if (!cache_thread.StartWithOptions( - base::Thread::Options(base::MessageLoop::TYPE_IO, 0))) + base::Thread::Options(base::MessagePump::Type::IO, 0))) return; g_data = new Data(); @@ -429,7 +429,7 @@ // Some time for the memory manager to flush stuff. base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(3)); - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); char* end; long int iteration = strtol(argv[1], &end, 0);
diff --git a/net/tools/testserver/run_testserver.cc b/net/tools/testserver/run_testserver.cc index 10ea873..0a997386 100644 --- a/net/tools/testserver/run_testserver.cc +++ b/net/tools/testserver/run_testserver.cc
@@ -9,9 +9,9 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/test/test_timeouts.h" #include "net/test/spawned_test_server/spawned_test_server.h" @@ -24,7 +24,7 @@ int main(int argc, const char* argv[]) { base::AtExitManager at_exit_manager; - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); // Process command line base::CommandLine::Init(argc, argv);
diff --git a/net/url_request/ftp_protocol_handler.cc b/net/url_request/ftp_protocol_handler.cc index 9334ca7..4b96c5a 100644 --- a/net/url_request/ftp_protocol_handler.cc +++ b/net/url_request/ftp_protocol_handler.cc
@@ -18,15 +18,18 @@ namespace net { std::unique_ptr<FtpProtocolHandler> FtpProtocolHandler::Create( - HostResolver* host_resolver) { + HostResolver* host_resolver, + FtpAuthCache* auth_cache) { + DCHECK(auth_cache); return base::WrapUnique(new FtpProtocolHandler( - base::WrapUnique(new FtpNetworkLayer(host_resolver)))); + base::WrapUnique(new FtpNetworkLayer(host_resolver)), auth_cache)); } std::unique_ptr<FtpProtocolHandler> FtpProtocolHandler::CreateForTesting( - std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory) { + std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory, + FtpAuthCache* auth_cache) { return base::WrapUnique( - new FtpProtocolHandler(std::move(ftp_transaction_factory))); + new FtpProtocolHandler(std::move(ftp_transaction_factory), auth_cache)); } FtpProtocolHandler::~FtpProtocolHandler() = default; @@ -41,14 +44,14 @@ } return new URLRequestFtpJob(request, network_delegate, - ftp_transaction_factory_.get(), - ftp_auth_cache_.get()); + ftp_transaction_factory_.get(), ftp_auth_cache_); } FtpProtocolHandler::FtpProtocolHandler( - std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory) + std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory, + FtpAuthCache* auth_cache) : ftp_transaction_factory_(std::move(ftp_transaction_factory)), - ftp_auth_cache_(new FtpAuthCache) { + ftp_auth_cache_(auth_cache) { DCHECK(ftp_transaction_factory_); }
diff --git a/net/url_request/ftp_protocol_handler.h b/net/url_request/ftp_protocol_handler.h index e06aa1a..e8843be3 100644 --- a/net/url_request/ftp_protocol_handler.h +++ b/net/url_request/ftp_protocol_handler.h
@@ -26,15 +26,16 @@ public: ~FtpProtocolHandler() override; - // Creates an FtpProtocolHandler using an FtpTransactionFactoryImpl and the - // specified HostResolver. - static std::unique_ptr<FtpProtocolHandler> Create( - HostResolver* host_resolver); + // Creates an FtpProtocolHandler using the specified HostResolver and + // FtpAuthCache. |auth_cache| cannot be null. + static std::unique_ptr<FtpProtocolHandler> Create(HostResolver* host_resolver, + FtpAuthCache* auth_cache); // Creates an FtpProtocolHandler using the specified FtpTransactionFactory, to // allow a mock to be used for testing. static std::unique_ptr<FtpProtocolHandler> CreateForTesting( - std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory); + std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory, + FtpAuthCache* auth_cache); URLRequestJob* MaybeCreateJob( URLRequest* request, @@ -44,10 +45,11 @@ friend class FtpTestURLRequestContext; explicit FtpProtocolHandler( - std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory); + std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory, + FtpAuthCache* auth_cache); std::unique_ptr<FtpTransactionFactory> ftp_transaction_factory_; - std::unique_ptr<FtpAuthCache> ftp_auth_cache_; + FtpAuthCache* ftp_auth_cache_; DISALLOW_COPY_AND_ASSIGN(FtpProtocolHandler); };
diff --git a/net/url_request/url_request_context.cc b/net/url_request/url_request_context.cc index 8f7623f..7f93577 100644 --- a/net/url_request/url_request_context.cc +++ b/net/url_request/url_request_context.cc
@@ -180,6 +180,9 @@ #endif // BUILDFLAG(ENABLE_REPORTING) set_enable_brotli(other->enable_brotli_); set_check_cleartext_permitted(other->check_cleartext_permitted_); +#if !BUILDFLAG(DISABLE_FTP_SUPPORT) + set_ftp_auth_cache(other->ftp_auth_cache_); +#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT) } } // namespace net
diff --git a/net/url_request/url_request_context.h b/net/url_request/url_request_context.h index d2a989c..6199f94 100644 --- a/net/url_request/url_request_context.h +++ b/net/url_request/url_request_context.h
@@ -58,6 +58,10 @@ class URLRequestJobFactory; class URLRequestThrottlerManager; +#if !BUILDFLAG(DISABLE_FTP_SUPPORT) +class FtpAuthCache; +#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT) + #if BUILDFLAG(ENABLE_REPORTING) class NetworkErrorLoggingService; class ReportingService; @@ -275,6 +279,13 @@ // Returns current value of the |check_cleartext_permitted| flag. bool check_cleartext_permitted() const { return check_cleartext_permitted_; } +#if !BUILDFLAG(DISABLE_FTP_SUPPORT) + void set_ftp_auth_cache(FtpAuthCache* auth_cache) { + ftp_auth_cache_ = auth_cache; + } + FtpAuthCache* ftp_auth_cache() { return ftp_auth_cache_; } +#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT) + // Sets a name for this URLRequestContext. Currently the name is used in // MemoryDumpProvier to annotate memory usage. The name does not need to be // unique. @@ -335,6 +346,9 @@ ReportingService* reporting_service_; NetworkErrorLoggingService* network_error_logging_service_; #endif // BUILDFLAG(ENABLE_REPORTING) +#if !BUILDFLAG(DISABLE_FTP_SUPPORT) + FtpAuthCache* ftp_auth_cache_; +#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT) // --------------------------------------------------------------------------- // Important: When adding any new members below, consider whether they need to
diff --git a/net/url_request/url_request_context_builder.cc b/net/url_request/url_request_context_builder.cc index 9994043..0ce6a35 100644 --- a/net/url_request/url_request_context_builder.cc +++ b/net/url_request/url_request_context_builder.cc
@@ -53,6 +53,7 @@ #endif #if !BUILDFLAG(DISABLE_FTP_SUPPORT) +#include "net/ftp/ftp_auth_cache.h" // nogncheck #include "net/ftp/ftp_network_layer.h" // nogncheck #include "net/url_request/ftp_protocol_handler.h" // nogncheck #endif @@ -673,8 +674,10 @@ #if !BUILDFLAG(DISABLE_FTP_SUPPORT) if (ftp_enabled_) { + storage->set_ftp_auth_cache(std::make_unique<FtpAuthCache>()); job_factory->SetProtocolHandler( - url::kFtpScheme, FtpProtocolHandler::Create(context->host_resolver())); + url::kFtpScheme, FtpProtocolHandler::Create(context->host_resolver(), + context->ftp_auth_cache())); } #endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
diff --git a/net/url_request/url_request_context_storage.cc b/net/url_request/url_request_context_storage.cc index 21da47e..e47b312 100644 --- a/net/url_request/url_request_context_storage.cc +++ b/net/url_request/url_request_context_storage.cc
@@ -24,6 +24,10 @@ #include "net/url_request/url_request_job_factory.h" #include "net/url_request/url_request_throttler_manager.h" +#if !BUILDFLAG(DISABLE_FTP_SUPPORT) +#include "net/ftp/ftp_auth_cache.h" +#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT) + #if BUILDFLAG(ENABLE_REPORTING) #include "net/network_error_logging/network_error_logging_service.h" #include "net/reporting/reporting_service.h" @@ -144,6 +148,14 @@ http_user_agent_settings_ = std::move(http_user_agent_settings); } +#if !BUILDFLAG(DISABLE_FTP_SUPPORT) +void URLRequestContextStorage::set_ftp_auth_cache( + std::unique_ptr<FtpAuthCache> ftp_auth_cache) { + context_->set_ftp_auth_cache(ftp_auth_cache.get()); + ftp_auth_cache_ = std::move(ftp_auth_cache); +} +#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT) + #if BUILDFLAG(ENABLE_REPORTING) void URLRequestContextStorage::set_reporting_service( std::unique_ptr<ReportingService> reporting_service) {
diff --git a/net/url_request/url_request_context_storage.h b/net/url_request/url_request_context_storage.h index 44cae848..eaca2bf 100644 --- a/net/url_request/url_request_context_storage.h +++ b/net/url_request/url_request_context_storage.h
@@ -19,6 +19,7 @@ class CookieStore; class CTPolicyEnforcer; class CTVerifier; +class FtpAuthCache; class HostResolver; class HttpAuthHandlerFactory; class HttpNetworkSession; @@ -82,6 +83,9 @@ std::unique_ptr<URLRequestThrottlerManager> throttler_manager); void set_http_user_agent_settings( std::unique_ptr<HttpUserAgentSettings> http_user_agent_settings); +#if !BUILDFLAG(DISABLE_FTP_SUPPORT) + void set_ftp_auth_cache(std::unique_ptr<FtpAuthCache> ftp_auth_cache); +#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT) #if BUILDFLAG(ENABLE_REPORTING) void set_reporting_service( @@ -117,6 +121,9 @@ std::unique_ptr<TransportSecurityState> transport_security_state_; std::unique_ptr<CTVerifier> cert_transparency_verifier_; std::unique_ptr<CTPolicyEnforcer> ct_policy_enforcer_; +#if !BUILDFLAG(DISABLE_FTP_SUPPORT) + std::unique_ptr<FtpAuthCache> ftp_auth_cache_; +#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT) // Not actually pointed at by the URLRequestContext, but may be used (but not // owned) by the HttpTransactionFactory.
diff --git a/net/url_request/url_request_ftp_fuzzer.cc b/net/url_request/url_request_ftp_fuzzer.cc index 699e060..e0f16dc 100644 --- a/net/url_request/url_request_ftp_fuzzer.cc +++ b/net/url_request/url_request_ftp_fuzzer.cc
@@ -11,6 +11,7 @@ #include "net/base/request_priority.h" #include "net/dns/context_host_resolver.h" #include "net/dns/fuzzed_host_resolver_util.h" +#include "net/ftp/ftp_auth_cache.h" #include "net/ftp/ftp_network_transaction.h" #include "net/ftp/ftp_transaction_factory.h" #include "net/socket/client_socket_factory.h" @@ -66,10 +67,12 @@ url_request_context.set_host_resolver(host_resolver.get()); net::URLRequestJobFactoryImpl job_factory; + net::FtpAuthCache auth_cache; job_factory.SetProtocolHandler( "ftp", net::FtpProtocolHandler::CreateForTesting( std::make_unique<FuzzedFtpTransactionFactory>( - host_resolver.get(), &fuzzed_socket_factory))); + host_resolver.get(), &fuzzed_socket_factory), + &auth_cache)); url_request_context.set_job_factory(&job_factory); url_request_context.Init();
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 1b646f5..4646cf10 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -143,6 +143,7 @@ #endif #if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) +#include "net/ftp/ftp_auth_cache.h" #include "net/ftp/ftp_network_layer.h" #include "net/url_request/ftp_protocol_handler.h" #endif @@ -12353,7 +12354,7 @@ void SetUpFactory() override { // Add FTP support to the default URLRequestContext. job_factory_impl_->SetProtocolHandler( - "ftp", FtpProtocolHandler::Create(&host_resolver_)); + "ftp", FtpProtocolHandler::Create(&host_resolver_, &ftp_auth_cache_)); } std::string GetTestFileContents() { @@ -12368,6 +12369,7 @@ protected: MockHostResolver host_resolver_; + FtpAuthCache ftp_auth_cache_; SpawnedTestServer ftp_test_server_; };
diff --git a/ppapi/nacl_irt/irt_pnacl_translator_compile.cc b/ppapi/nacl_irt/irt_pnacl_translator_compile.cc index 116b3f3..a2db35b7 100644 --- a/ppapi/nacl_irt/irt_pnacl_translator_compile.cc +++ b/ppapi/nacl_irt/irt_pnacl_translator_compile.cc
@@ -3,8 +3,8 @@ // found in the LICENSE file. #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "build/build_config.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_sync_channel.h" @@ -101,7 +101,7 @@ }; void ServeTranslateRequest(const struct nacl_irt_pnacl_compile_funcs* funcs) { - base::MessageLoop loop; + base::SingleThreadTaskExecutor main_task_executor; new TranslatorCompileListener(ppapi::GetRendererIPCChannelHandle(), funcs); base::RunLoop().Run(); }
diff --git a/ppapi/nacl_irt/irt_pnacl_translator_link.cc b/ppapi/nacl_irt/irt_pnacl_translator_link.cc index ccd1919..57073fb 100644 --- a/ppapi/nacl_irt/irt_pnacl_translator_link.cc +++ b/ppapi/nacl_irt/irt_pnacl_translator_link.cc
@@ -3,8 +3,8 @@ // found in the LICENSE file. #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "build/build_config.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_sync_channel.h" @@ -72,7 +72,7 @@ }; void ServeLinkRequest(CallbackFunc func) { - base::MessageLoop loop; + base::SingleThreadTaskExecutor main_task_executor; new TranslatorLinkListener(ppapi::GetRendererIPCChannelHandle(), func); base::RunLoop().Run(); }
diff --git a/ppapi/proxy/ppb_message_loop_proxy.cc b/ppapi/proxy/ppb_message_loop_proxy.cc index a2a2bb8..b38212b 100644 --- a/ppapi/proxy/ppb_message_loop_proxy.cc +++ b/ppapi/proxy/ppb_message_loop_proxy.cc
@@ -83,7 +83,7 @@ if (slot->Get()) return PP_ERROR_INPROGRESS; } - // TODO(dmichael) check that the current thread can support a message loop. + // TODO(dmichael) check that the current thread can support a task executor. // Take a ref to the MessageLoop on behalf of the TLS. Note that this is an // internal ref and not a plugin ref so the plugin can't accidentally @@ -94,7 +94,7 @@ single_thread_task_executor_.reset(new base::SingleThreadTaskExecutor); task_runner_ = base::ThreadTaskRunnerHandle::Get(); - // Post all pending work to the message loop. + // Post all pending work to the task executor. for (size_t i = 0; i < pending_tasks_.size(); i++) { const TaskInfo& info = pending_tasks_[i]; PostClosure(info.from_here, info.closure, info.delay_ms); @@ -169,7 +169,7 @@ } void MessageLoopResource::DetachFromThread() { - // Note that the message loop must be destroyed on the thread it was created + // Note that the task executor must be destroyed on the thread it was created // on. task_runner_ = NULL; single_thread_task_executor_.reset();
diff --git a/ppapi/proxy/ppb_message_loop_proxy.h b/ppapi/proxy/ppb_message_loop_proxy.h index 1a16bace..eb90e06 100644 --- a/ppapi/proxy/ppb_message_loop_proxy.h +++ b/ppapi/proxy/ppb_message_loop_proxy.h
@@ -68,7 +68,7 @@ // MessageLoopShared implementation. // - // Handles posting to the message loop if there is one, or the pending queue + // Handles posting to the task executor if there is one, or the pending queue // if there isn't. // NOTE: The given closure will be run *WITHOUT* acquiring the Proxy lock. // This only makes sense for user code and completely thread-safe @@ -97,11 +97,11 @@ // Number of invocations of Run currently on the stack. int nested_invocations_; - // Set to true when the message loop is destroyed to prevent forther + // Set to true when the task executor is destroyed to prevent forther // posting of work. bool destroyed_; - // Set to true if all message loop invocations should exit and that the + // Set to true if all task executor invocations should exit and that the // loop should be destroyed once it reaches the outermost Run invocation. bool should_destroy_; @@ -109,7 +109,7 @@ bool currently_handling_blocking_message_; - // Since we allow tasks to be posted before the message loop is actually + // Since we allow tasks to be posted before the task executor is actually // created (when it's associated with a thread), we keep tasks posted here // until that happens. Once the loop_ is created, this is unused. std::vector<TaskInfo> pending_tasks_;
diff --git a/remoting/base/BUILD.gn b/remoting/base/BUILD.gn index 9173c4a..89d605e 100644 --- a/remoting/base/BUILD.gn +++ b/remoting/base/BUILD.gn
@@ -23,8 +23,6 @@ "leaky_bucket.cc", "leaky_bucket.h", "name_value_map.h", - "platform_details.cc", - "platform_details.h", "rate_counter.cc", "rate_counter.h", "remoting_bot.cc", @@ -79,7 +77,6 @@ sources -= [ "chromium_url_request.cc", "chromoting_event.cc", - "platform_details.cc", "telemetry_log_writer.cc", "url_request_context_getter.cc", ]
diff --git a/remoting/base/chromoting_event.cc b/remoting/base/chromoting_event.cc index e20e7f7..c1e48ae 100644 --- a/remoting/base/chromoting_event.cc +++ b/remoting/base/chromoting_event.cc
@@ -8,7 +8,6 @@ #include "base/strings/stringize_macros.h" #include "base/system/sys_info.h" #include "remoting/base/name_value_map.h" -#include "remoting/base/platform_details.h" namespace remoting { @@ -187,7 +186,7 @@ void ChromotingEvent::AddSystemInfo() { SetString(kCpuKey, base::SysInfo::OperatingSystemArchitecture()); - SetString(kOsVersionKey, GetOperatingSystemVersionString()); + SetString(kOsVersionKey, base::SysInfo::OperatingSystemVersion()); SetString(kWebAppVersionKey, STRINGIZE(VERSION)); #if defined(OS_LINUX) Os os = Os::CHROMOTING_LINUX;
diff --git a/remoting/base/platform_details.cc b/remoting/base/platform_details.cc deleted file mode 100644 index 5caea5e..0000000 --- a/remoting/base/platform_details.cc +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "remoting/base/platform_details.h" - -#include "base/system/sys_info.h" -#include "build/build_config.h" - -#if defined(OS_MACOSX) && !defined(OS_IOS) -#include "base/mac/mac_util.h" -#endif - -namespace remoting { - -// Get the Operating System Version, removing the need to check for OS -// definitions, to keep the format used consistent. -std::string GetOperatingSystemVersionString() { -#if defined(OS_MACOSX) && !defined(OS_IOS) - if (base::mac::IsAtLeastOS10_10()) { - return base::SysInfo::OperatingSystemVersion(); - } else { - // MacOS Hosts prior to 10.10 were reporting incorrect OS versions after the - // removal of the 10.9 and lower checks back in ~M66. Since we don't know - // the exact version in this case, I've chosen a number that is obviously - // not a valid MacOS OS version. That way it will be easier to find if - // someone is unaware of this problem and does a code search to find it. - // See crbug.com/889259 for more context. - return "10.9.9999"; - } -#else - return base::SysInfo::OperatingSystemVersion(); -#endif -} - -} // namespace remoting
diff --git a/remoting/base/platform_details.h b/remoting/base/platform_details.h deleted file mode 100644 index dc0dd9c..0000000 --- a/remoting/base/platform_details.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef REMOTING_BASE_PLATFORM_DETAILS_H_ -#define REMOTING_BASE_PLATFORM_DETAILS_H_ - -#include <string> - -namespace remoting { - -// Returns the OS version in a standard format for any build target. -std::string GetOperatingSystemVersionString(); - -} // namespace remoting - -#endif // REMOTING_BASE_PLATFORM_DETAILS_H_
diff --git a/remoting/client/chromoting_client_runtime.cc b/remoting/client/chromoting_client_runtime.cc index d5f7440..c5c0a05 100644 --- a/remoting/client/chromoting_client_runtime.cc +++ b/remoting/client/chromoting_client_runtime.cc
@@ -8,8 +8,8 @@ #include "base/bind_helpers.h" #include "base/logging.h" #include "base/memory/singleton.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_current.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" @@ -33,22 +33,19 @@ DCHECK(!base::MessageLoopCurrent::Get()); VLOG(1) << "Starting main message loop"; - ui_loop_.reset(new base::MessageLoopForUI()); -#if defined(OS_IOS) - // TODO(ranj): Attach on BindToCurrentThread(). - ui_loop_->Attach(); -#endif + ui_task_executor_.reset( + new base::SingleThreadTaskExecutor(base::MessagePump::Type::UI)); #if defined(DEBUG) net::URLFetcher::SetIgnoreCertificateRequests(true); #endif // DEBUG - // |ui_loop_| runs on the main thread, so |ui_task_runner_| will run on the - // main thread. We can not kill the main thread when the message loop becomes - // idle so the callback function does nothing (as opposed to the typical - // base::MessageLoop::QuitClosure()) - ui_task_runner_ = - new AutoThreadTaskRunner(ui_loop_->task_runner(), base::DoNothing()); + // |ui_task_executor_| runs on the main thread, so |ui_task_runner_| will run + // on the main thread. We can not kill the main thread when the message loop + // becomes idle so the callback function does nothing (as opposed to the + // typical base::MessageLoop::QuitClosure()) + ui_task_runner_ = new AutoThreadTaskRunner(ui_task_executor_->task_runner(), + base::DoNothing()); audio_task_runner_ = AutoThread::Create("native_audio", ui_task_runner_); display_task_runner_ = AutoThread::Create("native_disp", ui_task_runner_); network_task_runner_ = AutoThread::CreateWithType(
diff --git a/remoting/client/chromoting_client_runtime.h b/remoting/client/chromoting_client_runtime.h index 3a0baccb3..33b2530d 100644 --- a/remoting/client/chromoting_client_runtime.h +++ b/remoting/client/chromoting_client_runtime.h
@@ -16,7 +16,7 @@ #include "remoting/base/telemetry_log_writer.h" namespace base { -class MessageLoopForUI; +class SingleThreadTaskExecutor; template <typename T> struct DefaultSingletonTraits; @@ -91,8 +91,8 @@ void InitializeOnNetworkThread(); // Chromium code's connection to the app message loop. Once created the - // MessageLoop will live for the life of the program. - std::unique_ptr<base::MessageLoopForUI> ui_loop_; + // SingleThreadTaskExecutor will live for the life of the program. + std::unique_ptr<base::SingleThreadTaskExecutor> ui_task_executor_; // References to native threads. scoped_refptr<AutoThreadTaskRunner> ui_task_runner_;
diff --git a/remoting/host/desktop_process_main.cc b/remoting/host/desktop_process_main.cc index e7112883..f8be3c0 100644 --- a/remoting/host/desktop_process_main.cc +++ b/remoting/host/desktop_process_main.cc
@@ -11,8 +11,8 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "build/build_config.h" #include "mojo/core/embedder/scoped_ipc_support.h" @@ -37,11 +37,11 @@ base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Me2Me"); - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::RunLoop run_loop; - scoped_refptr<AutoThreadTaskRunner> ui_task_runner = - new AutoThreadTaskRunner(message_loop.task_runner(), - run_loop.QuitClosure()); + scoped_refptr<AutoThreadTaskRunner> ui_task_runner = new AutoThreadTaskRunner( + main_task_executor.task_runner(), run_loop.QuitClosure()); // Launch the video capture thread. scoped_refptr<AutoThreadTaskRunner> video_capture_task_runner = @@ -49,13 +49,13 @@ // Launch the input thread. scoped_refptr<AutoThreadTaskRunner> input_task_runner = - AutoThread::CreateWithType( - "Input thread", ui_task_runner, base::MessageLoop::TYPE_IO); + AutoThread::CreateWithType("Input thread", ui_task_runner, + base::MessagePump::Type::IO); // Launch the I/O thread. scoped_refptr<AutoThreadTaskRunner> io_task_runner = AutoThread::CreateWithType("I/O thread", ui_task_runner, - base::MessageLoop::TYPE_IO); + base::MessagePump::Type::IO); mojo::core::ScopedIPCSupport ipc_support( io_task_runner->task_runner(),
diff --git a/remoting/host/host_config_upgrader.h b/remoting/host/host_config_upgrader.h index 53b9540..ae3ebe3e 100644 --- a/remoting/host/host_config_upgrader.h +++ b/remoting/host/host_config_upgrader.h
@@ -10,8 +10,8 @@ #include "base/files/file_path.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/values.h" #include "net/base/backoff_entry.h" #include "remoting/base/offline_token_exchanger.h" @@ -47,7 +47,7 @@ void WriteConfig(); - base::MessageLoopForIO message_loop_; + base::SingleThreadTaskExecutor io_task_executor_{base::MessagePump::Type::IO}; base::RunLoop run_loop_; int exit_code_ = 0; base::FilePath config_path_;
diff --git a/remoting/host/host_details.cc b/remoting/host/host_details.cc index 225fb04..906176a4 100644 --- a/remoting/host/host_details.cc +++ b/remoting/host/host_details.cc
@@ -4,19 +4,17 @@ #include "remoting/host/host_details.h" +#include "base/system/sys_info.h" #include "build/build_config.h" #if defined(OS_LINUX) #include "base/linux_util.h" -#include "base/system/sys_info.h" -#else -#include "remoting/base/platform_details.h" #endif namespace remoting { // Get the host Operating System Name, removing the need to check for OS -// definitions and keeps the keys used consistant. +// definitions and keeps the keys used consistent. std::string GetHostOperatingSystemName() { #if defined(OS_WIN) return "Windows"; @@ -39,7 +37,7 @@ #if defined(OS_LINUX) return base::GetLinuxDistro(); #else - return GetOperatingSystemVersionString(); + return base::SysInfo::OperatingSystemVersion(); #endif }
diff --git a/remoting/host/it2me/it2me_native_messaging_host_main.cc b/remoting/host/it2me/it2me_native_messaging_host_main.cc index f0c7b56..5ad317a 100644 --- a/remoting/host/it2me/it2me_native_messaging_host_main.cc +++ b/remoting/host/it2me/it2me_native_messaging_host_main.cc
@@ -9,8 +9,8 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/i18n/icu_util.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" @@ -67,9 +67,10 @@ } // namespace // Creates a It2MeNativeMessagingHost instance, attaches it to stdin/stdout and -// runs the message loop until It2MeNativeMessagingHost signals shutdown. +// runs the task executor until It2MeNativeMessagingHost signals shutdown. int It2MeNativeMessagingHostMain(int argc, char** argv) { - // This object instance is required by Chrome code (such as MessageLoop). + // This object instance is required by Chrome code (such as + // SingleThreadTaskExecutor). base::AtExitManager exit_manager; base::CommandLine::Init(argc, argv); @@ -199,10 +200,11 @@ #error Not implemented. #endif - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::RunLoop run_loop; - // NetworkChangeNotifier must be initialized after MessageLoop. + // NetworkChangeNotifier must be initialized after SingleThreadTaskExecutor. std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier( net::NetworkChangeNotifier::Create()); @@ -217,7 +219,7 @@ std::unique_ptr<ChromotingHostContext> context = ChromotingHostContext::Create(new remoting::AutoThreadTaskRunner( - message_loop.task_runner(), run_loop.QuitClosure())); + main_task_executor.task_runner(), run_loop.QuitClosure())); std::unique_ptr<PolicyWatcher> policy_watcher = PolicyWatcher::CreateWithTaskRunner(context->file_task_runner()); std::unique_ptr<extensions::NativeMessageHost> host(
diff --git a/remoting/host/remoting_me2me_host.cc b/remoting/host/remoting_me2me_host.cc index 59bdbd6..949ac5cd 100644 --- a/remoting/host/remoting_me2me_host.cc +++ b/remoting/host/remoting_me2me_host.cc
@@ -19,13 +19,13 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringize_macros.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "build/build_config.h" #include "components/policy/policy_constants.h" @@ -1842,16 +1842,17 @@ base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Me2Me"); - // Create the main message loop and start helper threads. - base::MessageLoopForUI message_loop; + // Create the main task executor and start helper threads. + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::RunLoop run_loop; std::unique_ptr<ChromotingHostContext> context = ChromotingHostContext::Create(new AutoThreadTaskRunner( - message_loop.task_runner(), run_loop.QuitClosure())); + main_task_executor.task_runner(), run_loop.QuitClosure())); if (!context) return kInitializationFailed; - // NetworkChangeNotifier must be initialized after MessageLoop. + // NetworkChangeNotifier must be initialized after SingleThreadTaskExecutor. std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier( net::NetworkChangeNotifier::Create()); @@ -1863,7 +1864,7 @@ base::TimeDelta::FromSeconds(kShutdownTimeoutSeconds)); new HostProcess(std::move(context), &exit_code, &shutdown_watchdog); - // Run the main (also UI) message loop until the host no longer needs it. + // Run the main (also UI) task executor until the host no longer needs it. run_loop.Run(); // Block until tasks blocking shutdown have completed their execution.
diff --git a/remoting/host/security_key/remote_security_key_main.cc b/remoting/host/security_key/remote_security_key_main.cc index a853c30..754942b 100644 --- a/remoting/host/security_key/remote_security_key_main.cc +++ b/remoting/host/security_key/remote_security_key_main.cc
@@ -10,8 +10,8 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread_task_runner_handle.h" #include "mojo/core/embedder/embedder.h" #include "mojo/core/embedder/scoped_ipc_support.h" @@ -161,7 +161,7 @@ int RemoteSecurityKeyMain(int argc, char** argv) { // This object instance is required by Chrome classes (such as MessageLoop). base::AtExitManager exit_manager; - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); base::CommandLine::Init(argc, argv); remoting::InitHostLogging();
diff --git a/remoting/host/setup/me2me_native_messaging_host_main.cc b/remoting/host/setup/me2me_native_messaging_host_main.cc index ba5cf504..026041e 100644 --- a/remoting/host/setup/me2me_native_messaging_host_main.cc +++ b/remoting/host/setup/me2me_native_messaging_host_main.cc
@@ -13,9 +13,9 @@ #include "base/command_line.h" #include "base/files/file.h" #include "base/i18n/icu_util.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/threading/thread.h" #include "build/build_config.h" @@ -56,7 +56,8 @@ namespace remoting { int Me2MeNativeMessagingHostMain(int argc, char** argv) { - // This object instance is required by Chrome code (such as MessageLoop). + // This object instance is required by Chrome code (such as + // SingleThreadTaskExecutor). base::AtExitManager exit_manager; base::CommandLine::Init(argc, argv); @@ -95,9 +96,10 @@ // An IO thread is needed for the pairing registry and URL context getter. base::Thread io_thread("io_thread"); io_thread.StartWithOptions( - base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); + base::Thread::Options(base::MessagePump::Type::IO, 0)); - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::RunLoop run_loop; scoped_refptr<DaemonController> daemon_controller = @@ -251,7 +253,7 @@ std::unique_ptr<ChromotingHostContext> context = ChromotingHostContext::Create(new remoting::AutoThreadTaskRunner( - message_loop.task_runner(), run_loop.QuitClosure())); + main_task_executor.task_runner(), run_loop.QuitClosure())); // Create the native messaging host. std::unique_ptr<extensions::NativeMessageHost> host(
diff --git a/remoting/host/setup/start_host_main.cc b/remoting/host/setup/start_host_main.cc index c2e178f..90bbad0 100644 --- a/remoting/host/setup/start_host_main.cc +++ b/remoting/host/setup/start_host_main.cc
@@ -237,7 +237,7 @@ /*consent_to_data_collection=*/true, auth_code, redirect_url, base::Bind(&OnDone)); - // Run the message loop until the StartHost completion callback. + // Run the task executor until the StartHost completion callback. base::RunLoop run_loop; g_active_run_loop = &run_loop; run_loop.Run();
diff --git a/remoting/host/win/chromoting_module.cc b/remoting/host/win/chromoting_module.cc index c0cae132..c972b40 100644 --- a/remoting/host/win/chromoting_module.cc +++ b/remoting/host/win/chromoting_module.cc
@@ -6,9 +6,9 @@ #include "base/lazy_instance.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/win/scoped_handle.h" #include "remoting/base/auto_thread_task_runner.h" #include "remoting/base/typed_buffer.h" @@ -115,11 +115,12 @@ return false; } - // Arrange to run |message_loop| until no components depend on it. - base::MessageLoopForUI message_loop; + // Arrange to run |main_task_executor| until no components depend on it. + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::RunLoop run_loop; g_module_task_runner.Get() = new AutoThreadTaskRunner( - message_loop.task_runner(), run_loop.QuitClosure()); + main_task_executor.task_runner(), run_loop.QuitClosure()); // Start accepting activations. result = CoResumeClassObjects();
diff --git a/remoting/host/win/host_service.cc b/remoting/host/win/host_service.cc index 461a55a..35b6eab 100644 --- a/remoting/host/win/host_service.cc +++ b/remoting/host/win/host_service.cc
@@ -16,10 +16,10 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread.h" #include "base/win/message_window.h" #include "base/win/scoped_com_initializer.h" @@ -204,8 +204,8 @@ scoped_refptr<AutoThreadTaskRunner> task_runner) { // Launch the I/O thread. scoped_refptr<AutoThreadTaskRunner> io_task_runner = - AutoThread::CreateWithType( - kIoThreadName, task_runner, base::MessageLoop::TYPE_IO); + AutoThread::CreateWithType(kIoThreadName, task_runner, + base::MessagePump::Type::IO); if (!io_task_runner.get()) { LOG(FATAL) << "Failed to start the I/O thread"; return; @@ -237,9 +237,10 @@ } void HostService::RunAsServiceImpl() { - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::RunLoop run_loop; - main_task_runner_ = message_loop.task_runner(); + main_task_runner_ = main_task_executor.task_runner(); weak_ptr_ = weak_factory_.GetWeakPtr(); // Register the service control handler. @@ -295,9 +296,10 @@ } int HostService::RunInConsole() { - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::RunLoop run_loop; - main_task_runner_ = message_loop.task_runner(); + main_task_runner_ = main_task_executor.task_runner(); weak_ptr_ = weak_factory_.GetWeakPtr(); int result = kInitializationFailed;
diff --git a/remoting/test/chromoting_test_driver.cc b/remoting/test/chromoting_test_driver.cc index 0503656..45fc2fa 100644 --- a/remoting/test/chromoting_test_driver.cc +++ b/remoting/test/chromoting_test_driver.cc
@@ -7,8 +7,8 @@ #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/strings/stringprintf.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" @@ -151,7 +151,7 @@ int main(int argc, char* argv[]) { base::TestSuite test_suite(argc, argv); base::FeatureList::InitializeInstance(std::string(), std::string()); - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); if (!base::CommandLine::InitializedForCurrentProcess()) { if (!base::CommandLine::Init(argc, argv)) {
diff --git a/remoting/test/ftl_services_playground_main.cc b/remoting/test/ftl_services_playground_main.cc index ca5d15f..ef23fff 100644 --- a/remoting/test/ftl_services_playground_main.cc +++ b/remoting/test/ftl_services_playground_main.cc
@@ -4,8 +4,8 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "mojo/core/embedder/embedder.h" #include "remoting/test/ftl_services_playground.h" @@ -14,7 +14,7 @@ base::AtExitManager exitManager; base::CommandLine::Init(argc, argv); - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); remoting::FtlServicesPlayground playground; if (playground.ShouldPrintHelp()) {
diff --git a/remoting/test/ftl_signaling_playground_main.cc b/remoting/test/ftl_signaling_playground_main.cc index 401df12b..51330eea 100644 --- a/remoting/test/ftl_signaling_playground_main.cc +++ b/remoting/test/ftl_signaling_playground_main.cc
@@ -4,8 +4,8 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "mojo/core/embedder/embedder.h" #include "remoting/test/ftl_signaling_playground.h" @@ -14,7 +14,7 @@ base::AtExitManager exitManager; base::CommandLine::Init(argc, argv); - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); remoting::FtlSignalingPlayground playground; if (playground.ShouldPrintHelp()) {
diff --git a/remoting/test/it2me_cli_host_main.cc b/remoting/test/it2me_cli_host_main.cc index 50c8928..7b3bc12c 100644 --- a/remoting/test/it2me_cli_host_main.cc +++ b/remoting/test/it2me_cli_host_main.cc
@@ -4,7 +4,7 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" @@ -30,7 +30,7 @@ base::GetLinuxDistro(); #endif // OS_LINUX - base::MessageLoopForIO message_loop; + base::SingleThreadTaskExecutor io_task_executor(base::MessagePump::Type::IO); remoting::It2MeCliHost cli_host; base::ThreadPoolInstance::CreateAndStartWithDefaultParams("It2MeCliHost");
diff --git a/services/metrics/ukm_api.md b/services/metrics/ukm_api.md index 58d74c6..61cbf8fe 100644 --- a/services/metrics/ukm_api.md +++ b/services/metrics/ukm_api.md
@@ -126,33 +126,44 @@ for an enumeration that emits only one result per page-load if it emits anything at all. An enumeration emitted more than once per source will result in proportions that total greater than 1.0 but are still relative to the total -number of loads. +number of loads. If an individual value is emitted more than once per source, +that value's proportion will be greater than 1.0. For example, `Security.SiteEngagement` emits one value (either 4 or 2) per source: -* https://www.google.com/ : 4 -* https://www.facebook.com/ : 2 -* https://www.wikipedia.com/ : 4 +* Source ID: 1, URL: https://www.google.com/, enum value: 4 +* Source ID: 2, URL: https://www.facebook.com/, enum value: 2 +* Source ID: 3, URL: https://www.wikipedia.com/, enum value: 4 +* Source ID: 4, URL: https://www.google.com/, enum value: 4 A proportion calculated over all sources would sum to 1.0: -* 2 (0.3333) -* 4 (0.6667) +* 2 (0.25) +* 4 (0.75) -In contrast, `Blink.UseCounter.Feature` emits multiple values per source: +In contrast, `VirtualKeyboard.Open:TextInputType` emits multiple values per +source, and can emit the same value multiple times per source. The sum of the +proportions for `VirtualKeyboard.Open:TextInputType` will be greater that 1.0, +and some proportions will be greater than 1.0. In the following example, +`TextInputType` is emitted multiple times per source, and `TextInputType=4` is +emitted more than once per source: -* https://www.google.com/ : 1, 2, 4, 6 -* https://www.facebook.com/ : 2, 4, 5 -* https://www.wikipedia.com/ : 1, 2, 4 +* Source ID: 1, URL:https://www.google.com/, enum values: [1, 2, 4, 6] +* Source ID: 2, URL:https://www.facebook.com/, enum values: [2, 4, 5, 4] +* Source ID: 3, URL:https://www.wikipedia.com/, enum values: [1, 2, 4] A proportion calculated over all sources would be: -* 1 (0.6667) -* 2 (1.0000) +* 1 (0.6667 = 2/3) +* 2 (1.0000 = 3/3) * 3 (absent) -* 4 (1.0000) -* 5 (0.3333) -* 6 (0.3333) +* 4 (1.3333 = 4/3) +* 5 (0.3333 = 1/3) +* 6 (0.3333 = 1/3) + +The denominator for each is 3 because there were 3 sources reporting the metric. +The numerator for each enum value is the count of how many times the value was +emitted. ## Get UkmRecorder instance
diff --git a/services/network/cross_origin_read_blocking.cc b/services/network/cross_origin_read_blocking.cc index 60a03f67..e4a07ea 100644 --- a/services/network/cross_origin_read_blocking.cc +++ b/services/network/cross_origin_read_blocking.cc
@@ -623,6 +623,9 @@ // |request_initiator_site_lock_|. If so, then treat this request as // same-origin (even if |request_initiator| might be cross-origin). See // also https://crbug.com/918660. + // TODO(lukasza): https://crbug.com/940068: Remove this code section + // once request_initiator is always set to the webpage (and never to the + // isolated world). if (VerifyRequestInitiatorLock(request_initiator_site_lock_, target_origin) == InitiatorLockCompatibility::kCompatibleLock) { return kAllow;
diff --git a/services/network/network_context.cc b/services/network/network_context.cc index 5d871fc..2eb42bf8 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc
@@ -602,11 +602,13 @@ if (network_service_) network_service_->DeregisterNetworkContext(this); - if (IsPrimaryNetworkContext()) { #if defined(USE_NSS_CERTS) + if (IsPrimaryNetworkContext() && + base::MessageLoopCurrentForIO::IsSet()) { // null in some unit tests. net::SetURLRequestContextForNSSHttpIO(nullptr); -#endif } +#endif + if (cert_net_fetcher_) cert_net_fetcher_->Shutdown(); @@ -2030,13 +2032,14 @@ result.url_request_context->proxy_resolution_service()); } +#if defined(USE_NSS_CERTS) // These must be matched by cleanup code just before the URLRequestContext is // destroyed. - if (params_->primary_network_context) { -#if defined(USE_NSS_CERTS) + if (params_->primary_network_context && + base::MessageLoopCurrentForIO::IsSet()) { // null in some unit tests. net::SetURLRequestContextForNSSHttpIO(result.url_request_context.get()); -#endif } +#endif cookie_manager_ = std::make_unique<CookieManager>( result.url_request_context->cookie_store(),
diff --git a/services/resource_coordinator/BUILD.gn b/services/resource_coordinator/BUILD.gn index 468e597..ccaa4f7 100644 --- a/services/resource_coordinator/BUILD.gn +++ b/services/resource_coordinator/BUILD.gn
@@ -7,6 +7,8 @@ # Others modules should only need the public targets. source_set("lib") { sources = [ + "memory_instrumentation/aggregate_metrics_processor.cc", + "memory_instrumentation/aggregate_metrics_processor.h", "memory_instrumentation/coordinator_impl.cc", "memory_instrumentation/coordinator_impl.h", "memory_instrumentation/graph.cc",
diff --git a/services/resource_coordinator/memory_instrumentation/aggregate_metrics_processor.cc b/services/resource_coordinator/memory_instrumentation/aggregate_metrics_processor.cc new file mode 100644 index 0000000..ad10ff29 --- /dev/null +++ b/services/resource_coordinator/memory_instrumentation/aggregate_metrics_processor.cc
@@ -0,0 +1,163 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/resource_coordinator/memory_instrumentation/aggregate_metrics_processor.h" + +#include <set> +#include <string> +#include <vector> + +#include "base/android/library_loader/anchor_functions.h" +#include "base/android/library_loader/anchor_functions_buildflags.h" +#include "base/bits.h" +#include "base/command_line.h" +#include "base/files/file.h" +#include "base/format_macros.h" +#include "base/logging.h" +#include "base/process/process_metrics.h" +#include "base/strings/stringprintf.h" +#include "base/trace_event/trace_event.h" +#include "services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h" + +#if BUILDFLAG(SUPPORTS_CODE_ORDERING) + +namespace { + +void LogNativeCodeResidentPages(const std::set<size_t>& accessed_pages_set) { + // |SUPPORTS_CODE_ORDERING| can only be enabled on Android. + const auto kResidentPagesPath = base::FilePath( + "/data/local/tmp/chrome/native-library-resident-pages.txt"); + + auto file = base::File(kResidentPagesPath, base::File::FLAG_CREATE_ALWAYS | + base::File::FLAG_WRITE); + + if (!file.IsValid()) { + DLOG(ERROR) << "Could not open " << kResidentPagesPath; + return; + } + + for (size_t page : accessed_pages_set) { + std::string page_str = base::StringPrintf("%" PRIuS "\n", page); + + if (file.WriteAtCurrentPos(page_str.c_str(), + static_cast<int>(page_str.size())) < 0) { + DLOG(WARNING) << "Error while dumping Resident pages"; + return; + } + } +} + +} // namespace + +namespace memory_instrumentation { + +mojom::AggregatedMetricsPtr ComputeGlobalNativeCodeResidentMemoryKb( + const std::map<base::ProcessId, mojom::RawOSMemDump*>& pid_to_pmd) { + std::vector<uint8_t> common_map; + auto metrics = mojom::AggregatedMetricsPtr(mojom::AggregatedMetrics::New()); + + for (const auto& pmd : pid_to_pmd) { + if (!pmd.second || pmd.second->native_library_pages_bitmap.empty()) { + DLOG(WARNING) << "No process pagemap entry for " << pmd.first; + return metrics; + } + + if (common_map.size() < pmd.second->native_library_pages_bitmap.size()) { + common_map.resize(pmd.second->native_library_pages_bitmap.size()); + } + for (size_t i = 0; i < pmd.second->native_library_pages_bitmap.size(); + ++i) { + common_map[i] |= pmd.second->native_library_pages_bitmap[i]; + } + } + + // |accessed_pages_set| will be ~40kB on 32 bit mode and ~80kB on 64 bit mode. + std::set<size_t> accessed_pages_set; + for (size_t i = 0; i < common_map.size(); i++) { + for (int j = 0; j < 8; j++) { + if (common_map[i] & (1 << j)) + accessed_pages_set.insert(i * 8 + j); + } + } + + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + "log-native-library-residency")) { + LogNativeCodeResidentPages(accessed_pages_set); + } + + const size_t kPageSize = base::GetPageSize(); + const size_t kb_per_page = kPageSize / 1024; + + int32_t native_library_resident_not_ordered_kb = + GlobalMemoryDump::AggregatedMetrics::kInvalid; + int32_t native_library_not_resident_ordered_kb = + GlobalMemoryDump::AggregatedMetrics::kInvalid; + int32_t native_library_resident_kb = + static_cast<int32_t>(accessed_pages_set.size() * kb_per_page); + + // Reporting the resident code data only requires |AreAnchorsSane()|, not + // |IsOrderingSane()| which is a stronger guarantee. + if (base::android::IsOrderingSane()) { + // Start and end markers are not necessarily aligned with page boundaries. + size_t start_of_text_page_index = base::android::kStartOfText / kPageSize; + // Range is [start_of_ordered_section_page_offset, + // end_of_ordered_section_page_offset) + size_t start_of_ordered_section_page_offset = + base::android::kStartOfOrderedText / kPageSize - + start_of_text_page_index; + size_t end_of_ordered_section_page_offset = + base::bits::Align(base::android::kEndOfOrderedText, kPageSize) / + kPageSize - + start_of_text_page_index; + + size_t resident_pages_in_ordered_section = 0; + size_t resident_pages_outside_ordered_section = 0; + for (size_t page : accessed_pages_set) { + if (page >= start_of_ordered_section_page_offset && + page < end_of_ordered_section_page_offset) { + resident_pages_in_ordered_section++; + } else { + resident_pages_outside_ordered_section++; + } + } + size_t ordered_section_pages = end_of_ordered_section_page_offset - + start_of_ordered_section_page_offset; + size_t not_resident_ordered_pages = + ordered_section_pages - resident_pages_in_ordered_section; + + native_library_resident_not_ordered_kb = static_cast<int32_t>( + resident_pages_outside_ordered_section * kb_per_page); + native_library_not_resident_ordered_kb = + static_cast<int32_t>(not_resident_ordered_pages * kb_per_page); + } + + // TODO(crbug.com/956464) replace adding |NativeCodeResidentMemory| to trace + // this way by adding it through |tracing_observer| in Finalize(). + TRACE_EVENT_INSTANT1(base::trace_event::MemoryDumpManager::kTraceCategory, + "ReportGlobalNativeCodeResidentMemoryKb", + TRACE_EVENT_SCOPE_GLOBAL, "NativeCodeResidentMemory", + native_library_resident_kb); + + metrics->native_library_resident_kb = native_library_resident_kb; + metrics->native_library_resident_not_ordered_kb = + native_library_resident_not_ordered_kb; + metrics->native_library_not_resident_ordered_kb = + native_library_not_resident_ordered_kb; + return metrics; +} + +} // namespace memory_instrumentation + +#else + +namespace memory_instrumentation { + +mojom::AggregatedMetricsPtr ComputeGlobalNativeCodeResidentMemoryKb( + const std::map<base::ProcessId, mojom::RawOSMemDump*>& pid_to_pmd) { + return mojom::AggregatedMetricsPtr(mojom::AggregatedMetrics::New()); +} + +} // namespace memory_instrumentation + +#endif // #if BUILDFLAG(SUPPORTS_CODE_ORDERING)
diff --git a/services/resource_coordinator/memory_instrumentation/aggregate_metrics_processor.h b/services/resource_coordinator/memory_instrumentation/aggregate_metrics_processor.h new file mode 100644 index 0000000..ae9a816 --- /dev/null +++ b/services/resource_coordinator/memory_instrumentation/aggregate_metrics_processor.h
@@ -0,0 +1,20 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_RESOURCE_COORDINATOR_MEMORY_INSTRUMENTATION_AGGREGATE_METRICS_PROCESSOR_H_ +#define SERVICES_RESOURCE_COORDINATOR_MEMORY_INSTRUMENTATION_AGGREGATE_METRICS_PROCESSOR_H_ + +#include <map> + +#include "base/process/process_handle.h" +#include "build/build_config.h" +#include "services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom.h" + +namespace memory_instrumentation { +mojom::AggregatedMetricsPtr ComputeGlobalNativeCodeResidentMemoryKb( + const std::map<base::ProcessId, mojom::RawOSMemDump*>& pid_to_pmd); + +} // namespace memory_instrumentation + +#endif // SERVICES_RESOURCE_COORDINATOR_MEMORY_INSTRUMENTATION_AGGREGATE_METRICS_PROCESSOR_H_
diff --git a/services/resource_coordinator/memory_instrumentation/queued_request_dispatcher.cc b/services/resource_coordinator/memory_instrumentation/queued_request_dispatcher.cc index b637a1a..044ffda0 100644 --- a/services/resource_coordinator/memory_instrumentation/queued_request_dispatcher.cc +++ b/services/resource_coordinator/memory_instrumentation/queued_request_dispatcher.cc
@@ -5,20 +5,21 @@ #include "services/resource_coordinator/memory_instrumentation/queued_request_dispatcher.h" #include <inttypes.h> +#include <utility> -#include "base/android/library_loader/anchor_functions_buildflags.h" #include "base/bind.h" #include "base/command_line.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" -#include "base/process/process_metrics.h" #include "base/strings/pattern.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" +#include "services/resource_coordinator/memory_instrumentation/aggregate_metrics_processor.h" #include "services/resource_coordinator/memory_instrumentation/graph_processor.h" #include "services/resource_coordinator/memory_instrumentation/switches.h" +#include "services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h" #if defined(OS_MACOSX) && !defined(OS_IOS) #include "base/mac/mac_util.h" @@ -71,76 +72,6 @@ #endif } -#if BUILDFLAG(SUPPORTS_CODE_ORDERING) -void LogNativeCodeResidentPages(const std::set<size_t>& accessed_pages_set) { - // |SUPPORTS_CODE_ORDERING| can only be enabled on Android. - const auto kResidentPagesPath = base::FilePath( - "/data/local/tmp/chrome/native-library-resident-pages.txt"); - - auto file = base::File(kResidentPagesPath, base::File::FLAG_CREATE_ALWAYS | - base::File::FLAG_WRITE); - - if (!file.IsValid()) { - DLOG(ERROR) << "Could not open " << kResidentPagesPath; - return; - } - - for (size_t page : accessed_pages_set) { - std::string page_str = base::StringPrintf("%" PRIuS "\n", page); - - if (file.WriteAtCurrentPos(page_str.c_str(), - static_cast<int>(page_str.size())) < 0) { - DLOG(WARNING) << "Error while dumping Resident pages"; - return; - } - } -} - -size_t ReportGlobalNativeCodeResidentMemoryKb( - const std::map<base::ProcessId, mojom::RawOSMemDump*>& pid_to_pmd) { - std::vector<uint8_t> common_map; - - for (const auto& pmd : pid_to_pmd) { - if (!pmd.second || pmd.second->native_library_pages_bitmap.empty()) { - DLOG(WARNING) << "No process pagemap entry for " << pmd.first; - return 0; - } - - if (common_map.size() < pmd.second->native_library_pages_bitmap.size()) { - common_map.resize(pmd.second->native_library_pages_bitmap.size()); - } - for (size_t i = 0; i < pmd.second->native_library_pages_bitmap.size(); - ++i) { - common_map[i] |= pmd.second->native_library_pages_bitmap[i]; - } - } - - // |accessed_pages_set| will be ~40kB on 32 bit mode and ~80kB on 64 bit mode. - std::set<size_t> accessed_pages_set; - for (size_t i = 0; i < common_map.size(); i++) { - for (int j = 0; j < 8; j++) { - if (common_map[i] & (1 << j)) - accessed_pages_set.insert(i * 8 + j); - } - } - - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - "log-native-library-residency")) { - LogNativeCodeResidentPages(accessed_pages_set); - } - - const size_t kPageSize = base::GetPageSize(); - const size_t native_resident_bytes = accessed_pages_set.size() * kPageSize; - // TODO(crbug.com/956464) replace adding |NativeCodeResidentMemory| to trace - // this way by adding it through |tracing_observer| in Finalize(). - TRACE_EVENT_INSTANT1(base::trace_event::MemoryDumpManager::kTraceCategory, - "ReportGlobalNativeCodeResidentMemoryKb", - TRACE_EVENT_SCOPE_GLOBAL, "NativeCodeResidentMemory", - native_resident_bytes); - return native_resident_bytes / 1024; -} -#endif // #if BUILDFLAG(SUPPORTS_CODE_ORDERING) - memory_instrumentation::mojom::OSMemDumpPtr CreatePublicOSDump( const mojom::RawOSMemDump& internal_os_dump, uint32_t shared_resident_kb) { @@ -526,7 +457,6 @@ mojom::GlobalMemoryDumpPtr global_dump(mojom::GlobalMemoryDump::New()); global_dump->start_time = request->start_time; global_dump->process_dumps.reserve(request->responses.size()); - global_dump->aggregated_metrics = mojom::AggregatedMetrics::New(); for (const auto& response : request->responses) { base::ProcessId pid = response.second.process_id; @@ -630,13 +560,8 @@ global_dump->process_dumps.push_back(std::move(pmd)); } - -#if BUILDFLAG(SUPPORTS_CODE_ORDERING) - size_t native_resident_kb = - ReportGlobalNativeCodeResidentMemoryKb(pid_to_os_dump); - global_dump->aggregated_metrics->native_library_resident_kb = - native_resident_kb; -#endif // BUILDFLAG(SUPPORTS_CODE_ORDERING) + global_dump->aggregated_metrics = + ComputeGlobalNativeCodeResidentMemoryKb(pid_to_os_dump); const bool global_success = request->failed_memory_dump_count == 0;
diff --git a/services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.cc b/services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.cc index 96e025b3..816615e0 100644 --- a/services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.cc +++ b/services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.cc
@@ -48,7 +48,9 @@ GlobalMemoryDump::AggregatedMetrics::AggregatedMetrics( mojom::AggregatedMetricsPtr aggregated_metrics) - : aggregated_metrics_(std::move(aggregated_metrics)) {} + : aggregated_metrics_(aggregated_metrics.is_null() + ? mojom::AggregatedMetrics::New() + : std::move(aggregated_metrics)) {} GlobalMemoryDump::AggregatedMetrics::~AggregatedMetrics() = default;
diff --git a/services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h b/services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h index 77f14ac..e7d7b44 100644 --- a/services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h +++ b/services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h
@@ -5,6 +5,8 @@ #ifndef SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_MEMORY_INSTRUMENTATION_GLOBAL_MEMORY_DUMP_H_ #define SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_MEMORY_INSTRUMENTATION_GLOBAL_MEMORY_DUMP_H_ +#include <memory> +#include <string> #include <utility> #include <vector> @@ -49,17 +51,25 @@ class COMPONENT_EXPORT(RESOURCE_COORDINATOR_PUBLIC_MEMORY_INSTRUMENTATION) AggregatedMetrics { public: - AggregatedMetrics(mojom::AggregatedMetricsPtr aggregated_metrics); + explicit AggregatedMetrics(mojom::AggregatedMetricsPtr aggregated_metrics); ~AggregatedMetrics(); - size_t native_library_resident_kb() const { - if (!aggregated_metrics_) - return 0; + int32_t native_library_resident_kb() const { return aggregated_metrics_->native_library_resident_kb; } + int32_t native_library_resident_not_ordered_kb() const { + return aggregated_metrics_->native_library_resident_not_ordered_kb; + } + + int32_t native_library_not_resident_ordered_kb() const { + return aggregated_metrics_->native_library_not_resident_ordered_kb; + } + + static constexpr int32_t kInvalid = -1; + private: - mojom::AggregatedMetricsPtr aggregated_metrics_; + const mojom::AggregatedMetricsPtr aggregated_metrics_; DISALLOW_COPY_AND_ASSIGN(AggregatedMetrics); };
diff --git a/services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom b/services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom index b284296..56704aa 100644 --- a/services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom +++ b/services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom
@@ -212,7 +212,10 @@ // Metrics aggregated across all processes. struct AggregatedMetrics { - uint32 native_library_resident_kb = 0; + // These values are not always available, -1 when invalid. + int32 native_library_resident_kb = 0; + int32 native_library_resident_not_ordered_kb = 0; + int32 native_library_not_resident_ordered_kb = 0; }; // This struct is returned by the public-facing API
diff --git a/services/service_manager/README.md b/services/service_manager/README.md index fdbd36d..50f0f2f 100644 --- a/services/service_manager/README.md +++ b/services/service_manager/README.md
@@ -475,7 +475,7 @@ #include "services/storage/storage_service.h" void ServiceMain(service_manager::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; storage::StorageService(std::move(request)).RunUntilTermination(); } ```
diff --git a/services/service_manager/tests/background_service_manager_test_service_main.cc b/services/service_manager/tests/background_service_manager_test_service_main.cc index 0cd954d4..4c2a64ea 100644 --- a/services/service_manager/tests/background_service_manager_test_service_main.cc +++ b/services/service_manager/tests/background_service_manager_test_service_main.cc
@@ -4,7 +4,7 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h" @@ -53,6 +53,6 @@ } // namespace service_manager void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; service_manager::TestClient(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/connect/connect_test_app.cc b/services/service_manager/tests/connect/connect_test_app.cc index 9f8f425..0c07de73 100644 --- a/services/service_manager/tests/connect/connect_test_app.cc +++ b/services/service_manager/tests/connect/connect_test_app.cc
@@ -6,10 +6,10 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_current.h" #include "base/optional.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/connector.h" @@ -208,6 +208,6 @@ } // namespace service_manager void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; service_manager::ConnectTestApp(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/connect/connect_test_class_app.cc b/services/service_manager/tests/connect/connect_test_class_app.cc index d895df0..0e20494 100644 --- a/services/service_manager/tests/connect/connect_test_class_app.cc +++ b/services/service_manager/tests/connect/connect_test_class_app.cc
@@ -4,8 +4,8 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/connector.h" @@ -87,7 +87,7 @@ } // namespace service_manager void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; service_manager::ConnectTestClassApp(std::move(request)) .RunUntilTermination(); }
diff --git a/services/service_manager/tests/connect/connect_test_package.cc b/services/service_manager/tests/connect/connect_test_package.cc index f5c9c95..15d3df3 100644 --- a/services/service_manager/tests/connect/connect_test_package.cc +++ b/services/service_manager/tests/connect/connect_test_package.cc
@@ -10,9 +10,9 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/optional.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/simple_thread.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" @@ -158,7 +158,7 @@ // base::SimpleThread: void Run() override { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; base::RunLoop run_loop; run_loop_ = &run_loop; service_binding_.Bind(std::move(request_)); @@ -271,6 +271,6 @@ } // namespace service_manager void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; service_manager::ConnectTestService(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/connect/connect_test_singleton_app.cc b/services/service_manager/tests/connect/connect_test_singleton_app.cc index 0e876d1..b8785f5 100644 --- a/services/service_manager/tests/connect/connect_test_singleton_app.cc +++ b/services/service_manager/tests/connect/connect_test_singleton_app.cc
@@ -3,14 +3,14 @@ // found in the LICENSE file. #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" #include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; service_manager::Service service; service_manager::ServiceBinding binding(&service, std::move(request)); service.RunUntilTermination();
diff --git a/services/service_manager/tests/lifecycle/app.cc b/services/service_manager/tests/lifecycle/app.cc index c5ea7740..b1af2696 100644 --- a/services/service_manager/tests/lifecycle/app.cc +++ b/services/service_manager/tests/lifecycle/app.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/tests/lifecycle/app_client.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; service_manager::test::AppClient(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/lifecycle/package.cc b/services/service_manager/tests/lifecycle/package.cc index 334803a..ad455c1 100644 --- a/services/service_manager/tests/lifecycle/package.cc +++ b/services/service_manager/tests/lifecycle/package.cc
@@ -7,7 +7,7 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service_binding.h" @@ -154,6 +154,6 @@ } // namespace void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; Package(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/lifecycle/parent.cc b/services/service_manager/tests/lifecycle/parent.cc index 3246e82..b72a498 100644 --- a/services/service_manager/tests/lifecycle/parent.cc +++ b/services/service_manager/tests/lifecycle/parent.cc
@@ -5,8 +5,8 @@ #include <memory> #include "base/bind.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/connector.h" @@ -66,6 +66,6 @@ } // namespace void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; Parent(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/service_manager/embedder.cc b/services/service_manager/tests/service_manager/embedder.cc index 30e2d07..403e48b1 100644 --- a/services/service_manager/tests/service_manager/embedder.cc +++ b/services/service_manager/tests/service_manager/embedder.cc
@@ -6,7 +6,7 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" #include "services/service_manager/public/cpp/service_executable/service_main.h" @@ -60,6 +60,6 @@ } // namespace void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; Embedder(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/service_manager/target.cc b/services/service_manager/tests/service_manager/target.cc index f7638ff..9b6d02a 100644 --- a/services/service_manager/tests/service_manager/target.cc +++ b/services/service_manager/tests/service_manager/target.cc
@@ -3,7 +3,7 @@ // found in the LICENSE file. #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" @@ -37,6 +37,6 @@ } // namespace void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; Target(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/shutdown/shutdown_client_app.cc b/services/service_manager/tests/shutdown/shutdown_client_app.cc index b497732..b5f1670 100644 --- a/services/service_manager/tests/shutdown/shutdown_client_app.cc +++ b/services/service_manager/tests/shutdown/shutdown_client_app.cc
@@ -4,7 +4,7 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/connector.h" @@ -68,6 +68,6 @@ } // namespace service_manager void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; service_manager::ShutdownClientApp(std::move(request)).RunUntilTermination(); }
diff --git a/services/service_manager/tests/shutdown/shutdown_service_app.cc b/services/service_manager/tests/shutdown/shutdown_service_app.cc index 40292e1..1b211f4 100644 --- a/services/service_manager/tests/shutdown/shutdown_service_app.cc +++ b/services/service_manager/tests/shutdown/shutdown_service_app.cc
@@ -4,7 +4,7 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h" @@ -53,6 +53,6 @@ } // namespace service_manager void ServiceMain(service_manager::mojom::ServiceRequest request) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; service_manager::ShutdownServiceApp(std::move(request)).RunUntilTermination(); }
diff --git a/services/tracing/perfetto/consumer_host.cc b/services/tracing/perfetto/consumer_host.cc index 974dbad..f840aa3 100644 --- a/services/tracing/perfetto/consumer_host.cc +++ b/services/tracing/perfetto/consumer_host.cc
@@ -25,9 +25,9 @@ #include "services/tracing/perfetto/track_event_json_exporter.h" #include "services/tracing/public/cpp/trace_event_args_whitelist.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/observable_events.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_packet.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_stats.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/protos/perfetto/config/trace_config.pb.h" namespace tracing {
diff --git a/services/tracing/perfetto/consumer_host_unittest.cc b/services/tracing/perfetto/consumer_host_unittest.cc index f3cd37dd..2af66e8 100644 --- a/services/tracing/perfetto/consumer_host_unittest.cc +++ b/services/tracing/perfetto/consumer_host_unittest.cc
@@ -25,8 +25,8 @@ #include "services/tracing/perfetto/perfetto_service.h" #include "services/tracing/perfetto/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_packet.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/protos/perfetto/config/trace_config.pb.h" #include "third_party/perfetto/protos/perfetto/trace/trace.pb.h" #include "third_party/perfetto/protos/perfetto/trace/trace_packet.pb.h"
diff --git a/services/tracing/perfetto/json_trace_exporter_unittest.cc b/services/tracing/perfetto/json_trace_exporter_unittest.cc index 15a3bc9..107033c 100644 --- a/services/tracing/perfetto/json_trace_exporter_unittest.cc +++ b/services/tracing/perfetto/json_trace_exporter_unittest.cc
@@ -20,8 +20,8 @@ #include "base/values.h" #include "services/tracing/public/mojom/perfetto_service.mojom.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_packet.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/protos/perfetto/trace/chrome/chrome_trace_event.pb.h" #include "third_party/perfetto/protos/perfetto/trace/trace_packet.pb.h"
diff --git a/services/tracing/perfetto/perfetto_tracing_coordinator.cc b/services/tracing/perfetto/perfetto_tracing_coordinator.cc index 62204988..7af17ff 100644 --- a/services/tracing/perfetto/perfetto_tracing_coordinator.cc +++ b/services/tracing/perfetto/perfetto_tracing_coordinator.cc
@@ -25,9 +25,9 @@ #include "services/tracing/public/mojom/constants.mojom.h" #include "services/tracing/public/mojom/perfetto_service.mojom.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/consumer.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_stats.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/tracing_service.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" namespace tracing {
diff --git a/services/tracing/perfetto/producer_host.cc b/services/tracing/perfetto/producer_host.cc index 8fdd6e6..891773a 100644 --- a/services/tracing/perfetto/producer_host.cc +++ b/services/tracing/perfetto/producer_host.cc
@@ -13,8 +13,8 @@ #include "services/tracing/public/cpp/perfetto/shared_memory.h" #include "services/tracing/public/cpp/tracing_features.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/commit_data_request.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/data_source_descriptor.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" +#include "third_party/perfetto/include/perfetto/tracing/core/data_source_descriptor.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" namespace tracing {
diff --git a/services/tracing/perfetto/test_utils.cc b/services/tracing/perfetto/test_utils.cc index b50d399..76fa666b4 100644 --- a/services/tracing/perfetto/test_utils.cc +++ b/services/tracing/perfetto/test_utils.cc
@@ -9,9 +9,9 @@ #include "base/run_loop.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/commit_data_request.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_packet.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_writer.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/protos/perfetto/common/commit_data_request.pb.h" #include "third_party/perfetto/protos/perfetto/trace/test_event.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/trace_packet.pb.h"
diff --git a/services/tracing/perfetto/track_event_json_exporter_unittest.cc b/services/tracing/perfetto/track_event_json_exporter_unittest.cc index 35a7476..4be9cc2 100644 --- a/services/tracing/perfetto/track_event_json_exporter_unittest.cc +++ b/services/tracing/perfetto/track_event_json_exporter_unittest.cc
@@ -18,8 +18,8 @@ #include "base/values.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_packet.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/protos/perfetto/trace/chrome/chrome_trace_event.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/trace_packet.pb.h"
diff --git a/services/tracing/public/cpp/perfetto/perfetto_config.h b/services/tracing/public/cpp/perfetto/perfetto_config.h index 32ae0b6f..b461678 100644 --- a/services/tracing/public/cpp/perfetto/perfetto_config.h +++ b/services/tracing/public/cpp/perfetto/perfetto_config.h
@@ -6,7 +6,7 @@ #define SERVICES_TRACING_PUBLIC_CPP_PERFETTO_PERFETTO_CONFIG_H_ #include "base/component_export.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" namespace base { namespace trace_event {
diff --git a/services/tracing/public/mojom/chrome_config_mojom_traits.h b/services/tracing/public/mojom/chrome_config_mojom_traits.h index ccdbba9..1deafb3 100644 --- a/services/tracing/public/mojom/chrome_config_mojom_traits.h +++ b/services/tracing/public/mojom/chrome_config_mojom_traits.h
@@ -12,7 +12,7 @@ #include "mojo/public/cpp/bindings/struct_traits.h" #include "services/tracing/public/mojom/perfetto_service.mojom.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/chrome_config.h" +#include "third_party/perfetto/include/perfetto/tracing/core/chrome_config.h" namespace mojo { template <>
diff --git a/services/tracing/public/mojom/data_source_config_mojom_traits.h b/services/tracing/public/mojom/data_source_config_mojom_traits.h index 4e357412..e749282 100644 --- a/services/tracing/public/mojom/data_source_config_mojom_traits.h +++ b/services/tracing/public/mojom/data_source_config_mojom_traits.h
@@ -12,8 +12,8 @@ #include "mojo/public/cpp/bindings/struct_traits.h" #include "services/tracing/public/mojom/perfetto_service.mojom.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/chrome_config.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/data_source_config.h" +#include "third_party/perfetto/include/perfetto/tracing/core/chrome_config.h" +#include "third_party/perfetto/include/perfetto/tracing/core/data_source_config.h" namespace mojo { template <>
diff --git a/services/tracing/public/mojom/data_source_descriptor_mojom_traits.h b/services/tracing/public/mojom/data_source_descriptor_mojom_traits.h index 56c7992..b98db41 100644 --- a/services/tracing/public/mojom/data_source_descriptor_mojom_traits.h +++ b/services/tracing/public/mojom/data_source_descriptor_mojom_traits.h
@@ -12,7 +12,7 @@ #include "mojo/public/cpp/bindings/struct_traits.h" #include "services/tracing/public/mojom/perfetto_service.mojom.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/data_source_descriptor.h" +#include "third_party/perfetto/include/perfetto/tracing/core/data_source_descriptor.h" namespace mojo { template <>
diff --git a/services/tracing/public/mojom/perfetto_service.typemap b/services/tracing/public/mojom/perfetto_service.typemap index 58a062b..3d6fe1ee 100644 --- a/services/tracing/public/mojom/perfetto_service.typemap +++ b/services/tracing/public/mojom/perfetto_service.typemap
@@ -1,10 +1,10 @@ mojom = "//services/tracing/public/mojom/perfetto_service.mojom" public_headers = [ "//third_party/perfetto/include/perfetto/ext/tracing/core/commit_data_request.h", - "//third_party/perfetto/include/perfetto/ext/tracing/core/data_source_config.h", - "//third_party/perfetto/include/perfetto/ext/tracing/core/data_source_descriptor.h", - "//third_party/perfetto/include/perfetto/ext/tracing/core/chrome_config.h", - "//third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h", + "//third_party/perfetto/include/perfetto/tracing/core/data_source_config.h", + "//third_party/perfetto/include/perfetto/tracing/core/data_source_descriptor.h", + "//third_party/perfetto/include/perfetto/tracing/core/chrome_config.h", + "//third_party/perfetto/include/perfetto/tracing/core/trace_config.h", ] traits_headers = [ "//services/tracing/public/mojom/commit_data_request_mojom_traits.h",
diff --git a/services/tracing/public/mojom/trace_config_mojom_traits.h b/services/tracing/public/mojom/trace_config_mojom_traits.h index bbd3b530..49fefba 100644 --- a/services/tracing/public/mojom/trace_config_mojom_traits.h +++ b/services/tracing/public/mojom/trace_config_mojom_traits.h
@@ -13,7 +13,7 @@ #include "mojo/public/cpp/bindings/struct_traits.h" #include "services/tracing/public/mojom/perfetto_service.mojom.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_config.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" namespace mojo {
diff --git a/services/video_capture/test/mock_device_shared_access_unittest.cc b/services/video_capture/test/mock_device_shared_access_unittest.cc index 5c261fd..cfd1d4c 100644 --- a/services/video_capture/test/mock_device_shared_access_unittest.cc +++ b/services/video_capture/test/mock_device_shared_access_unittest.cc
@@ -383,6 +383,11 @@ .WillOnce(InvokeWithoutArgs([&wait_loop]() { wait_loop.Quit(); })); subscription_2_.reset(); wait_loop.Run(); + + // DeviceMediaToMojoAdapter::Stop() issues a DeleteSoon for its |receiver_| + // on the current sequence. Wait for this before exiting the test in order to + // avoid leaked object failing ASAN tests. See also https://crbug.com/961066. + base::RunLoop().RunUntilIdle(); } TEST_F(MockVideoCaptureDeviceSharedAccessTest, @@ -396,6 +401,11 @@ .WillOnce(InvokeWithoutArgs([&wait_loop]() { wait_loop.Quit(); })); source_.reset(); wait_loop.Run(); + + // DeviceMediaToMojoAdapter::Stop() issues a DeleteSoon for its |receiver_| + // on the current sequence. Wait for this before exiting the test in order to + // avoid leaked object failing ASAN tests. See also https://crbug.com/961066. + base::RunLoop().RunUntilIdle(); } TEST_F(MockVideoCaptureDeviceSharedAccessTest,
diff --git a/third_party/abseil-cpp/absl/debugging/BUILD.gn b/third_party/abseil-cpp/absl/debugging/BUILD.gn index 99d21b73..a3c7cfe 100644 --- a/third_party/abseil-cpp/absl/debugging/BUILD.gn +++ b/third_party/abseil-cpp/absl/debugging/BUILD.gn
@@ -64,6 +64,7 @@ ":demangle_internal", "../base", "../base:core_headers", + "../base:dynamic_annotations", "../base:malloc_internal", ] }
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 b0f9d98e..7fce333 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
@@ -54,7 +54,7 @@ &GetCSSPropertyOffsetDistance(), &GetCSSPropertyOffsetRotate(), }; - DEFINE_STATIC_LOCAL(StylePropertyShorthand, offsetLonghands, (CSSPropertyID::kOffset, offsetProperties, base::size(offsetProperties))); + DEFINE_STATIC_LOCAL(const StylePropertyShorthand, offsetLonghands, (CSSPropertyID::kOffset, offsetProperties, base::size(offsetProperties))); return offsetLonghands; }
diff --git a/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_initial_values.h.tmpl b/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_initial_values.h.tmpl index ef475c3..8bf3e6e 100644 --- a/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_initial_values.h.tmpl +++ b/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_initial_values.h.tmpl
@@ -121,7 +121,7 @@ private: static const FilterOperations& InitialFilterInternal() { - DEFINE_STATIC_LOCAL(Persistent<FilterOperationsWrapper>, ops, + DEFINE_STATIC_LOCAL(const Persistent<FilterOperationsWrapper>, ops, (MakeGarbageCollected<FilterOperationsWrapper>())); return ops->Operations(); }
diff --git a/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h b/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h index 645f4d52..c4cec29 100644 --- a/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h +++ b/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h
@@ -56,7 +56,7 @@ // These should only be accessed on the PaintWorklet thread. String NameCopy() const { return name_.IsolatedCopy(); } - PaintWorkletStylePropertyMap::CrossThreadData StyleMapData() { + PaintWorkletStylePropertyMap::CrossThreadData StyleMapData() const { return PaintWorkletStylePropertyMap::CopyCrossThreadData(style_map_data_); }
diff --git a/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc b/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc index 34ac1b4..06c9242 100644 --- a/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc +++ b/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc
@@ -99,6 +99,7 @@ } // namespace +// static PaintWorkletStylePropertyMap::CrossThreadData PaintWorkletStylePropertyMap::BuildCrossThreadData( const Document& document, @@ -115,6 +116,7 @@ return data; } +// static PaintWorkletStylePropertyMap::CrossThreadData PaintWorkletStylePropertyMap::CopyCrossThreadData(const CrossThreadData& data) { PaintWorkletStylePropertyMap::CrossThreadData copied_data;
diff --git a/third_party/blink/renderer/core/editing/editing_style.cc b/third_party/blink/renderer/core/editing/editing_style.cc index b29d5db..5999546 100644 --- a/third_party/blink/renderer/core/editing/editing_style.cc +++ b/third_party/blink/renderer/core/editing/editing_style.cc
@@ -397,8 +397,6 @@ return CSSIdentifierValue::Create(size); } -float EditingStyle::no_font_delta_ = 0.0f; - EditingStyle::EditingStyle(ContainerNode* node, PropertiesToInclude properties_to_include) { Init(node, properties_to_include); @@ -622,7 +620,7 @@ bool EditingStyle::IsEmpty() const { return (!mutable_style_ || mutable_style_->IsEmpty()) && - font_size_delta_ == no_font_delta_; + font_size_delta_ == kNoFontDelta; } bool EditingStyle::GetTextDirection(WritingDirection& writing_direction) const { @@ -674,7 +672,7 @@ void EditingStyle::Clear() { mutable_style_.Clear(); is_monospace_font_ = false; - font_size_delta_ = no_font_delta_; + font_size_delta_ = kNoFontDelta; } EditingStyle* EditingStyle::Copy() const {
diff --git a/third_party/blink/renderer/core/editing/editing_style.h b/third_party/blink/renderer/core/editing/editing_style.h index fc7be19..9700794 100644 --- a/third_party/blink/renderer/core/editing/editing_style.h +++ b/third_party/blink/renderer/core/editing/editing_style.h
@@ -74,7 +74,7 @@ kExtractMatchingStyle, kDoNotExtractMatchingStyle }; - static float no_font_delta_; + static constexpr float kNoFontDelta = 0.0f; EditingStyle() = default; EditingStyle(ContainerNode*, @@ -147,7 +147,7 @@ int LegacyFontSize(Document*) const; float FontSizeDelta() const { return font_size_delta_; } - bool HasFontSizeDelta() const { return font_size_delta_ != no_font_delta_; } + bool HasFontSizeDelta() const { return font_size_delta_ != kNoFontDelta; } void SetProperty(CSSPropertyID, const String& value, @@ -177,7 +177,7 @@ Member<MutableCSSPropertyValueSet> mutable_style_; bool is_monospace_font_ = false; - float font_size_delta_ = no_font_delta_; + float font_size_delta_ = kNoFontDelta; bool is_vertical_align_ = false; friend class HTMLElementEquivalent;
diff --git a/third_party/blink/renderer/core/html/forms/email_input_type.cc b/third_party/blink/renderer/core/html/forms/email_input_type.cc index 699cd73..fd9a06f 100644 --- a/third_party/blink/renderer/core/html/forms/email_input_type.cc +++ b/third_party/blink/renderer/core/html/forms/email_input_type.cc
@@ -82,7 +82,7 @@ // Leak |idna| at the end. UErrorCode error_code = U_ZERO_ERROR; - static icu::IDNA* idna = + static const icu::IDNA* const idna = icu::IDNA::createUTS46Instance(kIdnaConversionOption, error_code); DCHECK(idna); icu::IDNAInfo idna_info;
diff --git a/third_party/blink/renderer/core/layout/layout_block_flow_line.cc b/third_party/blink/renderer/core/layout/layout_block_flow_line.cc index e9a2365..ffcf7628 100644 --- a/third_party/blink/renderer/core/layout/layout_block_flow_line.cc +++ b/third_party/blink/renderer/core/layout/layout_block_flow_line.cc
@@ -2289,10 +2289,11 @@ // The first clean line doesn't match, but we can check a handful of following // lines to try to match back up. - static int num_lines = 8; // The # of lines we're willing to match against. + // The # of lines we're willing to match against. + constexpr int kNumLines = 8; RootInlineBox* original_end_line = layout_state.EndLine(); RootInlineBox* line = original_end_line; - for (int i = 0; i < num_lines && line; i++, line = line->NextRootBox()) { + for (int i = 0; i < kNumLines && line; i++, line = line->NextRootBox()) { if (line->LineBreakObj() == resolver.GetPosition().GetLineLayoutItem() && line->LineBreakPos() == resolver.GetPosition().Offset()) { // We have a match.
diff --git a/third_party/blink/renderer/core/layout/layout_object.cc b/third_party/blink/renderer/core/layout/layout_object.cc index a70ad771..844b4192 100644 --- a/third_party/blink/renderer/core/layout/layout_object.cc +++ b/third_party/blink/renderer/core/layout/layout_object.cc
@@ -1788,6 +1788,8 @@ string_builder.Append('\t'); string_builder.Append(GetNode()->ToString()); } + if (LayoutBlockedByDisplayLock(DisplayLockContext::kChildren)) + string_builder.Append(" (display-locked)"); } void LayoutObject::DumpLayoutTreeAndMark(StringBuilder& string_builder, @@ -1807,11 +1809,14 @@ DumpLayoutObject(object_info, true, kShowTreeCharacterOffset); string_builder.Append(object_info); - for (const LayoutObject* child = SlowFirstChild(); child; - child = child->NextSibling()) { - string_builder.Append('\n'); - child->DumpLayoutTreeAndMark(string_builder, marked_object1, marked_label1, - marked_object2, marked_label2, depth + 1); + if (!LayoutBlockedByDisplayLock(DisplayLockContext::kChildren)) { + for (const LayoutObject* child = SlowFirstChild(); child; + child = child->NextSibling()) { + string_builder.Append('\n'); + child->DumpLayoutTreeAndMark(string_builder, marked_object1, + marked_label1, marked_object2, marked_label2, + depth + 1); + } } }
diff --git a/third_party/blink/renderer/core/layout/layout_tree_as_text.cc b/third_party/blink/renderer/core/layout/layout_tree_as_text.cc index a7ee036..ebc4716 100644 --- a/third_party/blink/renderer/core/layout/layout_tree_as_text.cc +++ b/third_party/blink/renderer/core/layout/layout_tree_as_text.cc
@@ -26,6 +26,7 @@ #include "third_party/blink/renderer/core/layout/layout_tree_as_text.h" #include "third_party/blink/renderer/core/css/css_property_value_set.h" +#include "third_party/blink/renderer/core/display_lock/display_lock_context.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/pseudo_element.h" #include "third_party/blink/renderer/core/editing/frame_selection.h" @@ -357,6 +358,9 @@ if (needs_layout) ts << ")"; } + + if (o.LayoutBlockedByDisplayLock(DisplayLockContext::kChildren)) + ts << " (display-locked)"; } static void WriteInlineBox(WTF::TextStream& ts, @@ -569,11 +573,13 @@ } } - for (LayoutObject* child = o.SlowFirstChild(); child; - child = child->NextSibling()) { - if (child->HasLayer()) - continue; - Write(ts, *child, indent + 1, behavior); + if (!o.LayoutBlockedByDisplayLock(DisplayLockContext::kChildren)) { + for (LayoutObject* child = o.SlowFirstChild(); child; + child = child->NextSibling()) { + if (child->HasLayer()) + continue; + Write(ts, *child, indent + 1, behavior); + } } if (o.IsLayoutEmbeddedContent()) {
diff --git a/third_party/blink/renderer/core/layout/line/line_box_list.cc b/third_party/blink/renderer/core/layout/line/line_box_list.cc index 777999a0..ad9d23cc 100644 --- a/third_party/blink/renderer/core/layout/line/line_box_list.cc +++ b/third_party/blink/renderer/core/layout/line/line_box_list.cc
@@ -50,13 +50,13 @@ const LineBoxList& LineBoxList::Empty() { // Need to use "static" because DISALLOW_NEW. - static LineBoxList empty; + static const LineBoxList empty; return empty; } const InlineTextBoxList& InlineTextBoxList::Empty() { // Need to use "static" because DISALLOW_NEW. - static InlineTextBoxList empty; + static const InlineTextBoxList empty; return empty; }
diff --git a/third_party/blink/renderer/core/layout/shapes/shape.cc b/third_party/blink/renderer/core/layout/shapes/shape.cc index c6f299e..41f2a54 100644 --- a/third_party/blink/renderer/core/layout/shapes/shape.cc +++ b/third_party/blink/renderer/core/layout/shapes/shape.cc
@@ -310,13 +310,10 @@ } static bool IsValidRasterShapeSize(const IntSize& size) { - static size_t max_image_size_bytes = 0; - if (!max_image_size_bytes) { - size_t size32_max_bytes = - 0xFFFFFFFF / 4; // Some platforms don't limit MaxDecodedImageBytes. - max_image_size_bytes = - std::min(size32_max_bytes, Platform::Current()->MaxDecodedImageBytes()); - } + // Some platforms don't limit MaxDecodedImageBytes. + constexpr size_t size32_max_bytes = 0xFFFFFFFF / 4; + static const size_t max_image_size_bytes = + std::min(size32_max_bytes, Platform::Current()->MaxDecodedImageBytes()); return size.Area() * 4 < max_image_size_bytes; }
diff --git a/third_party/blink/renderer/core/layout/text_autosizer.cc b/third_party/blink/renderer/core/layout/text_autosizer.cc index 3c7ddc7..0684e96 100644 --- a/third_party/blink/renderer/core/layout/text_autosizer.cc +++ b/third_party/blink/renderer/core/layout/text_autosizer.cc
@@ -1266,8 +1266,8 @@ // Clusters with a root that is significantly narrower than the // deepestBlockContainingAllText of their parent autosize independently of // their parent. - static float narrow_width_difference = 200; - if (cluster_text_width - content_width > narrow_width_difference) + constexpr float kNarrowWidthDifference = 200; + if (cluster_text_width - content_width > kNarrowWidthDifference) return true; return false;
diff --git a/third_party/blink/renderer/core/page/page.cc b/third_party/blink/renderer/core/page/page.cc index f584e4c..819ce53 100644 --- a/third_party/blink/renderer/core/page/page.cc +++ b/third_party/blink/renderer/core/page/page.cc
@@ -308,8 +308,6 @@ if (validation_message_client_) validation_message_client_->DocumentDetached(*document); hosts_using_features_.DocumentDetached(*document); - if (spatial_navigation_controller_ && document->GetFrame()->IsMainFrame()) - spatial_navigation_controller_->ResetMojoBindings(); } bool Page::OpenedByDOM() const {
diff --git a/third_party/blink/renderer/core/page/spatial_navigation_controller.cc b/third_party/blink/renderer/core/page/spatial_navigation_controller.cc index 782045c..7fb3c746 100644 --- a/third_party/blink/renderer/core/page/spatial_navigation_controller.cc +++ b/third_party/blink/renderer/core/page/spatial_navigation_controller.cc
@@ -213,6 +213,8 @@ // etc.) then reset navigation. if (interest_element_ && !interest_element_->GetDocument().View()) interest_element_ = nullptr; + // TODO(crbug.com/956209): should be checked via an integration test. + ResetMojoBindings(); } void SpatialNavigationController::Trace(blink::Visitor* visitor) {
diff --git a/third_party/blink/renderer/core/page/spatial_navigation_controller.h b/third_party/blink/renderer/core/page/spatial_navigation_controller.h index f6026b0..f5e8eec2 100644 --- a/third_party/blink/renderer/core/page/spatial_navigation_controller.h +++ b/third_party/blink/renderer/core/page/spatial_navigation_controller.h
@@ -40,8 +40,6 @@ void OnSpatialNavigationSettingChanged(); void FocusedNodeChanged(Document*); - void ResetMojoBindings(); - void Trace(blink::Visitor*); private: @@ -100,6 +98,7 @@ bool UpdateHasDefaultVideoControls(Element* element); const mojom::blink::SpatialNavigationHostPtr& GetSpatialNavigationHost(); + void ResetMojoBindings(); // The currently indicated element or nullptr if no node is indicated by // spatial navigation.
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc b/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc index a4e6f78..f936e11 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc
@@ -38,8 +38,8 @@ namespace blink { // We will only allow squashing if the bbox-area:squashed-area doesn't exceed -// the ratio |gSquashingSparsityTolerance|:1. -static uint64_t g_squashing_sparsity_tolerance = 6; +// the ratio |kSquashingSparsityTolerance|:1. +constexpr uint64_t kSquashingSparsityTolerance = 6; CompositingLayerAssigner::CompositingLayerAssigner( PaintLayerCompositor* compositor) @@ -90,7 +90,7 @@ const uint64_t new_squashed_area = squashing_state.total_area_of_squashed_rects + bounds.Size().Area(); return new_bounding_rect_area > - g_squashing_sparsity_tolerance * new_squashed_area; + kSquashingSparsityTolerance * new_squashed_area; } bool CompositingLayerAssigner::NeedsOwnBacking(const PaintLayer* layer) const {
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc b/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc index de4ac0d..11186d928 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc
@@ -56,10 +56,6 @@ } // namespace -// Set a big enough limit for the number of nodes to ensure memory usage is -// capped. Exceeding such limit will make the detactor stops recording entries. -constexpr size_t kImageNodeNumberLimit = 5000; - static bool LargeImageFirst(const base::WeakPtr<ImageRecord>& a, const base::WeakPtr<ImageRecord>& b) { DCHECK(a); @@ -347,26 +343,6 @@ ImageRecordsManager::ImageRecordsManager() : size_ordered_set_(&LargeImageFirst) {} -void ImageRecordsManager::SetNodeReattachedIfNeeded( - const DOMNodeId& visible_node_id) { - if (!detached_ids_.Contains(visible_node_id)) - return; - detached_ids_.erase(visible_node_id); -} - -base::WeakPtr<ImageRecord> ImageRecordsManager::FindVisibleRecord( - const BackgroundImageId& background_image_id) const { - DCHECK(visible_background_image_map_.Contains(background_image_id)); - return visible_background_image_map_.find(background_image_id) - ->value->AsWeakPtr(); -} - -base::WeakPtr<ImageRecord> ImageRecordsManager::FindVisibleRecord( - const DOMNodeId& node_id) const { - DCHECK(visible_node_map_.Contains(node_id)); - return visible_node_map_.find(node_id)->value->AsWeakPtr(); -} - void ImageRecordsManager::OnImageLoaded(const DOMNodeId& node_id, unsigned current_frame_index) { base::WeakPtr<ImageRecord> record = FindVisibleRecord(node_id); @@ -387,49 +363,6 @@ QueueToMeasurePaintTime(record, current_frame_index); } -void ImageRecordsManager::SetLoaded(base::WeakPtr<ImageRecord>& record) { - record->loaded = true; -} - -bool ImageRecordsManager::RecordedTooManyNodes() const { - return visible_node_map_.size() + visible_background_image_map_.size() + - invisible_node_ids_.size() > - kImageNodeNumberLimit; -} - -void ImageRecordsManager::SetNodeDetached(const DOMNodeId& visible_node_id) { - detached_ids_.insert(visible_node_id); -} - -bool ImageRecordsManager::HasUnregisteredRecordsInQueued( - unsigned last_registered_frame_index) { - DCHECK(last_registered_frame_index <= LastQueuedFrameIndex()); - return last_registered_frame_index < LastQueuedFrameIndex(); -} - -bool ImageRecordsManager::WasVisibleNodeLoaded(const DOMNodeId& node_id) const { - DCHECK(visible_node_map_.Contains(node_id)); - return visible_node_map_.at(node_id)->loaded; -} - -bool ImageRecordsManager::WasVisibleNodeLoaded( - const BackgroundImageId& background_image_id) const { - DCHECK(visible_background_image_map_.Contains(background_image_id)); - return visible_background_image_map_.at(background_image_id)->loaded; -} - -void ImageRecordsManager::QueueToMeasurePaintTime( - base::WeakPtr<ImageRecord>& record, - unsigned current_frame_index) { - images_queued_for_paint_time_.push(record); - record->frame_index = current_frame_index; -} - -void ImageRecordsManager::RecordInvisibleNode(const DOMNodeId& node_id) { - DCHECK(!RecordedTooManyNodes()); - invisible_node_ids_.insert(node_id); -} - void ImageRecordsManager::RecordVisibleNode(const DOMNodeId& node_id, const uint64_t& visual_size) { std::unique_ptr<ImageRecord> record = @@ -461,14 +394,6 @@ return record; } -void ImagePaintTimingDetector::StopRecordEntries() { - is_recording_ = false; -} - -bool ImagePaintTimingDetector::FinishedReportingImages() const { - return !is_recording_ && num_pending_swap_callbacks_ == 0; -} - ImageRecord* ImageRecordsManager::FindLargestPaintCandidate() const { DCHECK_EQ(visible_node_map_.size() + visible_background_image_map_.size(), size_ordered_set_.size());
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector.h b/third_party/blink/renderer/core/paint/image_paint_timing_detector.h index 019c923..ea67baf 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector.h +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector.h
@@ -55,14 +55,28 @@ std::set<base::WeakPtr<ImageRecord>, NodesQueueComparator>; public: + // Set a big enough limit for the number of nodes to ensure memory usage is + // capped. Exceeding such limit will make the detactor stops recording + // entries. + static constexpr size_t kImageNodeNumberLimit = 5000; + ImageRecordsManager(); ImageRecord* FindLargestPaintCandidate() const; bool AreAllVisibleNodesDetached() const; - void SetNodeDetached(const DOMNodeId& visible_node_id); - void SetNodeReattachedIfNeeded(const DOMNodeId& visible_node_id); + inline void SetNodeDetached(const DOMNodeId& visible_node_id) { + detached_ids_.insert(visible_node_id); + } + inline void SetNodeReattachedIfNeeded(const DOMNodeId& visible_node_id) { + if (!detached_ids_.Contains(visible_node_id)) + return; + detached_ids_.erase(visible_node_id); + } - void RecordInvisibleNode(const DOMNodeId&); + inline void RecordInvisibleNode(const DOMNodeId& node_id) { + DCHECK(!RecordedTooManyNodes()); + invisible_node_ids_.insert(node_id); + } void RecordVisibleNode(const DOMNodeId&, const uint64_t& visual_size); void RecordVisibleNode(const BackgroundImageId& background_image_id, const uint64_t& visual_size); @@ -79,40 +93,68 @@ return invisible_node_ids_.Contains(node_id); } - bool RecordedTooManyNodes() const; + inline bool RecordedTooManyNodes() const { + return visible_node_map_.size() + visible_background_image_map_.size() + + invisible_node_ids_.size() > + kImageNodeNumberLimit; + } - bool WasVisibleNodeLoaded(const DOMNodeId&) const; - bool WasVisibleNodeLoaded(const BackgroundImageId& background_image_id) const; + inline bool WasVisibleNodeLoaded(const DOMNodeId& node_id) const { + DCHECK(visible_node_map_.Contains(node_id)); + return visible_node_map_.at(node_id)->loaded; + } + inline bool WasVisibleNodeLoaded( + const BackgroundImageId& background_image_id) const { + DCHECK(visible_background_image_map_.Contains(background_image_id)); + return visible_background_image_map_.at(background_image_id)->loaded; + } void OnImageLoaded(const DOMNodeId&, unsigned current_frame_index); void OnImageLoaded(const BackgroundImageId&, unsigned current_frame_index); void OnImageLoadedInternal(base::WeakPtr<ImageRecord>&, unsigned current_frame_index); - bool NeedMeausuringPaintTime() const { + inline bool NeedMeausuringPaintTime() const { return !images_queued_for_paint_time_.empty(); } // Compare the last frame index in queue with the last frame index that has // registered for assigning paint time. - bool HasUnregisteredRecordsInQueued(unsigned last_registered_frame_index); + inline bool HasUnregisteredRecordsInQueued( + unsigned last_registered_frame_index) { + DCHECK(last_registered_frame_index <= LastQueuedFrameIndex()); + return last_registered_frame_index < LastQueuedFrameIndex(); + } void AssignPaintTimeToRegisteredQueuedNodes(const base::TimeTicks&, unsigned last_queued_frame_index); - unsigned LastQueuedFrameIndex() const { + inline unsigned LastQueuedFrameIndex() const { return images_queued_for_paint_time_.back()->frame_index; } private: // Find the image record of an visible image. - base::WeakPtr<ImageRecord> FindVisibleRecord(const DOMNodeId&) const; - base::WeakPtr<ImageRecord> FindVisibleRecord( - const BackgroundImageId& background_image_id) const; + inline base::WeakPtr<ImageRecord> FindVisibleRecord( + const DOMNodeId& node_id) const { + DCHECK(visible_node_map_.Contains(node_id)); + return visible_node_map_.find(node_id)->value->AsWeakPtr(); + } + inline base::WeakPtr<ImageRecord> FindVisibleRecord( + const BackgroundImageId& background_image_id) const { + DCHECK(visible_background_image_map_.Contains(background_image_id)); + return visible_background_image_map_.find(background_image_id) + ->value->AsWeakPtr(); + } std::unique_ptr<ImageRecord> CreateImageRecord( const DOMNodeId&, const ImageResourceContent* cached_image, const uint64_t& visual_size); - void QueueToMeasurePaintTime(base::WeakPtr<ImageRecord>&, - unsigned current_frame_index); - void SetLoaded(base::WeakPtr<ImageRecord>&); + inline void QueueToMeasurePaintTime(base::WeakPtr<ImageRecord>& record, + unsigned current_frame_index) { + images_queued_for_paint_time_.push(record); + record->frame_index = current_frame_index; + } + inline void SetLoaded(base::WeakPtr<ImageRecord>& record) { + record->loaded = true; + } unsigned max_record_id_ = 0; // We will never destroy the pointers within |visible_node_map_|. Once created @@ -176,9 +218,12 @@ // an image is recorded before stopping recording, and finish loading after // stopping recording, the detector can still observe the loading being // finished. - void StopRecordEntries(); - bool IsRecording() const { return is_recording_; } - bool FinishedReportingImages() const; + inline void StopRecordEntries() { is_recording_ = false; } + inline bool IsRecording() const { return is_recording_; } + inline bool FinishedReportingImages() const { + return !is_recording_ && num_pending_swap_callbacks_ == 0; + } + void Trace(blink::Visitor*); private:
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc b/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc index b03352e..4ce711e 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc
@@ -134,10 +134,13 @@ void TextPaintTimingDetector::NotifyNodeRemoved(DOMNodeId node_id) { if (!is_recording_) return; - if (!records_manager_.IsKnownVisibleNode(node_id)) - return; - records_manager_.SetNodeDetachedIfNeeded(node_id); - need_update_timing_at_frame_end_ = true; + if (records_manager_.IsKnownVisibleNode(node_id)) { + records_manager_.RemoveVisibleRecord(node_id); + need_update_timing_at_frame_end_ = true; + } else if (records_manager_.IsKnownInvisibleNode(node_id)) { + records_manager_.RemoveInvisibleRecord(node_id); + need_update_timing_at_frame_end_ = true; + } } void TextPaintTimingDetector::RegisterNotifySwapTime( @@ -196,8 +199,6 @@ DOMNodeId node_id = DOMNodeIds::IdForNode(node); DCHECK_NE(node_id, kInvalidDOMNodeId); - records_manager_.MarkNodeReattachedIfNeeded(node_id); - // The caller should check this. DCHECK(!aggregated_visual_rect.IsEmpty()); @@ -249,12 +250,16 @@ TextRecordsManager::TextRecordsManager() : size_ordered_set_(&LargeTextFirst) {} -void TextRecordsManager::SetNodeDetachedIfNeeded(const DOMNodeId& node_id) { - if (!visible_node_map_.Contains(node_id)) - return; - if (detached_ids_.Contains(node_id)) - return; - detached_ids_.insert(node_id); +void TextRecordsManager::RemoveVisibleRecord(const DOMNodeId& node_id) { + DCHECK(visible_node_map_.Contains(node_id)); + size_ordered_set_.erase(visible_node_map_.at(node_id)->AsWeakPtr()); + visible_node_map_.erase(node_id); + is_result_invalidated_ = true; +} + +void TextRecordsManager::RemoveInvisibleRecord(const DOMNodeId& node_id) { + DCHECK(invisible_node_ids_.Contains(node_id)); + invisible_node_ids_.erase(node_id); is_result_invalidated_ = true; } @@ -264,7 +269,15 @@ // consumed in a callback earlier than this one. That violates the assumption // that only one or zero callback will be called after one OnPaintFinished. DCHECK_GT(texts_queued_for_paint_time_.size(), 0UL); - for (auto& record : texts_queued_for_paint_time_) { + for (auto iterator = texts_queued_for_paint_time_.begin(); + iterator != texts_queued_for_paint_time_.end(); ++iterator) { + // The record may have been removed between the callback registration and + // invoking. + base::WeakPtr<TextRecord>& record = *iterator; + if (!record) { + texts_queued_for_paint_time_.erase(iterator); + continue; + } DCHECK(visible_node_map_.Contains(record->node_id)); DCHECK_EQ(record->paint_time, base::TimeTicks()); record->paint_time = timestamp; @@ -275,25 +288,6 @@ is_result_invalidated_ = true; } -void TextRecordsManager::MarkNodeReattachedIfNeeded(const DOMNodeId& node_id) { - if (!detached_ids_.Contains(node_id)) - return; - DCHECK(visible_node_map_.Contains(node_id) || - invisible_node_ids_.Contains(node_id)); - detached_ids_.erase(node_id); - is_result_invalidated_ = true; -} - -bool TextRecordsManager::HasRecorded(const DOMNodeId& node_id) const { - return visible_node_map_.Contains(node_id) || - invisible_node_ids_.Contains(node_id); -} - -void TextRecordsManager::RecordInvisibleNode(const DOMNodeId& node_id) { - DCHECK(!HasTooManyNodes()); - invisible_node_ids_.insert(node_id); -} - void TextRecordsManager::RecordVisibleNode(const DOMNodeId& node_id, const uint64_t& visual_size, const LayoutObject& text_object) { @@ -319,11 +313,6 @@ is_result_invalidated_ = true; } -void TextRecordsManager::QueueToMeasurePaintTime( - base::WeakPtr<TextRecord> record) { - texts_queued_for_paint_time_.push_back(std::move(record)); -} - bool TextRecordsManager::HasTooManyNodes() const { return visible_node_map_.size() + invisible_node_ids_.size() >= kTextNodeNumberLimit; @@ -340,8 +329,7 @@ // WeakPtr::IsValid() is expensive. We use raw pointer to reduce the checks. TextRecord* text_record = (*it).get(); DCHECK(text_record); - if (detached_ids_.Contains(text_record->node_id) || - text_record->paint_time.is_null()) + if (text_record->paint_time.is_null()) continue; DCHECK(visible_node_map_.Contains(text_record->node_id)); new_largest_paint_candidate = text_record;
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector.h b/third_party/blink/renderer/core/paint/text_paint_timing_detector.h index 4b9c0417..c6d325b 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector.h +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector.h
@@ -21,7 +21,6 @@ namespace blink { class LayoutBoxModelObject; -class LayoutObject; class LocalFrameView; class PropertyTreeState; class TextElementTiming; @@ -54,10 +53,12 @@ TextRecordsManager(); TextRecord* FindLargestPaintCandidate(); - void SetNodeDetachedIfNeeded(const DOMNodeId&); - void MarkNodeReattachedIfNeeded(const DOMNodeId&); - - void RecordInvisibleNode(const DOMNodeId&); + void RemoveVisibleRecord(const DOMNodeId&); + void RemoveInvisibleRecord(const DOMNodeId&); + inline void RecordInvisibleNode(const DOMNodeId& node_id) { + DCHECK(!HasTooManyNodes()); + invisible_node_ids_.insert(node_id); + } void RecordVisibleNode(const DOMNodeId&, const uint64_t& visual_size, const LayoutObject&); @@ -67,15 +68,22 @@ void AssignPaintTimeToQueuedNodes(const base::TimeTicks&); bool HasTooManyNodes() const; - bool HasRecorded(const DOMNodeId&) const; + inline bool HasRecorded(const DOMNodeId& node_id) const { + return visible_node_map_.Contains(node_id) || + invisible_node_ids_.Contains(node_id); + } size_t CountVisibleNodes() const { return visible_node_map_.size(); } size_t CountInvisibleNodes() const { return invisible_node_ids_.size(); } - bool IsKnownVisibleNode(const DOMNodeId& node_id) const { + inline bool IsKnownVisibleNode(const DOMNodeId& node_id) const { return visible_node_map_.Contains(node_id); } + inline bool IsKnownInvisibleNode(const DOMNodeId& node_id) const { + return invisible_node_ids_.Contains(node_id); + } + void StopRecordingLargestTextPaint(); bool IsRecordingLargestTextPaint() const { return is_recording_ltp_; } @@ -87,7 +95,9 @@ void Trace(blink::Visitor*); private: - void QueueToMeasurePaintTime(base::WeakPtr<TextRecord>); + inline void QueueToMeasurePaintTime(base::WeakPtr<TextRecord> record) { + texts_queued_for_paint_time_.push_back(std::move(record)); + } // This is used to cache the largest text paint result for better efficiency. // The result will be invalidated whenever any change is done to the variables // used in |FindLargestPaintCandidate|. @@ -99,7 +109,6 @@ RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled(); HashMap<DOMNodeId, std::unique_ptr<TextRecord>> visible_node_map_; HashSet<DOMNodeId> invisible_node_ids_; - HashSet<DOMNodeId> detached_ids_; // This is used to order the nodes in |visible_node_map_| so that we can find // the largest node efficiently. Note that the entries in |size_ordered_set_| // and |visible_node_map_| should always be added/deleted together.
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc b/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc index aeda73d..c502f39 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc
@@ -47,11 +47,8 @@ return 0u; return GetPaintTimingDetector() - .GetTextPaintTimingDetector() - ->records_manager_.visible_node_map_.size() - - GetPaintTimingDetector() - .GetTextPaintTimingDetector() - ->records_manager_.detached_ids_.size(); + .GetTextPaintTimingDetector() + ->records_manager_.visible_node_map_.size(); } unsigned CountRankingSetSize() { @@ -60,12 +57,6 @@ ->records_manager_.size_ordered_set_.size(); } - unsigned CountDetachedTexts() { - return GetPaintTimingDetector() - .GetTextPaintTimingDetector() - ->records_manager_.detached_ids_.size(); - } - void InvokeCallback() { TextPaintTimingDetector* detector = GetPaintTimingDetector().GetTextPaintTimingDetector(); @@ -220,7 +211,6 @@ GetDocument().getElementById("remove")); InvokeCallback(); EXPECT_EQ(CountVisibleTexts(), 0u); - EXPECT_EQ(CountDetachedTexts(), 1u); } TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_LargestText) {
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index 48b44188..726a16e3 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -279,7 +279,7 @@ "canvas/offscreencanvas/offscreen_canvas_test.cc", "credentialmanager/credentials_container_test.cc", "credentialmanager/password_credential_test.cc", - "csspaint/main_thread_document_paint_definition_test.cc", + "csspaint/document_paint_definition_test.cc", "csspaint/paint_rendering_context_2d_test.cc", "csspaint/paint_worklet_global_scope_test.cc", "csspaint/paint_worklet_proxy_client_test.cc",
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc index 9f30df41..13ce7f0e 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc +++ b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc
@@ -832,15 +832,6 @@ if (max_width && (!std::isfinite(*max_width) || *max_width <= 0)) return; - // Currently, SkPictureImageFilter does not support subpixel text - // anti-aliasing, which is expected when !creationAttributes().alpha, so we - // need to fall out of display list mode when drawing text to an opaque - // canvas. crbug.com/583809 - if (!IsComposited()) { - canvas()->DisableDeferral( - kDisableDeferralReasonSubPixelTextAntiAliasingSupport); - } - const Font& font = AccessFont(); font.GetFontDescription().SetSubpixelAscentDescent(true); const SimpleFontData* font_data = font.PrimaryFont();
diff --git a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc index 24f2220..70ab217 100644 --- a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc +++ b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc
@@ -385,14 +385,6 @@ if (max_width && (!std::isfinite(*max_width) || *max_width <= 0)) return; - // Currently, SkPictureImageFilter does not support subpixel text - // anti-aliasing, which is expected when !creationAttributes().alpha(), so we - // need to fall out of display list mode when drawing text to an opaque - // canvas. crbug.com/583809 - if (!IsComposited()) { - DisableDeferral(kDisableDeferralReasonSubPixelTextAntiAliasingSupport); - } - const Font& font = AccessFont(); font.GetFontDescription().SetSubpixelAscentDescent(true);
diff --git a/third_party/blink/renderer/modules/csspaint/BUILD.gn b/third_party/blink/renderer/modules/csspaint/BUILD.gn index c1333741..fe5e7878 100644 --- a/third_party/blink/renderer/modules/csspaint/BUILD.gn +++ b/third_party/blink/renderer/modules/csspaint/BUILD.gn
@@ -14,8 +14,6 @@ "css_paint_worklet.h", "document_paint_definition.cc", "document_paint_definition.h", - "main_thread_document_paint_definition.cc", - "main_thread_document_paint_definition.h", "paint_rendering_context_2d.cc", "paint_rendering_context_2d.h", "paint_size.h",
diff --git a/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc b/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc index cb1595a6..5f6b8ac 100644 --- a/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc +++ b/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc
@@ -8,7 +8,6 @@ #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h" #include "third_party/blink/renderer/modules/csspaint/document_paint_definition.h" -#include "third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.h" #include "third_party/blink/renderer/modules/csspaint/paint_worklet.h" #include "third_party/blink/renderer/platform/graphics/image.h" @@ -60,8 +59,6 @@ } bool CSSPaintImageGeneratorImpl::HasDocumentDefinition() const { - if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) - return paint_worklet_->GetMainThreadDocumentDefinitionMap().Contains(name_); return paint_worklet_->GetDocumentDefinitionMap().Contains(name_); } @@ -70,22 +67,22 @@ if (!HasDocumentDefinition()) return false; definition = paint_worklet_->GetDocumentDefinitionMap().at(name_); - if (definition != kInvalidDocumentPaintDefinition && - definition->GetRegisteredDefinitionCount() != - PaintWorklet::kNumGlobalScopes) { - definition = kInvalidDocumentPaintDefinition; + // In off-thread CSS Paint, we register CSSPaintDefinition on the worklet + // thread first. Once the same CSSPaintDefinition is successfully registered + // to all the paint worklet global scopes, we then post to the main thread and + // register that CSSPaintDefinition on the main thread. So for the off-thread + // case, as long as the DocumentPaintDefinition exists in the map, it should + // be valid. + if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) { + DCHECK(definition); + return true; + } + if (definition && definition->GetRegisteredDefinitionCount() != + PaintWorklet::kNumGlobalScopes) { + definition = nullptr; return false; } - return definition != kInvalidDocumentPaintDefinition; -} - -bool CSSPaintImageGeneratorImpl::GetValidMainThreadDocumentDefinition( - MainThreadDocumentPaintDefinition*& definition) const { - if (!paint_worklet_->GetMainThreadDocumentDefinitionMap().Contains(name_)) - return false; - definition = paint_worklet_->GetMainThreadDocumentDefinitionMap().at(name_); - DCHECK(definition); - return true; + return definition; } unsigned CSSPaintImageGeneratorImpl::GetRegisteredDefinitionCountForTesting() @@ -94,7 +91,7 @@ return 0; DocumentPaintDefinition* definition = paint_worklet_->GetDocumentDefinitionMap().at(name_); - if (definition == kInvalidDocumentPaintDefinition) + if (!definition) return 0; return definition->GetRegisteredDefinitionCount(); } @@ -102,12 +99,6 @@ const Vector<CSSPropertyID>& CSSPaintImageGeneratorImpl::NativeInvalidationProperties() const { DEFINE_STATIC_LOCAL(Vector<CSSPropertyID>, empty_vector, ()); - if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) { - MainThreadDocumentPaintDefinition* definition; - if (!GetValidMainThreadDocumentDefinition(definition)) - return empty_vector; - return definition->NativeInvalidationProperties(); - } DocumentPaintDefinition* definition; if (!GetValidDocumentDefinition(definition)) return empty_vector; @@ -117,12 +108,6 @@ const Vector<AtomicString>& CSSPaintImageGeneratorImpl::CustomInvalidationProperties() const { DEFINE_STATIC_LOCAL(Vector<AtomicString>, empty_vector, ()); - if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) { - MainThreadDocumentPaintDefinition* definition; - if (!GetValidMainThreadDocumentDefinition(definition)) - return empty_vector; - return definition->CustomInvalidationProperties(); - } DocumentPaintDefinition* definition; if (!GetValidDocumentDefinition(definition)) return empty_vector; @@ -130,27 +115,15 @@ } bool CSSPaintImageGeneratorImpl::HasAlpha() const { - if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) { - MainThreadDocumentPaintDefinition* definition; - if (!GetValidMainThreadDocumentDefinition(definition)) - return false; - return definition->alpha(); - } DocumentPaintDefinition* definition; if (!GetValidDocumentDefinition(definition)) return false; - return definition->GetPaintRenderingContext2DSettings()->alpha(); + return definition->alpha(); } const Vector<CSSSyntaxDescriptor>& CSSPaintImageGeneratorImpl::InputArgumentTypes() const { DEFINE_STATIC_LOCAL(Vector<CSSSyntaxDescriptor>, empty_vector, ()); - if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) { - MainThreadDocumentPaintDefinition* definition; - if (!GetValidMainThreadDocumentDefinition(definition)) - return empty_vector; - return definition->InputArgumentTypes(); - } DocumentPaintDefinition* definition; if (!GetValidDocumentDefinition(definition)) return empty_vector;
diff --git a/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h b/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h index 9739af4..6d37117 100644 --- a/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h +++ b/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h
@@ -19,7 +19,6 @@ class Document; class DocumentPaintDefinition; class Image; -class MainThreadDocumentPaintDefinition; class PaintWorklet; class MODULES_EXPORT CSSPaintImageGeneratorImpl final @@ -67,10 +66,6 @@ // document definition exists and is valid. bool GetValidDocumentDefinition(DocumentPaintDefinition*&) const; - // Used for off-thread CSS Paint. - bool GetValidMainThreadDocumentDefinition( - MainThreadDocumentPaintDefinition*&) const; - Member<Observer> observer_; Member<PaintWorklet> paint_worklet_; const String name_;
diff --git a/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc b/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc index ebddd9a..a6030820 100644 --- a/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc +++ b/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc
@@ -6,17 +6,22 @@ namespace blink { -DocumentPaintDefinition::DocumentPaintDefinition(CSSPaintDefinition* definition) - : paint_definition_(definition), registered_definitions_count_(1u) { - DCHECK(definition); -} +DocumentPaintDefinition::DocumentPaintDefinition( + const Vector<CSSPropertyID>& native_invalidation_properties, + const Vector<AtomicString>& custom_invalidation_properties, + const Vector<CSSSyntaxDescriptor>& input_argument_types, + bool alpha) + : native_invalidation_properties_(native_invalidation_properties), + custom_invalidation_properties_(custom_invalidation_properties), + input_argument_types_(input_argument_types), + alpha_(alpha), + registered_definitions_count_(1u) {} DocumentPaintDefinition::~DocumentPaintDefinition() = default; bool DocumentPaintDefinition::RegisterAdditionalPaintDefinition( const CSSPaintDefinition& other) { - if (GetPaintRenderingContext2DSettings()->alpha() != - other.GetPaintRenderingContext2DSettings()->alpha() || + if (alpha() != other.GetPaintRenderingContext2DSettings()->alpha() || NativeInvalidationProperties() != other.NativeInvalidationProperties() || CustomInvalidationProperties() != other.CustomInvalidationProperties() || InputArgumentTypes() != other.InputArgumentTypes()) @@ -25,8 +30,4 @@ return true; } -void DocumentPaintDefinition::Trace(blink::Visitor* visitor) { - visitor->Trace(paint_definition_); -} - } // namespace blink
diff --git a/third_party/blink/renderer/modules/csspaint/document_paint_definition.h b/third_party/blink/renderer/modules/csspaint/document_paint_definition.h index 028429a..eb634bcf 100644 --- a/third_party/blink/renderer/modules/csspaint/document_paint_definition.h +++ b/third_party/blink/renderer/modules/csspaint/document_paint_definition.h
@@ -8,7 +8,7 @@ #include "third_party/blink/renderer/core/css/css_syntax_descriptor.h" #include "third_party/blink/renderer/core/css/cssom/css_style_value.h" #include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h" -#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/modules/modules_export.h" namespace blink { @@ -22,25 +22,25 @@ // // The document has a map of document paint definitions. Initially the map is // empty; it is populated when registerPaint(name, paintCtor) is called. -class DocumentPaintDefinition final - : public GarbageCollectedFinalized<DocumentPaintDefinition> { +class MODULES_EXPORT DocumentPaintDefinition { public: - explicit DocumentPaintDefinition(CSSPaintDefinition*); + explicit DocumentPaintDefinition( + const Vector<CSSPropertyID>& native_invalidation_properties, + const Vector<AtomicString>& custom_invalidation_properties, + const Vector<CSSSyntaxDescriptor>& input_argument_types, + bool alpha); virtual ~DocumentPaintDefinition(); const Vector<CSSPropertyID>& NativeInvalidationProperties() const { - return paint_definition_->NativeInvalidationProperties(); + return native_invalidation_properties_; } const Vector<AtomicString>& CustomInvalidationProperties() const { - return paint_definition_->CustomInvalidationProperties(); + return custom_invalidation_properties_; } const Vector<CSSSyntaxDescriptor>& InputArgumentTypes() const { - return paint_definition_->InputArgumentTypes(); + return input_argument_types_; } - const PaintRenderingContext2DSettings* GetPaintRenderingContext2DSettings() - const { - return paint_definition_->GetPaintRenderingContext2DSettings(); - } + bool alpha() const { return alpha_; } bool RegisterAdditionalPaintDefinition(const CSSPaintDefinition&); @@ -48,10 +48,11 @@ return registered_definitions_count_; } - virtual void Trace(blink::Visitor*); - private: - Member<CSSPaintDefinition> paint_definition_; + Vector<CSSPropertyID> native_invalidation_properties_; + Vector<AtomicString> custom_invalidation_properties_; + Vector<CSSSyntaxDescriptor> input_argument_types_; + bool alpha_; unsigned registered_definitions_count_; };
diff --git a/third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition_test.cc b/third_party/blink/renderer/modules/csspaint/document_paint_definition_test.cc similarity index 64% rename from third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition_test.cc rename to third_party/blink/renderer/modules/csspaint/document_paint_definition_test.cc index 8d14348..ea17880 100644 --- a/third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition_test.cc +++ b/third_party/blink/renderer/modules/csspaint/document_paint_definition_test.cc
@@ -1,8 +1,8 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. +// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.h" +#include "third_party/blink/renderer/modules/csspaint/document_paint_definition.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" @@ -11,25 +11,24 @@ #include "third_party/blink/renderer/core/css/css_syntax_descriptor.h" #include "third_party/blink/renderer/core/css/css_syntax_string_parser.h" #include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h" -#include "third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d_settings.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { -TEST(MainThreadDocumentPaintDefinitionTest, NativeInvalidationProperties) { +TEST(DocumentPaintDefinitionTest, NativeInvalidationProperties) { Vector<CSSPropertyID> native_invalidation_properties = { CSSPropertyID::kColor, CSSPropertyID::kZoom, CSSPropertyID::kTop, }; - Vector<String> custom_invalidation_properties; + Vector<AtomicString> custom_invalidation_properties; Vector<CSSSyntaxDescriptor> input_argument_types; - MainThreadDocumentPaintDefinition document_definition( - native_invalidation_properties, custom_invalidation_properties, - input_argument_types, true); + DocumentPaintDefinition document_definition(native_invalidation_properties, + custom_invalidation_properties, + input_argument_types, true); EXPECT_EQ(document_definition.NativeInvalidationProperties().size(), 3u); for (size_t i = 0; i < 3; i++) { EXPECT_EQ(native_invalidation_properties[i], @@ -37,17 +36,17 @@ } } -TEST(MainThreadDocumentPaintDefinitionTest, CustomInvalidationProperties) { +TEST(DocumentPaintDefinitionTest, CustomInvalidationProperties) { Vector<CSSPropertyID> native_invalidation_properties; - Vector<String> custom_invalidation_properties = { + Vector<AtomicString> custom_invalidation_properties = { "--my-property", "--another-property", }; Vector<CSSSyntaxDescriptor> input_argument_types; - MainThreadDocumentPaintDefinition document_definition( - native_invalidation_properties, custom_invalidation_properties, - input_argument_types, true); + DocumentPaintDefinition document_definition(native_invalidation_properties, + custom_invalidation_properties, + input_argument_types, true); EXPECT_EQ(document_definition.CustomInvalidationProperties().size(), 2u); for (size_t i = 0; i < 2; i++) { EXPECT_EQ(custom_invalidation_properties[i], @@ -55,15 +54,15 @@ } } -TEST(MainThreadDocumentPaintDefinitionTest, Alpha) { +TEST(DocumentPaintDefinitionTest, Alpha) { Vector<CSSPropertyID> native_invalidation_properties; - Vector<String> custom_invalidation_properties; + Vector<AtomicString> custom_invalidation_properties; Vector<CSSSyntaxDescriptor> input_argument_types; - MainThreadDocumentPaintDefinition document_definition_with_alpha( + DocumentPaintDefinition document_definition_with_alpha( native_invalidation_properties, custom_invalidation_properties, input_argument_types, true); - MainThreadDocumentPaintDefinition document_definition_without_alpha( + DocumentPaintDefinition document_definition_without_alpha( native_invalidation_properties, custom_invalidation_properties, input_argument_types, false); @@ -71,16 +70,16 @@ EXPECT_FALSE(document_definition_without_alpha.alpha()); } -TEST(MainThreadDocumentPaintDefinitionTest, InputArgumentTypes) { +TEST(DocumentPaintDefinitionTest, InputArgumentTypes) { Vector<CSSPropertyID> native_invalidation_properties; - Vector<String> custom_invalidation_properties; + Vector<AtomicString> custom_invalidation_properties; Vector<CSSSyntaxDescriptor> input_argument_types = { CSSSyntaxStringParser("<length> | <color>").Parse().value(), CSSSyntaxStringParser("<integer> | foo | <color>").Parse().value()}; - MainThreadDocumentPaintDefinition document_definition( - native_invalidation_properties, custom_invalidation_properties, - input_argument_types, true); + DocumentPaintDefinition document_definition(native_invalidation_properties, + custom_invalidation_properties, + input_argument_types, true); EXPECT_EQ(document_definition.InputArgumentTypes().size(), 2u); for (size_t i = 0; i < 2; i++) {
diff --git a/third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.cc b/third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.cc deleted file mode 100644 index 01f69ea..0000000 --- a/third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.h" - -#include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h" - -namespace blink { - -MainThreadDocumentPaintDefinition::MainThreadDocumentPaintDefinition( - const Vector<CSSPropertyID>& native_invalidation_properties, - const Vector<String>& custom_invalidation_properties, - const Vector<CSSSyntaxDescriptor>& input_argument_types, - bool alpha) - : native_invalidation_properties_(native_invalidation_properties), - input_argument_types_(input_argument_types), - alpha_(alpha) { - custom_invalidation_properties_.ReserveInitialCapacity( - custom_invalidation_properties.size()); - for (const String& property : custom_invalidation_properties) - custom_invalidation_properties_.push_back(AtomicString(property)); -} - -MainThreadDocumentPaintDefinition::~MainThreadDocumentPaintDefinition() = - default; - -} // namespace blink
diff --git a/third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.h b/third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.h deleted file mode 100644 index aa0aee2..0000000 --- a/third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_MAIN_THREAD_DOCUMENT_PAINT_DEFINITION_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_MAIN_THREAD_DOCUMENT_PAINT_DEFINITION_H_ - -#include "third_party/blink/renderer/core/css/css_property_names.h" -#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h" -#include "third_party/blink/renderer/modules/modules_export.h" -#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" -#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" -#include "third_party/blink/renderer/platform/wtf/vector.h" - -namespace blink { - -// MainThreadDocumentPaintDefinition is a version of DocumentPaintDefinition for -// the OffMainThreadCSSPaint project. It is created on the main thread, using a -// copied version of native and custom invalidation properties. -class MODULES_EXPORT MainThreadDocumentPaintDefinition { - public: - explicit MainThreadDocumentPaintDefinition( - const Vector<CSSPropertyID>& native_invalidation_properties, - const Vector<String>& custom_invalidation_properties, - const Vector<CSSSyntaxDescriptor>& input_argument_types, - bool alpha); - virtual ~MainThreadDocumentPaintDefinition(); - - const Vector<CSSPropertyID>& NativeInvalidationProperties() const { - return native_invalidation_properties_; - } - // Use AtomicString so that it is consistent with CSSPaintImageGeneratorImpl. - const Vector<AtomicString>& CustomInvalidationProperties() const { - return custom_invalidation_properties_; - } - - const Vector<CSSSyntaxDescriptor>& InputArgumentTypes() const { - return input_argument_types_; - } - - bool alpha() const { return alpha_; } - - private: - Vector<CSSPropertyID> native_invalidation_properties_; - Vector<AtomicString> custom_invalidation_properties_; - Vector<CSSSyntaxDescriptor> input_argument_types_; - bool alpha_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_MAIN_THREAD_DOCUMENT_PAINT_DEFINITION_H_
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet.cc b/third_party/blink/renderer/modules/csspaint/paint_worklet.cc index 2550ad9..1affba91 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet.cc +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet.cc
@@ -31,7 +31,6 @@ const wtf_size_t PaintWorklet::kNumGlobalScopes = 2u; const size_t kMaxPaintCountToSwitch = 30u; -DocumentPaintDefinition* const kInvalidDocumentPaintDefinition = nullptr; // static PaintWorklet* PaintWorklet::From(LocalDOMWindow& window) { @@ -109,7 +108,7 @@ // Check if the existing document definition is valid or not. DocumentPaintDefinition* document_definition = document_definition_map_.at(name); - if (document_definition == kInvalidDocumentPaintDefinition) + if (!document_definition) return nullptr; PaintWorkletGlobalScopeProxy* proxy = @@ -139,7 +138,6 @@ void PaintWorklet::Trace(blink::Visitor* visitor) { visitor->Trace(pending_generator_registry_); - visitor->Trace(document_definition_map_); visitor->Trace(proxy_client_); Worklet::Trace(visitor); Supplement<LocalDOMWindow>::Trace(visitor); @@ -151,11 +149,11 @@ if (document_definition_map_.Contains(name)) { DocumentPaintDefinition* existing_document_definition = document_definition_map_.at(name); - if (existing_document_definition == kInvalidDocumentPaintDefinition) + if (!existing_document_definition) return; if (!existing_document_definition->RegisterAdditionalPaintDefinition( *definition)) { - document_definition_map_.Set(name, kInvalidDocumentPaintDefinition); + document_definition_map_.Set(name, nullptr); exception_state.ThrowDOMException( DOMExceptionCode::kNotSupportedError, "A class with name:'" + name + @@ -169,9 +167,12 @@ PaintWorklet::kNumGlobalScopes) pending_generator_registry_->NotifyGeneratorReady(name); } else { - DocumentPaintDefinition* document_definition = - MakeGarbageCollected<DocumentPaintDefinition>(definition); - document_definition_map_.Set(name, document_definition); + auto document_definition = std::make_unique<DocumentPaintDefinition>( + definition->NativeInvalidationProperties(), + definition->CustomInvalidationProperties(), + definition->InputArgumentTypes(), + definition->GetPaintRenderingContext2DSettings()->alpha()); + document_definition_map_.insert(name, std::move(document_definition)); } } @@ -181,11 +182,17 @@ Vector<String> custom_properties, Vector<CSSSyntaxDescriptor> input_argument_types, double alpha) { - DCHECK(!main_thread_document_definition_map_.Contains(name)); - auto definition = std::make_unique<MainThreadDocumentPaintDefinition>( - std::move(native_properties), std::move(custom_properties), + // Because this method is called cross-thread, |custom_properties| cannot be + // an AtomicString. Instead, convert to AtomicString now that we are on the + // main thread. + Vector<AtomicString> new_custom_properties; + new_custom_properties.ReserveInitialCapacity(custom_properties.size()); + for (const String& property : custom_properties) + new_custom_properties.push_back(AtomicString(property)); + auto definition = std::make_unique<DocumentPaintDefinition>( + std::move(native_properties), std::move(new_custom_properties), std::move(input_argument_types), alpha); - main_thread_document_definition_map_.insert(name, std::move(definition)); + document_definition_map_.insert(name, std::move(definition)); pending_generator_registry_->NotifyGeneratorReady(name); }
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet.h b/third_party/blink/renderer/modules/csspaint/paint_worklet.h index cbf1084b..6725821c 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet.h +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet.h
@@ -11,7 +11,6 @@ #include "third_party/blink/renderer/core/css/css_syntax_descriptor.h" #include "third_party/blink/renderer/core/workers/worklet.h" #include "third_party/blink/renderer/modules/csspaint/document_paint_definition.h" -#include "third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.h" #include "third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_proxy.h" #include "third_party/blink/renderer/modules/csspaint/paint_worklet_pending_generator_registry.h" #include "third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h" @@ -20,8 +19,6 @@ namespace blink { -extern DocumentPaintDefinition* const kInvalidDocumentPaintDefinition; - class CSSPaintImageGeneratorImpl; // Manages a paint worklet: @@ -50,35 +47,32 @@ int WorkletId() const { return worklet_id_; } void Trace(blink::Visitor*) override; - // Used for main-thread CSS Paint. The DocumentDefinitionMap tracks - // definitions registered via registerProperty; definitions are only - // considered valid once all global scopes have registered the same definition - // for the same thread. - typedef HeapHashMap<String, Member<DocumentPaintDefinition>> + // The DocumentDefinitionMap tracks definitions registered via + // registerProperty; definitions are only considered valid once all global + // scopes have registered the same definition for the same thread. + typedef HashMap<String, std::unique_ptr<DocumentPaintDefinition>> DocumentDefinitionMap; DocumentDefinitionMap& GetDocumentDefinitionMap() { return document_definition_map_; } + // Used for main-thread CSS Paint. Registers a definition for a given painter, + // ensuring that the same CSSPaintDefinition is registered on all global + // scopes. void RegisterCSSPaintDefinition(const String& name, CSSPaintDefinition*, ExceptionState&); // Used for off-thread CSS Paint. In this mode we are not responsible for // tracking whether a definition is valid - this method should only be called - // once all global scopes have registered the same - // |MainThreadDocumentPaintDefinition| for the same |name|. + // once all global scopes have registered the same |DocumentPaintDefinition| + // for the same |name|. void RegisterMainThreadDocumentPaintDefinition( const String& name, Vector<CSSPropertyID> native_properties, Vector<String> custom_properties, Vector<CSSSyntaxDescriptor> input_argument_types, double alpha); - typedef HashMap<String, std::unique_ptr<MainThreadDocumentPaintDefinition>> - MainThreadDocumentDefinitionMap; - const MainThreadDocumentDefinitionMap& GetMainThreadDocumentDefinitionMap() { - return main_thread_document_definition_map_; - } protected: // Since paint worklet has more than one global scope, we MUST override this @@ -100,6 +94,16 @@ virtual wtf_size_t SelectNewGlobalScope(); Member<PaintWorkletPendingGeneratorRegistry> pending_generator_registry_; + + // Used for both main and off-thread CSS Paint. + // For the main thread, this map tracks the definitions created on the main + // thread, and ensures that all global scopes have the same definition. + // + // For the off thread case, both the worklet and main thread have this map. + // The worklet version is responsible for verifying that all global scopes + // have the same definition, and the main thread version relies on that. + // + // The value of an entry being nullptr means that it is an invalid definition. DocumentDefinitionMap document_definition_map_; // The last document paint frame a paint worklet painted on. This is used to @@ -121,10 +125,6 @@ // to ensure that all global scopes get the same proxy client. Member<PaintWorkletProxyClient> proxy_client_; - // Used in off-thread CSS Paint, where it tracks valid definitions. - HashMap<String, std::unique_ptr<MainThreadDocumentPaintDefinition>> - main_thread_document_definition_map_; - DISALLOW_COPY_AND_ASSIGN(PaintWorklet); };
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc index 62db1ef..3d1bb160 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc
@@ -14,6 +14,7 @@ #include "third_party/blink/renderer/core/workers/global_scope_creation_params.h" #include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h" #include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h" +#include "third_party/blink/renderer/modules/csspaint/document_paint_definition.h" #include "third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h" #include "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h" #include "third_party/blink/renderer/modules/worklet/worklet_thread_test_common.h"
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.cc b/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.cc index 3bbc5bcb..db8a2fbe 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.cc +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.cc
@@ -13,7 +13,6 @@ #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/workers/worker_thread.h" #include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h" -#include "third_party/blink/renderer/modules/csspaint/main_thread_document_paint_definition.h" #include "third_party/blink/renderer/modules/csspaint/paint_worklet.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.h" @@ -81,13 +80,13 @@ const String& name, CSSPaintDefinition* definition, ExceptionState& exception_state) { - DocumentPaintDefinition* document_definition; if (document_definition_map_.Contains(name)) { - document_definition = document_definition_map_.at(name); - if (document_definition == kInvalidDocumentPaintDefinition) + DocumentPaintDefinition* document_definition = + document_definition_map_.at(name); + if (!document_definition) return; if (!document_definition->RegisterAdditionalPaintDefinition(*definition)) { - document_definition_map_.Set(name, kInvalidDocumentPaintDefinition); + document_definition_map_.Set(name, nullptr); exception_state.ThrowDOMException( DOMExceptionCode::kNotSupportedError, "A class with name:'" + name + @@ -95,11 +94,16 @@ return; } } else { - document_definition = - MakeGarbageCollected<DocumentPaintDefinition>(definition); - document_definition_map_.Set(name, document_definition); + auto document_definition = std::make_unique<DocumentPaintDefinition>( + definition->NativeInvalidationProperties(), + definition->CustomInvalidationProperties(), + definition->InputArgumentTypes(), + definition->GetPaintRenderingContext2DSettings()->alpha()); + document_definition_map_.insert(name, std::move(document_definition)); } + DocumentPaintDefinition* document_definition = + document_definition_map_.at(name); // Notify the main thread only once all global scopes have registered the same // named paint definition (with the same definition as well). if (document_definition->GetRegisteredDefinitionCount() == @@ -137,13 +141,12 @@ } void PaintWorkletProxyClient::Trace(blink::Visitor* visitor) { - visitor->Trace(document_definition_map_); Supplement<WorkerClients>::Trace(visitor); PaintWorkletPainter::Trace(visitor); } sk_sp<PaintRecord> PaintWorkletProxyClient::Paint( - CompositorPaintWorkletInput* compositor_input) { + const CompositorPaintWorkletInput* compositor_input) { // TODO: Can this happen? We don't register till all are here. if (global_scopes_.IsEmpty()) return sk_make_sp<PaintRecord>(); @@ -161,7 +164,8 @@ PaintWorkletGlobalScope* global_scope = global_scopes_[base::RandInt(0, PaintWorklet::kNumGlobalScopes - 1)]; - PaintWorkletInput* input = static_cast<PaintWorkletInput*>(compositor_input); + const PaintWorkletInput* input = + static_cast<const PaintWorkletInput*>(compositor_input); CSSPaintDefinition* definition = global_scope->FindDefinition(input->NameCopy()); PaintWorkletStylePropertyMap* style_map =
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h b/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h index 4d4687177..d1e3a48f 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h
@@ -25,7 +25,7 @@ // as choosing the global scope to use for any given paint request. // // This class is constructed on the main thread but it is used in the worklet -// backing thread. +// backing thread. The entire class is used for off-thread CSS Paint. class MODULES_EXPORT PaintWorkletProxyClient : public GarbageCollectedFinalized<PaintWorkletProxyClient>, public Supplement<WorkerClients>, @@ -51,7 +51,7 @@ // PaintWorkletPainter implementation. int GetWorkletId() const override { return worklet_id_; } - sk_sp<PaintRecord> Paint(CompositorPaintWorkletInput*) override; + sk_sp<PaintRecord> Paint(const CompositorPaintWorkletInput*) override; // Add a global scope to the PaintWorkletProxyClient. virtual void AddGlobalScope(WorkletGlobalScope*); @@ -74,7 +74,7 @@ GetGlobalScopesForTesting() const { return global_scopes_; } - const HeapHashMap<String, Member<DocumentPaintDefinition>>& + const HashMap<String, std::unique_ptr<DocumentPaintDefinition>>& DocumentDefinitionMapForTesting() const { return document_definition_map_; } @@ -119,7 +119,10 @@ // DocumentPaintDefinition or the definition is invalid. Additionally we // cannot tell the main thread about a paint definition until all global // scopes have registered it. - HeapHashMap<String, Member<DocumentPaintDefinition>> document_definition_map_; + // + // The value of an entry being nullptr means that it is an invalid definition. + HashMap<String, std::unique_ptr<DocumentPaintDefinition>> + document_definition_map_; // The main thread needs to know about registered paint definitions so that it // can invalidate any associated paint objects and correctly create the paint
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client_test.cc b/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client_test.cc index 40fc1d8..b78227a 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client_test.cc +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client_test.cc
@@ -218,7 +218,7 @@ // Things that can be different: alpha different, native properties // different, custom properties different, input type args different. - const HeapHashMap<String, Member<DocumentPaintDefinition>>& + const HashMap<String, std::unique_ptr<DocumentPaintDefinition>>& document_definition_map = proxy_client->DocumentDefinitionMapForTesting(); // Differing native properties.
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc index 5e0bb5d2..a753f9a 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc
@@ -24,7 +24,9 @@ static const char kInfinite[] = "infinite"; bool IsInLoadingState(blink::MediaControlsImpl& controls) { - return controls.State() == blink::MediaControlsImpl::kLoadingMetadata || + return controls.State() == blink::MediaControlsImpl::kLoadingMetadataPaused || + controls.State() == + blink::MediaControlsImpl::kLoadingMetadataPlaying || controls.State() == blink::MediaControlsImpl::kBuffering; }
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc index c9d21b5..031043ca 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc
@@ -58,7 +58,8 @@ void SimulateLoadingMetadata() { SetMediaElementState(HTMLMediaElement::kHaveNothing, HTMLMediaElement::kNetworkLoading); - EXPECT_EQ(media_controls_->State(), MediaControlsImpl::kLoadingMetadata); + EXPECT_EQ(media_controls_->State(), + MediaControlsImpl::kLoadingMetadataPaused); loading_element_->UpdateDisplayState(); }
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc b/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc index 75503f2d..32ddb77 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc +++ b/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc
@@ -120,14 +120,15 @@ constexpr int kMinScrubbingMessageWidth = 300; -const char* kStateCSSClasses[7] = { - "state-no-source", // kNoSource - "state-no-metadata", // kNotLoaded - "state-loading-metadata", // kLoadingMetadata - "state-stopped", // kStopped - "state-playing", // kPlaying - "state-buffering", // kBuffering - "state-scrubbing", // kScrubbing +const char* kStateCSSClasses[8] = { + "state-no-source", // kNoSource + "state-no-metadata", // kNotLoaded + "state-loading-metadata-paused", // kLoadingMetadataPaused + "state-loading-metadata-playing", // kLoadingMetadataPlaying + "state-stopped", // kStopped + "state-playing", // kPlaying + "state-buffering", // kBuffering + "state-scrubbing", // kScrubbing }; // The padding in pixels inside the button panel. @@ -746,17 +747,17 @@ Vector<String> toAdd; Vector<String> toRemove; - if (state < kLoadingMetadata) + if (state < kLoadingMetadataPaused) toAdd.push_back("phase-pre-ready"); else toRemove.push_back("phase-pre-ready"); - if (state > kLoadingMetadata) + if (state > kLoadingMetadataPlaying) toAdd.push_back("phase-ready"); else toRemove.push_back("phase-ready"); - for (int i = 0; i < 7; i++) { + for (int i = 0; i < 8; i++) { if (i == state) toAdd.push_back(kStateCSSClasses[i]); else @@ -766,7 +767,7 @@ if (MediaElement().ShouldShowControls() && ShouldShowVideoControls() && !VideoElement().HasAvailableVideoFrame() && VideoElement().PosterImageURL().IsEmpty() && - state <= ControlsState::kLoadingMetadata) { + state <= ControlsState::kLoadingMetadataPlaying) { toAdd.push_back(kShowDefaultPosterCSSClass); } else { toRemove.push_back(kShowDefaultPosterCSSClass); @@ -855,8 +856,10 @@ case HTMLMediaElement::kNetworkNoSource: return ControlsState::kNoSource; case HTMLMediaElement::kNetworkLoading: - if (ready_state == HTMLMediaElement::kHaveNothing) - return ControlsState::kLoadingMetadata; + if (ready_state == HTMLMediaElement::kHaveNothing) { + return MediaElement().paused() ? ControlsState::kLoadingMetadataPaused + : ControlsState::kLoadingMetadataPlaying; + } if (!MediaElement().paused() && ready_state != HTMLMediaElement::kHaveEnoughData) { return ControlsState::kBuffering;
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_impl.h b/third_party/blink/renderer/modules/media_controls/media_controls_impl.h index d242848..2a3b01d 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_impl.h +++ b/third_party/blink/renderer/modules/media_controls/media_controls_impl.h
@@ -172,8 +172,11 @@ // Metadata has not been loaded. kNotLoaded, - // Metadata is being loaded. - kLoadingMetadata, + // Metadata is being loaded and the media will not play once it's loaded. + kLoadingMetadataPaused, + + // Metadata is being loaded and the media will play once it's loaded. + kLoadingMetadataPlaying, // Metadata is loaded and the media is ready to play. This can be when the // media is paused, when it has ended or before the media has started
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc b/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc index 7009436..0339be8 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc +++ b/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc
@@ -1443,7 +1443,7 @@ MediaControls().MediaElement().removeAttribute(html_names::kPreloadAttr); SimulateLoadedMetadata(); - EXPECT_EQ(MediaControls().State(), MediaControlsImpl::kLoadingMetadata); + EXPECT_EQ(MediaControls().State(), MediaControlsImpl::kLoadingMetadataPaused); EXPECT_FALSE(PlayButtonElement()->hasAttribute(html_names::kDisabledAttr)); EXPECT_FALSE(
diff --git a/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css b/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css index bce3c52..b883a7d 100644 --- a/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css +++ b/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css
@@ -574,12 +574,23 @@ transition: none; } -.state-playing input[pseudo="-webkit-media-controls-play-button" i], -.state-playing input[pseudo="-webkit-media-controls-overlay-play-button" i]::-internal-media-controls-overlay-play-button-internal { +audio::-webkit-media-controls.state-playing input[pseudo="-webkit-media-controls-play-button" i], +video::-webkit-media-controls.state-playing input[pseudo="-webkit-media-controls-play-button" i], +video::-webkit-media-controls.state-playing input[pseudo="-webkit-media-controls-overlay-play-button" i]::-internal-media-controls-overlay-play-button-internal, +audio::-webkit-media-controls.state-loading-metadata-playing input[pseudo="-webkit-media-controls-play-button" i], +video::-webkit-media-controls.state-loading-metadata-playing input[pseudo="-webkit-media-controls-play-button" i], +video::-webkit-media-controls.state-loading-metadata-playing input[pseudo="-webkit-media-controls-overlay-play-button" i]::-internal-media-controls-overlay-play-button-internal, +audio::-webkit-media-controls.state-buffering input[pseudo="-webkit-media-controls-play-button" i], +video::-webkit-media-controls.state-buffering input[pseudo="-webkit-media-controls-play-button" i], +video::-webkit-media-controls.state-buffering input[pseudo="-webkit-media-controls-overlay-play-button" i]::-internal-media-controls-overlay-play-button-internal { background-image: -webkit-image-set(url(ic_pause.svg) 1x); } -video::-webkit-media-controls.state-playing:not(.audio-only) [pseudo="-webkit-media-controls-panel"] input[pseudo="-webkit-media-controls-play-button" i] { +/* For the play button inside the button panel, we want to use a white icon + * instead. */ +video::-webkit-media-controls.state-buffering [pseudo="-internal-media-controls-button-panel"] input[pseudo="-webkit-media-controls-play-button" i], +video::-webkit-media-controls.state-loading-metadata-playing [pseudo="-internal-media-controls-button-panel"] input[pseudo="-webkit-media-controls-play-button" i], +video::-webkit-media-controls.state-playing [pseudo="-internal-media-controls-button-panel"] input[pseudo="-webkit-media-controls-play-button" i] { background-image: -webkit-image-set(url(ic_pause_white.svg) 1x); }
diff --git a/third_party/blink/renderer/modules/permissions/permission_utils.cc b/third_party/blink/renderer/modules/permissions/permission_utils.cc index 7c195b7..4fd6403 100644 --- a/third_party/blink/renderer/modules/permissions/permission_utils.cc +++ b/third_party/blink/renderer/modules/permissions/permission_utils.cc
@@ -12,6 +12,7 @@ #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" #include "third_party/blink/renderer/core/workers/worker_thread.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -28,6 +29,19 @@ interface_provider->GetInterface(std::move(request)); } +String PermissionStatusToString(mojom::blink::PermissionStatus status) { + switch (status) { + case mojom::blink::PermissionStatus::GRANTED: + return "granted"; + case mojom::blink::PermissionStatus::DENIED: + return "denied"; + case mojom::blink::PermissionStatus::ASK: + return "prompt"; + } + NOTREACHED(); + return "denied"; +} + PermissionDescriptorPtr CreatePermissionDescriptor(PermissionName name) { auto descriptor = MojoPermissionDescriptor::New(); descriptor->name = name;
diff --git a/third_party/blink/renderer/modules/permissions/permission_utils.h b/third_party/blink/renderer/modules/permissions/permission_utils.h index eb2abc9..a199659 100644 --- a/third_party/blink/renderer/modules/permissions/permission_utils.h +++ b/third_party/blink/renderer/modules/permissions/permission_utils.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_MODULES_PERMISSIONS_PERMISSION_UTILS_H_ #include "third_party/blink/public/mojom/permissions/permission.mojom-blink.h" +#include "third_party/blink/renderer/platform/wtf/forward.h" namespace blink { @@ -14,6 +15,8 @@ void ConnectToPermissionService(ExecutionContext*, mojom::blink::PermissionServiceRequest); +String PermissionStatusToString(mojom::blink::PermissionStatus); + mojom::blink::PermissionDescriptorPtr CreatePermissionDescriptor( mojom::blink::PermissionName);
diff --git a/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc b/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc index 5e49093..b19155d 100644 --- a/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc +++ b/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc
@@ -20,20 +20,6 @@ const char kUserVisibleOnlyRequired[] = "Push subscriptions that don't enable userVisibleOnly are not supported."; -String PermissionStatusToString(mojom::blink::PermissionStatus status) { - switch (status) { - case mojom::blink::PermissionStatus::GRANTED: - return "granted"; - case mojom::blink::PermissionStatus::DENIED: - return "denied"; - case mojom::blink::PermissionStatus::ASK: - return "prompt"; - } - - NOTREACHED(); - return "denied"; -} - } // namespace // static
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index e857b35..0850c24 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -2095,6 +2095,7 @@ "graphics/image_decoding_store_test.cc", "graphics/image_frame_generator_test.cc", "graphics/image_layer_chromium_test.cc", + "graphics/paint_worklet_paint_dispatcher_test.cc", "graphics/test/fake_canvas_resource_host.h", "graphics/test/fake_gles2_interface.h", "graphics/test/fake_web_graphics_context_3d_provider.h",
diff --git a/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h b/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h index 3aa112f..b3280bc 100644 --- a/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h +++ b/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h
@@ -24,7 +24,7 @@ }; static bool CPUSupportsAVX() { - static bool supports = ::base::CPU().has_avx(); + static const bool supports = ::base::CPU().has_avx(); return supports; }
diff --git a/third_party/blink/renderer/platform/graphics/graphics_layer.cc b/third_party/blink/renderer/platform/graphics/graphics_layer.cc index bcf6afba..90df383 100644 --- a/third_party/blink/renderer/platform/graphics/graphics_layer.cc +++ b/third_party/blink/renderer/platform/graphics/graphics_layer.cc
@@ -1043,6 +1043,9 @@ if (client_.ShouldThrottleRendering()) return sk_sp<PaintRecord>(new PaintRecord); + if (client_.PaintBlockedByDisplayLock()) + return sk_sp<PaintRecord>(new PaintRecord); + FloatRect bounds((IntRect(IntPoint(), IntSize(Size())))); GraphicsContext graphics_context(GetPaintController()); graphics_context.BeginRecording(bounds);
diff --git a/third_party/blink/renderer/platform/graphics/graphics_types.h b/third_party/blink/renderer/platform/graphics/graphics_types.h index 97e98ed..2d485eb 100644 --- a/third_party/blink/renderer/platform/graphics/graphics_types.h +++ b/third_party/blink/renderer/platform/graphics/graphics_types.h
@@ -131,7 +131,6 @@ kDisableDeferralReasonExpensiveOverdrawHeuristic = 1, kDisableDeferralReasonUsingTextureBackedPattern = 2, kDisableDeferralReasonDrawImageOfVideo = 3, - kDisableDeferralReasonSubPixelTextAntiAliasingSupport = 5, kDisableDeferralReasonLowEndDevice = 7, kDisableDeferralReasonCount, };
diff --git a/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.cc b/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.cc index 9a5895b..18b5b38 100644 --- a/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.cc +++ b/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.cc
@@ -6,6 +6,8 @@ #include <utility> +#include "base/barrier_closure.h" +#include "base/callback_helpers.h" #include "base/synchronization/waitable_event.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record.h" @@ -43,6 +45,13 @@ return std::make_unique<PlatformPaintWorkletLayerPainter>(dispatcher); } +PaintWorkletPaintDispatcher::PaintWorkletPaintDispatcher() { + // PaintWorkletPaintDispatcher is created on the main thread but used on the + // compositor, so detach the sequence checker until a call is received. + DCHECK(IsMainThread()); + DETACH_FROM_SEQUENCE(sequence_checker_); +} + void PaintWorkletPaintDispatcher::RegisterPaintWorkletPainter( PaintWorkletPainter* painter, scoped_refptr<base::SingleThreadTaskRunner> painter_runner) { @@ -69,19 +78,13 @@ // |worklet_queue| once, instead of sending one PaintWorkletInput at a time. // This avoids thread hop and boost performance. sk_sp<cc::PaintRecord> PaintWorkletPaintDispatcher::Paint( - cc::PaintWorkletInput* input) { + const cc::PaintWorkletInput* input) { TRACE_EVENT0("cc", "PaintWorkletPaintDispatcher::Paint"); sk_sp<cc::PaintRecord> output = sk_make_sp<cc::PaintOpBuffer>(); - PaintWorkletPainterToTaskRunnerMap copied_painter_map; - { - MutexLocker lock(painter_map_mutex_); - if (painter_map_.IsEmpty()) - return output; - // TODO(xidachen): copying is a temporary solution to prevent deadlock. It - // should be automatically solved with CC work. - copied_painter_map = painter_map_; - } + PaintWorkletPainterToTaskRunnerMap copied_painter_map = GetPainterMapCopy(); + if (copied_painter_map.IsEmpty()) + return output; base::WaitableEvent done_event; @@ -97,7 +100,7 @@ PostCrossThreadTask( *task_runner, FROM_HERE, CrossThreadBindOnce( - [](PaintWorkletPainter* painter, cc::PaintWorkletInput* input, + [](PaintWorkletPainter* painter, const cc::PaintWorkletInput* input, std::unique_ptr<AutoSignal> completion, sk_sp<cc::PaintRecord>* output) { *output = painter->Paint(input); @@ -114,4 +117,86 @@ return output; } +void PaintWorkletPaintDispatcher::DispatchWorklets( + cc::PaintWorkletJobMap worklet_job_map, + PlatformPaintWorkletLayerPainter::DoneCallback done_callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + TRACE_EVENT0("cc", "PaintWorkletPaintDispatcher::DispatchWorklets"); + + // Dispatching to the worklets is an asynchronous process, but there should + // only be one dispatch going on at once. We store the completion callback and + // the PaintWorklet job map in the class during the dispatch, then clear them + // when we get results (see AsyncPaintDone). + DCHECK(on_async_paint_complete_.is_null()); + on_async_paint_complete_ = std::move(done_callback); + ongoing_jobs_ = std::move(worklet_job_map); + + scoped_refptr<base::SingleThreadTaskRunner> runner = + Thread::Current()->GetTaskRunner(); + WTF::CrossThreadClosure on_done = CrossThreadBind( + [](scoped_refptr<PaintWorkletPaintDispatcher> dispatcher, + scoped_refptr<base::SingleThreadTaskRunner> runner) { + PostCrossThreadTask( + *runner, FROM_HERE, + CrossThreadBind(&PaintWorkletPaintDispatcher::AsyncPaintDone, + dispatcher)); + }, + WrapRefCounted(this), WTF::Passed(std::move(runner))); + + // Use a base::RepeatingClosure to make sure that AsyncPaintDone is only + // called once, once all the worklets are done. If there are no inputs + // specified, base::RepeatingClosure will trigger immediately and so the + // callback will still happen. + base::RepeatingClosure repeating_on_done = base::BarrierClosure( + ongoing_jobs_.size(), ConvertToBaseCallback(std::move(on_done))); + + // Now dispatch the calls to the registered painters. For each input, we match + // the id to a registered worklet and dispatch a cross-thread call to it, + // using the above-created base::RepeatingClosure. + PaintWorkletPainterToTaskRunnerMap copied_painter_map = GetPainterMapCopy(); + for (auto& job : ongoing_jobs_) { + int worklet_id = job.first; + scoped_refptr<cc::PaintWorkletJobVector> jobs = job.second; + + // Wrap the barrier closure in a ScopedClosureRunner to guarantee it runs + // even if there is no matching worklet or the posted task does not run. + auto on_done_runner = + std::make_unique<base::ScopedClosureRunner>(repeating_on_done); + + auto it = copied_painter_map.find(worklet_id); + if (it == copied_painter_map.end()) + continue; + + PaintWorkletPainter* painter = it->value.first; + scoped_refptr<base::SingleThreadTaskRunner> task_runner = it->value.second; + DCHECK(!task_runner->BelongsToCurrentThread()); + + PostCrossThreadTask( + *task_runner, FROM_HERE, + CrossThreadBindOnce( + [](PaintWorkletPainter* painter, + scoped_refptr<cc::PaintWorkletJobVector> jobs, + std::unique_ptr<base::ScopedClosureRunner> on_done_runner) { + for (cc::PaintWorkletJob& job : jobs->data) { + job.SetOutput(painter->Paint(job.input().get())); + } + on_done_runner->RunAndReset(); + }, + WrapCrossThreadPersistent(painter), WTF::Passed(std::move(jobs)), + WTF::Passed(std::move(on_done_runner)))); + } +} + +void PaintWorkletPaintDispatcher::AsyncPaintDone() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + TRACE_EVENT0("cc", "PaintWorkletPaintDispatcher::AsyncPaintDone"); + std::move(on_async_paint_complete_).Run(std::move(ongoing_jobs_)); +} + +PaintWorkletPaintDispatcher::PaintWorkletPainterToTaskRunnerMap +PaintWorkletPaintDispatcher::GetPainterMapCopy() { + MutexLocker lock(painter_map_mutex_); + return painter_map_; +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.h b/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.h index bb18c17..f6db40b 100644 --- a/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.h +++ b/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.h
@@ -8,7 +8,9 @@ #include <memory> #include "base/macros.h" +#include "base/sequence_checker.h" #include "base/single_thread_task_runner.h" +#include "base/thread_annotations.h" #include "third_party/blink/renderer/platform/graphics/paint_worklet_painter.h" #include "third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.h" #include "third_party/blink/renderer/platform/heap/handle.h" @@ -38,12 +40,21 @@ CreateCompositorThreadPainter( scoped_refptr<PaintWorkletPaintDispatcher>& paintee); - PaintWorkletPaintDispatcher() = default; + PaintWorkletPaintDispatcher(); // Dispatches a single paint class instance - represented by a // PaintWorkletInput - to the appropriate PaintWorklet thread, and blocks // until it receives the result. - sk_sp<cc::PaintRecord> Paint(cc::PaintWorkletInput*); + sk_sp<cc::PaintRecord> Paint(const cc::PaintWorkletInput*); + + // Dispatches a set of paint class instances - each represented by a + // PaintWorkletInput - to the appropriate PaintWorklet threads, asynchronously + // returning the results on the calling thread via the passed callback. + // + // Only one dispatch may be going on at a given time; the caller must wait for + // the passed callback to be called before calling DispatchWorklets again. + void DispatchWorklets(cc::PaintWorkletJobMap, + PlatformPaintWorkletLayerPainter::DoneCallback); // Register and unregister a PaintWorklet (represented in this context by a // PaintWorkletPainter). A given PaintWorklet is registered once all its @@ -66,16 +77,44 @@ } private: + // Called when results are available for the previous call to + // |DispatchWorklets|. + void AsyncPaintDone(); + + // Provide a copy of the painter_map_; see comments on |painter_map_mutex_|. + PaintWorkletPainterToTaskRunnerMap GetPainterMapCopy(); + // This class handles paint class instances for multiple PaintWorklets. These // are disambiguated via the PaintWorklets unique id; this map exists to do // that disambiguation. - PaintWorkletPainterToTaskRunnerMap painter_map_; + PaintWorkletPainterToTaskRunnerMap painter_map_ + GUARDED_BY(painter_map_mutex_); - // The (Un)registerPaintWorkletPainter comes from the worklet thread, and the - // Paint call is initiated from the raster threads - this mutex ensures that - // accessing / updating the |painter_map_| is thread safe. + // Whilst an asynchronous paint is underway (see |DispatchWorklets|), we store + // the input jobs and the completion callback. The jobs are shared with the + // PaintWorklet thread(s) during the dispatch, whilst the callback only ever + // stays on the calling thread. + cc::PaintWorkletJobMap ongoing_jobs_; + base::OnceCallback<void(cc::PaintWorkletJobMap)> on_async_paint_complete_; + + // The (Un)registerPaintWorkletPainter comes from the worklet thread, the + // Paint call is initiated from the raster threads, and DispatchWorklet comes + // from the compositor thread - this mutex ensures that accessing / updating + // the |painter_map_| is thread safe. + // + // TODO(crbug.com/907897): Once we remove the raster thread path, we can + // convert PaintWorkletPaintDispatcher to have a WeakFactory, make all calls + // happen on the compositor thread, and remove this mutex. Mutex painter_map_mutex_; + // Used to ensure that appropriate methods are called on the same thread. + // Currently only used for the asynchronous dispatch path. + // + // TODO(crbug.com/907897): Once we remove the raster thread path, we can + // convert PaintWorkletPaintDispatcher to have a WeakFactory, make all calls + // happen on the compositor thread, and check this on all methods. + SEQUENCE_CHECKER(sequence_checker_); + DISALLOW_COPY_AND_ASSIGN(PaintWorkletPaintDispatcher); };
diff --git a/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher_test.cc b/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher_test.cc new file mode 100644 index 0000000..5e809ec0 --- /dev/null +++ b/third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher_test.cc
@@ -0,0 +1,241 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.h" + +#include "base/bind.h" +#include "base/run_loop.h" +#include "cc/paint/paint_worklet_job.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/public/platform/web_thread_type.h" +#include "third_party/blink/renderer/platform/scheduler/public/thread.h" + +using ::testing::_; +using ::testing::NiceMock; +using ::testing::Return; + +namespace blink { +namespace { +// We need a thread (or multiple threads) for the (mock) worklets to run on. +std::unique_ptr<Thread> CreateTestThread(const char* name) { + return Platform::Current()->CreateThread( + ThreadCreationParams(WebThreadType::kTestThread) + .SetThreadNameForTest(name)); +} + +class PaintWorkletPaintDispatcherAsyncTest : public ::testing::Test { + public: + PlatformPaintWorkletLayerPainter::DoneCallback CreateTestCompleteCallback() { + return base::BindOnce( + &PaintWorkletPaintDispatcherAsyncTest::VerifyResultAndFinish, + base::Unretained(this)); + } + + // Allows a test to block on |VerifyResultAndFinish| being called. If a + // PaintWorkletPaintDispatcherAsyncTest test times out, it likely means the + // callback created by |CreateTestCompleteCallback| was never posted by the + // worklet thread. + void WaitForTestCompletion() { run_loop_.Run(); } + + private: + void VerifyResultAndFinish(cc::PaintWorkletJobMap results) { + run_loop_.QuitClosure().Run(); + } + + base::RunLoop run_loop_; +}; + +class MockPaintWorkletPainter + : public GarbageCollectedFinalized<MockPaintWorkletPainter>, + public PaintWorkletPainter { + USING_GARBAGE_COLLECTED_MIXIN(MockPaintWorkletPainter); + + public: + MockPaintWorkletPainter(int worklet_id) { + ON_CALL(*this, GetWorkletId).WillByDefault(Return(worklet_id)); + } + ~MockPaintWorkletPainter() = default; + + MOCK_CONST_METHOD0(GetWorkletId, int()); + MOCK_METHOD1(Paint, sk_sp<PaintRecord>(const cc::PaintWorkletInput*)); +}; + +class MockPaintWorkletInput : public cc::PaintWorkletInput { + public: + explicit MockPaintWorkletInput(int worklet_id) { + ON_CALL(*this, WorkletId).WillByDefault(Return(worklet_id)); + } + ~MockPaintWorkletInput() = default; + + MOCK_CONST_METHOD0(GetSize, gfx::SizeF()); + MOCK_CONST_METHOD0(WorkletId, int()); +}; + +cc::PaintWorkletInput* AddPaintWorkletInputToMap(cc::PaintWorkletJobMap& map, + int worklet_id) { + if (!map.contains(worklet_id)) + map[worklet_id] = base::MakeRefCounted<cc::PaintWorkletJobVector>(); + auto input = base::MakeRefCounted<MockPaintWorkletInput>(worklet_id); + MockPaintWorkletInput* input_ptr = input.get(); + map[worklet_id]->data.emplace_back(std::move(input)); + return input_ptr; +} +} // namespace + +TEST_F(PaintWorkletPaintDispatcherAsyncTest, DispatchedWorkletIsPainted) { + auto dispatcher = base::MakeRefCounted<PaintWorkletPaintDispatcher>(); + + const int worklet_id = 4; + MockPaintWorkletPainter* mock_painter = + MakeGarbageCollected<NiceMock<MockPaintWorkletPainter>>(worklet_id); + std::unique_ptr<Thread> worklet_thread = CreateTestThread("WorkletThread"); + dispatcher->RegisterPaintWorkletPainter(mock_painter, + worklet_thread->GetTaskRunner()); + + cc::PaintWorkletJobMap job_map; + Vector<cc::PaintWorkletInput*> inputs = { + AddPaintWorkletInputToMap(job_map, worklet_id), + AddPaintWorkletInputToMap(job_map, worklet_id), + AddPaintWorkletInputToMap(job_map, worklet_id), + }; + + // The input jobs match the registered painter, so we should see a series of + // calls to Paint() with the appropriate PaintWorkletInputs. + for (cc::PaintWorkletInput* input : inputs) + EXPECT_CALL(*mock_painter, Paint(input)).Times(1); + dispatcher->DispatchWorklets(job_map, CreateTestCompleteCallback()); + + WaitForTestCompletion(); +} + +TEST_F(PaintWorkletPaintDispatcherAsyncTest, DispatchCompletesWithNoPainters) { + auto dispatcher = base::MakeRefCounted<PaintWorkletPaintDispatcher>(); + + cc::PaintWorkletJobMap job_map; + AddPaintWorkletInputToMap(job_map, /*worklet_id=*/2); + AddPaintWorkletInputToMap(job_map, /*worklet_id=*/2); + AddPaintWorkletInputToMap(job_map, /*worklet_id=*/5); + + // There are no painters to dispatch to, matching or otherwise, but the + // callback should still be called so this test passes if it doesn't hang on + // WaitForTestCompletion. + dispatcher->DispatchWorklets(job_map, CreateTestCompleteCallback()); + + WaitForTestCompletion(); +} + +TEST_F(PaintWorkletPaintDispatcherAsyncTest, DispatchHandlesEmptyInput) { + auto dispatcher = base::MakeRefCounted<PaintWorkletPaintDispatcher>(); + + const int worklet_id = 4; + auto* mock_painter = + MakeGarbageCollected<NiceMock<MockPaintWorkletPainter>>(worklet_id); + std::unique_ptr<Thread> worklet_thread = CreateTestThread("WorkletThread"); + dispatcher->RegisterPaintWorkletPainter(mock_painter, + worklet_thread->GetTaskRunner()); + + cc::PaintWorkletJobMap job_map; + + // The input job map is empty, so we should see no calls to Paint but the + // callback should still be called. + EXPECT_CALL(*mock_painter, Paint(_)).Times(0); + dispatcher->DispatchWorklets(job_map, CreateTestCompleteCallback()); + + WaitForTestCompletion(); +} + +TEST_F(PaintWorkletPaintDispatcherAsyncTest, DispatchSelectsCorrectPainter) { + auto dispatcher = base::MakeRefCounted<PaintWorkletPaintDispatcher>(); + + const int first_worklet_id = 2; + auto* first_mock_painter = + MakeGarbageCollected<NiceMock<MockPaintWorkletPainter>>(first_worklet_id); + std::unique_ptr<Thread> first_thread = CreateTestThread("WorkletThread1"); + dispatcher->RegisterPaintWorkletPainter(first_mock_painter, + first_thread->GetTaskRunner()); + + const int second_worklet_id = 3; + auto* second_mock_painter = + MakeGarbageCollected<NiceMock<MockPaintWorkletPainter>>( + second_worklet_id); + std::unique_ptr<Thread> second_thread = CreateTestThread("WorkletThread2"); + dispatcher->RegisterPaintWorkletPainter(second_mock_painter, + second_thread->GetTaskRunner()); + + cc::PaintWorkletJobMap job_map; + Vector<cc::PaintWorkletInput*> inputs{ + AddPaintWorkletInputToMap(job_map, second_worklet_id), + AddPaintWorkletInputToMap(job_map, second_worklet_id), + }; + + // Paint should only be called on the correct painter, with our input. + EXPECT_CALL(*first_mock_painter, Paint(_)).Times(0); + for (cc::PaintWorkletInput* input : inputs) { + EXPECT_CALL(*second_mock_painter, Paint(input)).Times(1); + } + dispatcher->DispatchWorklets(job_map, CreateTestCompleteCallback()); + + WaitForTestCompletion(); +} + +TEST_F(PaintWorkletPaintDispatcherAsyncTest, DispatchIgnoresNonMatchingInput) { + auto dispatcher = base::MakeRefCounted<PaintWorkletPaintDispatcher>(); + + const int worklet_id = 2; + auto* mock_painter = + MakeGarbageCollected<NiceMock<MockPaintWorkletPainter>>(worklet_id); + std::unique_ptr<Thread> worklet_thread = CreateTestThread("WorkletThread"); + dispatcher->RegisterPaintWorkletPainter(mock_painter, + worklet_thread->GetTaskRunner()); + + cc::PaintWorkletJobMap job_map; + const int non_registered_worklet_id = 3; + cc::PaintWorkletInput* matching_input = + AddPaintWorkletInputToMap(job_map, worklet_id); + AddPaintWorkletInputToMap(job_map, non_registered_worklet_id); + + // Only one job matches, so our painter should only be called once, and the + // callback should still be called. + EXPECT_CALL(*mock_painter, Paint(matching_input)).Times(1); + dispatcher->DispatchWorklets(job_map, CreateTestCompleteCallback()); + + WaitForTestCompletion(); +} + +TEST_F(PaintWorkletPaintDispatcherAsyncTest, + DispatchCorrectlyAssignsInputsToMultiplePainters) { + auto dispatcher = base::MakeRefCounted<PaintWorkletPaintDispatcher>(); + + const int first_worklet_id = 5; + auto* first_mock_painter = + MakeGarbageCollected<NiceMock<MockPaintWorkletPainter>>(first_worklet_id); + std::unique_ptr<Thread> first_thread = CreateTestThread("WorkletThread1"); + dispatcher->RegisterPaintWorkletPainter(first_mock_painter, + first_thread->GetTaskRunner()); + + const int second_worklet_id = 1; + auto* second_mock_painter = + MakeGarbageCollected<NiceMock<MockPaintWorkletPainter>>( + second_worklet_id); + std::unique_ptr<Thread> second_thread = CreateTestThread("WorkletThread2"); + dispatcher->RegisterPaintWorkletPainter(second_mock_painter, + second_thread->GetTaskRunner()); + + cc::PaintWorkletJobMap job_map; + cc::PaintWorkletInput* first_input = + AddPaintWorkletInputToMap(job_map, first_worklet_id); + cc::PaintWorkletInput* second_input = + AddPaintWorkletInputToMap(job_map, second_worklet_id); + + // Both painters should be called with the correct inputs. + EXPECT_CALL(*first_mock_painter, Paint(first_input)).Times(1); + EXPECT_CALL(*second_mock_painter, Paint(second_input)).Times(1); + dispatcher->DispatchWorklets(job_map, CreateTestCompleteCallback()); + + WaitForTestCompletion(); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/paint_worklet_painter.h b/third_party/blink/renderer/platform/graphics/paint_worklet_painter.h index 23aeb4b..43677c8 100644 --- a/third_party/blink/renderer/platform/graphics/paint_worklet_painter.h +++ b/third_party/blink/renderer/platform/graphics/paint_worklet_painter.h
@@ -31,7 +31,7 @@ virtual ~PaintWorkletPainter() = default; virtual int GetWorkletId() const = 0; - virtual sk_sp<PaintRecord> Paint(cc::PaintWorkletInput*) = 0; + virtual sk_sp<PaintRecord> Paint(const cc::PaintWorkletInput*) = 0; }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.cc b/third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.cc index c2fe1ce0..64567632 100644 --- a/third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.cc +++ b/third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.cc
@@ -27,8 +27,15 @@ } sk_sp<PaintRecord> PlatformPaintWorkletLayerPainter::Paint( - cc::PaintWorkletInput* input) { + const cc::PaintWorkletInput* input) { return dispatcher_->Paint(input); } +void PlatformPaintWorkletLayerPainter::DispatchWorklets( + cc::PaintWorkletJobMap worklet_data_map, + DoneCallback done_callback) { + dispatcher_->DispatchWorklets(std::move(worklet_data_map), + std::move(done_callback)); +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.h b/third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.h index 4cc7a0c6..c31745d 100644 --- a/third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.h +++ b/third_party/blink/renderer/platform/graphics/platform_paint_worklet_layer_painter.h
@@ -29,7 +29,8 @@ ~PlatformPaintWorkletLayerPainter() override; // cc::PaintWorkletLayerPainter - sk_sp<cc::PaintRecord> Paint(cc::PaintWorkletInput*) override; + sk_sp<cc::PaintRecord> Paint(const cc::PaintWorkletInput*) override; + void DispatchWorklets(cc::PaintWorkletJobMap, DoneCallback) override; private: scoped_refptr<PaintWorkletPaintDispatcher> dispatcher_;
diff --git a/third_party/blink/renderer/platform/heap/unified_heap_controller.cc b/third_party/blink/renderer/platform/heap/unified_heap_controller.cc index 619619e..c0cffa6 100644 --- a/third_party/blink/renderer/platform/heap/unified_heap_controller.cc +++ b/third_party/blink/renderer/platform/heap/unified_heap_controller.cc
@@ -180,24 +180,29 @@ return IsRootForNonTracingGCInternal(handle); } -void UnifiedHeapController::IncreaseAllocatedObjectSize(size_t delta_bytes) { - buffered_allocated_size_ += delta_bytes; - +void UnifiedHeapController::ReportBufferedAllocatedSizeIfPossible() { // Reported from a recursive sweeping call. if (thread_state()->IsSweepingInProgress() && thread_state()->SweepForbidden()) { return; } - if (buffered_allocated_size_ > 0) { + if (buffered_allocated_size_ < 0) { + DecreaseAllocatedSize(static_cast<size_t>(-buffered_allocated_size_)); + } else { IncreaseAllocatedSize(static_cast<size_t>(buffered_allocated_size_)); - buffered_allocated_size_ = 0; } + buffered_allocated_size_ = 0; +} + +void UnifiedHeapController::IncreaseAllocatedObjectSize(size_t delta_bytes) { + buffered_allocated_size_ += static_cast<int64_t>(delta_bytes); + ReportBufferedAllocatedSizeIfPossible(); } void UnifiedHeapController::DecreaseAllocatedObjectSize(size_t delta_bytes) { - // TODO(mlippautz): Add support for negative deltas in V8. - buffered_allocated_size_ -= delta_bytes; + buffered_allocated_size_ -= static_cast<int64_t>(delta_bytes); + ReportBufferedAllocatedSizeIfPossible(); } } // namespace blink
diff --git a/third_party/blink/renderer/platform/heap/unified_heap_controller.h b/third_party/blink/renderer/platform/heap/unified_heap_controller.h index fd72cb56..8070087 100644 --- a/third_party/blink/renderer/platform/heap/unified_heap_controller.h +++ b/third_party/blink/renderer/platform/heap/unified_heap_controller.h
@@ -61,6 +61,8 @@ static bool IsRootForNonTracingGCInternal( const v8::TracedGlobal<v8::Value>& handle); + void ReportBufferedAllocatedSizeIfPossible(); + ThreadState* const thread_state_; // Returns whether the Blink heap has been fully processed. bool is_tracing_done_ = false;
diff --git a/third_party/blink/renderer/platform/loader/fetch/unique_identifier.cc b/third_party/blink/renderer/platform/loader/fetch/unique_identifier.cc index 6a581e6..4f8d12b5 100644 --- a/third_party/blink/renderer/platform/loader/fetch/unique_identifier.cc +++ b/third_party/blink/renderer/platform/loader/fetch/unique_identifier.cc
@@ -29,12 +29,13 @@ */ #include <atomic> +#include <cstdint> #include "third_party/blink/renderer/platform/loader/fetch/unique_identifier.h" namespace blink { -static std::atomic_uint64_t g_unique_identifier(1); +static std::atomic<std::uint64_t> g_unique_identifier(1); uint64_t CreateUniqueIdentifier() { return g_unique_identifier.fetch_add(1, std::memory_order_relaxed);
diff --git a/third_party/blink/renderer/platform/scheduler/worker/worker_thread.cc b/third_party/blink/renderer/platform/scheduler/worker/worker_thread.cc index 6f45ed2..4e99f30 100644 --- a/third_party/blink/renderer/platform/scheduler/worker/worker_thread.cc +++ b/third_party/blink/renderer/platform/scheduler/worker/worker_thread.cc
@@ -91,7 +91,7 @@ // thread? sequence_manager_ = base::sequence_manager::CreateUnboundSequenceManager( base::sequence_manager::SequenceManager::Settings::Builder() - .SetMessagePumpType(base::MessageLoop::TYPE_DEFAULT) + .SetMessagePumpType(base::MessagePump::Type::DEFAULT) .SetRandomisedSamplingEnabled(true) .Build()); internal_task_queue_ = sequence_manager_->CreateTaskQueue(
diff --git a/third_party/blink/renderer/platform/testing/DEPS b/third_party/blink/renderer/platform/testing/DEPS index be9c017d0..bfaba57 100644 --- a/third_party/blink/renderer/platform/testing/DEPS +++ b/third_party/blink/renderer/platform/testing/DEPS
@@ -12,8 +12,8 @@ "+base/path_service.h", "+base/process", "+base/run_loop.h", - "+base/message_loop", "+base/metrics/statistics_recorder.h", + "+base/task/single_thread_task_executor.h", "+base/test/test_io_thread.h", "+cc", "+mojo/core/embedder",
diff --git a/third_party/blink/renderer/platform/testing/image_decode_bench.cc b/third_party/blink/renderer/platform/testing/image_decode_bench.cc index 951632a6..5aae7d8b 100644 --- a/third_party/blink/renderer/platform/testing/image_decode_bench.cc +++ b/third_party/blink/renderer/platform/testing/image_decode_bench.cc
@@ -16,7 +16,7 @@ #include "base/command_line.h" #include "base/files/file_util.h" #include "base/memory/scoped_refptr.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "mojo/core/embedder/embedder.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/image-decoders/image_decoder.h" @@ -135,7 +135,7 @@ } // namespace blink int main(int argc, char* argv[]) { - base::MessageLoop message_loop; + base::SingleThreadTaskExecutor main_task_executor; mojo::core::Init(); base::CommandLine::Init(argc, argv); blink::ImageDecodeBenchMain(argc, argv);
diff --git a/third_party/blink/renderer/platform/text/character.cc b/third_party/blink/renderer/platform/text/character.cc index 0dc3227..3832e4ca 100644 --- a/third_party/blink/renderer/platform/text/character.cc +++ b/third_party/blink/renderer/platform/text/character.cc
@@ -56,9 +56,7 @@ } static bool HasProperty(UChar32 c, CharacterProperty property) { - static UCPTrie* trie = nullptr; - if (!trie) - trie = CreateTrie(); + static const UCPTrie* trie = CreateTrie(); return UCPTRIE_FAST_GET(trie, UCPTRIE_16, c) & static_cast<CharacterPropertyType>(property); }
diff --git a/third_party/blink/renderer/platform/wtf/dtoa/double-conversion.cc b/third_party/blink/renderer/platform/wtf/dtoa/double-conversion.cc index 48821b40..ac604227 100644 --- a/third_party/blink/renderer/platform/wtf/dtoa/double-conversion.cc +++ b/third_party/blink/renderer/platform/wtf/dtoa/double-conversion.cc
@@ -43,8 +43,8 @@ const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() { int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN; - static DoubleToStringConverter converter(flags, "Infinity", "NaN", 'e', -6, - 21, 6, 0); + static const DoubleToStringConverter converter(flags, "Infinity", "NaN", 'e', + -6, 21, 6, 0); return converter; }
diff --git a/third_party/blink/web_tests/MSANExpectations b/third_party/blink/web_tests/MSANExpectations index 35cc111..3c80644 100644 --- a/third_party/blink/web_tests/MSANExpectations +++ b/third_party/blink/web_tests/MSANExpectations
@@ -184,6 +184,13 @@ crbug.com/856601 [ Linux ] virtual/streams-native/external/wpt/fetch/api/idl.any.sharedworker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window.html [ Pass Timeout ] crbug.com/856601 [ Linux ] fast/js/toString-stack-overflow.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/css/css-masking/idlharness.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/css/css-transitions/idlharness.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/import-maps/fallback.sub.tentative.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/notifications/idlharness.https.any.worker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/sms/idlharness.https.any.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/wake-lock/idlharness.https.any.worker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/fetch/api/idl.any.sharedworker.html [ Pass Timeout ] # background-fetch tests crash on MSAN crbug.com/869818 [ Linux ] external/wpt/background-fetch/fetch.https.window.html [ Pass Crash ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index c441b59..305f7c61 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -4788,10 +4788,6 @@ crbug.com/961439 external/wpt/cookies/samesite-none-secure/ [ Failure ] crbug.com/961439 virtual/samesite-by-default-cookies/external/wpt/cookies/samesite-none-secure/ [ Failure ] -# Deprecation messages for SameSite cookie changes cause flakes in cookies tests using document.cookie. -crbug.com/969144 [ Mac ] http/tests/security/cookies/base-tag.html [ Pass Failure ] -crbug.com/969144 [ Mac ] http/tests/security/cookies/base-about-blank.html [ Pass Failure ] - # Client hint tests that fail in content_shell but pass when run manually using # full browser. crbug.com/856700 external/wpt/client-hints/accept_ch_lifetime_same_origin_iframe.tentative.https.html [ Skip ] @@ -5766,6 +5762,41 @@ crbug.com/964239 external/wpt/css/css-scroll-snap/scroll-margin.html [ Pass Failure ] crbug.com/965389 [ Mac ] media/track/track-cue-rendering-position-auto.html [ Pass Failure ] +# TODO(crbug.com/943636): rebaseline and re-enable once https://chromium-review.googlesource.com/c/v8/v8/+/1593307 is rolled into chromium. +crbug.com/943636 external/wpt/screen-orientation/lock-unlock-check.html [ Pass Failure ] +crbug.com/943636 fast/dom/script-module-inline-error-gc.html [ Pass Failure ] +crbug.com/943636 fast/dom/HTMLAnchorElement/anchor-ismap-crash.html [ Pass Failure ] +crbug.com/943636 fast/dom/SelectorAPI/unknown-pseudo.html [ Pass Failure ] +crbug.com/943636 fast/encoding/meta-in-script.html [ Pass Failure ] +crbug.com/943636 fast/events/attribute-listener-deletion-crash.html [ Pass Failure ] +crbug.com/943636 fast/events/set-attribute-listener-window-onerror-crash.html [ Pass Failure ] +crbug.com/943636 fast/events/window-onerror-05.html [ Pass Failure ] +crbug.com/943636 fast/js/postfix-syntax.html [ Pass Failure ] +crbug.com/943636 fast/parser/entity-end-script-tag.html [ Pass Failure ] +crbug.com/943636 fast/workers/worker-onerror-01.html [ Pass Failure ] +crbug.com/943636 html5lib/generated/run-tests1-data.html [ Pass Failure ] +crbug.com/943636 html5lib/generated/run-tests1-write.html [ Pass Failure ] +crbug.com/943636 html5lib/generated/run-tests18-data.html [ Pass Failure ] +crbug.com/943636 html5lib/generated/run-tests18-write.html [ Pass Failure ] +crbug.com/943636 html5lib/generated/run-tests7-data.html [ Pass Failure ] +crbug.com/943636 html5lib/generated/run-tests7-write.html [ Pass Failure ] +crbug.com/943636 http/tests/devtools/console/console-eval-object-literal.js [ Pass Failure ] +crbug.com/943636 http/tests/devtools/console/console-link-to-snippet.js [ Pass Failure ] +crbug.com/943636 http/tests/devtools/console/console-log-eval-syntax-error.js [ Pass Failure ] +crbug.com/943636 http/tests/devtools/console/console-log-syntax-error.js [ Pass Failure ] +crbug.com/943636 http/tests/devtools/console/console-message-from-inline-with-url.js [ Pass Failure ] +crbug.com/943636 http/tests/devtools/sources/debugger/debugger-autocontinue-on-syntax-error.js [ Pass Failure ] +crbug.com/943636 http/tests/devtools/sources/debugger/debugger-compile-and-run.js [ Pass Failure ] +crbug.com/943636 inspector-protocol/runtime/runtime-callFunctionOn-async.js [ Pass Failure ] +crbug.com/943636 inspector-protocol/runtime/runtime-runScript-async.js [ Pass Failure ] +crbug.com/943636 paint/invalidation/svg/viewport-mask-update.html [ Pass Failure ] +crbug.com/943636 security/lazy-event-listener.html [ Pass Failure ] +crbug.com/943636 virtual/disable-blink-gen-property-trees/paint/invalidation/svg/viewport-mask-update.html [ Pass Failure ] +crbug.com/943636 virtual/mouseevent_fractional/fast/events/attribute-listener-deletion-crash.html [ Pass Failure ] +crbug.com/943636 virtual/mouseevent_fractional/fast/events/set-attribute-listener-window-onerror-crash.html [ Pass Failure ] +crbug.com/943636 virtual/mouseevent_fractional/fast/events/window-onerror-05.html [ Pass Failure ] +crbug.com/943636 virtual/omt-worker-fetch/fast/workers/worker-onerror-01.html [ Pass Failure ] + # Sheriff 2019-05-24 crbug.com/966932 [ Linux ] http/tests/devtools/a11y-axe-core/elements/main-tool-test.js [ Timeout Pass ]
diff --git a/third_party/blink/web_tests/http/tests/media/controls/toggle-class-with-state-source.html b/third_party/blink/web_tests/http/tests/media/controls/toggle-class-with-state-source.html index 2e5a8358..686d482 100644 --- a/third_party/blink/web_tests/http/tests/media/controls/toggle-class-with-state-source.html +++ b/third_party/blink/web_tests/http/tests/media/controls/toggle-class-with-state-source.html
@@ -13,7 +13,7 @@ checkControlsHasClasses(video, ["phase-pre-ready", "state-no-source", "use-default-poster"]); video.onstalled = t.step_func(() => { - checkControlsHasClass(video, "state-loading-metadata"); + checkControlsHasClass(video, "state-loading-metadata-playing"); }); video.onloadeddata = t.step_func(() => {
diff --git a/third_party/blink/web_tests/http/tests/security/cookies/base-about-blank-expected.txt b/third_party/blink/web_tests/http/tests/security/cookies/base-about-blank-expected.txt index 40aedc5..24b52d7 100644 --- a/third_party/blink/web_tests/http/tests/security/cookies/base-about-blank-expected.txt +++ b/third_party/blink/web_tests/http/tests/security/cookies/base-about-blank-expected.txt
@@ -1,4 +1,3 @@ -CONSOLE WARNING: [Deprecation] A cookie associated with a cross-site resource at http://localhost:8000/security/cookies/resources/set-a-cookie.html was set without the `SameSite` attribute. Starting in M77, Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592. Running test. secret=PASS
diff --git a/third_party/blink/web_tests/http/tests/security/cookies/base-tag-expected.txt b/third_party/blink/web_tests/http/tests/security/cookies/base-tag-expected.txt index 2de19173..b38b7e4 100644 --- a/third_party/blink/web_tests/http/tests/security/cookies/base-tag-expected.txt +++ b/third_party/blink/web_tests/http/tests/security/cookies/base-tag-expected.txt
@@ -1,4 +1,3 @@ -CONSOLE WARNING: [Deprecation] A cookie associated with a cross-site resource at http://localhost:8000/security/cookies/resources/set-a-cookie.html was set without the `SameSite` attribute. Starting in M77, Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592. Running test. secret=PASS Test complete.
diff --git a/third_party/blink/web_tests/http/tests/security/cookies/basic-expected.txt b/third_party/blink/web_tests/http/tests/security/cookies/basic-expected.txt index 2de19173..b38b7e4 100644 --- a/third_party/blink/web_tests/http/tests/security/cookies/basic-expected.txt +++ b/third_party/blink/web_tests/http/tests/security/cookies/basic-expected.txt
@@ -1,4 +1,3 @@ -CONSOLE WARNING: [Deprecation] A cookie associated with a cross-site resource at http://localhost:8000/security/cookies/resources/set-a-cookie.html was set without the `SameSite` attribute. Starting in M77, Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592. Running test. secret=PASS Test complete.
diff --git a/third_party/blink/web_tests/http/tests/security/cookies/cookie-theft-with-javascript-doc-expected.txt b/third_party/blink/web_tests/http/tests/security/cookies/cookie-theft-with-javascript-doc-expected.txt index 03305e2..ff43ca4 100644 --- a/third_party/blink/web_tests/http/tests/security/cookies/cookie-theft-with-javascript-doc-expected.txt +++ b/third_party/blink/web_tests/http/tests/security/cookies/cookie-theft-with-javascript-doc-expected.txt
@@ -1,2 +1 @@ -CONSOLE WARNING: [Deprecation] A cookie associated with a cross-site resource at http://localhost:8080/security/cookies/resources/innocent-victim-with-cookies.html was set without the `SameSite` attribute. Starting in M77, Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592. SUCCESS
diff --git a/third_party/crashpad/crashpad/snapshot/BUILD.gn b/third_party/crashpad/crashpad/snapshot/BUILD.gn index 4a3b3d1..25805c2 100644 --- a/third_party/crashpad/crashpad/snapshot/BUILD.gn +++ b/third_party/crashpad/crashpad/snapshot/BUILD.gn
@@ -95,16 +95,9 @@ "mac/process_snapshot_mac.h", "mac/process_types.cc", "mac/process_types.h", - "mac/process_types/all.proctype", - "mac/process_types/annotation.proctype", - "mac/process_types/crashpad_info.proctype", - "mac/process_types/crashreporterclient.proctype", "mac/process_types/custom.cc", - "mac/process_types/dyld_images.proctype", "mac/process_types/flavors.h", "mac/process_types/internal.h", - "mac/process_types/loader.proctype", - "mac/process_types/nlist.proctype", "mac/process_types/traits.h", "mac/system_snapshot_mac.cc", "mac/system_snapshot_mac.h",
diff --git a/third_party/google-truth/BUILD.gn b/third_party/google-truth/BUILD.gn index e7f9d86..39ff51cd 100644 --- a/third_party/google-truth/BUILD.gn +++ b/third_party/google-truth/BUILD.gn
@@ -13,9 +13,11 @@ # requires_android because of dependency on guava_android. requires_android = true - jar_path = "lib/truth-0.44.jar" + jar_path = "lib/truth-0.45.jar" deps = [ "//third_party/guava:guava_android_java", "//third_party/junit:junit", ] + + proguard_configs = [ "proguard.flags" ] }
diff --git a/third_party/google-truth/README.chromium b/third_party/google-truth/README.chromium index 88d18d9..4beb926 100644 --- a/third_party/google-truth/README.chromium +++ b/third_party/google-truth/README.chromium
@@ -1,7 +1,7 @@ Name: Fluent assertions for Java Short Name: google-truth URL: https://github.com/google/truth -Version: 0.44 +Version: 0.45 License: Apache 2.0 License File: NOT_SHIPPED Security Critical: no
diff --git a/third_party/google-truth/cipd.yaml b/third_party/google-truth/cipd.yaml index 34d66aca..a227958 100644 --- a/third_party/google-truth/cipd.yaml +++ b/third_party/google-truth/cipd.yaml
@@ -11,4 +11,4 @@ package: chromium/third_party/google-truth description: Google Truth Fluent Assertions Java Library data: - - file: lib/truth-0.44.jar + - file: lib/truth-0.45.jar
diff --git a/third_party/google-truth/proguard.flags b/third_party/google-truth/proguard.flags new file mode 100644 index 0000000..a395f1e --- /dev/null +++ b/third_party/google-truth/proguard.flags
@@ -0,0 +1 @@ +-dontwarn org.objectweb.asm.**
diff --git a/tools/accessibility/inspect/ax_dump_events.cc b/tools/accessibility/inspect/ax_dump_events.cc index 474aafde..5846b85 100644 --- a/tools/accessibility/inspect/ax_dump_events.cc +++ b/tools/accessibility/inspect/ax_dump_events.cc
@@ -8,9 +8,9 @@ #include "base/at_exit.h" #include "base/command_line.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" +#include "base/task/single_thread_task_executor.h" #include "tools/accessibility/inspect/ax_event_server.h" namespace { @@ -63,7 +63,8 @@ } base::AtExitManager exit_manager; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); const auto server = std::make_unique<tools::AXEventServer>(pid, pattern_str); base::RunLoop().Run(); return 0;
diff --git a/tools/ipc_fuzzer/message_replay/replay_process.h b/tools/ipc_fuzzer/message_replay/replay_process.h index 29c6914c..f8ba5fb7 100644 --- a/tools/ipc_fuzzer/message_replay/replay_process.h +++ b/tools/ipc_fuzzer/message_replay/replay_process.h
@@ -10,8 +10,8 @@ #include <memory> #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/synchronization/waitable_event.h" +#include "base/task/single_thread_task_executor.h" #include "base/threading/thread.h" #include "base/timer/timer.h" #include "ipc/ipc_channel_proxy.h" @@ -63,7 +63,7 @@ std::unique_ptr<content::ServiceManagerConnection> service_manager_connection_; std::unique_ptr<IPC::ChannelProxy> channel_; - base::MessageLoop main_loop_; + base::SingleThreadTaskExecutor main_task_executor_; base::Thread io_thread_; base::WaitableEvent shutdown_event_; MessageVector messages_;
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 397d556..52f6575a 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -30990,6 +30990,12 @@ </int> </enum> +<enum name="IOSOutOfSyncURLAction"> + <int value="0" label="No action"/> + <int value="1" label="Go back"/> + <int value="2" label="Go forward"/> +</enum> + <enum name="IOSPageLoadCountNavigationType"> <int value="0" label="Chrome URL Navigation"/> <int value="1" label="Same Document Web Navigation"/> @@ -33337,6 +33343,7 @@ <int value="-1807797669" label="google-doodle-url"/> <int value="-1804485171" label="disable-fullscreen-tab-detaching"/> <int value="-1802502753" label="enable-manual-password-generation:enabled"/> + <int value="-1799801575" label="CookieDeprecationMessages:enabled"/> <int value="-1798337879" label="enable-md-downloads"/> <int value="-1797739460" label="brotli-encoding:disabled"/> <int value="-1791226955" label="BreakingNewsPush:enabled"/> @@ -33763,6 +33770,7 @@ <int value="-1201183153" label="enable-centered-app-list"/> <int value="-1199159971" label="ContextualSuggestionsIPHReverseScroll:enabled"/> + <int value="-1197245070" label="CookieDeprecationMessages:disabled"/> <int value="-1197035323" label="ZeroSuggestRedirectToChrome:disabled"/> <int value="-1195194959" label="XGEOVisibleNetworks:disabled"/> <int value="-1190174011" label="enable-hdr"/> @@ -44151,6 +44159,12 @@ <int value="3" label="Timeout"/> </enum> +<enum name="PaintHoldingInputTiming"> + <int value="0" label="Before Lifecycle"/> + <int value="1" label="Before Commit"/> + <int value="2" label="After Commit"/> +</enum> + <enum name="PaletteModeCancelType"> <int value="0" label="Palette laser pointer mode is cancelled."/> <int value="1" label="Palette laser pointer mode is switched out of"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 73a9f0ce..eaf2d0d 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -59670,6 +59670,30 @@ </summary> </histogram> +<histogram name="Memory.NativeLibrary.NotResidentOrderedCodeMemoryFootprint" + units="KB" expires_after="2019-12-01"> + <owner>lizeb@chromium.org</owner> + <summary> + The size of the native library code which was ordered, yet is not resident + in memory, across all processes. This metric is computed by parsing + proc/self/pagemap and counting native library pages that are mapped and + present in RAM for at least one Chrome process. Recorded once per UMA ping. + Available only on Android. + </summary> +</histogram> + +<histogram name="Memory.NativeLibrary.ResidentNotOrderedCodeMemoryFootprint" + units="KB" expires_after="2019-12-01"> + <owner>lizeb@chromium.org</owner> + <summary> + The size of the native library code which is outside the ordered section, + yet is resident in memory, across all processes. This metric is computed by + parsing proc/self/pagemap and counting native library pages that are mapped + and present in RAM for at least one Chrome process. Recorded once per UMA + ping. Available only on Android. + </summary> +</histogram> + <histogram name="Memory.NetworkService.PrivateMemoryFootprint" units="MiB" expires_after="2020-05-06"> <owner>mmenke@chromium.org</owner> @@ -89664,6 +89688,15 @@ </summary> </histogram> +<histogram name="PaintHolding.InputTiming" enum="PaintHoldingInputTiming" + expires_after="M78"> + <owner>schenney@chromium.org</owner> + <owner>paint-dev@chromium.org</owner> + <summary> + Records whether or not input arrived before the first commit. + </summary> +</histogram> + <histogram name="Parser.AppendBytesDelay" units="ms" expires_after="2017-08-12"> <obsolete> Deprecated Aug 2017 @@ -97319,6 +97352,18 @@ </summary> </histogram> +<histogram name="PluginVm.SetupTime" units="ms" expires_after="2019-12-01"> + <owner>aoldemeier@chromium.org</owner> + <owner>okalitova@chromium.org</owner> + <owner>timloh@chromium.org</owner> + <summary> + Recorded at each successful attempt to set up PluginVm, recording the time + that user spent waiting for setup to be finished. When error occurs during + setup and user clicks retry button - time between pressing retry button and + setup being finished is recorded. + </summary> +</histogram> + <histogram name="Power.BacklightLevelOnAC" units="%"> <owner>derat@chromium.org</owner> <summary> @@ -128792,6 +128837,17 @@ </summary> </histogram> +<histogram name="Sync.PersistedModelTypeIdMismatch" enum="SyncModelTypes" + expires_after="M90"> + <owner>mastiz@chromium.org</owner> + <owner>mamir@chromium.org</owner> + <summary> + Emitted when the model type id in the persisted sync metadata mismatches the + model type id expected by the processor. It's recorded upon loading the + metadata and before trying to connect to sync. It's recorded per data type. + </summary> +</histogram> + <histogram name="Sync.PostedClientToServerMessage" enum="SyncClientToServerMessageContents"> <owner>mastiz@chromium.org</owner> @@ -140749,6 +140805,17 @@ </summary> </histogram> +<histogram name="WebController.BackForwardListOutOfSyncInProvisionalNavigation" + enum="IOSOutOfSyncURLAction"> + <owner>ajuma@chromium.org</owner> + <summary> + [iOS] Records the action take when the backForwardList of the WebView is out + of sync with the URL exposed by the WebView when starting a new provisional + navigation. The URLs can get out of sync because of a bugs in WebKit. This + is only recorded when the URLs are out of sync. + </summary> +</histogram> + <histogram name="WebController.CertVerificationErrorsCacheHit" enum="BooleanCacheHit" expires_after="M77"> <owner>eugenebut@chromium.org</owner>
diff --git a/tools/traffic_annotation/summary/annotations.xml b/tools/traffic_annotation/summary/annotations.xml index fe5d4e44..b17f0c9 100644 --- a/tools/traffic_annotation/summary/annotations.xml +++ b/tools/traffic_annotation/summary/annotations.xml
@@ -145,7 +145,7 @@ <item id="lib_address_input" hash_code="50816767" type="0" content_hash_code="57977576" os_list="linux,windows" file_path="third_party/libaddressinput/chromium/chrome_metadata_source.cc"/> <item id="logo_service" hash_code="35473769" type="0" content_hash_code="20271299" os_list="linux,windows" file_path="components/search_provider_logos/logo_service_impl.cc"/> <item id="logo_tracker" hash_code="36859107" type="0" deprecated="2018-12-07" content_hash_code="67588075" file_path=""/> - <item id="metrics_report_ukm" hash_code="727478" type="0" content_hash_code="40919254" os_list="linux,windows" file_path="components/metrics/net/net_metrics_log_uploader.cc"/> + <item id="metrics_report_ukm" hash_code="727478" type="0" content_hash_code="102972932" os_list="linux,windows" file_path="components/metrics/net/net_metrics_log_uploader.cc"/> <item id="metrics_report_uma" hash_code="727528" type="0" content_hash_code="10176197" os_list="linux,windows" file_path="components/metrics/net/net_metrics_log_uploader.cc"/> <item id="mirroring_get_setup_info" hash_code="78447809" type="0" content_hash_code="112561099" os_list="linux,windows" file_path="components/mirroring/service/session_monitor.cc"/> <item id="missing" hash_code="77012883" type="0" reserved="1" os_list="linux,windows" file_path=""/>
diff --git a/ui/accessibility/ax_range.h b/ui/accessibility/ax_range.h index 15bc702..49b6387 100644 --- a/ui/accessibility/ax_range.h +++ b/ui/accessibility/ax_range.h
@@ -10,6 +10,7 @@ #include <vector> #include "base/strings/string16.h" +#include "ui/accessibility/ax_role_properties.h" #include "ui/accessibility/ax_tree_manager_map.h" #include "ui/accessibility/platform/ax_platform_node_delegate.h" @@ -162,22 +163,22 @@ return anchors; } - // Appends rects in screen coordinates of all text nodes that span between + // Appends rects in screen coordinates of all anchor nodes that span between // anchor_ and focus_. Rects outside of the viewport are skipped. std::vector<gfx::Rect> GetScreenRects() const { - DCHECK_LE(*anchor_, *focus_); + AXRange forward_range = GetForwardRange(); std::vector<gfx::Rect> rectangles; - auto current_line_start = anchor_->Clone(); - auto range_end = focus_->Clone(); + auto current_line_start = forward_range.anchor()->Clone(); + auto range_end = forward_range.focus()->Clone(); - while (*current_line_start < *range_end) { + while (*current_line_start <= *range_end) { auto current_line_end = current_line_start->CreateNextLineEndPosition( ui::AXBoundaryBehavior::CrossBoundary); - if (*current_line_end > *range_end) + if (current_line_end->IsNullPosition() || *current_line_end > *range_end) current_line_end = range_end->Clone(); - DCHECK(current_line_end->GetAnchor() == current_line_start->GetAnchor()); + DCHECK_EQ(current_line_end->GetAnchor(), current_line_start->GetAnchor()); if (current_line_start->GetAnchor()->data().role == ax::mojom::Role::kInlineTextBox) { @@ -192,15 +193,23 @@ AXPlatformNodeDelegate* current_anchor_delegate = manager->GetDelegate(current_tree_id, current_anchor->id()); - gfx::Rect current_rect = - current_anchor_delegate->GetHypertextRangeBoundsRect( - current_line_start->text_offset(), - current_line_end->text_offset(), AXCoordinateSystem::kScreen, - AXClippingBehavior::kClipped); + gfx::Rect current_rect; + // For text anchors, we retrieve the bounding rectangles of its text + // content. For non-text anchors (such as checkboxes, images, etc.), we + // want to directly retrieve their bounding rectangles. + if (IsTextOrLineBreak(current_anchor->data().role)) { + current_rect = current_anchor_delegate->GetInnerTextRangeBoundsRect( + current_line_start->text_offset(), current_line_end->text_offset(), + AXCoordinateSystem::kScreen, AXClippingBehavior::kClipped); + } else { + current_rect = current_anchor_delegate->GetBoundsRect( + AXCoordinateSystem::kScreen, AXClippingBehavior::kClipped); + } - // Only add rects that are within the current viewport. The 'clipped' - // parameter for GetHypertextRangeBoundsRect will return an empty rect in - // that case. + // We only add rects that are within the current viewport. If the bounding + // rect is outside the viewport, the 'clipped' parameter in the bounds + // API's above will result in returning an empty rect and we omit it in + // the final result. if (!current_rect.IsEmpty()) rectangles.emplace_back(current_rect);
diff --git a/ui/accessibility/ax_range_unittest.cc b/ui/accessibility/ax_range_unittest.cc index 9c26bbe..fc5498e 100644 --- a/ui/accessibility/ax_range_unittest.cc +++ b/ui/accessibility/ax_range_unittest.cc
@@ -8,6 +8,7 @@ #include <vector> #include "base/strings/string16.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/ax_node.h" #include "ui/accessibility/ax_node_data.h" @@ -15,6 +16,7 @@ #include "ui/accessibility/ax_serializable_tree.h" #include "ui/accessibility/ax_tree_serializer.h" #include "ui/accessibility/ax_tree_update.h" +#include "ui/accessibility/platform/test_ax_node_wrapper.h" namespace ui { @@ -43,7 +45,7 @@ constexpr int32_t STATIC_TEXT2_ID = 8; constexpr int32_t INLINE_BOX2_ID = 9; -class AXRangeTest : public testing::Test { +class AXRangeTest : public testing::Test, public AXTreeManager { public: const base::string16 LINE_1 = base::ASCIIToUTF16("Line 1"); const base::string16 LINE_2 = base::ASCIIToUTF16("Line 2"); @@ -59,6 +61,20 @@ void SetUp() override; void TearDown() override; + AXNode* GetRootNode() const { return tree_->root(); } + + // AXTreeManager implementation. + AXNode* GetNodeFromTree(const AXTreeID tree_id, + const int32_t node_id) const override; + AXPlatformNodeDelegate* GetDelegate(const AXTreeID tree_id, + const int32_t node_id) const override; + AXPlatformNodeDelegate* GetRootDelegate( + const AXTreeID tree_id) const override; + AXTreeID GetTreeID() const override; + AXTreeID GetParentTreeID() const override; + AXNode* GetRootAsAXNode() const override; + AXNode* GetParentNodeFromParentTreeAsAXNode() const override; + AXNodeData root_; AXNodeData button_; AXNodeData check_box_; @@ -69,7 +85,7 @@ AXNodeData inline_box1_; AXNodeData inline_box2_; - AXTree tree_; + std::unique_ptr<AXTree> tree_; private: DISALLOW_COPY_AND_ASSIGN(AXRangeTest); @@ -128,6 +144,17 @@ inline_box1_.role = ax::mojom::Role::kInlineTextBox; inline_box1_.AddState(ax::mojom::State::kEditable); inline_box1_.SetName("Line 1"); + inline_box1_.relative_bounds.bounds = gfx::RectF(220, 20, 100, 30); + std::vector<int32_t> character_offsets1; + // The width of each character is 5px. + character_offsets1.push_back(225); // "L" {220, 20, 5x30} + character_offsets1.push_back(230); // "i" {225, 20, 5x30} + character_offsets1.push_back(235); // "n" {230, 20, 5x30} + character_offsets1.push_back(240); // "e" {235, 20, 5x30} + character_offsets1.push_back(245); // " " {240, 20, 5x30} + character_offsets1.push_back(250); // "1" {245, 20, 5x30} + inline_box1_.AddIntListAttribute( + ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets1); inline_box1_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0, 5}); inline_box1_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, @@ -149,6 +176,17 @@ inline_box2_.role = ax::mojom::Role::kInlineTextBox; inline_box2_.AddState(ax::mojom::State::kEditable); inline_box2_.SetName("Line 2"); + inline_box2_.relative_bounds.bounds = gfx::RectF(220, 50, 100, 30); + std::vector<int32_t> character_offsets2; + // The width of each character is 7 px. + character_offsets2.push_back(227); // "L" {220, 50, 7x30} + character_offsets2.push_back(234); // "i" {227, 50, 7x30} + character_offsets2.push_back(241); // "n" {234, 50, 7x30} + character_offsets2.push_back(248); // "e" {241, 50, 7x30} + character_offsets2.push_back(255); // " " {248, 50, 7x30} + character_offsets2.push_back(262); // "2" {255, 50, 7x30} + inline_box2_.AddIntListAttribute( + ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets2); inline_box2_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0, 5}); inline_box2_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, @@ -162,34 +200,81 @@ initial_state.has_tree_data = true; initial_state.tree_data.tree_id = AXTreeID::CreateNewAXTreeID(); initial_state.tree_data.title = "Dialog title"; - AXSerializableTree src_tree(initial_state); - std::unique_ptr<AXTreeSource<const AXNode*, AXNodeData, AXTreeData>> - tree_source(src_tree.CreateTreeSource()); - AXTreeSerializer<const AXNode*, AXNodeData, AXTreeData> serializer( - tree_source.get()); - AXTreeUpdate update; - serializer.SerializeChanges(src_tree.root(), &update); - ASSERT_TRUE(tree_.Unserialize(update)); - AXNodePosition::SetTreeForTesting(&tree_); + tree_.reset(new AXTree(initial_state)); + AXNodePosition::SetTreeForTesting(tree_.get()); + AXTreeManagerMap::GetInstance().AddTreeManager( + initial_state.tree_data.tree_id, this); } void AXRangeTest::TearDown() { AXNodePosition::SetTreeForTesting(nullptr); + AXTreeManagerMap::GetInstance().RemoveTreeManager(tree_->data().tree_id); +} + +AXNode* AXRangeTest::GetNodeFromTree(const AXTreeID tree_id, + const int32_t node_id) const { + if (GetTreeID() == tree_id) + return tree_->GetFromId(node_id); + + return nullptr; +} + +AXPlatformNodeDelegate* AXRangeTest::GetDelegate(const AXTreeID tree_id, + const int32_t node_id) const { + AXNode* node = GetNodeFromTree(tree_id, node_id); + if (node) { + TestAXNodeWrapper* wrapper = + TestAXNodeWrapper::GetOrCreate(tree_.get(), node); + + return wrapper; + } + return nullptr; +} + +AXPlatformNodeDelegate* AXRangeTest::GetRootDelegate( + const AXTreeID tree_id) const { + if (GetTreeID() == tree_id) { + AXNode* root_node = GetRootNode(); + + if (root_node) { + TestAXNodeWrapper* wrapper = + TestAXNodeWrapper::GetOrCreate(tree_.get(), root_node); + return wrapper; + } + } + + return nullptr; +} + +AXTreeID AXRangeTest::GetTreeID() const { + return tree_->data().tree_id; +} + +AXTreeID AXRangeTest::GetParentTreeID() const { + return GetTreeID(); +} + +ui::AXNode* AXRangeTest::GetRootAsAXNode() const { + return GetRootNode(); +} + +ui::AXNode* AXRangeTest::GetParentNodeFromParentTreeAsAXNode() const { + return nullptr; } } // namespace -TEST_F(AXRangeTest, AXRangeEqualityOperators) { +TEST_F(AXRangeTest, EqualityOperators) { TestPositionInstance null_position = AXNodePosition::CreateNullPosition(); TestPositionInstance test_position1 = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, button_.id, 0 /* text_offset */, + tree_->data().tree_id, button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance test_position2 = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, line_break_.id, 1 /* text_offset */, + tree_->data().tree_id, line_break_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance test_position3 = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, inline_box2_.id, 0 /* text_offset */, + tree_->data().tree_id, inline_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); // Invalid ranges (with at least one null endpoint). @@ -220,15 +305,15 @@ EXPECT_EQ(test_positions_1_and_2, test_positions_1_and_3); } -TEST_F(AXRangeTest, AXRangeGetTextWithWholeObjects) { +TEST_F(AXRangeTest, GetTextWithWholeObjects) { base::string16 all_text = BUTTON_TEXT.substr(0).append(TEXT_VALUE); // Create a range starting from the button object and ending at the last // character of the root, i.e. at the last character of the second line in the // text field. TestPositionInstance start = AXNodePosition::CreateTreePosition( - tree_.data().tree_id, root_.id, 0 /* child_index */); + tree_->data().tree_id, root_.id, 0 /* child_index */); TestPositionInstance end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, root_.id, all_text.length() /* text_offset */, + tree_->data().tree_id, root_.id, all_text.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange forward_range(start->Clone(), end->Clone()); @@ -238,11 +323,11 @@ // Button start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, button_.id, 0 /* text_offset */, + tree_->data().tree_id, button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, button_.id, BUTTON_TEXT.length() /* text_offset */, + tree_->data().tree_id, button_.id, BUTTON_TEXT.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange button_range(start->Clone(), end->Clone()); @@ -252,10 +337,10 @@ // text_field_ start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, text_field_.id, 0 /* text_offset */, + tree_->data().tree_id, text_field_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); end = - AXNodePosition::CreateTextPosition(tree_.data().tree_id, text_field_.id, + AXNodePosition::CreateTextPosition(tree_->data().tree_id, text_field_.id, TEXT_VALUE.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); @@ -267,12 +352,12 @@ // static_text1_ start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text1_.id, 0 /* text_offset */, + tree_->data().tree_id, static_text1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text1_.id, LINE_1.length() /* text_offset */, - ax::mojom::TextAffinity::kDownstream); + tree_->data().tree_id, static_text1_.id, + LINE_1.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange static_text1_range(start->Clone(), end->Clone()); EXPECT_EQ(LINE_1, static_text1_range.GetText()); @@ -282,12 +367,12 @@ // static_text2_ start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text2_.id, 0 /* text_offset */, + tree_->data().tree_id, static_text2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text2_.id, LINE_2.length() /* text_offset */, - ax::mojom::TextAffinity::kDownstream); + tree_->data().tree_id, static_text2_.id, + LINE_2.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange static_text2_range(start->Clone(), end->Clone()); EXPECT_EQ(LINE_2, static_text2_range.GetText()); @@ -297,12 +382,12 @@ // static_text1_ to static_text2_ start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text1_.id, 0 /* text_offset */, + tree_->data().tree_id, static_text1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text2_.id, LINE_2.length() /* text_offset */, - ax::mojom::TextAffinity::kDownstream); + tree_->data().tree_id, static_text2_.id, + LINE_2.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange static_text_range(start->Clone(), end->Clone()); EXPECT_EQ(TEXT_VALUE, static_text_range.GetText()); @@ -311,11 +396,11 @@ EXPECT_EQ(TEXT_VALUE, static_text_range_backward.GetText()); // root_ to static_text2_'s end - start = AXNodePosition::CreateTreePosition(tree_.data().tree_id, root_.id, + start = AXNodePosition::CreateTreePosition(tree_->data().tree_id, root_.id, 0 /* child_index */); end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text2_.id, LINE_2.length() /* text_offset */, - ax::mojom::TextAffinity::kDownstream); + tree_->data().tree_id, static_text2_.id, + LINE_2.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange root_to_static2_text_range(start->Clone(), end->Clone()); EXPECT_EQ(all_text, root_to_static2_text_range.GetText()); @@ -326,10 +411,10 @@ // root_ to static_text2_'s start base::string16 text_up_to_text2_tree_start = BUTTON_TEXT.substr(0).append(LINE_1).append(base::ASCIIToUTF16("\n")); - start = AXNodePosition::CreateTreePosition(tree_.data().tree_id, root_.id, + start = AXNodePosition::CreateTreePosition(tree_->data().tree_id, root_.id, 0 /* child_index */); end = AXNodePosition::CreateTreePosition( - tree_.data().tree_id, static_text2_.id, 0 /* child_index */); + tree_->data().tree_id, static_text2_.id, 0 /* child_index */); TestPositionRange root_to_static2_tree_range(start->Clone(), end->Clone()); EXPECT_EQ(text_up_to_text2_tree_start, root_to_static2_tree_range.GetText()); TestPositionRange root_to_static2_tree_range_backward(std::move(end), @@ -338,17 +423,17 @@ root_to_static2_tree_range_backward.GetText()); } -TEST_F(AXRangeTest, AXRangeGetTextWithTextOffsets) { +TEST_F(AXRangeTest, GetTextWithTextOffsets) { base::string16 most_text = BUTTON_TEXT.substr(2).append(TEXT_VALUE).substr(0, 15); // Create a range starting from the button object and ending two characters // before the end of the root. TestPositionInstance start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, button_.id, 2 /* text_offset */, + tree_->data().tree_id, button_.id, 2 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); TestPositionInstance end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text2_.id, 4 /* text_offset */, + tree_->data().tree_id, static_text2_.id, 4 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange forward_range(start->Clone(), end->Clone()); @@ -359,10 +444,10 @@ // root_ to static_text2_'s start with offsets base::string16 text_up_to_text2_tree_start = BUTTON_TEXT.substr(0).append(TEXT_VALUE).substr(0, 16); - start = AXNodePosition::CreateTreePosition(tree_.data().tree_id, root_.id, + start = AXNodePosition::CreateTreePosition(tree_->data().tree_id, root_.id, 0 /* child_index */); end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text2_.id, 3 /* text_offset */, + tree_->data().tree_id, static_text2_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange root_to_static2_tree_range(start->Clone(), end->Clone()); @@ -373,54 +458,54 @@ root_to_static2_tree_range_backward.GetText()); } -TEST_F(AXRangeTest, AXRangeGetTextWithEmptyRanges) { +TEST_F(AXRangeTest, GetTextWithEmptyRanges) { // empty string with non-leaf tree position base::string16 empty_string(base::ASCIIToUTF16("")); TestPositionInstance start = AXNodePosition::CreateTreePosition( - tree_.data().tree_id, root_.id, 0 /* child_index */); + tree_->data().tree_id, root_.id, 0 /* child_index */); TestPositionRange non_leaf_tree_range(start->Clone(), start->Clone()); EXPECT_EQ(empty_string, non_leaf_tree_range.GetText()); // empty string with leaf tree position start = AXNodePosition::CreateTreePosition( - tree_.data().tree_id, inline_box1_.id, 0 /* child_index */); + tree_->data().tree_id, inline_box1_.id, 0 /* child_index */); TestPositionRange leaf_empty_range(start->Clone(), start->Clone()); EXPECT_EQ(empty_string, leaf_empty_range.GetText()); // empty string with leaf text position and no offset start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, inline_box1_.id, 0 /* text_offset */, + tree_->data().tree_id, inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange leaf_text_no_offset(start->Clone(), start->Clone()); EXPECT_EQ(empty_string, leaf_text_no_offset.GetText()); // empty string with leaf text position with offset start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, inline_box1_.id, 3 /* text_offset */, + tree_->data().tree_id, inline_box1_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange leaf_text_offset(start->Clone(), start->Clone()); EXPECT_EQ(empty_string, leaf_text_offset.GetText()); // empty string with non-leaf text with no offset start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, root_.id, 0 /* text_offset */, + tree_->data().tree_id, root_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange non_leaf_text_no_offset(start->Clone(), start->Clone()); EXPECT_EQ(empty_string, non_leaf_text_no_offset.GetText()); // empty string with non-leaf text position with offset start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, root_.id, 3 /* text_offset */, + tree_->data().tree_id, root_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange non_leaf_text_offset(start->Clone(), start->Clone()); EXPECT_EQ(empty_string, non_leaf_text_offset.GetText()); // empty string with same position between two anchors, but different offsets TestPositionInstance after_end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, line_break_.id, 1 /* text_offset */, + tree_->data().tree_id, line_break_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance before_start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, static_text2_.id, 0 /* text_offset */, + tree_->data().tree_id, static_text2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); AXRange<AXPosition<AXNodePosition, AXNode>> @@ -433,45 +518,204 @@ EXPECT_EQ(empty_string, same_position_different_anchors_backward.GetText()); } -TEST_F(AXRangeTest, AXRangeGetAnchors) { +TEST_F(AXRangeTest, GetScreenRects) { + // Setting up ax ranges for testing. + TestPositionInstance button = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, button_.id, 0 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + + TestPositionInstance check_box = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, check_box_.id, 0 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + + TestPositionInstance line1_start = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, inline_box1_.id, 0 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + TestPositionInstance line1_second_char = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, inline_box1_.id, 1 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + TestPositionInstance line1_middle = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, inline_box1_.id, 3 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + TestPositionInstance line1_second_to_last_char = + AXNodePosition::CreateTextPosition(tree_->data().tree_id, inline_box1_.id, + 5 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + TestPositionInstance line1_end = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, inline_box1_.id, 6 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + + TestPositionInstance line2_start = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, inline_box2_.id, 0 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + TestPositionInstance line2_second_char = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, inline_box2_.id, 1 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + TestPositionInstance line2_middle = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, inline_box2_.id, 3 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + TestPositionInstance line2_second_to_last_char = + AXNodePosition::CreateTextPosition(tree_->data().tree_id, inline_box2_.id, + 5 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + TestPositionInstance line2_end = AXNodePosition::CreateTextPosition( + tree_->data().tree_id, inline_box2_.id, 6 /* text_offset */, + ax::mojom::TextAffinity::kDownstream); + + // Since a button is not visible to the text representation, it spans an + // empty anchor whose start and end positions are the same. + TestPositionRange button_range(button->Clone(), button->Clone()); + std::vector<gfx::Rect> expected_screen_rects; + expected_screen_rects = {gfx::Rect(20, 20, 200, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(button_range.GetScreenRects())); + + // Since a check box is not visible to the text representation, it spans an + // empty anchor whose start and end positions are the same. + TestPositionRange check_box_range(check_box->Clone(), check_box->Clone()); + expected_screen_rects = {gfx::Rect(20, 50, 200, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(check_box_range.GetScreenRects())); + + // Retrieving bounding box of text line 1, its whole range. + // 0 1 2 3 4 5 + // |L|i|n|e| |1| + // |-----------| + TestPositionRange line1_whole_range(line1_start->Clone(), line1_end->Clone()); + expected_screen_rects = {gfx::Rect(220, 20, 30, 30)}; // + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line1_whole_range.GetScreenRects())); + + // Retrieving bounding box of text line 1, its first half range. + // 0 1 2 3 4 5 + // |L|i|n|e| |1| + // |-----| + TestPositionRange line1_first_half_range(line1_start->Clone(), + line1_middle->Clone()); + expected_screen_rects = {gfx::Rect(220, 20, 15, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line1_first_half_range.GetScreenRects())); + + // Retrieving bounding box of text line 1, its second half range. + // 0 1 2 3 4 5 + // |L|i|n|e| |1| + // |-----| + TestPositionRange line1_second_half_range(line1_middle->Clone(), + line1_end->Clone()); + expected_screen_rects = {gfx::Rect(235, 20, 15, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line1_second_half_range.GetScreenRects())); + + // Retrieving bounding box of text line 1, its mid range. + // 0 1 2 3 4 5 + // |L|i|n|e| |1| + // |-------| + TestPositionRange line1_mid_range(line1_second_char->Clone(), + line1_second_to_last_char->Clone()); + expected_screen_rects = {gfx::Rect(225, 20, 20, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line1_mid_range.GetScreenRects())); + + // Retrieving bounding box of text line 2, its whole range. + // 0 1 2 3 4 5 + // |L|i|n|e| |2| + // |-----------| + TestPositionRange line2_whole_range(line2_start->Clone(), line2_end->Clone()); + expected_screen_rects = {gfx::Rect(220, 50, 42, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line2_whole_range.GetScreenRects())); + + // Retrieving bounding box of text line 2, its first half range. + // 0 1 2 3 4 5 + // |L|i|n|e| |2| + // |-----| + TestPositionRange line2_first_half_range(line2_start->Clone(), + line2_middle->Clone()); + expected_screen_rects = {gfx::Rect(220, 50, 21, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line2_first_half_range.GetScreenRects())); + + // Retrieving bounding box of text line 2, its second half range. + // 0 1 2 3 4 5 + // |L|i|n|e| |2| + // |-----| + TestPositionRange line2_second_half_range(line2_middle->Clone(), + line2_end->Clone()); + expected_screen_rects = {gfx::Rect(241, 50, 21, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line2_second_half_range.GetScreenRects())); + + // Retrieving bounding box of text line 2, its mid range. + // 0 1 2 3 4 5 + // |L|i|n|e| |2| + // |-------| + TestPositionRange line2_mid_range(line2_second_char->Clone(), + line2_second_to_last_char->Clone()); + expected_screen_rects = {gfx::Rect(227, 50, 28, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line2_mid_range.GetScreenRects())); + + // Retrieving bounding boxes of text line 1 and line 2, the entire range. + // |L|i|n|e| |1|\n|L|i|n|e| |2| + // |--------------------------| + TestPositionRange line1_line2_whole_range(line1_start->Clone(), + line2_end->Clone()); + expected_screen_rects = {gfx::Rect(220, 20, 30, 30), + gfx::Rect(220, 50, 42, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line1_line2_whole_range.GetScreenRects())); + + // Retrieving bounding boxes of the range that spans from the middle of text + // line 1 to the middle of text line 2. + // |L|i|n|e| |1|\n|L|i|n|e| |2| + // |--------------| + TestPositionRange line1_line2_mid_range(line1_middle->Clone(), + line2_middle->Clone()); + expected_screen_rects = {gfx::Rect(235, 20, 15, 30), + gfx::Rect(220, 50, 21, 30)}; + EXPECT_THAT(expected_screen_rects, + testing::ContainerEq(line1_line2_mid_range.GetScreenRects())); +} + +TEST_F(AXRangeTest, GetAnchors) { TestPositionInstance button_start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, button_.id, 0 /* text_offset */, + tree_->data().tree_id, button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance button_middle = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, button_.id, 3 /* text_offset */, + tree_->data().tree_id, button_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance button_end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, button_.id, 6 /* text_offset */, + tree_->data().tree_id, button_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); // Since a check box is not visible to the text representation, it spans an // empty anchor whose start and end positions are the same. TestPositionInstance check_box = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, check_box_.id, 0 /* text_offset */, + tree_->data().tree_id, check_box_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, inline_box1_.id, 0 /* text_offset */, + tree_->data().tree_id, inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_middle = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, inline_box1_.id, 3 /* text_offset */, + tree_->data().tree_id, inline_box1_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, inline_box1_.id, 6 /* text_offset */, + tree_->data().tree_id, inline_box1_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line_break_start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, line_break_.id, 0 /* text_offset */, + tree_->data().tree_id, line_break_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line_break_end = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, line_break_.id, 1 /* text_offset */, + tree_->data().tree_id, line_break_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_start = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, inline_box2_.id, 0 /* text_offset */, + tree_->data().tree_id, inline_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_middle = AXNodePosition::CreateTextPosition( - tree_.data().tree_id, inline_box2_.id, 3 /* text_offset */, + tree_->data().tree_id, inline_box2_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange whole_anchor_range(button_start->Clone(),
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc index 7d0d303..e3bde07 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -165,21 +165,16 @@ return cell_get_type; } -AXPlatformNodeAuraLinux* ToAXPlatformNodeAuraLinux( - AXPlatformNodeAuraLinuxObject* atk_object) { - if (!atk_object) - return nullptr; - - return atk_object->m_object; -} - AXPlatformNodeAuraLinux* AtkObjectToAXPlatformNodeAuraLinux( AtkObject* atk_object) { if (!atk_object) return nullptr; - if (IS_AX_PLATFORM_NODE_AURALINUX(atk_object)) - return ToAXPlatformNodeAuraLinux(AX_PLATFORM_NODE_AURALINUX(atk_object)); + if (IS_AX_PLATFORM_NODE_AURALINUX(atk_object)) { + AXPlatformNodeAuraLinuxObject* platform_object = + AX_PLATFORM_NODE_AURALINUX(atk_object); + return platform_object->m_object; + } return nullptr; } @@ -934,6 +929,8 @@ g_return_val_if_fail(ATK_HYPERTEXT(hypertext), 0); AXPlatformNodeAuraLinux* obj = AtkObjectToAXPlatformNodeAuraLinux(ATK_OBJECT(hypertext)); + if (!obj) + return -1; auto it = obj->GetAXHypertext().hyperlink_offset_to_index.find(char_index); if (it == obj->GetAXHypertext().hyperlink_offset_to_index.end()) @@ -1258,21 +1255,21 @@ const AXPlatformNode* parent_platform_node = AXPlatformNode::FromNativeViewAccessible( ax_platform_node_delegate->GetParent()); - if (parent_platform_node) { - const AXPlatformNodeDelegate* parent_ax_platform_node_delegate = - parent_platform_node->GetDelegate(); - if (parent_ax_platform_node_delegate) { - return ax_platform_node_delegate->GetHypertextRangeBoundsRect( - start_offset, end_offset, AXCoordinateSystem::kRootFrame, - AXClippingBehavior::kUnclipped) - - parent_ax_platform_node_delegate - ->GetBoundsRect(AXCoordinateSystem::kRootFrame, - AXClippingBehavior::kClipped) - .OffsetFromOrigin(); - } - } + if (!parent_platform_node) + return gfx::Rect(); - return gfx::Rect(); + const AXPlatformNodeDelegate* parent_ax_platform_node_delegate = + parent_platform_node->GetDelegate(); + if (!parent_ax_platform_node_delegate) + return gfx::Rect(); + + return ax_platform_node_delegate->GetHypertextRangeBoundsRect( + start_offset, end_offset, AXCoordinateSystem::kRootFrame, + AXClippingBehavior::kUnclipped) - + parent_ax_platform_node_delegate + ->GetBoundsRect(AXCoordinateSystem::kRootFrame, + AXClippingBehavior::kClipped) + .OffsetFromOrigin(); } void GetCharacterExtents(AtkText* atk_text, @@ -1394,7 +1391,8 @@ AXPlatformNodeAuraLinux* child = AtkObjectToAXPlatformNodeAuraLinux(obj->ChildAtIndex(index)); - DCHECK(child); + if (!child) + return FALSE; if (!child->SupportsSelectionWithAtkSelection()) return FALSE; @@ -1419,7 +1417,8 @@ for (int i = 0; i < child_count; ++i) { AXPlatformNodeAuraLinux* child = AtkObjectToAXPlatformNodeAuraLinux(obj->ChildAtIndex(i)); - DCHECK(child); + if (!child) + continue; if (!child->SupportsSelectionWithAtkSelection()) continue; @@ -1449,7 +1448,8 @@ AtkObject* child = obj->ChildAtIndex(i); AXPlatformNodeAuraLinux* child_ax_node = AtkObjectToAXPlatformNodeAuraLinux(child); - DCHECK(child_ax_node); + if (!child_ax_node) + continue; if (child_ax_node->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected)) { if (selected_count == requested_child_index) @@ -1472,7 +1472,8 @@ for (int i = 0; i < child_count; ++i) { AXPlatformNodeAuraLinux* child = AtkObjectToAXPlatformNodeAuraLinux(obj->ChildAtIndex(i)); - DCHECK(child); + if (!child) + continue; if (child->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected)) ++selected_count; @@ -1491,20 +1492,22 @@ AXPlatformNodeAuraLinux* child = AtkObjectToAXPlatformNodeAuraLinux(obj->ChildAtIndex(index)); - DCHECK(child); - return child->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected); + return child && child->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected); } gboolean RemoveSelection(AtkSelection* selection, gint index_into_selected_children) { AXPlatformNodeAuraLinux* obj = AtkObjectToAXPlatformNodeAuraLinux(ATK_OBJECT(selection)); + if (!obj) + return FALSE; int child_count = obj->GetChildCount(); for (int i = 0; i < child_count; ++i) { AXPlatformNodeAuraLinux* child = AtkObjectToAXPlatformNodeAuraLinux(obj->ChildAtIndex(i)); - DCHECK(child); + if (!child) + continue; bool selected = child->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected); @@ -1534,7 +1537,8 @@ for (int i = 0; i < child_count; ++i) { AXPlatformNodeAuraLinux* child = AtkObjectToAXPlatformNodeAuraLinux(obj->ChildAtIndex(i)); - DCHECK(child); + if (!child) + continue; if (!child->SupportsSelectionWithAtkSelection()) continue; @@ -2571,6 +2575,9 @@ return nullptr; auto* node = AtkObjectToAXPlatformNodeAuraLinux(g_current_focused); + if (!node) + return nullptr; + int32_t id = node->GetIntAttribute(ax::mojom::IntAttribute::kActivedescendantId); if (auto* descendant = node->GetDelegate()->GetFromNodeID(id)) @@ -2994,6 +3001,8 @@ get_row_column_span(cell, &row, &col, &row_span, &col_span); } else { auto* obj = AtkObjectToAXPlatformNodeAuraLinux(atk_object_); + if (!obj) + return; row = obj->GetTableRow(); col = obj->GetTableColumn(); row_span = obj->GetTableRowSpan(); @@ -3039,9 +3048,11 @@ // If selection and focus are the same, when the active descendant changes // as a result of selection, a focus event will be emitted. We don't want to // emit duplicate notifications. - auto* node = AtkObjectToAXPlatformNodeAuraLinux(descendant); - if (node->SelectionAndFocusAreTheSame()) - return; + { + auto* node = AtkObjectToAXPlatformNodeAuraLinux(descendant); + if (node && node->SelectionAndFocusAreTheSame()) + return; + } // While there is an ATK active-descendant-changed event, it is meant for // objects which manage their descendants (and claim to do so). The Core-AAM @@ -3279,7 +3290,8 @@ // // If the selection is changing on a collapsed select element, focus remains // on the select element and not the newly-selected descendant. - if (AXPlatformNodeBase* parent = FromNativeViewAccessible(GetParent())) { + if (AXPlatformNodeBase* parent = + AtkObjectToAXPlatformNodeAuraLinux(GetParent())) { if (parent->GetData().role == ax::mojom::Role::kMenuListPopup) return !parent->GetData().HasState(ax::mojom::State::kInvisible); } @@ -3362,7 +3374,8 @@ // We always want to notify on the top frame. AXPlatformNodeAuraLinux* window = AtkObjectToAXPlatformNodeAuraLinux(g_active_top_level_frame); - window->OnNameChanged(); + if (window) + window->OnNameChanged(); } void AXPlatformNodeAuraLinux::OnSubtreeCreated() { @@ -3578,6 +3591,9 @@ const AXPlatformNode* parent_node = AXPlatformNode::FromNativeViewAccessible(parent); + if (!parent) + return gfx::Vector2d(); + return parent_node->GetDelegate() ->GetBoundsRect(AXCoordinateSystem::kScreen, AXClippingBehavior::kUnclipped) @@ -3592,6 +3608,9 @@ const AXPlatformNode* frame_node = AXPlatformNode::FromNativeViewAccessible(frame); + if (!frame_node) + return gfx::Vector2d(); + return frame_node->GetDelegate() ->GetBoundsRect(AXCoordinateSystem::kScreen, AXClippingBehavior::kUnclipped) @@ -3675,6 +3694,8 @@ for (int i = 0; i < child_count; ++i) { auto* child = AtkObjectToAXPlatformNodeAuraLinux(delegate_->ChildAtIndex(i)); + if (!child) + continue; if (child->IsTextOnlyObject()) { current_offset +=
diff --git a/ui/accessibility/platform/ax_platform_node_textprovider_win_unittest.cc b/ui/accessibility/platform/ax_platform_node_textprovider_win_unittest.cc index b59ea570..e5fe26b 100644 --- a/ui/accessibility/platform/ax_platform_node_textprovider_win_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_textprovider_win_unittest.cc
@@ -181,9 +181,9 @@ text_data.id = 2; text_data.role = ax::mojom::Role::kInlineTextBox; text_data.SetName("text"); - // spacing: "t-e-x---t--" + // spacing: "t-e-x---t-" text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kCharacterOffsets, - {2, 2, 4, 2}); + {2, 4, 8, 10}); ui::AXNodeData root_data; root_data.id = 1;
diff --git a/ui/accessibility/platform/ax_platform_node_textrangeprovider_win_unittest.cc b/ui/accessibility/platform/ax_platform_node_textrangeprovider_win_unittest.cc index bb21290..3c0b696 100644 --- a/ui/accessibility/platform/ax_platform_node_textrangeprovider_win_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_textrangeprovider_win_unittest.cc
@@ -260,6 +260,142 @@ return update; } + ui::AXTreeUpdate BuildAXTreeForBoundingRectangles() { + // AXTree content: + // <button>Button</button><input type="checkbox">Line 1<br>Line 2 + ui::AXNodeData root; + ui::AXNodeData button; + ui::AXNodeData check_box; + ui::AXNodeData text_field; + ui::AXNodeData static_text1; + ui::AXNodeData line_break; + ui::AXNodeData static_text2; + ui::AXNodeData inline_box1; + ui::AXNodeData inline_box2; + + const int ROOT_ID = 1; + const int BUTTON_ID = 2; + const int CHECK_BOX_ID = 3; + const int TEXT_FIELD_ID = 4; + const int STATIC_TEXT1_ID = 5; + const int INLINE_BOX1_ID = 6; + const int LINE_BREAK_ID = 7; + const int STATIC_TEXT2_ID = 8; + const int INLINE_BOX2_ID = 9; + + root.id = ROOT_ID; + button.id = BUTTON_ID; + check_box.id = CHECK_BOX_ID; + text_field.id = TEXT_FIELD_ID; + static_text1.id = STATIC_TEXT1_ID; + inline_box1.id = INLINE_BOX1_ID; + line_break.id = LINE_BREAK_ID; + static_text2.id = STATIC_TEXT2_ID; + inline_box2.id = INLINE_BOX2_ID; + + std::string LINE_1_TEXT = "Line 1"; + std::string LINE_2_TEXT = "Line 2"; + std::string LINE_BREAK_TEXT = "\n"; + std::string ALL_TEXT = LINE_1_TEXT + LINE_BREAK_TEXT + LINE_2_TEXT; + std::string BUTTON_TEXT = "Button"; + std::string CHECKBOX_TEXT = "Check box"; + + root.role = ax::mojom::Role::kRootWebArea; + + button.role = ax::mojom::Role::kButton; + button.SetHasPopup(ax::mojom::HasPopup::kMenu); + button.SetName(BUTTON_TEXT); + button.SetValue(BUTTON_TEXT); + button.relative_bounds.bounds = gfx::RectF(20, 20, 200, 30); + button.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId, + check_box.id); + root.child_ids.push_back(button.id); + + check_box.role = ax::mojom::Role::kCheckBox; + check_box.SetCheckedState(ax::mojom::CheckedState::kTrue); + check_box.SetName(CHECKBOX_TEXT); + check_box.relative_bounds.bounds = gfx::RectF(20, 50, 200, 30); + check_box.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId, + button.id); + root.child_ids.push_back(check_box.id); + + text_field.role = ax::mojom::Role::kTextField; + text_field.AddState(ax::mojom::State::kEditable); + text_field.SetValue(ALL_TEXT); + text_field.AddIntListAttribute( + ax::mojom::IntListAttribute::kCachedLineStarts, + std::vector<int32_t>{0, 7}); + text_field.child_ids.push_back(static_text1.id); + text_field.child_ids.push_back(line_break.id); + text_field.child_ids.push_back(static_text2.id); + root.child_ids.push_back(text_field.id); + + static_text1.role = ax::mojom::Role::kStaticText; + static_text1.AddState(ax::mojom::State::kEditable); + static_text1.SetName(LINE_1_TEXT); + static_text1.child_ids.push_back(inline_box1.id); + + inline_box1.role = ax::mojom::Role::kInlineTextBox; + inline_box1.AddState(ax::mojom::State::kEditable); + inline_box1.SetName(LINE_1_TEXT); + inline_box1.relative_bounds.bounds = gfx::RectF(220, 20, 100, 30); + std::vector<int32_t> character_offsets1; + // The width of each character is 5px. + character_offsets1.push_back(225); // "L" {220, 20, 5x30} + character_offsets1.push_back(230); // "i" {225, 20, 5x30} + character_offsets1.push_back(235); // "n" {230, 20, 5x30} + character_offsets1.push_back(240); // "e" {235, 20, 5x30} + character_offsets1.push_back(245); // " " {240, 20, 5x30} + character_offsets1.push_back(250); // "1" {245, 20, 5x30} + inline_box1.AddIntListAttribute( + ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets1); + inline_box1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts, + std::vector<int32_t>{0, 5}); + inline_box1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, + std::vector<int32_t>{4, 6}); + inline_box1.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId, + line_break.id); + + line_break.role = ax::mojom::Role::kLineBreak; + line_break.AddState(ax::mojom::State::kEditable); + line_break.SetName(LINE_BREAK_TEXT); + line_break.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId, + inline_box1.id); + + static_text2.role = ax::mojom::Role::kStaticText; + static_text2.AddState(ax::mojom::State::kEditable); + static_text2.SetName(LINE_2_TEXT); + static_text2.child_ids.push_back(inline_box2.id); + + inline_box2.role = ax::mojom::Role::kInlineTextBox; + inline_box2.AddState(ax::mojom::State::kEditable); + inline_box2.SetName(LINE_2_TEXT); + inline_box2.relative_bounds.bounds = gfx::RectF(220, 50, 100, 30); + std::vector<int32_t> character_offsets2; + // The width of each character is 7 px. + character_offsets2.push_back(227); // "L" {220, 50, 7x30} + character_offsets2.push_back(234); // "i" {227, 50, 7x30} + character_offsets2.push_back(241); // "n" {234, 50, 7x30} + character_offsets2.push_back(248); // "e" {241, 50, 7x30} + character_offsets2.push_back(255); // " " {248, 50, 7x30} + character_offsets2.push_back(262); // "2" {255, 50, 7x30} + inline_box2.AddIntListAttribute( + ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets2); + inline_box2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts, + std::vector<int32_t>{0, 5}); + inline_box2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, + std::vector<int32_t>{4, 6}); + + AXTreeUpdate update; + update.has_tree_data = true; + update.root_id = ROOT_ID; + update.nodes = {root, button, check_box, + text_field, static_text1, inline_box1, + line_break, static_text2, inline_box2}; + update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + return update; + } + ui::AXTreeUpdate BuildAXTreeForMove() { ui::AXNodeData group1_data; group1_data.id = 2; @@ -2218,70 +2354,73 @@ TEST_F(AXPlatformNodeTextRangeProviderTest, TestITextRangeProviderGetBoundingRectangles) { - ui::AXNodeData text_data; - text_data.id = 2; - text_data.role = ax::mojom::Role::kStaticText; - text_data.relative_bounds.bounds = gfx::RectF(100, 150, 200, 200); - text_data.SetName("some text"); - - ui::AXNodeData more_text_data; - more_text_data.id = 3; - more_text_data.role = ax::mojom::Role::kStaticText; - more_text_data.relative_bounds.bounds = gfx::RectF(200, 250, 100, 100); - more_text_data.SetName("more text"); - - ui::AXNodeData root_data; - root_data.id = 1; - root_data.role = ax::mojom::Role::kRootWebArea; - root_data.child_ids = {2, 3}; - - ui::AXTreeUpdate update; - ui::AXTreeData tree_data; - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - update.tree_data = tree_data; - update.has_tree_data = true; - update.root_id = root_data.id; - update.nodes.push_back(root_data); - update.nodes.push_back(text_data); - update.nodes.push_back(more_text_data); - + ui::AXTreeUpdate update = BuildAXTreeForBoundingRectangles(); Init(update); - - AXNode* root_node = GetRootNode(); AXNodePosition::SetTreeForTesting(tree_.get()); - AXTreeManagerMap::GetInstance().AddTreeManager(tree_data.tree_id, this); - + AXTreeManagerMap::GetInstance().AddTreeManager(update.tree_data.tree_id, + this); ComPtr<ITextRangeProvider> text_range_provider; - GetTextRangeProviderFromTextNode(text_range_provider, - root_node->children()[0]); - base::win::ScopedSafearray rectangles; + int count; + + // Expected bounding rects: + // <button>Button</button><input type="checkbox">Line 1<br>Line 2 + // |---------------------||---------------------||----| |------| + GetTextRangeProviderFromTextNode(text_range_provider, GetRootNode()); EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetBoundingRectangles(rectangles.Receive())); - std::vector<double> expected_values = {100, 150, 200, 200}; + std::vector<double> expected_values = {20, 20, 200, 30, /* button */ + 20, 50, 200, 30, /* check box */ + 220, 20, 30, 30, /* line 1 */ + 220, 50, 42, 30 /* line 2 */}; EXPECT_UIA_DOUBLE_SAFEARRAY_EQ(rectangles.Get(), expected_values); rectangles.Reset(); - ComPtr<ITextRangeProvider> document_textrange; - GetTextRangeProviderFromTextNode(document_textrange, root_node); - + // Move the text range end back by one character. + // Expected bounding rects: + // <button>Button</button><input type="checkbox">Line 1<br>Line 2 + // |---------------------||---------------------||----| |----| + ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit( + TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -1, &count)); + ASSERT_EQ(-1, count); EXPECT_HRESULT_SUCCEEDED( - document_textrange->GetBoundingRectangles(rectangles.Receive())); - expected_values = {100, 150, 200, 200, 200, 250, 100, 100}; + text_range_provider->GetBoundingRectangles(rectangles.Receive())); + expected_values = {20, 20, 200, 30, /* button */ + 20, 50, 200, 30, /* check box */ + 220, 20, 30, 30, /* line 1 */ + 220, 50, 35, 30 /* line 2 */}; EXPECT_UIA_DOUBLE_SAFEARRAY_EQ(rectangles.Get(), expected_values); rectangles.Reset(); - EXPECT_UIA_MOVE(document_textrange, TextUnit_Character, - /*count*/ 9, - /*expected_text*/ L"m", - /*expected_count*/ 9); - + // Move the text range end back by one line. + // Expected bounding rects: + // <button>Button</button><input type="checkbox">Line 1<br>Line 2 + // |---------------------||---------------------||-----| + ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit( + TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ -1, &count)); + ASSERT_EQ(-1, count); EXPECT_HRESULT_SUCCEEDED( - document_textrange->GetBoundingRectangles(rectangles.Receive())); - expected_values = {200, 250, 100, 100}; + text_range_provider->GetBoundingRectangles(rectangles.Receive())); + expected_values = {20, 20, 200, 30, /* button */ + 20, 50, 200, 30, /* check box */ + 220, 20, 30, 30 /* line 1 */}; + EXPECT_UIA_DOUBLE_SAFEARRAY_EQ(rectangles.Get(), expected_values); + rectangles.Reset(); + + // Move the text range end back by one line. + // Expected bounding rects: + // <button>Button</button><input type="checkbox">Line 1<br>Line 2 + // |---------------------||---------------------| + ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit( + TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ -1, &count)); + ASSERT_EQ(-1, count); + EXPECT_HRESULT_SUCCEEDED( + text_range_provider->GetBoundingRectangles(rectangles.Receive())); + expected_values = {20, 20, 200, 30, /* button */ + 20, 50, 200, 30 /* check box */}; EXPECT_UIA_DOUBLE_SAFEARRAY_EQ(rectangles.Get(), expected_values); - AXTreeManagerMap::GetInstance().RemoveTreeManager(tree_data.tree_id); + AXTreeManagerMap::GetInstance().RemoveTreeManager(update.tree_data.tree_id); } TEST_F(AXPlatformNodeTextRangeProviderTest,
diff --git a/ui/accessibility/platform/test_ax_node_wrapper.cc b/ui/accessibility/platform/test_ax_node_wrapper.cc index 8b59b36..5c24558 100644 --- a/ui/accessibility/platform/test_ax_node_wrapper.cc +++ b/ui/accessibility/platform/test_ax_node_wrapper.cc
@@ -114,14 +114,11 @@ } int TestAXNodeWrapper::GetChildCount() { - return int{node_->children().size()}; + return InternalChildCount(); } gfx::NativeViewAccessible TestAXNodeWrapper::ChildAtIndex(int index) { - CHECK_GE(index, 0); - CHECK_LT(index, GetChildCount()); - TestAXNodeWrapper* child_wrapper = - GetOrCreate(tree_, node_->children()[size_t{index}]); + TestAXNodeWrapper* child_wrapper = InternalGetChild(index); return child_wrapper ? child_wrapper->ax_platform_node()->GetNativeViewAccessible() : nullptr; @@ -134,7 +131,7 @@ switch (coordinate_system) { case AXCoordinateSystem::kScreen: { // We could optionally add clipping here if ever needed. - gfx::RectF bounds = GetData().relative_bounds.bounds; + gfx::RectF bounds = GetLocation(); bounds.Offset(g_offset); return gfx::ToEnclosingRect(bounds); } @@ -153,24 +150,23 @@ AXOffscreenResult* offscreen_result) const { switch (coordinate_system) { case AXCoordinateSystem::kScreen: { - gfx::RectF bounds = GetData().relative_bounds.bounds; - bounds.Offset(g_offset); - if (GetData().HasIntListAttribute( - ax::mojom::IntListAttribute::kCharacterOffsets)) { - const std::vector<int32_t>& offsets = GetData().GetIntListAttribute( - ax::mojom::IntListAttribute::kCharacterOffsets); - int32_t x = bounds.x(); - int32_t width = 0; - for (int i = 0; i < static_cast<int>(offsets.size()); i++) { - if (i < start_offset) - x += offsets[i]; - else if (i < end_offset) - width += offsets[i]; - else - break; + gfx::RectF bounds = GetLocation(); + // This implementation currently only deals with text node that has role + // kInlineTextBox and kStaticText. + // For test purposes, assume node with kStaticText always has a single + // child with role kInlineTextBox. + if (GetData().role == ax::mojom::Role::kInlineTextBox) { + bounds = GetInlineTextRect(start_offset, end_offset); + } else if (GetData().role == ax::mojom::Role::kStaticText && + InternalChildCount() > 0) { + TestAXNodeWrapper* child = InternalGetChild(0); + if (child != nullptr && + child->GetData().role == ax::mojom::Role::kInlineTextBox) { + bounds = child->GetInlineTextRect(start_offset, end_offset); } - bounds = gfx::RectF(x, bounds.y(), width, bounds.height()); } + + bounds.Offset(g_offset); return gfx::ToEnclosingRect(bounds); } case AXCoordinateSystem::kRootFrame: @@ -190,7 +186,7 @@ case AXCoordinateSystem::kScreen: { // Ignoring start, len, and clipped, as there's no clean way to map these // via unit tests. - gfx::RectF bounds = GetData().relative_bounds.bounds; + gfx::RectF bounds = GetLocation(); bounds.Offset(g_offset); return gfx::ToEnclosingRect(bounds); } @@ -641,6 +637,20 @@ return node_->GetSetSize(); } +gfx::RectF TestAXNodeWrapper::GetLocation() const { + return GetData().relative_bounds.bounds; +} + +int TestAXNodeWrapper::InternalChildCount() const { + return int{node_->children().size()}; +} + +TestAXNodeWrapper* TestAXNodeWrapper::InternalGetChild(int index) const { + CHECK_GE(index, 0); + CHECK_LT(index, InternalChildCount()); + return GetOrCreate(tree_, node_->children()[size_t{index}]); +} + // Recursive helper function for GetDescendants. Aggregates all of the // descendants for a given node within the descendants vector. void TestAXNodeWrapper::Descendants( @@ -663,4 +673,32 @@ return descendants; } +gfx::RectF TestAXNodeWrapper::GetInlineTextRect(const int start_offset, + const int end_offset) const { + DCHECK(start_offset >= 0 && end_offset >= 0 && start_offset <= end_offset); + const std::vector<int32_t>& character_offsets = GetData().GetIntListAttribute( + ax::mojom::IntListAttribute::kCharacterOffsets); + gfx::RectF location = GetLocation(); + gfx::RectF bounds; + + switch (static_cast<ax::mojom::TextDirection>( + GetData().GetIntAttribute(ax::mojom::IntAttribute::kTextDirection))) { + // Currently only kNone and kLtr are supported text direction. + case ax::mojom::TextDirection::kNone: + case ax::mojom::TextDirection::kLtr: { + int start_pixel_offset = + start_offset > 0 ? character_offsets[start_offset - 1] : location.x(); + int end_pixel_offset = + end_offset > 0 ? character_offsets[end_offset - 1] : location.x(); + bounds = + gfx::RectF(start_pixel_offset, location.y(), + end_pixel_offset - start_pixel_offset, location.height()); + break; + } + default: + NOTIMPLEMENTED(); + } + return bounds; +} + } // namespace ui
diff --git a/ui/accessibility/platform/test_ax_node_wrapper.h b/ui/accessibility/platform/test_ax_node_wrapper.h index b935d6b..adfa923 100644 --- a/ui/accessibility/platform/test_ax_node_wrapper.h +++ b/ui/accessibility/platform/test_ax_node_wrapper.h
@@ -123,6 +123,9 @@ int32_t GetPosInSet() const override; int32_t GetSetSize() const override; const std::vector<gfx::NativeViewAccessible> GetDescendants() const override; + gfx::RectF GetLocation() const; + int InternalChildCount() const; + TestAXNodeWrapper* InternalGetChild(int index) const; private: TestAXNodeWrapper(AXTree* tree, AXNode* node); @@ -142,6 +145,11 @@ void Descendants(const AXNode* node, std::vector<gfx::NativeViewAccessible>* descendants) const; + // Return the bounds of inline text in this node's coordinate system (which is + // relative to its container node specified in AXRelativeBounds). + gfx::RectF GetInlineTextRect(const int start_offset, + const int end_offset) const; + AXTree* tree_; AXNode* node_; ui::AXUniqueId unique_id_;
diff --git a/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java b/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java index d699d11..e4d91921 100644 --- a/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java +++ b/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java
@@ -183,8 +183,22 @@ return; } - if (shouldUsePhotoPicker - && requestPermissions[i].equals(storagePermission)) { + // TODO(finnur): Remove once we figure out the cause of crbug.com/950024. + if (shouldUsePhotoPicker) { + if (permissions.length != requestPermissions.length) { + throw new RuntimeException( + String.format("Permissions arrays misaligned: %d != %d", + permissions.length, requestPermissions.length)); + } + + if (!permissions[i].equals(requestPermissions[i])) { + throw new RuntimeException( + String.format("Permissions arrays don't match: %s != %s", + permissions[i], requestPermissions[i])); + } + } + + if (shouldUsePhotoPicker && permissions[i].equals(storagePermission)) { onFileNotSelected(); return; }
diff --git a/ui/aura/demo/demo_main.cc b/ui/aura/demo/demo_main.cc index 125d40b..ce90b31 100644 --- a/ui/aura/demo/demo_main.cc +++ b/ui/aura/demo/demo_main.cc
@@ -9,10 +9,10 @@ #include "base/i18n/icu_util.h" #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/message_loop/message_loop.h" #include "base/power_monitor/power_monitor.h" #include "base/power_monitor/power_monitor_device_source.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "build/build_config.h" #include "components/viz/host/host_frame_sink_manager.h" @@ -143,8 +143,9 @@ display::win::SetDefaultDeviceScaleFactor(1.0f); #endif - // Create the message-loop here before creating the root window. - base::MessageLoopForUI message_loop; + // Create the task executor here before creating the root window. + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::ThreadPoolInstance::CreateAndStartWithDefaultParams("demo"); ui::InitializeInputMethodForTesting();
diff --git a/ui/gl/features.gni b/ui/gl/features.gni index 456990c..a90d220 100644 --- a/ui/gl/features.gni +++ b/ui/gl/features.gni
@@ -14,5 +14,5 @@ # Should Dawn support be compiled to back the WebGPU implementation. # Also controls linking Dawn depedencies in such as SPIRV-Tools and # SPIRV-Cross - use_dawn = false + use_dawn = is_mac }
diff --git a/ui/ozone/demo/ozone_demo.cc b/ui/ozone/demo/ozone_demo.cc index 76d712a..07e8344 100644 --- a/ui/ozone/demo/ozone_demo.cc +++ b/ui/ozone/demo/ozone_demo.cc
@@ -8,8 +8,8 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/debug/stack_trace.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" @@ -70,7 +70,8 @@ mojo::core::Init(); - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::ThreadPoolInstance::CreateAndStartWithDefaultParams("OzoneDemo"); ui::OzonePlatform::InitParams params;
diff --git a/ui/ozone/demo/skia/skia_demo.cc b/ui/ozone/demo/skia/skia_demo.cc index 097756c9..bc523f7 100644 --- a/ui/ozone/demo/skia/skia_demo.cc +++ b/ui/ozone/demo/skia/skia_demo.cc
@@ -8,8 +8,8 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/debug/stack_trace.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/task/thread_pool/thread_pool.h" #include "base/trace_event/trace_event.h" #include "components/tracing/common/trace_to_console.h" @@ -43,9 +43,10 @@ mojo::core::Init(); - // Build UI thread message loop. This is used by platform + // Build UI thread task executor. This is used by platform // implementations for event polling & running background tasks. - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); base::ThreadPoolInstance::CreateAndStartWithDefaultParams("SkiaDemo"); ui::OzonePlatform::InitParams params;
diff --git a/ui/ozone/platform/drm/gpu/gbm_surface_factory.cc b/ui/ozone/platform/drm/gpu/gbm_surface_factory.cc index 126be375..25fa807 100644 --- a/ui/ozone/platform/drm/gpu/gbm_surface_factory.cc +++ b/ui/ozone/platform/drm/gpu/gbm_surface_factory.cc
@@ -115,6 +115,12 @@ return supported_buffer_formats; } + // Skip the virtual graphics memory manager device. + if (base::LowerCaseEqualsASCII(gbm_device_get_backend_name(device.get()), + "vgem")) { + continue; + } + for (int i = 0; i <= static_cast<int>(gfx::BufferFormat::LAST); ++i) { const gfx::BufferFormat buffer_format = static_cast<gfx::BufferFormat>(i); if (base::ContainsValue(supported_buffer_formats, buffer_format))
diff --git a/ui/ozone/platform/wayland/wayland_buffer_fuzzer.cc b/ui/ozone/platform/wayland/wayland_buffer_fuzzer.cc index c4ad4ed3..06f3cb62 100644 --- a/ui/ozone/platform/wayland/wayland_buffer_fuzzer.cc +++ b/ui/ozone/platform/wayland/wayland_buffer_fuzzer.cc
@@ -13,7 +13,7 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" -#include "base/message_loop/message_loop.h" +#include "base/task/single_thread_task_executor.h" #include "base/test/fuzzed_data_provider.h" #include "testing/gmock/include/gmock/gmock.h" #include "ui/gfx/geometry/rect.h" @@ -61,7 +61,8 @@ DRM_FORMAT_XRGB2101010, DRM_FORMAT_XBGR2101010, DRM_FORMAT_RGB565, DRM_FORMAT_UYVY, DRM_FORMAT_NV12, DRM_FORMAT_YVU420}; - base::MessageLoopForUI message_loop; + base::SingleThreadTaskExecutor main_task_executor( + base::MessagePump::Type::UI); MockPlatformWindowDelegate delegate; std::unique_ptr<ui::WaylandConnection> connection =
diff --git a/ui/views/controls/webview/webview.cc b/ui/views/controls/webview/webview.cc index 85a5587f..fa63248 100644 --- a/ui/views/controls/webview/webview.cc +++ b/ui/views/controls/webview/webview.cc
@@ -53,11 +53,7 @@ // WebView, public: WebView::WebView(content::BrowserContext* browser_context) - : holder_(new NativeViewHost()), - embed_fullscreen_widget_mode_enabled_(false), - is_embedding_fullscreen_widget_(false), - browser_context_(browser_context), - allow_accelerators_(false) { + : holder_(new NativeViewHost()), browser_context_(browser_context) { AddChildView(holder_); // Takes ownership of |holder_|. } @@ -79,7 +75,7 @@ if (replacement == web_contents()) return; SetCrashedOverlayView(nullptr); - DetachWebContents(); + DetachWebContentsNativeView(); WebContentsObserver::Observe(replacement); // web_contents() now returns |replacement| from here onwards. UpdateCrashedOverlayView(); @@ -87,11 +83,12 @@ wc_owner_.reset(); if (embed_fullscreen_widget_mode_enabled_) { is_embedding_fullscreen_widget_ = - web_contents() && web_contents()->GetFullscreenRenderWidgetHostView(); + fullscreen_native_view_for_testing_ || + (web_contents() && web_contents()->GetFullscreenRenderWidgetHostView()); } else { DCHECK(!is_embedding_fullscreen_widget_); } - AttachWebContents(); + AttachWebContentsNativeView(); NotifyAccessibilityWebContentsChanged(); MaybeEnableAutoResize(); @@ -203,7 +200,7 @@ void WebView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add) - AttachWebContents(); + AttachWebContentsNativeView(); } bool WebView::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) { @@ -348,16 +345,23 @@ //////////////////////////////////////////////////////////////////////////////// // WebView, private: -void WebView::AttachWebContents() { - TRACE_EVENT0("views", "WebView::AttachWebContents"); +void WebView::AttachWebContentsNativeView() { + TRACE_EVENT0("views", "WebView::AttachWebContentsNativeView"); // Prevents attachment if the WebView isn't already in a Widget, or it's // already attached. if (!GetWidget() || !web_contents()) return; - const gfx::NativeView view_to_attach = is_embedding_fullscreen_widget_ ? - web_contents()->GetFullscreenRenderWidgetHostView()->GetNativeView() : - web_contents()->GetNativeView(); + gfx::NativeView view_to_attach; + if (is_embedding_fullscreen_widget_) { + view_to_attach = fullscreen_native_view_for_testing_ + ? fullscreen_native_view_for_testing_ + : web_contents() + ->GetFullscreenRenderWidgetHostView() + ->GetNativeView(); + } else { + view_to_attach = web_contents()->GetNativeView(); + } OnBoundsChanged(bounds()); if (holder_->native_view() == view_to_attach) return; @@ -381,24 +385,24 @@ OnWebContentsAttached(); } -void WebView::DetachWebContents() { - TRACE_EVENT0("views", "WebView::DetachWebContents"); - if (web_contents()) { +void WebView::DetachWebContentsNativeView() { + TRACE_EVENT0("views", "WebView::DetachWebContentsNativeView"); + if (web_contents()) holder_->Detach(); - } } void WebView::ReattachForFullscreenChange(bool enter_fullscreen) { DCHECK(embed_fullscreen_widget_mode_enabled_); const bool web_contents_has_separate_fs_widget = - web_contents() && web_contents()->GetFullscreenRenderWidgetHostView(); + fullscreen_native_view_for_testing_ || + (web_contents() && web_contents()->GetFullscreenRenderWidgetHostView()); if (is_embedding_fullscreen_widget_ || web_contents_has_separate_fs_widget) { // Shutting down or starting up the embedding of the separate fullscreen // widget. Need to detach and re-attach to a different native view. - DetachWebContents(); + DetachWebContentsNativeView(); is_embedding_fullscreen_widget_ = enter_fullscreen && web_contents_has_separate_fs_widget; - AttachWebContents(); + AttachWebContentsNativeView(); } else { // Entering or exiting "non-Flash" fullscreen mode, where the native view is // the same. So, do not change attachment.
diff --git a/ui/views/controls/webview/webview.h b/ui/views/controls/webview/webview.h index 2d358a9d..e85d9df5 100644 --- a/ui/views/controls/webview/webview.h +++ b/ui/views/controls/webview/webview.h
@@ -165,8 +165,8 @@ private: friend class WebViewUnitTest; - void AttachWebContents(); - void DetachWebContents(); + void AttachWebContentsNativeView(); + void DetachWebContentsNativeView(); void ReattachForFullscreenChange(bool enter_fullscreen); void UpdateCrashedOverlayView(); void NotifyAccessibilityWebContentsChanged(); @@ -185,16 +185,16 @@ // Non-NULL if |web_contents()| was created and is owned by this WebView. std::unique_ptr<content::WebContents> wc_owner_; // When true, WebView auto-embeds fullscreen widgets as a child view. - bool embed_fullscreen_widget_mode_enabled_; + bool embed_fullscreen_widget_mode_enabled_ = false; // Set to true while WebView is embedding a fullscreen widget view as a child // view instead of the normal WebContentsView render view. Note: This will be // false in the case of non-Flash fullscreen. - bool is_embedding_fullscreen_widget_; + bool is_embedding_fullscreen_widget_ = false; // Set to true when |holder_| is letterboxed (scaled to be smaller than this // view, to preserve its aspect ratio). bool is_letterboxing_ = false; content::BrowserContext* browser_context_; - bool allow_accelerators_; + bool allow_accelerators_ = false; View* crashed_overlay_view_ = nullptr; // Minimum and maximum sizes to determine WebView bounds for auto-resizing. @@ -206,6 +206,13 @@ // WebContents's main RenderFrameHost. ui::AXTreeID child_ax_tree_id_; + // Used as the fullscreen NativeView if + // |embed_fullscreen_widget_mode_enabled_| is enabled. This is only set in + // tests as injecting a different value for + // WebContents::GetFullscreenRenderWidgetHostView() is rather tricky in + // unit-tests. + gfx::NativeView fullscreen_native_view_for_testing_ = nullptr; + DISALLOW_COPY_AND_ASSIGN(WebView); };
diff --git a/ui/views/controls/webview/webview_unittest.cc b/ui/views/controls/webview/webview_unittest.cc index 8950e86..aff0d51 100644 --- a/ui/views/controls/webview/webview_unittest.cc +++ b/ui/views/controls/webview/webview_unittest.cc
@@ -190,6 +190,10 @@ content::WebContents::CreateParams(browser_context_.get())); } + void SetFullscreenNativeView(WebView* web_view, gfx::NativeView native_view) { + web_view->fullscreen_native_view_for_testing_ = native_view; + } + private: std::unique_ptr<content::RenderViewHostTestEnabler> rvh_enabler_; std::unique_ptr<content::TestBrowserContext> browser_context_; @@ -561,4 +565,44 @@ delete crashed_overlay_view; } +#if defined(USE_AURA) +namespace { + +// TODO(sky): factor this for mac. +gfx::Rect GetNativeViewBounds(gfx::NativeView native_view) { + return native_view->bounds(); +} + +} // namespace + +TEST_F(WebViewUnitTest, LayoutFullscreenNativeView) { + web_view()->SetEmbedFullscreenWidgetMode(true); + // WebView lazily creates WebContents. Force creation. + web_view()->GetWebContents(); + // Layout is async, force a layout now to ensure bounds are set. + web_view()->Layout(); + const gfx::Rect initial_bounds = + GetNativeViewBounds(web_view()->GetWebContents()->GetNativeView()); + EXPECT_NE(gfx::Rect(), initial_bounds); + + // Create another WebContents for a separate gfx::NativeView. The WebContent's + // gfx::NativeView is used as the fullscreen widget for web_view(). + const std::unique_ptr<content::WebContents> fullscreen_web_contents( + CreateWebContents()); + EXPECT_NE(initial_bounds, + GetNativeViewBounds(fullscreen_web_contents->GetNativeView())); + SetFullscreenNativeView(web_view(), fullscreen_web_contents->GetNativeView()); + + // Trigger going fullscreen. Once fullscreen, the fullscreen gfx::NativeView + // should be immediately resized. + static_cast<content::WebContentsObserver*>(web_view()) + ->DidShowFullscreenWidget(); + EXPECT_EQ(initial_bounds, + GetNativeViewBounds(fullscreen_web_contents->GetNativeView())); + + static_cast<content::WebContentsObserver*>(web_view()) + ->DidDestroyFullscreenWidget(); +} +#endif + } // namespace views